

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 SageMaker Training Compiler 執行 TensorFlow 訓練任務
<a name="training-compiler-enable-tensorflow"></a>

您可以使用任何 SageMaker AI 介面，透過 SageMaker Training Compiler 執行訓練任務：Amazon SageMaker Studio Classic 適用於 Python (Boto3) 的 AWS SDK、Amazon SageMaker 筆記本執行個體，以及 AWS Command Line Interface。

**Topics**
+ [使用 SageMaker Python SDK](#training-compiler-enable-tensorflow-pysdk)
+ [使用 SageMaker AI Python SDK 和衍伸 SageMaker AI 架構深度學習容器](#training-compiler-enable-tensorflow-sdk-extend-container)
+ [使用 SageMaker AI `CreateTrainingJob` API 作業啟動 SageMaker Training Compiler](#training-compiler-enable-tensorflow-api)

## 使用 SageMaker Python SDK
<a name="training-compiler-enable-tensorflow-pysdk"></a>

若要開啟 SageMaker Training Compiler，請將 `compiler_config` 參數新增至 SageMaker AI TensorFlow 或 Hugging Face 估算器。匯入 `TrainingCompilerConfig` 類別並將其執行個體傳遞至 `compiler_config` 參數。下列程式碼範例顯示已開啟 SageMaker Training Compiler 的 SageMaker AI 估算器類別結構。

**提示**  
若要透過 TensorFlow 和轉換器程式庫提供的預先建置模型開始使用，請嘗試使用[測試過的模型](training-compiler-support.md#training-compiler-tested-models)的參考資料表中提供的批次大小。

**注意**  
適用於 TensorFlow 的 SageMaker Training Compiler 可透過 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()
```

若要準備訓練指令碼，請參閱以下頁面。
+ 使用 TensorFlow Keras (`tf.keras.*`) 建構模型的[適用於單一 GPU 訓練](training-compiler-tensorflow.md#training-compiler-tensorflow-models-keras-single-gpu)。
+ 使用 TensorFlow 模組 (`tf.*` 不包含 TensorFlow Keras 模組) 建構模型的[適用於單一 GPU 訓練](training-compiler-tensorflow.md#training-compiler-tensorflow-models-no-keras-single-gpu)。

------
#### [ 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()
```

若要準備訓練指令碼，請參閱以下頁面。
+ 具備 Hugging Face 轉換器的 TensorFlow Keras 模型的[適用於單一 GPU 訓練](training-compiler-tensorflow.md#training-compiler-tensorflow-models-transformers-keras-single-gpu)
+ 具備 Hugging Face 轉換器的 TensorFlow 模型的[適用於單一 GPU 訓練](training-compiler-tensorflow.md#training-compiler-tensorflow-models-transformers-no-keras-single-gpu)

------

### 適用於分散式訓練
<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()
```

**提示**  
若要準備訓練指令碼，請參閱以下頁面。  
具備 Hugging Face 轉換器的 TensorFlow Keras 模型的[適用於分散式訓練](training-compiler-tensorflow.md#training-compiler-tensorflow-models-transformers-keras-distributed)
具備 Hugging Face 轉換器的 TensorFlow 模型的[適用於分散式訓練](training-compiler-tensorflow.md#training-compiler-tensorflow-models-transformers-no-keras-distributed)

------

下列清單是使用編譯器執行 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 Training Compiler 支援的 Hugging Face 轉換器程式庫版本。若要尋找可用版本，請參閱[支援的架構](training-compiler-support.md#training-compiler-supported-frameworks)。
+ `framework_version` 或 `tensorflow_version` (str) – 必要。指定由 SageMaker Training Compiler 支援的 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`。啟用 SageMaker Training Compiler 時，請嘗試較大的批次大小並相應地調整學習速率。若要尋找使用編譯器和調整批次大小以提高訓練速度的案例研究，請參閱[測試過的模型](training-compiler-support.md#training-compiler-tested-models)和[SageMaker Training Compiler 範例筆記本與部落格](training-compiler-examples-and-blogs.md)。
+ `compiler_config` (TrainingCompilerConfig 物件) – 必要。包含此參數，以開啟 SageMaker Training Compiler。下列是 `TrainingCompilerConfig` 類型的參數。
  + `enabled` (bool) – 選用。指定 `True` 或 `False` 以開啟或關閉 SageMaker Training Compiler。預設值為 `True`。
  + `debug` (bool) – 選用。若要從編譯器加速型訓練任務接收更詳細的訓練日誌，請將其變更為 `True`。不過，額外的記錄可能會增加額外負荷，並降低已編譯的訓練任務。預設值為 `False`。

**警告**  
如果您開啟 SageMaker Debugger，可能會影響 SageMaker Training Compiler 的效能。我們建議您在執行 SageMaker Training Compiler 時關閉偵錯工具，以確保不會影響效能。如需詳細資訊，請參閱[考量事項](training-compiler-tips-pitfalls.md#training-compiler-tips-pitfalls-considerations)。若要關閉偵錯工具功能，請將下列兩個引數新增至估算器：  

```
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 AI 架構深度學習容器
<a name="training-compiler-enable-tensorflow-sdk-extend-container"></a>

AWS 適用於 TensorFlow 的深度學習容器 (DLC) 使用 TensorFlow 的調整版本，其中包含開放原始碼 TensorFlow 架構上的變更。[SageMaker AI 架構深度學習容器](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#sagemaker-framework-containers-sm-support-only)已針對 AWS 基礎架構和 Amazon SageMaker AI 進行最佳化。藉由使用 DLC 的優勢，SageMaker Training Compiler 整合新增對原生 TensorFlow 的更多效能改善。此外，您可以透過延伸 DLC 映像來建立自訂訓練容器。

**注意**  
此 Docker 自訂功能目前僅適用於 TensorFlow。

若要為您的使用案例擴充和自訂 SageMaker AI TensorFlow DLC，請使用以下指示。

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

使用下列 Dockerfile 範本延伸 SageMaker AI TensorFlow DLC。您必須使用 SageMaker AI TensorFlow DLC 映像作為 Docker 容器的基礎映像。若要尋找 SageMaker AI TensorFlow DLC 映像 URI，請參閱[支援的架構](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 架構 DLC 時，請考量下列缺陷：
+ 不會明確解除安裝或變更 SageMaker AI 容器中的 TensorFlow 套件版本。這樣做會導致 AWS 最佳化的 TensorFlow 套件被開放原始碼 TensorFlow 套件覆寫，這可能會導致效能降低。
+ 注意具有特定 TensorFlow 版本或類別做為相依項的套件。這些套件可能會隱含地解除安裝 AWS 最佳化 TensorFlow，並安裝開放原始碼 TensorFlow 套件。

例如，有一個已知問題，即 [tensorflow/models](https://github.com/tensorflow/models) 和 [tensorflow/text](https://github.com/tensorflow/text) 程式庫一律嘗試[重新安裝開放原始碼 TensorFlow](https://github.com/tensorflow/models/issues/9267) 的已知問題。如果您需要安裝這些程式庫，以為您的使用案例選擇特定版本，我們建議您查看適用於第 2.9 版或更新版本的 SageMaker AI TensorFlow DLC Dockerfile。Dockerfile 路徑通常採用下列格式：`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 SDK 估算器執行
<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 AI `CreateTrainingJob` API 作業啟動 SageMaker Training Compiler
<a name="training-compiler-enable-tensorflow-api"></a>

SageMaker Training Compiler 組態選項必須透過 [`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 的深度學習容器映像 URI 的完整清單，請參閱[支援的架構](training-compiler-support.md#training-compiler-supported-frameworks)。