GKE Standard モードで GPU を使用してモデルをトレーニングする

このクイックスタート チュートリアルでは、Google Kubernetes Engine(GKE)で GPU を使用するトレーニング モデルをデプロイし、予測を Cloud Storage に保存する方法について説明します。このチュートリアルでは、TensorFlow モデルと GKE Standard クラスタを使用します。こうしたワークロードは、Autopilot クラスタでより少ない設定手順で実行することもできます。 手順については、GKE Autopilot モードで GPU を使用してモデルをトレーニングするをご覧ください。

このドキュメントは、Standard クラスタがすでに存在し、GPU ワークロードを初めて実行する GKE 管理者を対象としています。

始める前に

  1. In the Cloud de Confiance console, on the project selector page, select or create a Cloud de Confiance 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 role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  2. If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.

  3. Verify that billing is enabled for your Cloud de Confiance project.

  4. Enable the Kubernetes Engine 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 the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. Cloud de Confiance コンソールで Cloud Shell をアクティブにします。

    Cloud Shell をアクティブにする

    Cloud de Confiance コンソールの下部にある Cloud Shell セッションが開始し、コマンドライン プロンプトが表示されます。Cloud Shell はシェル環境です。Google Cloud CLI がすでにインストールされており、現在のプロジェクトの値もすでに設定されています。セッションが初期化されるまで数秒かかることがあります。

必要なロール

GPU でモデルをトレーニングするために必要な権限を取得するには、プロジェクトに対する次の IAM ロールを付与するよう管理者に依頼してください。

ロールの付与については、プロジェクト、フォルダ、組織へのアクセス権の管理をご覧ください。

必要な権限は、カスタムロールや他の事前定義ロールから取得することもできます。

サンプル リポジトリのクローンを作成する

Cloud Shell で、次のコマンドを実行します。

git clone https://github.com/GoogleCloudPlatform/ai-on-gke/ ai-on-gke
cd ai-on-gke/tutorials-and-examples/gpu-examples/training-single-gpu

Standard モードのクラスタと GPU ノードプールを作成する

Cloud Shell で以下の操作を行います。

  1. Workload Identity Federation for GKE を使用する Standard クラスタを作成し、Cloud Storage FUSE ドライバをインストールします。

    gcloud container clusters create gke-gpu-cluster \
        --addons GcsFuseCsiDriver \
        --location=us-central1 \
        --num-nodes=1 \
        --workload-pool=PROJECT_ID.s3ns.svc.id.goog
    

    PROJECT_ID は、実際の Cloud de Confianceプロジェクト ID に置き換えます。

    クラスタの作成には数分かかることもあります。

  2. GPU ノードプールを作成します。

    gcloud container node-pools create gke-gpu-pool-1 \
        --accelerator=type=nvidia-tesla-t4,count=1,gpu-driver-version=default \
        --machine-type=n1-standard-16 --num-nodes=1 \
        --location=us-central1 \
        --cluster=gke-gpu-cluster
    

Cloud Storage バケットを作成する

  1. Cloud de Confiance コンソールで、[バケットの作成] ページに移動します。

    [バケットの作成] に移動

  2. [バケットに名前を付ける] フィールドに、次の名前を入力します。

    PROJECT_ID-gke-gpu-bucket
    
  3. [続行] をクリックします。

  4. [ロケーション タイプ] で、[リージョン] を選択します。

  5. [リージョン] リストで us-central1 (Iowa) を選択し、[続行] をクリックします。

  6. [データのストレージ クラスを選択する] セクションで、[続行] をクリックします。

  7. [オブジェクトへのアクセスを制御する方法を選択する] セクションで、[アクセス制御] には [均一] を選択します。

  8. [作成] をクリックします。

  9. [公開アクセスの防止] ダイアログで、[このバケットに対する公開アクセス禁止を適用する] チェックボックスをオンにして、[確認] をクリックします。

GKE 用 Workload Identity 連携を使用してバケットにアクセスするようにクラスタを構成する

クラスタから Cloud Storage バケットにアクセスできるようにする手順は次のとおりです。

  1. Cloud de Confiance サービス アカウントを作成する。
  2. クラスタに Kubernetes ServiceAccount を作成する。
  3. Kubernetes ServiceAccount を Cloud de Confiance サービス アカウントにバインドする。

