在 GKE Standard 模式中使用 GPU 訓練模型
本快速入門導覽課程說明如何在 Google Kubernetes Engine (GKE) 中,使用 GPU 部署訓練模型,並將預測結果儲存在 Cloud Storage。本教學課程使用 TensorFlow 模型和 GKE Standard 叢集。您也可以在 Autopilot 叢集上執行這些工作負載,設定步驟更少。如需操作說明,請參閱「在 GKE Autopilot 模式中使用 GPU 訓練模型」。
本文適用對象為現有 Standard 叢集的 GKE 管理員,且想首次執行 GPU 工作負載。
事前準備
- 登入 Google Cloud 帳戶。如果您未曾使用過 Google Cloud,歡迎建立帳戶,親自體驗實際使用我們產品的成效。新客戶還能獲得價值 $300 美元的免費抵免額,用於執行、測試及部署工作負載。
-
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 role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
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.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Kubernetes Engine and Cloud Storage APIs, if any are not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.-
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 role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
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.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Kubernetes Engine and Cloud Storage APIs, if any are not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.-
在 Google Cloud 控制台啟用 Cloud Shell。
Google Cloud 控制台底部會開啟 Cloud Shell 工作階段,並顯示指令列提示。Cloud Shell 是已安裝 Google Cloud CLI 的殼層環境,並已設定適用於您目前專案的值。工作階段可能要幾秒鐘的時間才能初始化。
必要的角色
如要取得在 GPU 上訓練模型所需的權限,請要求管理員授予您專案的下列 IAM 角色:
-
Kubernetes Engine 管理員 (
roles/container.admin):管理 GKE 叢集 -
管理 Cloud Storage bucket:Storage 管理員 (
roles/storage.admin) -
授予專案的 IAM 角色:專案 IAM 管理員 (
roles/resourcemanager.projectIamAdmin)
如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。
複製範例存放區
在 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 執行下列操作:
建立使用 Workload Identity Federation for GKE 的 Standard 叢集,並安裝 Cloud Storage FUSE 驅動程式:
gcloud container clusters create gke-gpu-cluster \ --addons GcsFuseCsiDriver \ --location=us-east4 \ --num-nodes=1 \ --workload-pool=PROJECT_ID.svc.id.goog將
PROJECT_ID替換為您的 Google Cloud專案 ID。叢集建立作業可能需要幾分鐘才能完成。
建立 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-east4 \ --cluster=gke-gpu-cluster
建立 Cloud Storage bucket
前往 Google Cloud 控制台的「Create a bucket」(建立 bucket) 頁面:
在「Name your bucket」(為 bucket 命名) 欄位中輸入下列名稱:
PROJECT_ID-gke-gpu-bucket按一下「繼續」。
在「位置類型」部分,選取「區域」。
在「Region」(區域) 清單中選取「
us-east4 (Northern Virginia)」,然後按一下「Continue」(繼續)。在「選擇資料的儲存空間級別」部分,點選「繼續」。
在「Choose how to control access to objects」(選擇如何控制物件的存取權) 專區中,將「Access control」(存取控管) 設為「Uniform」(統一)。
點選「建立」。
在「Public access will be prevented」(系統會禁止公開存取) 對話方塊中,確認已勾選「Enforce public access prevention on this bucket」(強制禁止公開存取這個值區) 核取方塊,然後按一下「Confirm」(確認)。
設定叢集,使用 Workload Identity Federation for GKE 存取 bucket
如要讓叢集存取 Cloud Storage bucket,請執行下列操作:
- 在叢集中建立 Kubernetes ServiceAccount。
- 將 IAM 角色授予 Kubernetes ServiceAccount。
在叢集中建立 Kubernetes ServiceAccount
在 Cloud Shell 中執行下列操作:
建立 Kubernetes 命名空間:
kubectl create namespace gke-ai-namespace在命名空間中建立 Kubernetes ServiceAccount:
kubectl create serviceaccount gpu-k8s-sa --namespace=gke-ai-namespace
將 IAM 角色授予 Kubernetes ServiceAccount
在 Cloud Shell 中,將 Storage 物件管理員 (roles/storage.objectAdmin) 和儲存空間分析 Collector Service (roles/storage.insightsCollectorService) 角色授予 Kubernetes ServiceAccount:
gcloud projects add-iam-policy-binding PROJECT_ID \
--member="principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/PROJECT_ID.svc.id.goog/subject/ns/gke-ai-namespace/sa/gpu-k8s-sa" \
--role=roles/storage.objectAdmin \
--condition=None
gcloud projects add-iam-policy-binding PROJECT_ID \
--member="principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/PROJECT_ID.svc.id.goog/subject/ns/gke-ai-namespace/sa/gpu-k8s-sa" \
--role=roles/storage.insightsCollectorService \
--condition=None
更改下列內容:
PROJECT_ID:您的 Google Cloud 專案 ID。PROJECT_NUMBER:您的 Google Cloud 專案編號。
確認 Pod 可存取 Cloud Storage bucket
在 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-ai-namespace apply -f -這個指令會將您建立的環境變數,替換為資訊清單中的對應參照。您也可以在文字編輯器中開啟資訊清單,並將
$K8S_SA_NAME和$BUCKET_NAME替換為對應的值。在 bucket 中建立範例檔案:
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-ai-namespace --timeout=180sPod 準備就緒後,輸出內容如下:
pod/test-tensorflow-pod condition met在 TensorFlow 容器中開啟殼層:
kubectl -n gke-ai-namespace exec --stdin --tty test-tensorflow-pod --container tensorflow -- /bin/bash嘗試讀取您建立的範例檔案:
ls /data輸出內容會顯示範例檔案。
查看記錄,找出附加至 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')退出容器:
exit刪除範例 Pod:
kubectl delete -f src/gke-config/standard-tensorflow-bash.yaml \ --namespace=gke-ai-namespace
使用 MNIST 資料集進行訓練和預測
在本節中,您將使用 MNIST 範例資料集執行訓練工作負載。
將範例資料複製到 Cloud Storage bucket:
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查看訓練工作:
部署訓練工作:
envsubst < src/gke-config/standard-tf-mnist-train.yaml | kubectl -n gke-ai-namespace apply -f -這個指令會將您建立的環境變數,替換為資訊清單中的對應參照。您也可以在文字編輯器中開啟資訊清單,並將
$K8S_SA_NAME和$BUCKET_NAME替換為對應的值。等待工作狀態變更為
Completed:kubectl wait -n gke-ai-namespace --for=condition=Complete job/mnist-training-job --timeout=180s輸出結果會與下列內容相似:
job.batch/mnist-training-job condition met查看 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刪除訓練工作負載:
kubectl -n gke-ai-namespace delete -f src/gke-config/standard-tf-mnist-train.yaml
部署推論工作負載
在本節中,您將部署推論工作負載,以範例資料集做為輸入內容,並傳回預測結果。
將要預測的圖片複製到 bucket:
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-ai-namespace apply -f -這個指令會將您建立的環境變數,替換為資訊清單中的對應參照。您也可以在文字編輯器中開啟資訊清單,並將
$K8S_SA_NAME和$BUCKET_NAME替換為對應的值。等待工作狀態變更為
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查看 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.
清除所用資源
如要避免系統向您的 Google Cloud 帳戶收取本指南所建立資源的費用,請執行下列任一操作:
- 保留 GKE 叢集:刪除叢集中的 Kubernetes 資源和 Google Cloud 資源
- 保留 Google Cloud 專案:刪除 GKE 叢集和 Google Cloud 資源
- 刪除專案
刪除叢集中的 Kubernetes 資源和 Google Cloud 資源
刪除 Kubernetes 命名空間和您部署的工作負載:
kubectl -n gke-ai-namespace delete -f src/gke-config/standard-tf-mnist-batch-predict.yaml kubectl delete namespace gke-ai-namespace刪除 Cloud Storage bucket:
前往「Buckets」(值區) 頁面:
選取
PROJECT_ID-gke-gpu-bucket的核取方塊。按一下「刪除」圖示 。
如要確認刪除,請輸入
DELETE,然後按一下「刪除」。
刪除 GKE 叢集和 Google Cloud 資源
刪除 GKE 叢集:
前往「Clusters」(叢集) 頁面:
勾選
gke-gpu-cluster的核取方塊。按一下「刪除」圖示 。
如要確認刪除,請輸入
gke-gpu-cluster,然後按一下「刪除」。
刪除 Cloud Storage bucket:
前往「Buckets」(值區) 頁面:
選取
PROJECT_ID-gke-gpu-bucket的核取方塊。按一下「刪除」圖示 。
如要確認刪除,請輸入
DELETE,然後按一下「刪除」。
刪除專案
- 前往 Google Cloud 控制台的「Manage resources」(管理資源) 頁面。
- 在專案清單中選取要刪除的專案,然後點選「Delete」(刪除)。
- 在對話方塊中輸入專案 ID,然後按一下 [Shut down] (關閉) 以刪除專案。