

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# SageMaker トレーニングコンパイラを使用して TensorFlow トレーニングジョブを実行する
<a name="training-compiler-enable-tensorflow"></a>

任意の SageMaker AI インターフェイスを使用して、SageMaker Training Compiler: Amazon SageMaker Studio Classic、Amazon SageMaker ノートブックインスタンス AWS SDK for Python (Boto3)、および でトレーニングジョブを実行できます 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 をオンにするには、SageMaker AI TensorFlow または Hugging Face の推定器に `compiler_config` パラメータを追加します。`TrainingCompilerConfig` クラスをインポートし、そのインスタンスを `compiler_config` パラメータに渡します。次のコード例は、SageMaker Training Compiler をオンにした場合の SageMaker AI 推定器クラスの構造を示しています。

**ヒント**  
TensorFlow と Transformers ライブラリが提供するビルド済みモデルの使用を開始するには、[テスト済みモデル](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 モジュール (TensorFlow Keras モジュールを除く `tf.*`) を使用して構築されたモデルの [単一 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 Transformer を使用した TensorFlow Keras モデルの[単一 GPU のトレーニングの場合](training-compiler-tensorflow.md#training-compiler-tensorflow-models-transformers-keras-single-gpu)
+ Hugging Face Transformer を使用した 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 Transformer を使用した TensorFlow Keras モデルの[分散トレーニングの場合](training-compiler-tensorflow.md#training-compiler-tensorflow-models-transformers-keras-distributed)
Hugging Face Transformer を使用した 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 Transformers のライブラリバージョンを指定します。使用可能なバージョンを見つけるには、「[サポートされるフレームワーク](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 デバッガーをオンにすると、SageMaker Training Compiler のパフォーマンスに影響を与える可能性があります。SageMaker Training Compiler の実行時にデバッガーをオフにして、パフォーマンスに影響が出ないようにすることをお勧めします。詳細については、「[考慮事項](training-compiler-tips-pitfalls.md#training-compiler-tips-pitfalls-considerations)」を参照してください。デバッガー機能をオフにするには、次の 2 つの引数を推定器に追加します。  

```
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 を調べるには、「[Supported Frameworks](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
...
```

詳細については、「[Step 2: Create and upload the Dockerfile and Python training scripts](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)しようとするという既知の問題があります。これらのライブラリをインストールしてユースケースに合う特定のバージョンを選択する必要がある場合は、v2.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 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)」を参照してください。