

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 启用 SageMaker 训练编译器
<a name="training-compiler-enable"></a>

**重要**  
Amazon Web Services (AWS) 宣布， SageMaker 训练编译器将没有新版本或新版本。你可以继续通过现有的 Dee AWS p Learning Containers (DLCs) 使用 SageMaker SageMaker 训练编译器进行训练。值得注意的是，根据[AWS 深度学习容器（Deep Learning Containers Framework Support）政策 AWS](https://docs.aws.amazon.com/deep-learning-containers/latest/devguide/support-policy.html)，虽然现有内容 DLCs 仍然可以访问，但它们将不再收到来自的补丁或更新。

SageMaker 训练编译器内置于 SageMaker Python SDK 和 Dee AWS p Learning Containers 中，因此您无需更改工作流程即可启用训练编译器。选择与您的使用案例匹配的下列主题之一。

**Topics**
+ [

# 使用 PyTorch 训练编译器运行 SageMaker 训练作业
](training-compiler-enable-pytorch.md)
+ [

# 使用 TensorFlow 训练编译器运行 SageMaker 训练作业
](training-compiler-enable-tensorflow.md)

# 使用 PyTorch 训练编译器运行 SageMaker 训练作业
<a name="training-compiler-enable-pytorch"></a>

您可以使用任何 SageMaker AI 接口通过 Training Compiler 运行训练作业：Amazon SageMaker Studio Classic 适用于 Python (Boto3) 的 AWS SDK、Amazon SageMaker 笔记本实例和 AWS Command Line Interface。 SageMaker 

**Topics**
+ [

## 使用 SageMaker Python 开发工具包
](#training-compiler-enable-pytorch-pysdk)
+ [

## 使用 SageMaker AI `CreateTrainingJob` API 操作
](#training-compiler-enable-pytorch-api)

## 使用 SageMaker Python 开发工具包
<a name="training-compiler-enable-pytorch-pysdk"></a>

SageMaker 训练编译器 PyTorch 可通过 SageMaker AI [https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/sagemaker.pytorch.html](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/sagemaker.pytorch.html)和[https://sagemaker.readthedocs.io/en/stable/frameworks/huggingface/sagemaker.huggingface.html#hugging-face-estimator](https://sagemaker.readthedocs.io/en/stable/frameworks/huggingface/sagemaker.huggingface.html#hugging-face-estimator)框架估算器类获得。要打开 SageMaker 训练编译器，请将`compiler_config`参数添加到 SageMaker AI 估计器中。导入 `TrainingCompilerConfig` 类，并将它的一个实例传递给 `compiler_config` 参数。以下代码示例显示了开启 SageMaker 训练编译器的 SageMaker AI 估算器类的结构。

**提示**  
要开始使用 PyTorch 或《变形金刚》提供的预建模型，请尝试使用参考表中提供的批次大小，网址为[经过测试的模型](training-compiler-support.md#training-compiler-tested-models)。

**注意**  
原生 PyTorch 支持在 SageMaker Python SDK v2.121.0 及更高版本中可用。请务必相应地更新 SageMaker Python 开发工具包。

**注意**  
从 PyTorch v1.12.0 开始，“ SageMaker 训练编译器” 容器可用。 PyTorch 请注意，的 SageMaker 训练编译器容器未预先打包 Hu PyTorch gging Face Transformers。如果您需要在容器中安装库，请务必在提交训练作业时将 `requirements.txt` 文件添加到源目录下。  
对于 PyTorch v1.11.0 及更早版本，请使用之前版本的 Hugging Face 和 T SageMaker raining Compiler 容器。 PyTorch  
有关框架版本和相应容器信息的完整列表，请参阅[支持的框架](training-compiler-support.md#training-compiler-supported-frameworks)。

有关适合您的使用案例的信息，请参阅下列选项之一。

### 对于单个 GPU 训练
<a name="training-compiler-estimator-pytorch-single"></a>

------
#### [ PyTorch v1.12.0 and later ]

要编译和训练 PyTorch 模型，请使用 SageMaker 训练编译器配置 A SageMaker I PyTorch 估算器，如以下代码示例所示。

**注意**  
这种原生 PyTorch 支持在 SageMaker AI Python SDK v2.120.0 及更高版本中可用。请务必更新 SageMaker AI Python 软件开发工具包。

```
from sagemaker.pytorch import PyTorch, TrainingCompilerConfig

# the original max batch size that can fit into GPU memory without compiler
batch_size_native=12
learning_rate_native=float('5e-5')

# an updated max batch size that can fit into GPU memory with compiler
batch_size=64

# update learning rate
learning_rate=learning_rate_native/batch_size_native*batch_size

hyperparameters={
    "n_gpus": 1,
    "batch_size": batch_size,
    "learning_rate": learning_rate
}

pytorch_estimator=PyTorch(
    entry_point='train.py',
    source_dir='path-to-requirements-file', # Optional. Add this if need to install additional packages.
    instance_count=1,
    instance_type='ml.p3.2xlarge',
    framework_version='1.13.1',
    py_version='py3',
    hyperparameters=hyperparameters,
    compiler_config=TrainingCompilerConfig(),
    disable_profiler=True,
    debugger_hook_config=False
)

pytorch_estimator.fit()
```

------
#### [ Hugging Face Transformers with PyTorch v1.11.0 and before ]

要使用编译和训练转换器模型 PyTorch，请使用训练编译器配置 A SageMaker I Hugging Face 估计器 SageMaker ，如以下代码示例所示。

```
from sagemaker.huggingface import HuggingFace, TrainingCompilerConfig

# the original max batch size that can fit into GPU memory without compiler
batch_size_native=12
learning_rate_native=float('5e-5')

# an updated max batch size that can fit into GPU memory with compiler
batch_size=64

# update learning rate
learning_rate=learning_rate_native/batch_size_native*batch_size

hyperparameters={
    "n_gpus": 1,
    "batch_size": batch_size,
    "learning_rate": learning_rate
}

pytorch_huggingface_estimator=HuggingFace(
    entry_point='train.py',
    instance_count=1,
    instance_type='ml.p3.2xlarge',
    transformers_version='4.21.1',
    pytorch_version='1.11.0',
    hyperparameters=hyperparameters,
    compiler_config=TrainingCompilerConfig(),
    disable_profiler=True,
    debugger_hook_config=False
)

pytorch_huggingface_estimator.fit()
```

要准备训练脚本，请参阅以下页面。
+ [对于单个 GPU 训练](training-compiler-pytorch-models.md#training-compiler-pytorch-models-transformers-trainer-single-gpu)使用 Hugging Face Transformers 训练[器](https://huggingface.co/docs/transformers/main_classes/trainer) API 的 PyTorch 模型
+ [对于单个 GPU 训练](training-compiler-pytorch-models.md#training-compiler-pytorch-models-non-trainer-single-gpu)[没有 Hugging Face Transformers Trainer API 的 PyTorch 模型](https://huggingface.co/transformers/main_classes/trainer.html)

要查找 end-to-end示例，请参阅以下笔记本：
+ [使用 AD 数据集编译和训练 Hugging Face Transformers 训练器模型进行 SQu问答](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-training-compiler/huggingface/pytorch_single_gpu_single_node/albert-base-v2/albert-base-v2.html) 
+ [使用训练编译`BERT`器使用 SST 数据集 SageMaker 编译和训练 Hugging Face Transformer 模型](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-training-compiler/huggingface/pytorch_single_gpu_single_node/bert-base-cased/bert-base-cased-single-node-single-gpu.html) 
+ [使用 SST2 数据集编译和训练二元分类训练器模型，用于单节点单 GPU 训练](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-training-compiler/huggingface/pytorch_single_gpu_single_node/roberta-base/roberta-base.html)

------

### 对于分布式训练
<a name="training-compiler-estimator-pytorch-distributed"></a>

------
#### [ PyTorch v1.12 ]

对于 PyTorch v1.12，您可以通过在 SageMaker AI PyTorch 估算器类的`distribution`参数中添加指定的`pytorch_xla`选项，使用 SageMaker 训练编译器运行分布式训练。

**注意**  
这种原生 PyTorch 支持在 SageMaker AI Python SDK v2.121.0 及更高版本中可用。请务必更新 SageMaker AI Python 软件开发工具包。

```
from sagemaker.pytorch import PyTorch, TrainingCompilerConfig

# choose an instance type, specify the number of instances you want to use,
# and set the num_gpus variable the number of GPUs per instance.
instance_count=1
instance_type='ml.p3.8xlarge'
num_gpus=4

# the original max batch size that can fit to GPU memory without compiler
batch_size_native=16
learning_rate_native=float('5e-5')

# an updated max batch size that can fit to GPU memory with compiler
batch_size=26

# update learning rate
learning_rate=learning_rate_native/batch_size_native*batch_size*num_gpus*instance_count

hyperparameters={
    "n_gpus": num_gpus,
    "batch_size": batch_size,
    "learning_rate": learning_rate
}

pytorch_estimator=PyTorch(
    entry_point='your_training_script.py',
    source_dir='path-to-requirements-file', # Optional. Add this if need to install additional packages.
    instance_count=instance_count,
    instance_type=instance_type,
    framework_version='1.13.1',
    py_version='py3',
    hyperparameters=hyperparameters,
    compiler_config=TrainingCompilerConfig(),
    distribution ={'pytorchxla' : { 'enabled': True }},
    disable_profiler=True,
    debugger_hook_config=False
)

pytorch_estimator.fit()
```

**提示**  
要准备训练脚本，请参阅 [PyTorch](training-compiler-pytorch-models.md)

------
#### [ Transformers v4.21 with PyTorch v1.11 ]

 PyTorch 在 v1.11 及更高版本中， SageMaker 训练编译器可用于分布式训练，参数中指定了`pytorch_xla``distribution`选项。

```
from sagemaker.huggingface import HuggingFace, TrainingCompilerConfig

# choose an instance type, specify the number of instances you want to use,
# and set the num_gpus variable the number of GPUs per instance.
instance_count=1
instance_type='ml.p3.8xlarge'
num_gpus=4

# the original max batch size that can fit to GPU memory without compiler
batch_size_native=16
learning_rate_native=float('5e-5')

# an updated max batch size that can fit to GPU memory with compiler
batch_size=26

# update learning rate
learning_rate=learning_rate_native/batch_size_native*batch_size*num_gpus*instance_count

hyperparameters={
    "n_gpus": num_gpus,
    "batch_size": batch_size,
    "learning_rate": learning_rate
}

pytorch_huggingface_estimator=HuggingFace(
    entry_point='your_training_script.py',
    instance_count=instance_count,
    instance_type=instance_type,
    transformers_version='4.21.1',
    pytorch_version='1.11.0',
    hyperparameters=hyperparameters,
    compiler_config=TrainingCompilerConfig(),
    distribution ={'pytorchxla' : { 'enabled': True }},
    disable_profiler=True,
    debugger_hook_config=False
)

pytorch_huggingface_estimator.fit()
```

**提示**  
要准备训练脚本，请参阅以下页面。  
[对于分布式训练](training-compiler-pytorch-models.md#training-compiler-pytorch-models-transformers-trainer-distributed)使用 Hugging Face Transformers 训练[器](https://huggingface.co/transformers/main_classes/trainer.html) API 的 PyTorch 模型
[对于分布式训练](training-compiler-pytorch-models.md#training-compiler-pytorch-models-non-trainer-distributed)[没有 Hugging Face Transformers Trainer API 的 PyTorch 模型](https://huggingface.co/transformers/main_classes/trainer.html)

------
#### [ Transformers v4.17 with PyTorch v1.10.2 and before ]

对于支持的 PyTorch v1.10.2 及更早版本，Training Compiler 需要另一种机制来启动分布式 SageMaker 训练作业。要运行分布式训 SageMaker 练，Training Compiler 要求您将 SageMaker AI 分布式训练启动器脚本传递给`entry_point`参数，并将训练脚本传递给`hyperparameters`参数。以下代码示例显示了如何配置应用所需更改的 A SageMaker I Hugging Face 估算器。

```
from sagemaker.huggingface import HuggingFace, TrainingCompilerConfig

# choose an instance type, specify the number of instances you want to use,
# and set the num_gpus variable the number of GPUs per instance.
instance_count=1
instance_type='ml.p3.8xlarge'
num_gpus=4

# the original max batch size that can fit to GPU memory without compiler
batch_size_native=16
learning_rate_native=float('5e-5')

# an updated max batch size that can fit to GPU memory with compiler
batch_size=26

# update learning rate
learning_rate=learning_rate_native/batch_size_native*batch_size*num_gpus*instance_count

training_script="your_training_script.py"

hyperparameters={
    "n_gpus": num_gpus,
    "batch_size": batch_size,
    "learning_rate": learning_rate,
    "training_script": training_script     # Specify the file name of your training script.
}

pytorch_huggingface_estimator=HuggingFace(
    entry_point='distributed_training_launcher.py',    # Specify the distributed training launcher script.
    instance_count=instance_count,
    instance_type=instance_type,
    transformers_version='4.17.0',
    pytorch_version='1.10.2',
    hyperparameters=hyperparameters,
    compiler_config=TrainingCompilerConfig(),
    disable_profiler=True,
    debugger_hook_config=False
)

pytorch_huggingface_estimator.fit()
```

启动器脚本应如下所示。它包装训练脚本，并根据所选训练实例的大小配置分布式训练环境。

```
# distributed_training_launcher.py

#!/bin/python

import subprocess
import sys

if __name__ == "__main__":
    arguments_command = " ".join([arg for arg in sys.argv[1:]])
    """
    The following line takes care of setting up an inter-node communication
    as well as managing intra-node workers for each GPU.
    """
    subprocess.check_call("python -m torch_xla.distributed.sm_dist " + arguments_command, shell=True)
```

**提示**  
要准备训练脚本，请参阅以下页面。  
[对于分布式训练](training-compiler-pytorch-models.md#training-compiler-pytorch-models-transformers-trainer-distributed)使用 Hugging Face Transformers 训练[器](https://huggingface.co/transformers/main_classes/trainer.html) API 的 PyTorch 模型
[对于分布式训练](training-compiler-pytorch-models.md#training-compiler-pytorch-models-non-trainer-distributed)[没有 Hugging Face Transformers Trainer API 的 PyTorch 模型](https://huggingface.co/transformers/main_classes/trainer.html)

**提示**  
要查找 end-to-end示例，请参阅以下笔记本：  
[使用 Transformers Trainer API 以及用于单节点多 GPU 训练 SST2 的数据集编译和训练 GPT2 模型](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/language-modeling-multi-gpu-single-node.html)
[使用 Transformers Trainer API 以及用于多节点多 GPU 训练 SST2 的数据集编译和训练 GPT2 模型](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_multiple_node/language-modeling-multi-gpu-multi-node.html)

------

以下列表是使用编译器运行 SageMaker 训练作业所需的最少参数集。

**注意**  
使用 SageMaker AI Hugging Face 估算器时，必须指定`transformers_version`、`pytorch_version``hyperparameters`、`compiler_config`和参数才能 SageMaker 启用 Training Compiler。您无法使用 `image_uri` 手动指定集成了 [支持的框架](training-compiler-support.md#training-compiler-supported-frameworks) 上列出的深度学习容器的 Training Compiler。
+ `entry_point` (str) – 必需。指定训练脚本的文件名。
**注意**  
要使用 Training Compiler 和 PyTorch v1.10.2 及更低版本运行分布式 SageMaker 训练，请为此参数指定启动器脚本的文件名。启动器脚本应已准备好，以便包装您的训练脚本并配置分布式训练环境。有关更多信息，请参阅以下示例笔记本：  
[使用 Transformers Trainer API 以及用于单节点多 GPU 训练 SST2 的数据集编译和训练 GPT2 模型](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_single_node/language-modeling-multi-gpu-single-node.html)
[使用 Transformers Trainer API 以及用于多节点多 GPU 训练 SST2 的数据集编译和训练 GPT2 模型](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-training-compiler/huggingface/pytorch_multiple_gpu_multiple_node/language-modeling-multi-gpu-multi-node.html)
+ `source_dir` (str) – 可选。如果需要安装其他包，请添加此项。要安装包，您需要在此目录下准备一个 `requirements.txt` 文件。
+ `instance_count` (int) – 必需。指定实例数。
+ `instance_type` (str) – 必需。指定实例类型。
+ `transformers_version`(str) — 仅在使用 SageMaker AI Hugging Face 估算器时才需要。指定训练编译器支持 SageMaker 的 Hugging Face 变形金刚库版本。要查找可用版本，请参阅 [支持的框架](training-compiler-support.md#training-compiler-supported-frameworks)。
+ `framework_version` 或 `pytorch_version` (str) – 必需。指定 SageMaker 训练编译器支持的 PyTorch 版本。要查找可用版本，请参阅 [支持的框架](training-compiler-support.md#training-compiler-supported-frameworks)。
**注意**  
使用 SageMaker AI Hugging Face 估计器时，必须同时指定和。`transformers_version` `pytorch_version`
+ `hyperparameters` (dict) – 可选。为训练作业指定超参数，例如 `n_gpus`、`batch_size` 和 `learning_rate`。启用 T SageMaker raining Compiler 后，请尝试更大的批量大小并相应地调整学习率。要查找有关使用编译器和调整的批处理大小以提高训练速度的案例研究，请参阅[经过测试的模型](training-compiler-support.md#training-compiler-tested-models)和[SageMaker 训练编译器示例笔记本和博客](training-compiler-examples-and-blogs.md)。
**注意**  
要使用 SageMaker Training Compiler 和 PyTorch v1.10.2 及更低版本运行分布式训练`"training_script"`，您需要添加其他参数来指定您的训练脚本，如前面的代码示例所示。
+ `compiler_config`（TrainingCompilerConfig 对象）-激活 SageMaker 训练编译器所必需的。添加此参数可开启 SageMaker 训练编译器。下面是 `TrainingCompilerConfig` 类的参数。
  + `enabled` (bool) – 可选。指定`True`或`False`以打开或关闭 SageMaker 训练编译器。默认值为 `True`。
  + `debug` (bool) – 可选。要从编译器加速的训练作业中接收更详细的训练日志，请将此项更改为 `True`。但是，额外的日志记录可能会增加开销并减缓编译后的训练作业。默认值为 `False`。
+ `distribution` (dict) – 可选。要使用训练编译器运行分布式 SageMaker 训练作业，请添加`distribution = { 'pytorchxla' : { 'enabled': True }}`。

**警告**  
如果您打开 SageMaker 调试器，可能会影响 SageMaker 训练编译器的性能。我们建议您在运行 SageMaker Training Compiler 时关闭调试器，以确保不会对性能产生影响。有关更多信息，请参阅 [注意事项](training-compiler-tips-pitfalls.md#training-compiler-tips-pitfalls-considerations)。要关闭 Debugger 功能，请向估算器添加以下两个参数：  

```
disable_profiler=True,
debugger_hook_config=False
```

如果使用编译器成功启动训练作业，则在作业初始化阶段将收到以下日志：
+ 与 `TrainingCompilerConfig(debug=False)`

  ```
  Found configuration for Training Compiler
  Configuring SM Training Compiler...
  ```
+ 与 `TrainingCompilerConfig(debug=True)`

  ```
  Found configuration for Training Compiler
  Configuring SM Training Compiler...
  Training Compiler set to debug mode
  ```

## 使用 SageMaker AI `CreateTrainingJob` API 操作
<a name="training-compiler-enable-pytorch-api"></a>

SageMaker 必须通过 [`CreateTrainingJob`API 操作](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html)的请求语法中的`AlgorithmSpecification`和`HyperParameters`字段指定训练编译器配置选项。

```
"AlgorithmSpecification": {
    "TrainingImage": "<sagemaker-training-compiler-enabled-dlc-image>"
},

"HyperParameters": {
    "sagemaker_training_compiler_enabled": "true",
    "sagemaker_training_compiler_debug_mode": "false",
    "sagemaker_pytorch_xla_multi_worker_enabled": "false"    // set to "true" for distributed training
}
```

要查找已 SageMaker 实现 Training Compiler 的深度学习容器镜像 URIs 的完整列表，请参阅[支持的框架](training-compiler-support.md#training-compiler-supported-frameworks)。

# 使用 TensorFlow 训练编译器运行 SageMaker 训练作业
<a name="training-compiler-enable-tensorflow"></a>

您可以使用任何 SageMaker AI 接口通过 Training Compiler 运行训练作业：Amazon SageMaker Studio Classic 适用于 Python (Boto3) 的 AWS SDK、Amazon SageMaker 笔记本实例和 AWS Command Line Interface。 SageMaker 

**Topics**
+ [

## 使用 SageMaker Python 开发工具包
](#training-compiler-enable-tensorflow-pysdk)
+ [

## 使用 SageMaker AI Python SDK 和扩展 SageMaker 人工智能框架 Deep Learning Containers
](#training-compiler-enable-tensorflow-sdk-extend-container)
+ [

## 使用 SageMaker A `CreateTrainingJob` I API 操作启用 SageMaker 训练编译器
](#training-compiler-enable-tensorflow-api)

## 使用 SageMaker Python 开发工具包
<a name="training-compiler-enable-tensorflow-pysdk"></a>

要打开 T SageMaker raining Compiler，请将`compiler_config`参数添加到 SageMaker AI TensorFlow 或 Hugging Face 估算器中。导入 `TrainingCompilerConfig` 类，并将它的一个实例传递给 `compiler_config` 参数。以下代码示例显示了开启 SageMaker 训练编译器的 SageMaker AI 估算器类的结构。

**提示**  
要开始使用由《变形金刚》 TensorFlow 和《变形金刚》库提供的预建模型，请尝试使用参考表中提供的批次大小。[经过测试的模型](training-compiler-support.md#training-compiler-tested-models)

**注意**  
SageMaker 训练编译器可 TensorFlow 通过 SageMaker AI [TensorFlow](https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/sagemaker.tensorflow.html#tensorflow-estimator)和 [Hugging Face 框架估算](https://sagemaker.readthedocs.io/en/stable/frameworks/huggingface/sagemaker.huggingface.html#hugging-face-estimator)器获得。

有关适合您的使用案例的信息，请参阅下列选项之一。

### 对于单个 GPU 训练
<a name="training-compiler-estimator-tensorflow-single"></a>

------
#### [ TensorFlow ]

```
from sagemaker.tensorflow import TensorFlow, TrainingCompilerConfig

# the original max batch size that can fit into GPU memory without compiler
batch_size_native=12
learning_rate_native=float('5e-5')

# an updated max batch size that can fit into GPU memory with compiler
batch_size=64    

# update the global learning rate
learning_rate=learning_rate_native/batch_size_native*batch_size

hyperparameters={
    "n_gpus": 1,
    "batch_size": batch_size,
    "learning_rate": learning_rate
}

tensorflow_estimator=TensorFlow(
    entry_point='train.py',
    instance_count=1,
    instance_type='ml.p3.2xlarge',
    framework_version='2.9.1',
    hyperparameters=hyperparameters,
    compiler_config=TrainingCompilerConfig(),
    disable_profiler=True,
    debugger_hook_config=False
)

tensorflow_estimator.fit()
```

要准备训练脚本，请参阅以下页面。
+ [对于单个 GPU 训练](training-compiler-tensorflow.md#training-compiler-tensorflow-models-keras-single-gpu)使用 TensorFlow Keras (`tf.keras.*`) 构造的模型。
+ [对于单个 GPU 训练](training-compiler-tensorflow.md#training-compiler-tensorflow-models-no-keras-single-gpu)使用 TensorFlow 模块（`tf.*`不包括 TensorFlow Keras 模块）构造的模型。

------
#### [ Hugging Face Estimator with TensorFlow ]

```
from sagemaker.huggingface import HuggingFace, TrainingCompilerConfig

# the original max batch size that can fit into GPU memory without compiler
batch_size_native=12
learning_rate_native=float('5e-5')

# an updated max batch size that can fit into GPU memory with compiler
batch_size=64

# update the global learning rate
learning_rate=learning_rate_native/batch_size_native*batch_size

hyperparameters={
    "n_gpus": 1,
    "batch_size": batch_size,
    "learning_rate": learning_rate
}

tensorflow_huggingface_estimator=HuggingFace(
    entry_point='train.py',
    instance_count=1,
    instance_type='ml.p3.2xlarge',
    transformers_version='4.21.1',
    tensorflow_version='2.6.3',
    hyperparameters=hyperparameters,
    compiler_config=TrainingCompilerConfig(),
    disable_profiler=True,
    debugger_hook_config=False
)

tensorflow_huggingface_estimator.fit()
```

要准备训练脚本，请参阅以下页面。
+ [对于单个 GPU 训练](training-compiler-tensorflow.md#training-compiler-tensorflow-models-transformers-keras-single-gpu)带有 Hugging Face T TensorFlow ransformers 的 Keras 模型
+ [对于单个 GPU 训练](training-compiler-tensorflow.md#training-compiler-tensorflow-models-transformers-no-keras-single-gpu)带有 Hugging Face Transformers 的 TensorFlow 模型

------

### 对于分布式训练
<a name="training-compiler-estimator-tensorflow-distributed"></a>

------
#### [ Hugging Face Estimator with TensorFlow ]

```
from sagemaker.huggingface import HuggingFace, TrainingCompilerConfig

# choose an instance type, specify the number of instances you want to use,
# and set the num_gpus variable the number of GPUs per instance.
instance_count=1
instance_type='ml.p3.8xlarge'
num_gpus=4

# the original max batch size that can fit to GPU memory without compiler
batch_size_native=16
learning_rate_native=float('5e-5')

# an updated max batch size that can fit to GPU memory with compiler
batch_size=26

# update learning rate
learning_rate=learning_rate_native/batch_size_native*batch_size*num_gpus*instance_count

hyperparameters={
    "n_gpus": num_gpus,
    "batch_size": batch_size,
    "learning_rate": learning_rate
}

tensorflow_huggingface_estimator=HuggingFace(
    entry_point='train.py',
    instance_count=instance_count,
    instance_type=instance_type,
    transformers_version='4.21.1',
    tensorflow_version='2.6.3',
    hyperparameters=hyperparameters,
    compiler_config=TrainingCompilerConfig(),
    disable_profiler=True,
    debugger_hook_config=False
)

tensorflow_huggingface_estimator.fit()
```

**提示**  
要准备训练脚本，请参阅以下页面。  
[对于分布式训练](training-compiler-tensorflow.md#training-compiler-tensorflow-models-transformers-keras-distributed)带有 Hugging Face T TensorFlow ransformers 的 Keras 模型
[对于分布式训练](training-compiler-tensorflow.md#training-compiler-tensorflow-models-transformers-no-keras-distributed)带有 Hugging Face Transformers 的 TensorFlow 模型

------

以下列表是使用编译器运行 SageMaker 训练作业所需的最少参数集。

**注意**  
使用 SageMaker AI Hugging Face 估算器时，必须指定`transformers_version`、`tensorflow_version``hyperparameters`、`compiler_config`和参数才能 SageMaker 启用 Training Compiler。您无法使用 `image_uri` 手动指定集成了 [支持的框架](training-compiler-support.md#training-compiler-supported-frameworks) 上列出的深度学习容器的 Training Compiler。
+ `entry_point` (str) – 必需。指定训练脚本的文件名。
+ `instance_count` (int) – 必需。指定实例数。
+ `instance_type` (str) – 必需。指定实例类型。
+ `transformers_version`(str) — 仅在使用 SageMaker AI Hugging Face 估算器时才需要。指定训练编译器支持 SageMaker 的 Hugging Face 变形金刚库版本。要查找可用版本，请参阅 [支持的框架](training-compiler-support.md#training-compiler-supported-frameworks)。
+ `framework_version` 或 `tensorflow_version` (str) – 必需。指定 SageMaker 训练编译器支持的 TensorFlow 版本。要查找可用版本，请参阅 [支持的框架](training-compiler-support.md#training-compiler-supported-frameworks)。
**注意**  
使用 SageMaker AI TensorFlow 估算器时，必须指定。`framework_version`  
使用 SageMaker AI Hugging Face 估计器时，必须同时指定和。`transformers_version` `tensorflow_version`
+ `hyperparameters` (dict) – 可选。为训练作业指定超参数，例如 `n_gpus`、`batch_size` 和 `learning_rate`。启用 T SageMaker raining Compiler 后，请尝试更大的批量大小并相应地调整学习率。要查找有关使用编译器和调整的批处理大小以提高训练速度的案例研究，请参阅[经过测试的模型](training-compiler-support.md#training-compiler-tested-models)和[SageMaker 训练编译器示例笔记本和博客](training-compiler-examples-and-blogs.md)。
+ `compiler_config`（TrainingCompilerConfig 对象）-必填。添加此参数可打开 “ SageMaker 训练编译器”。下面是 `TrainingCompilerConfig` 类的参数。
  + `enabled` (bool) – 可选。指定`True`或`False`以打开或关闭 SageMaker 训练编译器。默认值为 `True`。
  + `debug` (bool) – 可选。要从编译器加速的训练作业中接收更详细的训练日志，请将此项更改为 `True`。但是，额外的日志记录可能会增加开销并减缓编译后的训练作业。默认值为 `False`。

**警告**  
如果打开 SageMaker Debugger，可能会影响 SageMaker 训练编译器的性能。我们建议您在运行 SageMaker Training Compiler 时关闭调试器，以确保不会对性能产生影响。有关更多信息，请参阅 [注意事项](training-compiler-tips-pitfalls.md#training-compiler-tips-pitfalls-considerations)。要关闭 Debugger 功能，请向估算器添加以下两个参数：  

```
disable_profiler=True,
debugger_hook_config=False
```

如果使用编译器成功启动训练作业，则在作业初始化阶段将收到以下日志：
+ 与 `TrainingCompilerConfig(debug=False)`

  ```
  Found configuration for Training Compiler
  Configuring SM Training Compiler...
  ```
+ 与 `TrainingCompilerConfig(debug=True)`

  ```
  Found configuration for Training Compiler
  Configuring SM Training Compiler...
  Training Compiler set to debug mode
  ```

## 使用 SageMaker AI Python SDK 和扩展 SageMaker 人工智能框架 Deep Learning Containers
<a name="training-compiler-enable-tensorflow-sdk-extend-container"></a>

AWS Deep Learning Conta TensorFlow iners（DLC） TensorFlow的改编版本包括开源 TensorFlow 框架之上的更改。[SageMaker AI Framework Deep Learning](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#sagemaker-framework-containers-sm-support-only) Containers 针对底层 AWS 基础设施和 Amazon A SageMaker I 进行了优化。利用使用 SageMaker 训练编译器的优势，与原生版本相比 DLCs，Training Compiler 集成增加了更多的性能改进 TensorFlow。此外，您可以通过扩展 DLC 映像来创建自定义训练容器。

**注意**  
此 Docker 自定义功能目前仅适用于。 TensorFlow

要 TensorFlow DLCs 针对您的用例扩展和自定义 SageMaker AI，请按照以下说明进行操作。

### 创建 Dockerfile
<a name="training-compiler-enable-tensorflow-sdk-extend-container-create-dockerfile"></a>

使用以下 Dockerfile 模板扩展 SageMaker AI TensorFlow DLC。你必须使用 SageMaker AI TensorFlow DLC 镜像作为 Docker 容器的基础镜像。要查找 A SageMaker I TensorFlow DLC 图片 URIs，请参阅[支持的框架](https://docs.aws.amazon.com/sagemaker/latest/dg/training-compiler-support.html#training-compiler-supported-frameworks)。

```
# SageMaker AI TensorFlow Deep Learning Container image
FROM 763104351884.dkr.ecr.<aws-region>.amazonaws.com/tensorflow-training:<image-tag>

ENV PATH="/opt/ml/code:${PATH}"

# This environment variable is used by the SageMaker AI container 
# to determine user code directory.
ENV SAGEMAKER_SUBMIT_DIRECTORY /opt/ml/code

# Add more code lines to customize for your use-case
...
```

有关更多信息，请参阅[步骤 2：创建并上传 Dockerfile 和 Python 训练脚本](https://docs.aws.amazon.com/sagemaker/latest/dg/adapt-training-container.html#byoc-training-step2)。

扩展 SageMaker AI 框架 DLCs时，请考虑以下陷阱：
+ 请勿在 AI 容器中明确卸载或更改 SageMaker AI 容器中 TensorFlow 软件包的版本。这样做会导致 AWS 经过优化的 TensorFlow 软件包被开源 TensorFlow 软件包覆盖，从而可能导致性能下降。
+ 注意以特定 TensorFlow 版本或风格作为依赖项的软件包。这些软件包可能会隐式卸载 AWS 经过优化的软件包 TensorFlow 并安装开源 TensorFlow 软件包。

[例如，有一个已知问题，那就是 tensorflow/models 和 [tensorflow/](https://github.com/tensorflow/models)[text 库总是尝试重新安装](https://github.com/tensorflow/text)开源。 TensorFlow](https://github.com/tensorflow/models/issues/9267)如果您需要安装这些库来为自己的用例选择特定版本，我们建议您查看 2.9 或更高版本的 SageMaker AI TensorFlow DLC Dockerfiles。Dockerfiles 的路径通常采用以下格式：`tensorflow/training/docker/<tensorflow-version>/py3/<cuda-version>/Dockerfile.gpu`。在 Dockerfiles 中，您应该找到按顺序重新安装 AWS 托管 TensorFlow 二进制文件（指定给`TF_URL`环境变量）和其他依赖项的代码行。重新安装部分应与以下示例类似：

```
# tf-models does not respect existing installations of TensorFlow 
# and always installs open source TensorFlow

RUN pip3 install --no-cache-dir -U \
    tf-models-official==x.y.z

RUN pip3 uninstall -y tensorflow tensorflow-gpu \
  ; pip3 install --no-cache-dir -U \
    ${TF_URL} \
    tensorflow-io==x.y.z \
    tensorflow-datasets==x.y.z
```

### 构建并推送到 ECR
<a name="training-compiler-enable-tensorflow-sdk-extend-container-build-and-push"></a>

要构建 Docker 容器并将其推送到 Amazon ECR，请按照以下链接中的说明进行操作：
+ [步骤 3：构建容器](https://docs.aws.amazon.com/sagemaker/latest/dg/adapt-training-container.html#byoc-training-step3)
+ [步骤 4：测试容器](https://docs.aws.amazon.com/sagemaker/latest/dg/adapt-training-container.html#byoc-training-step4)
+ [步骤 5：将容器推送至 Amazon ECR](https://docs.aws.amazon.com/sagemaker/latest/dg/adapt-training-container.html#byoc-training-step5)

### 使用 SageMaker Python 软件开发工具包估算器运行
<a name="training-compiler-enable-tensorflow-sdk-extend-container-run-job"></a>

照常使用 SageMaker AI TensorFlow 框架估算器。您必须指定 `image_uri` 以使用您在 Amazon ECR 中托管的新容器。

```
import sagemaker, boto3
from sagemaker import get_execution_role
from sagemaker.tensorflow import TensorFlow, TrainingCompilerConfig

account_id = boto3.client('sts').get_caller_identity().get('Account')
ecr_repository = 'tf-custom-container-test'
tag = ':latest'

region = boto3.session.Session().region_name

uri_suffix = 'amazonaws.com'

byoc_image_uri = '{}.dkr.ecr.{}.{}/{}'.format(
    account_id, region, uri_suffix, ecr_repository + tag
)

byoc_image_uri
# This should return something like
# 111122223333.dkr.ecr.us-east-2.amazonaws.com/tf-custom-container-test:latest

estimator = TensorFlow(
    image_uri=image_uri,
    role=get_execution_role(),
    base_job_name='tf-custom-container-test-job',
    instance_count=1,
    instance_type='ml.p3.8xlarge'
    compiler_config=TrainingCompilerConfig(),
    disable_profiler=True,
    debugger_hook_config=False
)

# Start training
estimator.fit()
```

## 使用 SageMaker A `CreateTrainingJob` I API 操作启用 SageMaker 训练编译器
<a name="training-compiler-enable-tensorflow-api"></a>

SageMaker 必须通过 [`CreateTrainingJob`API 操作](https://amazonaws.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html)的请求语法中的`AlgorithmSpecification`和`HyperParameters`字段指定训练编译器配置选项。

```
"AlgorithmSpecification": {
    "TrainingImage": "<sagemaker-training-compiler-enabled-dlc-image>"
},

"HyperParameters": {
    "sagemaker_training_compiler_enabled": "true",
    "sagemaker_training_compiler_debug_mode": "false"
}
```

要查找已 SageMaker 实现 Training Compiler 的深度学习容器镜像 URIs 的完整列表，请参阅[支持的框架](training-compiler-support.md#training-compiler-supported-frameworks)。