Cloud de Confiance サービス アカウントを作成する

  1. Cloud de Confiance コンソールで、[サービス アカウントの作成] ページに移動します。

    [サービス アカウントの作成] に移動

  2. [サービス アカウント ID] フィールドに「gke-ai-sa」と入力します。

  3. [作成して続行] をクリックします。

  4. [ロール] リストで、[Cloud Storage] > [Storage Insights コレクタ サービス] ロールを選択します。

  5. [ 別のロールを追加] をクリックします。

  6. [ロールを選択] リストで、[Cloud Storage] > [Storage Object Admin] ロールを選択します。

  7. [続行] をクリックして [完了] をクリックします。

クラスタに Kubernetes ServiceAccount を作成する

Cloud Shell で、次の操作を行います。

  1. Kubernetes Namespace を作成します。

    kubectl create namespace gke-ai-namespace
    
  2. Namespace に Kubernetes ServiceAccount を作成します。

    kubectl create serviceaccount gpu-k8s-sa --namespace=gke-ai-namespace
    

Kubernetes ServiceAccount を Cloud de Confiance サービス アカウントにバインドする

Cloud Shell で、次のコマンドを実行します。

  1. Cloud de Confiance サービス アカウントに IAM バインディングを追加します。

    gcloud iam service-accounts add-iam-policy-binding gke-ai-sa@PROJECT_ID.s3ns.iam.gserviceaccount.com \
        --role roles/iam.workloadIdentityUser \
        --member "serviceAccount:PROJECT_ID.s3ns.svc.id.goog[gke-ai-namespace/gpu-k8s-sa]"
    

    --member フラグは、 Cloud de Confiance上の Kubernetes ServiceAccount の完全な ID を指定します。

  2. Kubernetes ServiceAccount にアノテーションを付けます。

    kubectl annotate serviceaccount gpu-k8s-sa \
        --namespace gke-ai-namespace \
        iam.gke.io/gcp-service-account=gke-ai-sa@PROJECT_ID.s3ns.iam.gserviceaccount.com
    

Pod が Cloud Storage バケットにアクセスできることを確認する

  1. Cloud Shell で、次の環境変数を作成します。

    export K8S_SA_NAME=gpu-k8s-sa
    export BUCKET_NAME=PROJECT_ID-gke-gpu-bucket
    

    PROJECT_ID は、実際の Cloud de Confianceプロジェクト ID に置き換えます。

  2. TensorFlow コンテナを含む Pod を作成します。

    envsubst < src/gke-config/standard-tensorflow-bash.yaml | kubectl --namespace=gke-ai-namespace apply -f -
    

    このコマンドで、作成した環境変数がマニフェスト内の対応する参照に代入されます。マニフェストをテキスト エディタで開いて、$K8S_SA_NAME$BUCKET_NAME を対応する値に置き換えることもできます。

  3. バケットにサンプル ファイルを作成します。

    touch sample-file
    gcloud storage cp sample-file gs://PROJECT_ID-gke-gpu-bucket
    
  4. Pod の準備ができるまで待ちます。

    kubectl wait --for=condition=Ready pod/test-tensorflow-pod -n=gke-ai-namespace --timeout=180s
    

    Pod の準備ができると、出力は次のようになります。

    pod/test-tensorflow-pod condition met
    
  5. TensorFlow コンテナでシェルを開きます。

    kubectl -n gke-ai-namespace exec --stdin --tty test-tensorflow-pod --container tensorflow -- /bin/bash
    
  6. 作成したサンプル ファイルを閲覧してみます。

    ls /data
    

    出力にサンプル ファイルが表示されます。

  7. ログを確認して Pod に接続されている GPU を特定します。

    python3 -m pip install 'tensorflow[and-cuda]'
    python -c "import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))"
    

    出力には、Pod に接続された GPU が次のように表示されます。

    ...
    PhysicalDevice(name='/physical_device:GPU:0',device_type='GPU')
    
  8. コンテナを終了します。

    exit
    
  9. サンプル Pod を削除します。

    kubectl delete -f src/gke-config/standard-tensorflow-bash.yaml \
        --namespace=gke-ai-namespace
    

