

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

# 独自のトレーニングコンテナの適応
<a name="adapt-training-container"></a>

独自のトレーニングモデルを実行するには、Amazon SageMaker ノートブックインスタンスで [Amazon SageMaker トレーニングツールキット](https://github.com/aws/sagemaker-training-toolkit)を使用して Docker コンテナを構築します。

## ステップ 1: SageMaker ノートブックインスタンスを作成する
<a name="byoc-training-step1"></a>

1. Amazon SageMaker AI コンソール ([https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/)) を開きます。

1. 左側のナビゲーションペインで、**[Notebook]** (ノートブック)、**[Notebook instances]** (ノートブックインスタンス)、**[Create notebook instance]** (ノートブックインスタンスの作成) の順に選択します。

1. **[ノートブックインスタンスの作成]** ページで、次の情報を入力します。

   1. [**ノートブックインスタンス名**] に「**RunScriptNotebookInstance**」と入力します。

   1. [**ノートブックインスタンスタイプ**] で、[**ml.t2.medium**] を選択します。

   1. **[Permissions and encryption]** (アクセス許可と暗号化) セクションで、以下の操作を行います。

      1. **[IAM role]** (IAM ロール) は、**[Create a new role]** (新しいロールの作成) を選択します。新しいウィンドウが開きます。

      1. **[Create an IAM role]** (IAM ロールの作成) ページで、**[Specific S3 buckets]** (特定の S3 バケット) を選択し、**sagemaker-run-script** という名前の Amazon S3 バケットを指定して、**[Create role]** (ロールの作成) を選択します。

         SageMaker AI は、`AmazonSageMaker-ExecutionRole-{{YYYYMMDD}}T{{HHmmSS}}` という名前の IAM ロールを作成します。例えば、`AmazonSageMaker-ExecutionRole-20190429T110788`。実行ロールの命名規則では、ロールが作成された日時を `T` で区切って使用することに注意してください。

   1. **[Root Access]** (ルートアクセス) で、**[Enable]** (有効) を選択します。

   1. **[Create notebook instance]** (ノートブックインスタンスの作成) を選択します。

1. **[Notebook instances]** (ノートブックインスタンス) ページでは **[Status]** (ステータス) は **[Pending]** (保留中) となっています。Amazon SageMaker AI が機械学習コンピューティングインスタンス (この場合ノートブックインスタンス) を起動し、ML ストレージボリュームをアタッチするまでに、数分を要する場合があります。ノートブックインスタンスには、事前設定された Jupyter ノートブックサーバーと一連の Anaconda ライブラリがあります。詳細については、「[  CreateNotebookInstance](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateNotebookInstance.html)」を参照してください。

   

1. 作成したノートブックの **[名前]** をクリックします。新しいページが開きます。

1.  **[Permissions and encryption]** (アクセス許可と暗号化) セクションで、**[the IAM role ARN number]** (IAM ロールの ARN 番号) をコピーし、メモ帳ファイルに貼り付けて、一時的に保存します。この IAM ロールの ARN 番号は、後でノートブックインスタンスでローカルトレーニング推定器を構成するために使用します。[**the IAM role ARN number (IAM ロールの ARN 番号)**] は、次のようになります。`'arn:aws:iam::111122223333:role/service-role/AmazonSageMaker-ExecutionRole-20190429T110788'`

1. ノートブックインスタンスのステータスが **[InService]** (InService) に変わったら、**[Open JupyterLab]** (JupyterLab を開く) を選択します。

## ステップ 2: Dockerfile および Python トレーニングスクリプトを作成してアップロードする
<a name="byoc-training-step2"></a>

1. JupyterLab が開いたら、JupyterLab のホームディレクトリに新しいフォルダを作成します。左上隅で、**[New Folder]** (新しいフォルダ) アイコンをクリックし、フォルダ名 `docker_test_folder` を入力します。

1. `docker_test_folder` ディレクトリに `Dockerfile` という名前のテキストファイルを作成します。

   1. 左上隅の **[New Launcher]** (新しいランチャー) アイコン (\+) を選択します。

   1. 右ペインの**[Other]** (その他) セクションで、**[Text File]** (テキストファイル) を選択します。

   1. 次の `Dockerfile` サンプルコードをテキストファイルに貼り付けます。

      ```
      #Download an open source TensorFlow Docker image
      FROM tensorflow/tensorflow:latest-gpu-jupyter
      
      # Install sagemaker-training toolkit that contains the common functionality necessary to create a container compatible with SageMaker AI and the Python SDK.
      RUN pip3 install sagemaker-training
      
      # Copies the training code inside the container
      COPY train.py /opt/ml/code/train.py
      
      # Defines train.py as script entrypoint
      ENV SAGEMAKER_PROGRAM train.py
      ```

      Dockerfile のスクリプトは以下のタスクを実行します。
      + `FROM tensorflow/tensorflow:latest-gpu-jupyter` - 最新の TensorFlow Docker ベースイメージをダウンロードします。これは、コンテナの構築に持ち込む任意の Docker ベースイメージと、 AWS 構築済みのコンテナベースイメージに置き換えることができます。
      + `RUN pip install sagemaker-training` - SageMaker AI に対応するコンテナを作成するために必要な一般的な機能を備えている [SageMaker AI トレーニングツールキット](https://github.com/aws/sagemaker-training-toolkit)をインストールします。
      + `COPY train.py /opt/ml/code/train.py` - SageMaker AI で所定のコンテナ内の場所にスクリプトをコピーします。スクリプトは、このフォルダにある必要があります。
      + `ENV SAGEMAKER_PROGRAM train.py` - トレーニングスクリプト `train.py` をコンテナの `/opt/ml/code` フォルダにコピーされたエンドポイントスクリプトとして処理します。これは、独自のコンテナを構築する場合に指定する必要がある唯一の環境変数です。

   1.  左側のディレクトリナビゲーションペインでは、テキストファイル名は自動的に `untitled.txt` に設定されます。ファイルの名前を変更するには、ファイルを右クリックし、**[Rename]** (名前の変更) で、ファイル名を `.txt` 拡張子のない `Dockerfile` に変更し、`Ctrl+s` または `Command+s` を押してファイルを保存します。

1. トレーニングスクリプト `train.py` を `docker_test_folder` にアップロードします。次のスクリプトの例を使用して、この演習用に [MNIST データセット](https://en.wikipedia.org/wiki/MNIST_database)でトレーニングされた手書きの数字を読み取るモデルを作成できます。

   ```
   import tensorflow as tf
   import os
   
   mnist = tf.keras.datasets.mnist
   
   (x_train, y_train), (x_test, y_test) = mnist.load_data()
   x_train, x_test = x_train / 255.0, x_test / 255.0
   
   model = tf.keras.models.Sequential([
   tf.keras.layers.Flatten(input_shape=(28, 28)),
   tf.keras.layers.Dense(128, activation='relu'),
   tf.keras.layers.Dropout(0.2),
   tf.keras.layers.Dense(10, activation='softmax')
   ])
   
   model.compile(optimizer='adam',
   loss='sparse_categorical_crossentropy',
   metrics=['accuracy'])
   
   model.fit(x_train, y_train, epochs=1)
   model_save_dir = f"{os.environ.get('SM_MODEL_DIR')}/1"
   
   model.evaluate(x_test, y_test)
   tf.saved_model.save(model, model_save_dir)
   ```

## ステップ 3: コンテナを構築する
<a name="byoc-training-step3"></a>

1. JupyterLab ホームディレクトリで、Jupyter ノートブックを開きます。新しいノートブックを開くには、**[新しい起動]** アイコンを選択し、次に **[ノートブック]** セクションで **conda\_tensorflow2** の最新バージョンを選択します。

1. 最初のノートブックセルで次のコマンドを実行して、`docker_test_folder` ディレクトリに変更します。

   ```
   cd ~/SageMaker/docker_test_folder
   ```

   これにより、次のように現在のディレクトリが返されます。

   ```
   ! pwd
   ```

   `output: /home/ec2-user/SageMaker/docker_test_folder`

1. Docker コンテナを構築するには、次の Docker ビルドコマンド (最後のスペースとピリオドも含めます) を実行します。

   ```
   ! docker build -t tf-custom-container-test .
   ```

   Docker のビルドコマンドは、作成した Docker ディレクトリ (この場合は `docker_test_folder`) から実行する必要があります。
**注記**  
Docker が Dockerfile を見つけられないという次のエラーメッセージが表示された場合は、Dockerfile の名前が正しいこと、およびそのディレクトリに保存されていることを確認してください。  

   ```
   unable to prepare context: unable to evaluate symlinks in Dockerfile path: 
   lstat /home/ec2-user/SageMaker/docker/Dockerfile: no such file or directory
   ```
`docker` は、現在のディレクトリ内で拡張子を付けずに、`Dockerfile` と名付けられたファイルを検索します。別の名前を指定した場合は、`-f` フラグを付けて手動でファイル名を渡すことができます。例えば、Dockerfile に `Dockerfile-text.txt` という名前を付けた場合、次のコマンドを実行します  

   ```
   ! docker build -t tf-custom-container-test -f Dockerfile-text.txt .
   ```

## ステップ 4: コンテナをテストする
<a name="byoc-training-step4"></a>

1. ノートブックインスタンスでローカルにコンテナをテストするには、Jupyter ノートブックを開きます。**[新しいランチャー]** を選択し、**[ノートブック]** セクションで **conda\_tensorflow2** の最新バージョンを選択します。

1. 次のサンプルスクリプトをノートブックのコードセルに貼り付けて、SageMaker AI 推定器を設定します。

   ```
   import sagemaker
   from sagemaker.estimator import Estimator
   
   estimator = Estimator(image_uri='{{tf-custom-container-test}}',
                         role={{sagemaker.get_execution_role()}},
                         instance_count={{1}},
                         instance_type={{'local'}})
   
   estimator.fit()
   ```

   前述のコード例では、`sagemaker.get_execution_role()` を `role` 引数に指定して、SageMaker AI セッションに設定されたロールを自動的に取得します。ノートブックインスタンスを設定したときに使用した **[IAM ロール ARN 番号]** の文字列値に置き換えることもできます。ARN は次のようになります。`'arn:aws:iam::111122223333:role/service-role/AmazonSageMaker-ExecutionRole-20190429T110788'`

1. コードセルを実行します。このテストでは、トレーニングの環境設定、環境変数に使用された値、データのソース、およびトレーニング中に得られた損失と正確性が出力されます。

## ステップ 5: Amazon Elastic Container Registry (Amazon ECR) にコンテナをプッシュする
<a name="byoc-training-step5"></a>

1. このローカルモードテストが正常に実行されたら、Docker コンテナを [Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) にプッシュし、それを使用してトレーニングジョブを実行できます。Amazon ECR の代わりにプライベート Docker レジストリを使用する場合は、「[Push your training container to a private registry](https://docs.aws.amazon.com/sagemaker/latest/dg/docker-containers-adapt-your-own-private-registry.html)」を参照してください。

   ノートブックセルで次のコマンドラインを実行します。

   ```
   %%sh
   
   # Specify an algorithm name
   algorithm_name=tf-custom-container-test
   
   account=$(aws sts get-caller-identity --query Account --output text)
   
   # Get the region defined in the current configuration (default to us-west-2 if none defined)
   region=$(aws configure get region)
   region=${region:-us-west-2}
   
   fullname="${account}.dkr.ecr.${region}.amazonaws.com/${algorithm_name}:latest"
   
   # If the repository doesn't exist in ECR, create it.
   
   aws ecr describe-repositories --repository-names "${algorithm_name}" > /dev/null 2>&1
   if [ $? -ne 0 ]
   then
   aws ecr create-repository --repository-name "${algorithm_name}" > /dev/null
   fi
   
   # Get the login command from ECR and execute it directly
   
   aws ecr get-login-password --region ${region}|docker login --username AWS --password-stdin ${fullname}
   
   # Build the docker image locally with the image name and then push it to ECR
   # with the full name.
   
   docker build -t ${algorithm_name} .
   docker tag ${algorithm_name} ${fullname}
   
   docker push ${fullname}
   ```
**注記**  
この bash シェルスクリプトは、次のエラーメッセージに似た許可の問題が発生する可能性があります。  

   ```
   "denied: User: [ARN] is not authorized to perform: ecr:InitiateLayerUpload on resource:
   arn:aws:ecr:us-east-1:[id]:repository/tf-custom-container-test"
   ```
このエラーが発生した場合は、**AmazonEC2ContainerRegistryFullAccess** ポリシーを IAM ロールにアタッチする必要があります。[IAM コンソール](https://console.aws.amazon.com/iam/home)に移動し、左側のナビゲーションペインで、**[ロール]** を選択し、ノートブックインスタンスに使用した IAM ロールを検索します。**[Permission]** (許可) タブで、**[Attach policies]** (ポリシーをアタッチ) ボタンをクリックし、**AmazonEC2ContainerRegistryFullAccess** ポリシーを検索します。ポリシーのチェックボックスをオンにして、**[アクセス許可の追加]** を選択して終了します。

1. Studio ノートブックセルで次のコードを実行して、トレーニングコンテナの Amazon ECR イメージを呼び出します。

   ```
   import boto3
   
   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'
   if region in ['cn-north-1', 'cn-northwest-1']:
       uri_suffix = 'amazonaws.com.cn'
   
   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/sagemaker-byoc-test:latest
   ```

1. 前のステップで取得した `ecr_image` を使用して SageMaker AI 推定器オブジェクトを構成します。次のコードサンプルでは、SageMaker AI 推定器を `byoc_image_uri` で構成し、Amazon EC2 インスタンスでトレーニングジョブを開始します。

------
#### [ SageMaker Python SDK v1 ]

   ```
   import sagemaker
   from sagemaker import get_execution_role
   from sagemaker.estimator import Estimator
   
   estimator = Estimator(image_uri=byoc_image_uri,
                         role=get_execution_role(),
                         base_job_name='tf-custom-container-test-job',
                         instance_count=1,
                         instance_type='ml.g4dn.xlarge')
   
   #train your model
   estimator.fit()
   ```

------
#### [ SageMaker Python SDK v2 ]

   ```
   import sagemaker
   from sagemaker import get_execution_role
   from sagemaker.estimator import Estimator
   
   estimator = Estimator(image_uri=byoc_image_uri,
                         role=get_execution_role(),
                         base_job_name='tf-custom-container-test-job',
                         instance_count=1,
                         instance_type='ml.g4dn.xlarge')
   
   #train your model
   estimator.fit()
   ```

------

1. 独自のコンテナを使用してモデルをデプロイする場合は、「[Adapting Your Own Inference Container](https://docs.aws.amazon.com/sagemaker/latest/dg/adapt-inference-container.html)」を参照してください。TensorFlow モデルをデプロイできる AWSフレームワークコンテナを使用することもできます。モデル例をデプロイして手書きの数字を読み取るには、前のサブステップでモデルのトレーニングに使ったのと同じノートブックに、次のスクリプトの例を入力して、デプロイに必要なイメージ URI (ユニバーサルリソース識別子) を取得し、モデルをデプロイします。

   ```
   import boto3
   import sagemaker
   
   #obtain image uris
   from sagemaker import image_uris
   container = image_uris.retrieve(framework='tensorflow',region='us-west-2',version='2.11.0',
                       image_scope='inference',instance_type='ml.g4dn.xlarge')
   
   #create the model entity, endpoint configuration and endpoint
   predictor = estimator.deploy(1,instance_type='ml.g4dn.xlarge',image_uri=container)
   ```

   次のコード例を使用して、MNIST データセットの手書き数字の例を使用してモデルをテストします。

   ```
   #Retrieve an example test dataset to test
   import numpy as np
   import matplotlib.pyplot as plt
   from keras.datasets import mnist
   
   # Load the MNIST dataset and split it into training and testing sets
   (x_train, y_train), (x_test, y_test) = mnist.load_data()
   # Select a random example from the training set
   example_index = np.random.randint(0, x_train.shape[0])
   example_image = x_train[example_index]
   example_label = y_train[example_index]
   
   # Print the label and show the image
   print(f"Label: {example_label}")
   plt.imshow(example_image, cmap='gray')
   plt.show()
   ```

   テスト用の手書き数字を TensorFlow が取り込んでテスト予測を行える形式に変換します。

   ```
   from sagemaker.serializers import JSONSerializer
   data = {"instances": example_image.tolist()}
   predictor.serializer=JSONSerializer() #update the predictor to use the JSONSerializer
   predictor.predict(data) #make the prediction
   ```

カスタムコンテナをローカルでテストし、Amazon ECR イメージにプッシュする方法を示す完全な例については、「[独自の TensorFlow コンテナを構築する](https://sagemaker-examples.readthedocs.io/en/latest/advanced_functionality/tensorflow_bring_your_own/tensorflow_bring_your_own.html)」のサンプルノートブックを参照してください。

**ヒント**  
システム使用率の問題 (CPU ボトルネックや GPU の低使用率など) を監視し、トレーニングの問題 (オーバーフィット、オーバートレーニング、テンソルの爆発、勾配消失など) を特定するためのトレーニングジョブをプロファイリングおよびデバッグするには、Amazon SageMaker Debugger を使用します。詳細については、「[カスタムトレーニングで Debugger を使用する](debugger-bring-your-own-container.md)」を参照してください。

## ステップ 6: リソースをクリーンアップする
<a name="byoc-training-step6"></a>

**入門サンプルを終了したときにリソースをクリーンアップするには**

1. [SageMaker AI コンソール](https://console.aws.amazon.com/sagemaker/)を開き、ノートブックインスタンス ** [RunScriptNotebookInstance]**、**[アクション]**、**[停止]** の順に選択します。インスタンスが停止するまで、数分かかる場合があります。

1. インスタンスの **[Status]** (ステータス) が**[Stopped]** (停止) に変化したら、**[Actions]** (アクション)、**[Delete]** (削除) の順に選択し、ダイアログボックスで **[Delete]** (削除) を選択します。インスタンスが削除されるまで、数分かかる場合があります。ノートブックインスタンスが削除されると、テーブルには表示されなくなります。

1. [Amazon S3 コンソール](https://console.aws.amazon.com/s3/)を開き、モデルのアーティファクトとトレーニングデータセットを保存するために作成したバケットを削除します。

1. [IAM コンソール](https://console.aws.amazon.com/iam/)を開き、IAM ロールを削除します。アクセス許可ポリシーを作成した場合は、それも削除することができます。
**注記**  
 Docker コンテナは、実行後に自動的にシャットダウンします。削除する必要はありません。

## ブログと導入事例
<a name="byoc-blogs-and-examples"></a>

以下のブログでは、Amazon SageMaker AI でカスタムトレーニングコンテナを使用するケーススタディについて説明しています。
+ 「[Why bring your own container to Amazon SageMaker AI and how to do it right](https://medium.com/@pandey.vikesh/why-bring-your-own-container-to-amazon-sagemaker-and-how-to-do-it-right-bc158fe41ed1)」、*Medium* (2023 年 1 月 20 日)