Questa guida mostra come addestrare un modello su Google Kubernetes Engine (GKE) utilizzando Ray, PyTorch e il componente aggiuntivo Ray Operator.
Informazioni su Ray
Ray è un framework di calcolo scalabile open source per applicazioni AI/ML. Ray Train è un componente di Ray progettato per l'addestramento e l'ottimizzazione dei modelli distribuiti. Puoi utilizzare l'API Ray Train per scalare l'addestramento su più macchine e per integrarla con librerie di machine learning come PyTorch.
Puoi eseguire il deployment dei job di addestramento Ray utilizzando la risorsa RayCluster o RayJob. Devi utilizzare una risorsa RayJob quando esegui il deployment dei job Ray in produzione per i seguenti motivi
- La risorsa RayJob crea un cluster Ray effimero che può essere eliminato automaticamente al termine di un job.
- La risorsa RayJob supporta i criteri di ripetizione per l'esecuzione resiliente dei job.
- Puoi gestire i job Ray utilizzando pattern API Kubernetes familiari.
prepara l'ambiente
Per preparare l'ambiente:
Avvia una sessione di Cloud Shell dalla console Google Cloud facendo clic su
Attiva Cloud Shell nella consoleGoogle Cloud . Viene avviata una sessione nel riquadro inferiore della console Google Cloud .
Imposta le variabili di ambiente:
export PROJECT_ID=PROJECT_ID export CLUSTER_NAME=ray-cluster export COMPUTE_REGION=us-central1 export COMPUTE_ZONE=us-central1-c export CLUSTER_VERSION=CLUSTER_VERSION export TUTORIAL_HOME=`pwd`
Sostituisci quanto segue:
PROJECT_ID
: il tuo Google Cloud ID progetto.CLUSTER_VERSION
: la versione di GKE da utilizzare. Deve essere1.30.1
o successiva.
Clona il repository GitHub:
git clone https://github.com/GoogleCloudPlatform/kubernetes-engine-samples
Passa alla directory di lavoro:
cd kubernetes-engine-samples/ai-ml/gke-ray/raytrain/pytorch-mnist
Crea un ambiente virtuale Python:
python -m venv myenv && \ source myenv/bin/activate
Crea un cluster GKE
Crea un cluster GKE Autopilot o Standard:
Autopilot
Crea un cluster Autopilot:
gcloud container clusters create-auto ${CLUSTER_NAME} \
--enable-ray-operator \
--cluster-version=${CLUSTER_VERSION} \
--location=${COMPUTE_REGION}
Standard
Crea un cluster Standard:
gcloud container clusters create ${CLUSTER_NAME} \
--addons=RayOperator \
--cluster-version=${CLUSTER_VERSION} \
--machine-type=e2-standard-8 \
--location=${COMPUTE_ZONE} \
--num-nodes=4
Esegui il deployment di una risorsa RayCluster
Esegui il deployment di una risorsa RayCluster nel tuo cluster:
Esamina il seguente manifest:
Questo manifest descrive una risorsa personalizzata RayCluster.
Applica il manifest al cluster GKE:
kubectl apply -f ray-cluster.yaml
Verifica che la risorsa RayCluster sia pronta:
kubectl get raycluster
L'output è simile al seguente:
NAME DESIRED WORKERS AVAILABLE WORKERS CPUS MEMORY GPUS STATUS AGE pytorch-mnist-cluster 2 2 6 20Gi 0 ready 63s
In questo output,
ready
nella colonnaSTATUS
indica che la risorsa RayCluster è pronta.
Connettiti alla risorsa RayCluster
Connettiti alla risorsa RayCluster per inviare un job Ray.
Verifica che GKE abbia creato il servizio RayCluster:
kubectl get svc pytorch-mnist-cluster-head-svc
L'output è simile al seguente:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE pytorch-mnist-cluster-head-svc ClusterIP 34.118.238.247 <none> 10001/TCP,8265/TCP,6379/TCP,8080/TCP 109s
Stabilisci una sessione di port forwarding con l'head Ray:
kubectl port-forward svc/pytorch-mnist-cluster-head-svc 8265:8265 2>&1 >/dev/null &
Verifica che il client Ray possa connettersi al cluster Ray utilizzando localhost:
ray list nodes --address http://localhost:8265
L'output è simile al seguente:
Stats: ------------------------------ Total: 3 Table: ------------------------------ NODE_ID NODE_IP IS_HEAD_NODE STATE NODE_NAME RESOURCES_TOTAL LABELS 0 1d07447d7d124db641052a3443ed882f913510dbe866719ac36667d2 10.28.1.21 False ALIVE 10.28.1.21 CPU: 2.0 ray.io/node_id: 1d07447d7d124db641052a3443ed882f913510dbe866719ac36667d2 # Several lines of output omitted
Addestra un modello
Addestra un modello PyTorch utilizzando il set di dati Fashion MNIST:
Invia un job Ray e attendi il completamento:
ray job submit --submission-id pytorch-mnist-job --working-dir . --runtime-env-json='{"pip": ["torch", "torchvision"], "excludes": ["myenv"]}' --address http://localhost:8265 -- python train.py
L'output è simile al seguente:
Job submission server address: http://localhost:8265 -------------------------------------------- Job 'pytorch-mnist-job' submitted successfully -------------------------------------------- Next steps Query the logs of the job: ray job logs pytorch-mnist-job Query the status of the job: ray job status pytorch-mnist-job Request the job to be stopped: ray job stop pytorch-mnist-job Handling connection for 8265 Tailing logs until the job exits (disable with --no-wait): ... ...
Verifica lo stato del job:
ray job status pytorch-mnist
L'output è simile al seguente:
Job submission server address: http://localhost:8265 Status for job 'pytorch-mnist-job': RUNNING Status message: Job is currently running.
Attendi che
Status for job
siaCOMPLETE
. Questa operazione può richiedere 15 minuti o più.Visualizza i log dei job Ray:
ray job logs pytorch-mnist
L'output è simile al seguente:
Training started with configuration: ╭─────────────────────────────────────────────────╮ │ Training config │ ├──────────────────────────────────────────────────┤ │ train_loop_config/batch_size_per_worker 8 │ │ train_loop_config/epochs 10 │ │ train_loop_config/lr 0.001 │ ╰─────────────────────────────────────────────────╯ # Several lines omitted Training finished iteration 10 at 2024-06-19 08:29:36. Total running time: 9min 18s ╭───────────────────────────────╮ │ Training result │ ├────────────────────────────────┤ │ checkpoint_dir_name │ │ time_this_iter_s 25.7394 │ │ time_total_s 351.233 │ │ training_iteration 10 │ │ accuracy 0.8656 │ │ loss 0.37827 │ ╰───────────────────────────────╯ # Several lines omitted ------------------------------- Job 'pytorch-mnist' succeeded -------------------------------
Esegui il deployment di un RayJob
La risorsa personalizzata RayJob gestisce il ciclo di vita di una risorsa RayCluster durante l'esecuzione di un singolo job Ray.
Esamina il seguente manifest:
Questo manifest descrive una risorsa personalizzata RayJob.
Applica il manifest al cluster GKE:
kubectl apply -f ray-job.yaml
Verifica che la risorsa RayJob sia in esecuzione:
kubectl get rayjob
L'output è simile al seguente:
NAME JOB STATUS DEPLOYMENT STATUS START TIME END TIME AGE pytorch-mnist-job RUNNING Running 2024-06-19T15:43:32Z 2m29s
In questo output, la colonna
DEPLOYMENT STATUS
indica che la risorsa RayJob èRunning
.Visualizza lo stato della risorsa RayJob:
kubectl logs -f -l job-name=pytorch-mnist-job
L'output è simile al seguente:
Training started with configuration: ╭─────────────────────────────────────────────────╮ │ Training config │ ├──────────────────────────────────────────────────┤ │ train_loop_config/batch_size_per_worker 8 │ │ train_loop_config/epochs 10 │ │ train_loop_config/lr 0.001 │ ╰─────────────────────────────────────────────────╯ # Several lines omitted Training finished iteration 10 at 2024-06-19 08:29:36. Total running time: 9min 18s ╭───────────────────────────────╮ │ Training result │ ├────────────────────────────────┤ │ checkpoint_dir_name │ │ time_this_iter_s 25.7394 │ │ time_total_s 351.233 │ │ training_iteration 10 │ │ accuracy 0.8656 │ │ loss 0.37827 │ ╰───────────────────────────────╯ # Several lines omitted ------------------------------- Job 'pytorch-mnist' succeeded -------------------------------
Verifica che il job Ray sia completato:
kubectl get rayjob
L'output è simile al seguente:
NAME JOB STATUS DEPLOYMENT STATUS START TIME END TIME AGE pytorch-mnist-job SUCCEEDED Complete 2024-06-19T15:43:32Z 2024-06-19T15:51:12Z 9m6s
In questo output, la colonna
DEPLOYMENT STATUS
indica che la risorsa RayJob èComplete
.