MNIST データセットを使用してトレーニングと予測を行う

このセクションでは、サンプル データセット MNIST でトレーニング ワークロードを実行します。

  1. サンプルデータを Cloud Storage バケットにコピーします。

    gcloud storage cp src/tensorflow-mnist-example gs://PROJECT_ID-gke-gpu-bucket/ --recursive
    
  2. 次の環境変数を作成します。

    export K8S_SA_NAME=gpu-k8s-sa
    export BUCKET_NAME=PROJECT_ID-gke-gpu-bucket
    
  3. トレーニング Job を確認します。

    # Copyright 2023 Google LLC
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #      http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    
    apiVersion: batch/v1
    kind: Job
    metadata:
      name: mnist-training-job
    spec:
      template:
        metadata:
          name: mnist
          annotations:
            gke-gcsfuse/volumes: "true"
        spec:
          nodeSelector:
            cloud.google.com/gke-accelerator: nvidia-tesla-t4
          tolerations:
          - key: "nvidia.com/gpu"
            operator: "Exists"
            effect: "NoSchedule"
          containers:
          - name: tensorflow
            image: tensorflow/tensorflow:latest-gpu 
            command: ["/bin/bash", "-c", "--"]
            args: ["cd /data/tensorflow-mnist-example; pip install -r requirements.txt; python tensorflow_mnist_train_distributed.py"]
            resources:
              limits:
                nvidia.com/gpu: 1
                cpu: 1
                memory: 3Gi
            volumeMounts:
            - name: gcs-fuse-csi-vol
              mountPath: /data
              readOnly: false
          serviceAccountName: $K8S_SA_NAME
          volumes:
          - name: gcs-fuse-csi-vol
            csi:
              driver: gcsfuse.csi.storage.gke.io
              readOnly: false
              volumeAttributes:
                bucketName: $BUCKET_NAME
                mountOptions: "implicit-dirs"
          restartPolicy: "Never"
  4. トレーニング Job をデプロイします。

    envsubst < src/gke-config/standard-tf-mnist-train.yaml | kubectl -n gke-ai-namespace apply -f -
    

    このコマンドで、作成した環境変数がマニフェスト内の対応する参照に代入されます。マニフェストをテキスト エディタで開いて、$K8S_SA_NAME$BUCKET_NAME を対応する値に置き換えることもできます。

  5. Job のステータスが Completed になるまで待ちます。

    kubectl wait -n gke-ai-namespace --for=condition=Complete job/mnist-training-job --timeout=180s
    

    出力は次のようになります。

    job.batch/mnist-training-job condition met
    
  6. TensorFlow コンテナのログを確認します。

    kubectl logs -f jobs/mnist-training-job -c tensorflow -n gke-ai-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
    
  7. トレーニング ワークロードを削除します。

    kubectl -n gke-ai-namespace delete -f src/gke-config/standard-tf-mnist-train.yaml
    

推論ワークロードをデプロイする

このセクションでは、サンプル データセットを入力として受け取り、予測を返す推論ワークロードをデプロイします。

  1. 予測に使用する画像をバケットにコピーします。

    gcloud storage cp data/mnist_predict gs://PROJECT_ID-gke-gpu-bucket/ --recursive
    
  2. 推論ワークロードを確認します。

    # Copyright 2023 Google LLC
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #      http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    
    apiVersion: batch/v1
    kind: Job
    metadata:
      name: mnist-batch-prediction-job
    spec:
      template:
        metadata:
          name: mnist
          annotations:
            gke-gcsfuse/volumes: "true"
        spec:
          nodeSelector:
            cloud.google.com/gke-accelerator: nvidia-tesla-t4
          tolerations:
          - key: "nvidia.com/gpu"
            operator: "Exists"
            effect: "NoSchedule"
          containers:
          - name: tensorflow
            image: tensorflow/tensorflow:latest-gpu 
            command: ["/bin/bash", "-c", "--"]
            args: ["cd /data/tensorflow-mnist-example; pip install -r requirements.txt; python tensorflow_mnist_batch_predict.py"]
            resources:
              limits:
                nvidia.com/gpu: 1
                cpu: 1
                memory: 3Gi
            volumeMounts:
            - name: gcs-fuse-csi-vol
              mountPath: /data
              readOnly: false
          serviceAccountName: $K8S_SA_NAME
          volumes:
          - name: gcs-fuse-csi-vol
            csi:
              driver: gcsfuse.csi.storage.gke.io
              readOnly: false
              volumeAttributes:
                bucketName: $BUCKET_NAME
                mountOptions: "implicit-dirs"
          restartPolicy: "Never"
  3. 推論ワークロードをデプロイします。

    envsubst < src/gke-config/standard-tf-mnist-batch-predict.yaml | kubectl -n gke-ai-namespace apply -f -
    

    このコマンドで、作成した環境変数がマニフェスト内の対応する参照に代入されます。マニフェストをテキスト エディタで開いて、$K8S_SA_NAME$BUCKET_NAME を対応する値に置き換えることもできます。

  4. Job のステータスが Completed になるまで待ちます。

    kubectl wait -n gke-ai-namespace --for=condition=Complete job/mnist-batch-prediction-job --timeout=180s
    

    出力は次のようになります。

    job.batch/mnist-batch-prediction-job condition met
    
  5. TensorFlow コンテナのログを確認します。

    kubectl logs -f jobs/mnist-batch-prediction-job -c tensorflow -n gke-ai-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.
    

