GKE Autopilot モードで GPU を使用してモデルをトレーニングする
このクイックスタートでは、Google Kubernetes Engine(GKE)で GPU を使用するトレーニング モデルをデプロイし、予測を Cloud Storage に保存する方法について説明します。このドキュメントは、Autopilot モードのクラスタがすでに存在し、GPU ワークロードを初めて実行する GKE 管理者を対象としています。
クラスタに個別の GPU ノードプールを作成すると、これらのワークロードを Standard クラスタで実行することもできます。手順については、GKE Standard モードで GPU を使用してモデルをトレーニングするをご覧ください。
始める前に
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
- 
    
    
      
        In the Google Cloud console, on the project selector page, select or create a Google Cloud project. Roles required to select or create a project - Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- 
      Create a project: To create a project, you need the Project Creator
      (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
 
- 
  
    Verify that billing is enabled for your Google Cloud project. 
- 
  
  
    
      Enable the GKE and Cloud Storage APIs. Roles required to enable APIs To enable APIs, you need the Service Usage Admin IAM role ( roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles.
- 
      Install the Google Cloud CLI. 
- 
          外部 ID プロバイダ(IdP)を使用している場合は、まず連携 ID を使用して gcloud CLI にログインする必要があります。 
- 
        gcloud CLI を初期化するには、次のコマンドを実行します。 gcloud init
- 
    
    
      
        In the Google Cloud console, on the project selector page, select or create a Google Cloud project. Roles required to select or create a project - Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- 
      Create a project: To create a project, you need the Project Creator
      (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
 
- 
  
    Verify that billing is enabled for your Google Cloud project. 
- 
  
  
    
      Enable the GKE and Cloud Storage APIs. Roles required to enable APIs To enable APIs, you need the Service Usage Admin IAM role ( roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles.
- 
      Install the Google Cloud CLI. 
- 
          外部 ID プロバイダ(IdP)を使用している場合は、まず連携 ID を使用して gcloud CLI にログインする必要があります。 
- 
        gcloud CLI を初期化するには、次のコマンドを実行します。 gcloud init
- 
    
    In the Google Cloud console, activate Cloud Shell. At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize. 
- Google Cloud コンソールで、[Autopilot クラスタの作成] ページに移動します。 
- [名前] フィールドに「 - gke-gpu-cluster」と入力します。
- [リージョン] リストで [ - us-central1] を選択します。
- [作成] をクリックします。 
- Google Cloud コンソールで、[バケットの作成] ページに移動します。 
- [バケットに名前を付ける] フィールドに、次の名前を入力します。 - PROJECT_ID-gke-gpu-bucket- PROJECT_IDは、実際の Google Cloudプロジェクト ID に置き換えます。
- [続行] をクリックします。 
- [ロケーション タイプ] で、[リージョン] を選択します。 
- [リージョン] リストで - us-central1 (Iowa)を選択し、[続行] をクリックします。
- [データのストレージ クラスを選択する] セクションで、[続行] をクリックします。 
- [オブジェクトへのアクセスを制御する方法を選択する] セクションで、[アクセス制御] には [均一] を選択します。 
- [作成] をクリックします。 
- [公開アクセスの防止] ダイアログで、[このバケットに対する公開アクセス禁止を適用する] チェックボックスをオンにして、[確認] をクリックします。 
- クラスタに Kubernetes ServiceAccount を作成する。
- ServiceAccount がバケットにアクセスできるように IAM 許可ポリシーを作成する。
- クラスタに接続します。 - gcloud container clusters get-credentials gke-gpu-cluster \ --location=us-central1
- Kubernetes Namespace を作成します。 - kubectl create namespace gke-gpu-namespace
- Namespace に Kubernetes ServiceAccount を作成します。 - kubectl create serviceaccount gpu-k8s-sa --namespace=gke-gpu-namespace
- Cloud Shell で、次の環境変数を作成します。 - export K8S_SA_NAME=gpu-k8s-sa export BUCKET_NAME=PROJECT_ID-gke-gpu-bucket- PROJECT_IDは、実際の Google Cloudプロジェクト ID に置き換えます。
- TensorFlow コンテナを含む Pod を作成します。 - envsubst < src/gke-config/standard-tensorflow-bash.yaml | kubectl --namespace=gke-gpu-namespace apply -f -- このコマンドで、作成した環境変数がマニフェスト内の対応する参照に挿入されます。マニフェストをテキスト エディタで開いて、 - $K8S_SA_NAMEと- $BUCKET_NAMEを対応する値に置き換えることもできます。
- バケットにサンプル ファイルを作成します。 - touch sample-file gcloud storage cp sample-file gs://PROJECT_ID-gke-gpu-bucket
- Pod の準備ができるまで待ちます。 - kubectl wait --for=condition=Ready pod/test-tensorflow-pod -n=gke-gpu-namespace --timeout=180s- Pod の準備ができると、出力は次のようになります。 - pod/test-tensorflow-pod condition met- コマンドがタイムアウトした場合、GKE は Pod を実行する新しいノードをまだ作成している可能性があります。コマンドをもう一度実行し、Pod の準備が整うまで待ちます。 
- TensorFlow コンテナでシェルを開きます。 - kubectl -n gke-gpu-namespace exec --stdin --tty test-tensorflow-pod --container tensorflow -- /bin/bash
- 作成したサンプル ファイルを閲覧してみます。 - ls /data- 出力にサンプル ファイルが表示されます。 
- ログを確認して Pod に接続されている GPU を特定します。 - python -c "import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))"- 出力には、Pod に接続された GPU が次のように表示されます。 - ... PhysicalDevice(name='/physical_device:GPU:0',device_type='GPU')
- コンテナを終了します。 - exit
- サンプル Pod を削除します。 - kubectl delete -f src/gke-config/standard-tensorflow-bash.yaml \ --namespace=gke-gpu-namespace
- サンプルデータを Cloud Storage バケットにコピーします。 - gcloud storage cp src/tensorflow-mnist-example gs://PROJECT_ID-gke-gpu-bucket/ --recursive
- 次の環境変数を作成します。 - export K8S_SA_NAME=gpu-k8s-sa export BUCKET_NAME=PROJECT_ID-gke-gpu-bucket
- トレーニング Job を確認します。 
- トレーニング Job をデプロイします。 - envsubst < src/gke-config/standard-tf-mnist-train.yaml | kubectl -n gke-gpu-namespace apply -f -- このコマンドで、作成した環境変数がマニフェスト内の対応する参照に置き換えます。マニフェストをテキスト エディタで開いて、 - $K8S_SA_NAMEと- $BUCKET_NAMEを対応する値に置き換えることもできます。
- Job のステータスが - Completedになるまで待ちます。- kubectl wait -n gke-gpu-namespace --for=condition=Complete job/mnist-training-job --timeout=180s- Job の準備ができている場合、出力は次のようになります。 - job.batch/mnist-training-job condition met- コマンドがタイムアウトした場合、GKE は Pod を実行する新しいノードをまだ作成している可能性があります。コマンドをもう一度実行し、Job の準備が整うまで待ちます。 
- TensorFlow コンテナのログを確認します。 - kubectl logs -f jobs/mnist-training-job -c tensorflow -n gke-gpu-namespace- 出力には、以下のイベントの発生が示されます。 - 必要な Python パッケージのインストール
- MNIST データセットのダウンロード
- GPU を使用したモデルのトレーニング
- モデルを保存する
- モデルを評価する
 - ... Epoch 12/12 927/938 [============================>.] - ETA: 0s - loss: 0.0188 - accuracy: 0.9954 Learning rate for epoch 12 is 9.999999747378752e-06 938/938 [==============================] - 5s 6ms/step - loss: 0.0187 - accuracy: 0.9954 - lr: 1.0000e-05 157/157 [==============================] - 1s 4ms/step - loss: 0.0424 - accuracy: 0.9861 Eval loss: 0.04236088693141937, Eval accuracy: 0.9861000180244446 Training finished. Model saved
- トレーニング ワークロードを削除します。 - kubectl -n gke-gpu-namespace delete -f src/gke-config/standard-tf-mnist-train.yaml
- 予測に使用する画像をバケットにコピーします。 - gcloud storage cp data/mnist_predict gs://PROJECT_ID-gke-gpu-bucket/ --recursive
- 推論ワークロードを確認します。 
- 推論ワークロードをデプロイします。 - envsubst < src/gke-config/standard-tf-mnist-batch-predict.yaml | kubectl -n gke-gpu-namespace apply -f -- このコマンドで、作成した環境変数がマニフェスト内の対応する参照に置き換えます。マニフェストをテキスト エディタで開いて、 - $K8S_SA_NAMEと- $BUCKET_NAMEを対応する値に置き換えることもできます。
- Job のステータスが - Completedになるまで待ちます。- kubectl wait -n gke-gpu-namespace --for=condition=Complete job/mnist-batch-prediction-job --timeout=180s- 出力は次のようになります。 - job.batch/mnist-batch-prediction-job condition met
- TensorFlow コンテナのログを確認します。 - kubectl logs -f jobs/mnist-batch-prediction-job -c tensorflow -n gke-gpu-namespace- 出力は、次のような各画像の予測とモデルの信頼度です。 - Found 10 files belonging to 1 classes. 1/1 [==============================] - 2s 2s/step The image /data/mnist_predict/0.png is the number 0 with a 100.00 percent confidence. The image /data/mnist_predict/1.png is the number 1 with a 99.99 percent confidence. The image /data/mnist_predict/2.png is the number 2 with a 100.00 percent confidence. The image /data/mnist_predict/3.png is the number 3 with a 99.95 percent confidence. The image /data/mnist_predict/4.png is the number 4 with a 100.00 percent confidence. The image /data/mnist_predict/5.png is the number 5 with a 100.00 percent confidence. The image /data/mnist_predict/6.png is the number 6 with a 99.97 percent confidence. The image /data/mnist_predict/7.png is the number 7 with a 100.00 percent confidence. The image /data/mnist_predict/8.png is the number 8 with a 100.00 percent confidence. The image /data/mnist_predict/9.png is the number 9 with a 99.65 percent confidence.
- GKE クラスタを保持する場合: クラスタにある Kubernetes リソースと Google Cloud リソースを削除する
- Google Cloud プロジェクトを保持する場合: GKE クラスタと Google Cloud リソースを削除する
- プロジェクトを削除する
- Kubernetes Namespace とデプロイしたワークロードを削除します。 - kubectl -n gke-gpu-namespace delete -f src/gke-config/standard-tf-mnist-batch-predict.yaml kubectl delete namespace gke-gpu-namespace
- Cloud Storage バケットを削除します。 - [バケット] ページに移動します。 
- PROJECT_ID-gke-gpu-bucketのチェックボックスをオンにします。
- [削除] をクリックします。 
- 削除を確定するには、「 - DELETE」と入力して [削除] をクリックします。
 
- Google Cloud サービス アカウントを削除します。 - [サービス アカウント] ページに移動します。 
- プロジェクトを選択します。 
- gke-gpu-sa@PROJECT_ID.iam.gserviceaccount.comのチェックボックスをオンにします。
- [削除] をクリックします。 
- 削除を確定するには、[削除] をクリックします。 
 
- GKE クラスタを削除します。 - [クラスタ] ページに移動します。 
- gke-gpu-clusterのチェックボックスをオンにします。
- [削除] をクリックします。 
- 削除を確定するには、「 - gke-gpu-cluster」と入力して [削除] をクリックします。
 
- Cloud Storage バケットを削除します。 - [バケット] ページに移動します。 
- PROJECT_ID-gke-gpu-bucketのチェックボックスをオンにします。
- [削除] をクリックします。 
- 削除を確定するには、「 - DELETE」と入力して [削除] をクリックします。
 
- Google Cloud サービス アカウントを削除します。 - [サービス アカウント] ページに移動します。 
- プロジェクトを選択します。 
- gke-gpu-sa@PROJECT_ID.iam.gserviceaccount.comのチェックボックスをオンにします。
- [削除] をクリックします。 
- 削除を確定するには、[削除] をクリックします。 
 
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
サンプル リポジトリのクローンを作成する
Cloud Shell で、次のコマンドを実行します。
git clone https://github.com/GoogleCloudPlatform/ai-on-gke && \
cd ai-on-gke/tutorials-and-examples/gpu-examples/training-single-gpu
クラスタを作成する
Cloud Storage バケットを作成する
Workload Identity Federation for GKE を使用してバケットにアクセスするようにクラスタを構成する
クラスタから Cloud Storage バケットにアクセスできるようにする手順は次のとおりです。
クラスタに Kubernetes ServiceAccount を作成する
Cloud Shell で、次の操作を行います。
バケットに IAM 許可ポリシーを作成する
バケットに対する Storage オブジェクト管理者(roles/storage.objectAdmin)ロールを Kubernetes ServiceAccount に付与します。
gcloud storage buckets add-iam-policy-binding gs://PROJECT_ID-gke-gpu-bucket \
    --member=principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/PROJECT_ID.svc.id.goog/subject/ns/gke-gpu-namespace/sa/gpu-k8s-sa \
    --role=roles/storage.objectAdmin \
    --condition=None
PROJECT_NUMBER は、使用する Google Cloudプロジェクト番号に置き換えます。
Pod が Cloud Storage バケットにアクセスできることを確認する
MNIST データセットを使用してトレーニングと予測を行う
このセクションでは、サンプル データセット MNIST でトレーニング ワークロードを実行します。
推論ワークロードをデプロイする
このセクションでは、サンプル データセットを入力として受け取り、予測を返す推論ワークロードをデプロイします。
クリーンアップ
このガイドで作成したリソースについて Google Cloud アカウントに課金されないようにするには、次のいずれかを行います。