クリーンアップ

このガイドで作成したリソースについて Cloud de Confiance アカウントに課金されないようにするには、次のいずれかを行います。

  • GKE クラスタを保持する場合: クラスタにある Kubernetes リソースと Cloud de Confiance リソースを削除する
  • Cloud de Confiance プロジェクトを保持する場合: GKE クラスタと Cloud de Confiance リソースを削除する
  • プロジェクトを削除する

クラスタにある Kubernetes リソースと Cloud de Confiance リソースを削除する

  1. Kubernetes Namespace とデプロイしたワークロードを削除します。

    kubectl -n gke-ai-namespace delete -f src/gke-config/standard-tf-mnist-batch-predict.yaml
    kubectl delete namespace gke-ai-namespace
    
  2. Cloud Storage バケットを削除します。

    1. [バケット] ページに移動します。

      [バケット] に移動

    2. PROJECT_ID-gke-gpu-bucket のチェックボックスをオンにします。

    3. [削除] をクリックします。

    4. 削除を確定するには、「DELETE」と入力して [削除] をクリックします。

  3. Cloud de Confiance サービス アカウントを削除します。

    1. [サービス アカウント] ページに移動します。

      [サービス アカウント] に移動

    2. プロジェクトを選択します。

    3. gke-ai-sa@PROJECT_ID.s3ns.iam.gserviceaccount.com のチェックボックスをオンにします。

    4. [削除] をクリックします。

    5. 削除を確定するには、[削除] をクリックします。

GKE クラスタと Cloud de Confiance リソースを削除する

  1. GKE クラスタを削除します。

    1. [クラスタ] ページに移動します。

      [クラスタ] に移動

    2. gke-gpu-cluster のチェックボックスをオンにします。

    3. [削除] をクリックします。

    4. 削除を確定するには、「gke-gpu-cluster」と入力して [削除] をクリックします。

  2. Cloud Storage バケットを削除します。

    1. [バケット] ページに移動します。

      [バケット] に移動

    2. PROJECT_ID-gke-gpu-bucket のチェックボックスをオンにします。

    3. [削除] をクリックします。

    4. 削除を確定するには、「DELETE」と入力して [削除] をクリックします。

  3. Cloud de Confiance サービス アカウントを削除します。

    1. [サービス アカウント] ページに移動します。

      [サービス アカウント] に移動

    2. プロジェクトを選択します。

    3. gke-ai-sa@PROJECT_ID.s3ns.iam.gserviceaccount.com のチェックボックスをオンにします。

    4. [削除] をクリックします。

    5. 削除を確定するには、[削除] をクリックします。

プロジェクトを削除する

  1. Cloud de Confiance コンソールで [リソースの管理] ページに移動します。

    [リソースの管理] に移動

  2. プロジェクト リストで、削除するプロジェクトを選択し、[削除] をクリックします。
  3. ダイアログでプロジェクト ID を入力し、[シャットダウン] をクリックしてプロジェクトを削除します。

次のステップ