Trainer scenarios
Introduction
This article presents a set of MLOps Studio Trainer test scenarios performed from within Notebooks.
The article focuses primarily on the PyTorchJob framework and includes both successful and negative scenarios. These scenarios help verify standard job execution, runtime behavior, validation errors, pod-level failures, and job failures launched through both Notebook code and kubectl.
Prerequisites
Before you begin, make sure that the following requirements are met.
No. 1 Access to the CloudFerro MLOps Platform
You need access to the CloudFerro MLOps Platform and to a workspace where MLOps Studio components are available.
For more information, see: Access the MLOps Studio workspace
No. 2 Access to MLOps Studio Notebooks
All scenarios in this article are performed from within a Notebook. You must be able to create and open a Notebook in your namespace.
For more information, see:
Access a MLOps Studio notebook environment with Visual Studio Code Remote Tunnels
Access a MLOps Studio notebook environment with kubectl port-forward
No. 3 A valid user namespace
Some scenarios require you to submit jobs in your own namespace. If the example namespace shown in the code differs from yours, replace it with the correct one before running the commands.
No. 4 Basic familiarity with MLOps Studio Trainer
This article assumes that you are already familiar with the main Trainer concepts, such as runtimes, PyTorchJob, and monitoring training execution.
For background information, see: MLOps Studio Trainer overview
Overview
All scenarios are performed on Notebooks.
The PyTorchJob framework is primarily used here. The basic scenario for the TFJob, JAXJob, and XGBoostJob frameworks can be found here: Scenarios for other frameworks
Scenario - launching Trainer
Steps:
Create a Notebook with the pytorch-full option
Connect to the Notebook.
Add code to the first cell.
# Cell 1: Installation !pip install -q kubernetes pyyaml pandas # Cell 2: Setup from kubernetes import client, config import yaml, time, pandas as pd from IPython.display import clear_output # Connect to the cluster config.load_incluster_config() custom_api = client.CustomObjectsApi(client.ApiClient()) # Get namespace with open('/var/run/secrets/kubernetes.io/serviceaccount/namespace', 'r') as f: NAMESPACE = f.read().strip() print(f"Setup OK! Namespace: {NAMESPACE}")
Run the above cell.
Add code to the next cell.
# Cell 3: MNIST test on CPU, definition of a training function # that handles comprehensive model training optimal_job = { "apiVersion": "kubeflow.org/v1", "kind": "PyTorchJob", "metadata": { "name": "mnist-optimized", "namespace": NAMESPACE }, "spec": { "pytorchReplicaSpecs": { "Master": { "replicas": 1, "restartPolicy": "OnFailure", "template": { "spec": { "containers": [{ "name": "pytorch", "image": "docker.io/kubeflowkatib/pytorch-mnist:v1beta1-45c5727", "command": [ "python3", "/opt/pytorch-mnist/mnist.py", "--epochs=1", "--no-cuda", "--batch-size=16", # Small batch for CPU "--log-interval=50" ], "resources": { "requests": { "cpu": "400m", # 0.4 CPU "memory": "800Mi" # 0.8 GB }, "limits": { "cpu": "500m", # Max 0.5 CPU "memory": "1Gi" # Max 1 GB } } }] } } } } } } # Create job custom_api.create_namespaced_custom_object( group="kubeflow.org", version="v1", namespace=NAMESPACE, plural="pytorchjobs", body=optimal_job ) print("Job created!")
Run the above cell. In case of error 409, check this article:
Add the next cell with code.
import subprocess import time # Check status result = subprocess.run( ["kubectl", "get", "pods", "-n", NAMESPACE, "-l", "training.kubeflow.org/job-name=mnist-optimized"], capture_output=True, text=True ) print("Pod status:\n") print(result.stdout) # If Running or Completed, show logs if "Running" in result.stdout or "Completed" in result.stdout: print("\nLogs (last 30 lines):\n") logs = subprocess.run( ["kubectl", "logs", "-n", NAMESPACE, "-l", "training.kubeflow.org/job-name=mnist-optimized", "--tail=30"], capture_output=True, text=True ) print(logs.stdout) elif "Pending" in result.stdout: print("\nPending...\n") describe = subprocess.run( ["kubectl", "describe", "pod", "-n", NAMESPACE, "-l", "training.kubeflow.org/job-name=mnist-optimized"], capture_output=True, text=True ) # Show only Events events_start = describe.stdout.find("Events:") if events_start > 0: print(describe.stdout[events_start:])
Run the above cell.
Results:
Data of the following type should appear underneath.
Status pod: NAME READY STATUS RESTARTS AGE mnist-optimized-master-0 0/2 Completed 0 22m Logs (last 30 lines): ... 2025-11-27T10:12:06Z INFO Train Epoch: 1 [57600/60000 (96%)] loss=0.1448 2025-11-27T10:12:13Z INFO Train Epoch: 1 [58400/60000 (97%)] loss=0.4880 2025-11-27T10:12:22Z INFO Train Epoch: 1 [59200/60000 (99%)] loss=0.1072 2025-11-27T10:12:46Z INFO {metricName: accuracy, metricValue: 0.8341};{metricName: loss, metricValue: 0.4630}If it does not refresh automatically, the last cell can be executed again. In that case, the percentage value should already be changing.
Finally, it is good to perform a cleanup.
# Cleanup - remove all old jobs import time jobs_to_delete = ["mnist-optimized"] for job_name in jobs_to_delete: try: custom_api.delete_namespaced_custom_object( group="kubeflow.org", version="v1", namespace=NAMESPACE, plural="pytorchjobs", name=job_name ) print(f"Removed {job_name}") except: pass # Job does not exist, OK time.sleep(5) print("Cleanup finished")
Scenario - using a custom PyTorch CPU Runtime
Steps:
Create a Notebook as above.
Add the following code to a cell and run it. Pay attention to the correct namespace.
from kubernetes import client, config import time config.load_incluster_config() custom_api = client.CustomObjectsApi() core_api = client.CoreV1Api() # Use YOUR user namespace (not "kubeflow") MY_NAMESPACE = "kubeflow-user-example-com" print(f"Working in namespace: {MY_NAMESPACE}")
Add the following code to the second cell and run it. In case of an error like
PodDefault pytorch-cpu-small already exists, change theruntime_nameto something else.runtime_name = "pytorch-cpu-small" poddefault = { "apiVersion": "kubeflow.org/v1alpha1", "kind": "PodDefault", "metadata": { "name": runtime_name, "namespace": MY_NAMESPACE }, "spec": { "desc": "PyTorch CPU Small (0.5 CPU, 1Gi RAM)", "selector": { "matchLabels": { "runtime": runtime_name } }, "env": [ {"name": "OMP_NUM_THREADS", "value": "1"}, {"name": "MKL_NUM_THREADS", "value": "1"}, {"name": "CUSTOM_RUNTIME", "value": "true"} ] } } try: custom_api.create_namespaced_custom_object( group="kubeflow.org", version="v1alpha1", namespace=MY_NAMESPACE, plural="poddefaults", body=poddefault ) print(f"Created PodDefault: {runtime_name}") except client.exceptions.ApiException as e: if e.status == 409: print(f"PodDefault {runtime_name} already exists") else: print(f"Error: {e}")
Something like this should appear: Created PodDefault pytorch-cpu-small
Add the following code to the next cell and run it.
job_name = f"pytorch-training-{int(time.time())}" pytorch_job = { "apiVersion": "kubeflow.org/v1", "kind": "PyTorchJob", "metadata": { "name": job_name, "namespace": MY_NAMESPACE }, "spec": { "pytorchReplicaSpecs": { "Master": { "replicas": 1, "restartPolicy": "OnFailure", "template": { "metadata": { "labels": { "runtime": runtime_name } }, "spec": { "containers": [{ "name": "pytorch", "image": "pytorch/pytorch:latest", "command": ["python", "-c"], "args": [""" import torch import os print('Training with Custom Runtime') print(f'PyTorch version: {torch.__version__}') print(f'OMP_NUM_THREADS: {os.getenv("OMP_NUM_THREADS")}') print(f'MKL_NUM_THREADS: {os.getenv("MKL_NUM_THREADS")}') print(f'CUSTOM_RUNTIME: {os.getenv("CUSTOM_RUNTIME")}') # Simple training simulation for epoch in range(5): print(f'✓ Epoch {epoch+1}/5') print('Training completed!') """], "env": [ {"name": "OMP_NUM_THREADS", "value": "1"}, {"name": "MKL_NUM_THREADS", "value": "1"}, {"name": "CUSTOM_RUNTIME", "value": "true"} ], "resources": { "requests": {"cpu": "0.5", "memory": "1Gi"}, "limits": {"cpu": "0.5", "memory": "1Gi"} } }] } } } } } } response = custom_api.create_namespaced_custom_object( group="kubeflow.org", version="v1", namespace=MY_NAMESPACE, plural="pytorchjobs", body=pytorch_job ) print(f"Submitted PyTorchJob: {job_name}")
Something like this should appear: Submitted PyTorchJob: pytorch-training-1764075709
Add the following code to the next cell and run it.
""" Job monitoring - checks status every 5 seconds Saves logs during execution so they remain available afterwards """ from datetime import datetime def monitor_pytorch_job(job_name, namespace, max_checks=30): """Monitor the PyTorchJob until completion""" print(f"Monitoring PyTorchJob: {job_name}") print("="*70) # Dictionary for storing pod logs saved_logs = {} for i in range(max_checks): timestamp = datetime.now().strftime("%H:%M:%S") try: # Get job status job = custom_api.get_namespaced_custom_object( group="kubeflow.org", version="v1", namespace=namespace, plural="pytorchjobs", name=job_name ) status = job.get('status', {}) conditions = status.get('conditions', []) # Display job status if conditions: latest = conditions[-1] condition_type = latest.get('type', 'Unknown') message = latest.get('message', '') print(f"\n[{timestamp}] Job status: {condition_type}") if message: print(f" Message: {message}") # Get pods and their statuses pods = core_api.list_namespaced_pod( namespace=namespace, label_selector=f"training.kubeflow.org/job-name={job_name}" ) if pods.items: for pod in pods.items: pod_name = pod.metadata.name phase = pod.status.phase print(f" Pod: {pod_name}") print(f" Status: {phase}") # Fetch and save logs when pod is Running or Succeeded if phase in ["Running", "Succeeded"]: try: # Get full logs full_logs = core_api.read_namespaced_pod_log( name=pod_name, namespace=namespace ) saved_logs[pod_name] = full_logs # Show only the last 3 lines as preview if full_logs: print(f" Latest logs:") for line in full_logs.strip().split('\n')[-3:]: print(f" {line}") except Exception: if pod_name not in saved_logs: try: prev_logs = core_api.read_namespaced_pod_log( name=pod_name, namespace=namespace, previous=True ) saved_logs[pod_name] = prev_logs except: pass # Check whether job finished if conditions and conditions[-1].get('type') in ['Succeeded', 'Failed']: print("\n" + "="*70) print(f"Job finished: {conditions[-1].get('type')}") print("="*70) # Show saved logs and verify custom runtime if saved_logs: for pod_name, logs in saved_logs.items(): print(f"\nFull logs from: {pod_name}") print("-"*70) print(logs) print("\n" + "="*70) print("Custom Runtime verification:") print("="*70) if "CUSTOM_RUNTIME: true" in logs: print("✓ Custom runtime was successfully applied!") else: print("✗ Custom runtime may not have been applied") else: print("\n⚠ Could not retrieve pod logs") print("Possible reasons:") print(" - Pod was removed too quickly") print(" - Container finished before logs were collected") print(" - Problem with cluster logging") return conditions[-1].get('type') except Exception as e: print(f"[{timestamp}] Error: {e}") # Wait 5 seconds before the next check if i < max_checks - 1: time.sleep(5) print("\n" + "="*70) print("Timeout - monitoring finished") # Show any logs collected before timeout if saved_logs: print("\nCollected logs before timeout:") for pod_name, logs in saved_logs.items(): print(f"\n{pod_name}:") print("-"*70) print(logs) return "Timeout" # Run monitoring final_status = monitor_pytorch_job(job_name, MY_NAMESPACE)
Results:
Training finished successfully and a message of the following type appears.
Getting logs... ====================================================================== Logs from: pytorch-training-1764075709-master-0 ====================================================================== Training with Custom Runtime PyTorch version: 2.2.1 OMP_NUM_THREADS: 1 MKL_NUM_THREADS: 1 ✓ Epoch 1/5 ✓ Epoch 2/5 ✓ Epoch 3/5 ✓ Epoch 4/5 ✓ Epoch 5/5 Training completed! Custom runtime was successfully applied!
It is good to do a cleanup at the end.
""" Cleanup - removing created resources """ print("Cleaning up resources...") print("="*70) # Remove PyTorchJob try: custom_api.delete_namespaced_custom_object( group="kubeflow.org", version="v1", namespace=MY_NAMESPACE, plural="pytorchjobs", name=job_name ) print(f"✓ Removed PyTorchJob: {job_name}") except client.exceptions.ApiException as e: if e.status == 404: print(f" PyTorchJob {job_name} not found (already removed)") else: print(f" Error while deleting PyTorchJob: {e}") # Remove PodDefault try: custom_api.delete_namespaced_custom_object( group="kubeflow.org", version="v1alpha1", namespace=MY_NAMESPACE, plural="poddefaults", name=runtime_name ) print(f"✓ Removed PodDefault: {runtime_name}") except client.exceptions.ApiException as e: if e.status == 404: print(f" PodDefault {runtime_name} not found (already removed)") else: print(f" Error while deleting PodDefault: {e}") print("="*70) print("Cleanup finished!")
Scenario – Trainer – missing required section pytorchReplicaSpecs
Steps:
Execute the steps as in the scenario using a custom PyTorch CPU Runtime, but replace the
pytorch_jobsection with something like this — a definition of an incorrectPyTorchJobwhere thepytorchReplicaSpecssection is intentionally missing.Add the following code to a cell.
# Cell 3: Trainer – missing required section pytorchReplicaSpecs from kubernetes import client broken_job = { "apiVersion": "kubeflow.org/v1", "kind": "PyTorchJob", "metadata": { "name": "mnist-missing-replicas", "namespace": NAMESPACE }, "spec": { # INTENTIONALLY: missing "pytorchReplicaSpecs" section } } try: custom_api.create_namespaced_custom_object( group="kubeflow.org", version="v1", namespace=NAMESPACE, plural="pytorchjobs", body=broken_job ) print("❌ Job mnist-missing-replicas was created, but it should not have been") except client.exceptions.ApiException as e: print("✅ Expected error while creating the job") print(f"HTTP status: {e.status}") print("Error body:") print(e.body)
Run the above cell.
Results:
The job should not be created in the cluster.
An error message should appear in the Notebook.
The exact wording may vary, but:
The HTTP code is typically 400 or 422.
The error body contains information that the required section/key pytorchReplicaSpecs is missing, or an equivalent message.
Scenario acceptance criteria: The Trainer/UI does not allow the job to be created silently. The user receives a clear message that the definition is incorrect because pytorchReplicaSpecs is missing.
Scenario – Trainer – incorrect data type in the replicas field
Steps:
Execute the steps as in the scenario using a custom PyTorch CPU Runtime, but replace the
pytorch_jobsection with something like this — aPyTorchJobdefinition with an incorrect data type in thereplicasfield, string instead of a number.Add the following code to a cell.
# Cell 3: Trainer – incorrect type of the replicas field from kubernetes import client invalid_type_job = { "apiVersion": "kubeflow.org/v1", "kind": "PyTorchJob", "metadata": { "name": "mnist-invalid-replicas-type", "namespace": NAMESPACE }, "spec": { "pytorchReplicaSpecs": { "Master": { "replicas": "one", # incorrect type – should be int, not string "restartPolicy": "OnFailure", "template": { "spec": { "containers": [{ "name": "pytorch", "image": "docker.io/kubeflowkatib/pytorch-mnist:v1beta1-45c5727", "command": [ "python3", "/opt/pytorch-mnist/mnist.py", "--epochs=1", "--no-cuda", "--batch-size=16", "--log-interval=50" ], "resources": { "requests": { "cpu": "400m", "memory": "800Mi" }, "limits": { "cpu": "500m", "memory": "1Gi" } } }] } } } } } } try: custom_api.create_namespaced_custom_object( group="kubeflow.org", version="v1", namespace=NAMESPACE, plural="pytorchjobs", body=invalid_type_job ) print("❌ Job mnist-invalid-replicas-type was created, but it should not have been") except client.exceptions.ApiException as e: print("✅ Expected error while creating the job") print(f"HTTP status: {e.status}") print("Error body:") print(e.body)
Run the above cell.
Results:
The job should not be created. Something like this should appear in the Notebook.
HTTP status: 400 or 422 Error body: ... spec.pytorchReplicaSpecs.Master.replicas: Invalid value ...
The exact content depends on the CRD configuration and validation, but:
The HTTP code is typically 400 or 422.
The error body contains a reference to the replicas field and information that the value or type is incorrect, such as
expected integerorinvalid type.
Scenario acceptance criteria:
The Trainer/UI shows the user a clear error regarding the incorrect type or value of replicas, rather than a generic internal server error or a silent failure.
Scenario – Trainer – incorrect container image (pod-level error – ErrImagePull)
Steps:
Execute the steps as in the scenario using a custom PyTorch CPU Runtime, but replace the
pytorch_jobsection with something like this — aPyTorchJobdefinition with a non-existent or incorrect image.Add the following code to a cell.
# Cell 3: Trainer – incorrect container image from kubernetes import client bad_image_job = { "apiVersion": "kubeflow.org/v1", "kind": "PyTorchJob", "metadata": { "name": "mnist-bad-image", "namespace": NAMESPACE }, "spec": { "pytorchReplicaSpecs": { "Master": { "replicas": 1, "restartPolicy": "OnFailure", "template": { "spec": { "containers": [{ "name": "pytorch", # Intentionally incorrect / non-existent image tag "image": "docker.io/kubeflowkatib/pytorch-mnist:nonexistent-tag", "command": [ "python3", "/opt/pytorch-mnist/mnist.py", "--epochs=1", "--no-cuda", "--batch-size=16", "--log-interval=50" ], "resources": { "requests": { "cpu": "400m", "memory": "800Mi" }, "limits": { "cpu": "500m", "memory": "1Gi" } } }] } } } } } } response = custom_api.create_namespaced_custom_object( group="kubeflow.org", version="v1", namespace=NAMESPACE, plural="pytorchjobs", body=bad_image_job ) print("Job with incorrect image was created – expecting an error at pod level")
Run the above cell.
Add the next cell with code — checking the pod status and events.
# Cell 4: Checking pod status and events for incorrect image import subprocess import time # Wait a moment for pod creation time.sleep(10) result = subprocess.run( ["kubectl", "get", "pods", "-n", NAMESPACE, "-l", "training.kubeflow.org/job-name=mnist-bad-image"], capture_output=True, text=True ) print("Pod status:\n") print(result.stdout) describe = subprocess.run( ["kubectl", "describe", "pod", "-n", NAMESPACE, "-l", "training.kubeflow.org/job-name=mnist-bad-image"], capture_output=True, text=True ) events_start = describe.stdout.find("Events:") if events_start > 0: print("\nEvents:\n") print(describe.stdout[events_start:]) else: print("\nNo Events section in the pod description\n")
Run the above cell.
Results:
In the Pod status section, something like this should appear.
NAME READY STATUS RESTARTS AGE mnist-bad-image-master-0 0/1 ErrImagePull 0 30s
or ImagePullBackOff in the STATUS column.
In the Events section from
kubectl describe pod, there should be a message like:Failed to pull image "docker.io/kubeflowkatib/pytorch-mnist:nonexistent-tag"or
pull access denied, repository does not exist or may require authorization
The job should transition to a Failed state after several attempts to pull the image.
Scenario acceptance criteria:
The Trainer/UI shows that the job has failed.
The user has access to information stating that the cause of the error is a problem with the container image, ErrImagePull or ImagePullBackOff, together with the message from events.
The failure is not hidden under a generic job failed message without details.
Scenario - launching Trainer via kubectl
Steps:
Switch to the appropriate namespace. All code is based on kubeflow-user-example-com. If you have a different namespace, change it in the file and the commands.
Launch the Trainer.
cat <<EOF | kubectl apply -f - apiVersion: kubeflow.org/v1 kind: PyTorchJob metadata: name: pytorch-cpu-simple namespace: kubeflow-user-example-com spec: pytorchReplicaSpecs: Master: replicas: 1 restartPolicy: OnFailure template: spec: containers: - name: pytorch image: pytorch/pytorch:latest command: - python - -c args: - | import torch import time print("="*60) print("PyTorch CPU Training") print("="*60) print(f"PyTorch version: {torch.__version__}") print(f"CUDA available: {torch.cuda.is_available()}") print(f"CPU threads: {torch.get_num_threads()}") print("") # Simple model print("Creating neural network...") model = torch.nn.Sequential( torch.nn.Linear(784, 256), torch.nn.ReLU(), torch.nn.Linear(256, 128), torch.nn.ReLU(), torch.nn.Linear(128, 10) ) print(f"Model parameters: {sum(p.numel() for p in model.parameters())}") # Dummy data print("Generating training data...") batch_size = 64 x = torch.randn(batch_size, 784) y = torch.randint(0, 10, (batch_size,)) # Training print("") print("Starting training...") criterion = torch.nn.CrossEntropyLoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.01) for epoch in range(1, 6): start_time = time.time() # Forward outputs = model(x) loss = criterion(outputs, y) # Backward optimizer.zero_grad() loss.backward() optimizer.step() elapsed = time.time() - start_time print(f"Epoch {epoch}/5 - Loss: {loss.item():.4f} - Time: {elapsed:.3f}s") print("") print("="*60) print("Training completed successfully!") print("="*60) env: - name: OMP_NUM_THREADS value: "2" - name: MKL_NUM_THREADS value: "2" resources: requests: cpu: "500m" memory: "1Gi" limits: cpu: "500m" memory: "1Gi" EOF
Optional: wait until the training is finished, maximum 5 minutes.
kubectl wait --for=condition=Succeeded --timeout=300s \ pytorchjob/pytorch-cpu-simple -n kubeflow-user-example-com
Results:
The status should eventually appear as Succeeded when you run:
kubectl get pytorchjobs pytorch-cpu-simple -n kubeflow-user-example-com
Pods show the status Completed when running:
kubectl get pods -n kubeflow-user-example-com \ -l training.kubeflow.org/job-name=pytorch-cpu-simple
The text Training completed successfully! appears when running:
kubectl logs -n kubeflow-user-example-com \ -l training.kubeflow.org/job-name=pytorch-cpu-simple
Scenario – error when launching via kubectl
Description:
In this scenario, the error is artificial and intentional. It is specifically designed to test the behavior of MLOps Studio and Trainer in the event of a failed training.
The script starts normally, creates the model, and runs several epochs.
Everything works until the
raise RuntimeError(...)point.At that moment, Python throws an exception that is not caught anywhere, with no
try/except.The process in the container terminates with an exit code != 0, for example Exit Code: 1.
Steps:
Switch to the appropriate namespace. All code is based on kubeflow-user-example-com. If you have a different namespace, change it in the file and the commands.
Launch the Trainer.
cat <<EOF | kubectl apply -f - apiVersion: kubeflow.org/v1 kind: PyTorchJob metadata: name: pytorch-cpu-failing namespace: kubeflow-user-example-com spec: pytorchReplicaSpecs: Master: replicas: 1 restartPolicy: Never template: spec: containers: - name: pytorch image: pytorch/pytorch:latest command: - python - -c args: - | import torch import time print("="*60) print("PyTorch CPU Failing Training") print("="*60) print(f"PyTorch version: {torch.__version__}") print(f"CUDA available: {torch.cuda.is_available()}") print("") # Simple model print("Creating neural network...") model = torch.nn.Sequential( torch.nn.Linear(784, 256), torch.nn.ReLU(), torch.nn.Linear(256, 128), torch.nn.ReLU(), torch.nn.Linear(128, 10) ) batch_size = 64 x = torch.randn(batch_size, 784) y = torch.randint(0, 10, (batch_size,)) criterion = torch.nn.CrossEntropyLoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.01) for epoch in range(1, 4): start_time = time.time() outputs = model(x) loss = criterion(outputs, y) optimizer.zero_grad() loss.backward() optimizer.step() elapsed = time.time() - start_time print(f"Epoch {epoch}/3 - Loss: {loss.item():.4f} - Time: {elapsed:.3f}s") print("") print("About to fail intentionally...") # Intentional failure raise RuntimeError("Intentional training failure for negative test") env: - name: OMP_NUM_THREADS value: "2" - name: MKL_NUM_THREADS value: "2" resources: requests: cpu: "500m" memory: "1Gi" limits: cpu: "500m" memory: "1Gi" EOF
Optional: wait until the training is finished, maximum 5 minutes.
kubectl wait --for=condition=Failed --timeout=300s \ pytorchjob/pytorch-cpu-failing -n kubeflow-user-example-com
Results:
Status Failed.
kubectl get pytorchjobs pytorch-cpu-failing -n kubeflow-user-example-com
Error in the description.
kubectl describe pytorchjob pytorch-cpu-failing -n kubeflow-user-example-com
Pods show the status Error.
kubectl get pods -n kubeflow-user-example-com \ -l training.kubeflow.org/job-name=pytorch-cpu-failing
Scenario – Invalid NCCL backend on a CPU cluster
Description:
This scenario checks what happens when you misconfigure distributed training in PyTorch, specifically when you force the nccl backend on a cluster without GPUs, CPU-only.
In other words: does the stack, PyTorchJob + Kubernetes + your monitoring, handle a mid-training error resulting from an incorrect distributed backend configuration in a reasonable way?
We create a PyTorchJob with:
1 Master
2 Workers, meaning world_size > 1, distributed mode enabled
In the Master and Worker code:
Instead of
backend='gloo', we setbackend='nccl'.nccl normally requires a GPU and a specific environment.
When the Pods start, the code attempts to execute:
dist.init_process_group(backend='nccl', ...)
which should result in a crash.
Steps:
Setup in the first cell and run it.
""" 01_setup.py – installation of libraries, connection to cluster, namespace """ import subprocess import sys # Install required libraries if not yet present subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "kubernetes", "pyyaml", "pandas"]) from kubernetes import client, config import yaml, time, pandas as pd from IPython.display import clear_output # Connect to cluster config.load_incluster_config() custom_api = client.CustomObjectsApi(client.ApiClient()) core_api = client.CoreV1Api(client.ApiClient()) # Get namespace from service account with open('/var/run/secrets/kubernetes.io/serviceaccount/namespace', 'r') as f: NAMESPACE = f.read().strip() print(f"Setup OK! Namespace: {NAMESPACE}")
Create a PyTorchJob with the NCCL backend.
""" 02_create_pytorchjob_nccl_fail.py – create PyTorchJob with NCCL backend """ from kubernetes import client job_name = "pytorch-distributed-cpu-nccl-fail" distributed_job_nccl_fail = { "apiVersion": "kubeflow.org/v1", "kind": "PyTorchJob", "metadata": { "name": job_name, "namespace": NAMESPACE }, "spec": { "pytorchReplicaSpecs": { "Master": { "replicas": 1, "restartPolicy": "OnFailure", "template": { "metadata": { "annotations": { "sidecar.istio.io/inject": "false" } }, "spec": { "containers": [{ "name": "pytorch", "image": "pytorch/pytorch:latest", "command": ["python", "-c"], "args": [ """ import torch import torch.distributed as dist import os import time from datetime import timedelta print('='*70) print('Distributed PyTorch Training – NEGATIVE TEST (NCCL on CPU)') print('='*70) rank = int(os.environ.get('RANK', 0)) world_size = int(os.environ.get('WORLD_SIZE', 1)) master_addr = os.environ.get('MASTER_ADDR', 'localhost') master_port = os.environ.get('MASTER_PORT', '23456') print('\\nDistributed Config:') print(f' Rank: {rank}') print(f' World Size: {world_size}') print(f' Master: {master_addr}:{master_port}') print(f' Backend: nccl (forced – expecting an error on CPU)') if world_size > 1: print('\\nWaiting for all workers to connect...') print('(Negative test: init_process_group should fail)') try: dist.init_process_group( backend='nccl', init_method=f'tcp://{master_addr}:{master_port}', rank=rank, world_size=world_size, timeout=timedelta(seconds=600) ) print('Process group initialized (this would be unexpected on CPU cluster)') print(f' Is initialized: {dist.is_initialized()}') print(f' Backend: {dist.get_backend()}') except Exception as e: print('ERROR (EXPECTED): Failed to initialize process group with NCCL on CPU:') print(f' {e}') raise else: print('\\nSingle process mode – this is not the target of this negative test') print('\\nStarting training simulation...') for epoch in range(5): print(f' Epoch {epoch+1}/5 on rank {rank}') time.sleep(2) if world_size > 1 and dist.is_initialized(): dist.barrier() if rank == 0: print(f' All {world_size} workers synchronized at epoch {epoch+1}') if world_size > 1 and dist.is_initialized(): dist.destroy_process_group() print(f'\\nTraining completed on rank {rank}') print('='*70) """ ], "resources": { "requests": {"cpu": "500m", "memory": "1Gi"}, "limits": {"cpu": "500m", "memory": "1Gi"} }, "env": [ {"name": "OMP_NUM_THREADS", "value": "1"}, {"name": "MKL_NUM_THREADS", "value": "1"}, {"name": "NCCL_DEBUG", "value": "INFO"}, {"name": "PYTHONUNBUFFERED", "value": "1"} ] }] } } }, "Worker": { "replicas": 2, "restartPolicy": "OnFailure", "template": { "metadata": { "annotations": { "sidecar.istio.io/inject": "false" } }, "spec": { "containers": [{ "name": "pytorch", "image": "pytorch/pytorch:latest", "command": ["python", "-c"], "args": [ """ import torch import torch.distributed as dist import os import time from datetime import timedelta rank = int(os.environ.get('RANK', 0)) world_size = int(os.environ.get('WORLD_SIZE', 1)) master_addr = os.environ.get('MASTER_ADDR', 'localhost') master_port = os.environ.get('MASTER_PORT', '23456') print(f'[Worker {rank}] NEGATIVE TEST – NCCL backend on CPU') print(f'[Worker {rank}] Connecting to {master_addr}:{master_port}') if world_size > 1: try: dist.init_process_group( backend='nccl', init_method=f'tcp://{master_addr}:{master_port}', rank=rank, world_size=world_size, timeout=timedelta(seconds=600) ) print(f'[Worker {rank}] Process group initialized (unexpected)') except Exception as e: print(f'[Worker {rank}] ERROR (EXPECTED): Failed to connect with NCCL on CPU:') print(f' {e}') raise print(f'[Worker {rank}] Starting training...') for epoch in range(5): print(f'[Worker {rank}] Epoch {epoch+1}/5') time.sleep(2) if world_size > 1 and dist.is_initialized(): dist.barrier() if world_size > 1 and dist.is_initialized(): dist.destroy_process_group() print(f'[Worker {rank}] Training completed') """ ], "resources": { "requests": {"cpu": "500m", "memory": "1Gi"}, "limits": {"cpu": "500m", "memory": "1Gi"} }, "env": [ {"name": "OMP_NUM_THREADS", "value": "1"}, {"name": "MKL_NUM_THREADS", "value": "1"}, {"name": "PYTHONUNBUFFERED", "value": "1"} ] }] } } } } } } try: custom_api.create_namespaced_custom_object( group="kubeflow.org", version="v1", namespace=NAMESPACE, plural="pytorchjobs", body=distributed_job_nccl_fail ) print(f"Job created: {job_name}") except Exception as e: print(f"Error while creating the job: {e}")
Monitoring, logs, events, status.
""" 03_monitor_pytorchjob_nccl_fail.py – monitoring, logs, events, status """ import subprocess import time import json from IPython.display import clear_output job_name = "pytorch-distributed-cpu-nccl-fail" print(f"Monitoring distributed training for job: {job_name}\n") print("Expected result: pods in Failed / CrashLoopBackOff due to NCCL error\n") print("Press Ctrl+C to stop monitoring\n") print("="*80) # Pod monitoring try: for i in range(60): clear_output(wait=True) print(f"Distributed Training Monitor (refresh {i+1}/60)") print("="*80) result = subprocess.run( [ "kubectl", "get", "pods", "-n", NAMESPACE, "-l", f"training.kubeflow.org/job-name={job_name}", "-o", "custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName,START:.status.startTime" ], capture_output=True, text=True ) print("\nPod Status:") print(result.stdout) lines = result.stdout.strip().split('\n')[1:] if lines and lines[0]: pending = sum(1 for line in lines if 'Pending' in line) running = sum(1 for line in lines if 'Running' in line) succeeded = sum(1 for line in lines if 'Succeeded' in line) failed = sum(1 for line in lines if 'Failed' in line) print(f"\nStatus Summary:") print(f" Pending: {pending}") print(f" Running: {running}") print(f" Succeeded: {succeeded}") print(f" Failed: {failed}") if failed > 0: print("\nEXPECTED: Some pods Failed – check logs (NCCL backend on CPU).") break elif succeeded == 3: print("\nUNEXPECTED: all pods Succeeded.") break elif running > 0: print("\nPods Running – waiting for failure or completion.") elif pending > 0 and running > 0: print("\nPods are starting independently.") time.sleep(5) except KeyboardInterrupt: print("\n\nMonitoring stopped by user") # Detailed logs print("\nFetching logs from all pods...\n") result = subprocess.run( [ "kubectl", "get", "pods", "-n", NAMESPACE, "-l", f"training.kubeflow.org/job-name={job_name}", "-o", "jsonpath={.items[*].metadata.name}" ], capture_output=True, text=True ) pod_names = result.stdout.split() if not pod_names: print("No pods for this job") else: for pod_name in pod_names: print("="*80) print(f"Logs from: {pod_name}") print("="*80) logs = subprocess.run( ["kubectl", "logs", "-n", NAMESPACE, pod_name, "--tail=50"], capture_output=True, text=True ) print(logs.stdout) print("\n") # Scheduler and events print("Checking scheduler and events...\n") pods_result = subprocess.run( [ "kubectl", "get", "pods", "-n", NAMESPACE, "-l", f"training.kubeflow.org/job-name={job_name}", "-o", "jsonpath={.items[*].metadata.name}" ], capture_output=True, text=True ) pod_list = pods_result.stdout.split() if pod_list: first_pod = pod_list[0] print(f"Scheduler used by {first_pod}:") scheduler = subprocess.run( [ "kubectl", "get", "pod", first_pod, "-n", NAMESPACE, "-o", "jsonpath={.spec.schedulerName}" ], capture_output=True, text=True ) print(f" {scheduler.stdout if scheduler.stdout else 'default-scheduler'}\n") print("\n" + "="*80) print("Pod Events:") print("="*80 + "\n") for pod_name in pod_list: print(f"\n{pod_name}:") events = subprocess.run( [ "kubectl", "get", "events", "-n", NAMESPACE, "--field-selector", f"involvedObject.name={pod_name}", "--sort-by", ".lastTimestamp" ], capture_output=True, text=True ) if events.stdout.strip(): print(events.stdout) else: print(" (no events)") else: print("No pods – no scheduler/events to show.") # PyTorchJob status print("\nPyTorchJob status:\n") print("="*80) result = subprocess.run( ["kubectl", "get", "pytorchjob", job_name, "-n", NAMESPACE, "-o", "json"], capture_output=True, text=True ) if result.returncode == 0: job_data = json.loads(result.stdout) print(f"Name: {job_data['metadata']['name']}") print(f"Namespace: {job_data['metadata']['namespace']}") print(f"Created: {job_data['metadata']['creationTimestamp']}") if 'status' in job_data: status = job_data['status'] print("\nStatus:") if 'conditions' in status: for condition in status['conditions']: print(f" {condition['type']}: {condition['status']}") if 'reason' in condition: print(f" Reason: {condition['reason']}") if 'message' in condition: print(f" Message: {condition['message']}") if 'replicaStatuses' in status: print("\nReplica Statuses:") for replica_type, replica_status in status['replicaStatuses'].items(): print(f" {replica_type}:") for key, value in replica_status.items(): print(f" {key}: {value}") else: print(f"Job not found: {job_name}")
Results:
Master and Worker Pods will not transition to
Succeeded. Instead, they will be in a Failed or CrashLoopBackOff state.In the Pod logs, you will see messages indicating that the process group failed to initialize with the nccl backend, such as NCCL error or unsupported.
In the monitoring status summary, you will see Failed > 0 and a message such as:
EXPECTED: Some pods Failed – check logs (NCCL backend on CPU).
In the master logs:
ValueError: ProcessGroupNCCL is only supported with GPUs, no GPUs found! ERROR (EXPECTED): Failed to initialize process group with NCCL on CPU:
In the worker logs:
ERROR (EXPECTED): Failed to connect with NCCL on CPU: ValueError: ProcessGroupNCCL is only supported with GPUs, no GPUs found!
Gloo on CPU
Kubeflow PyTorchJob – Gloo on CPU
Cell 0 - notebook
Create notebook with basic setup
Open Kubeflow Central Dashboard.
Open Notebooks.
Click New Notebook.
Use:
Name:
gloo-cpu-testCPU:
1Memory:
2GiGPU:
0Workspace:
5GiImage: Python/PyTorch image with Jupyter
Click Launch.
When the Notebook is ready, click Connect.
Cell 1 – Setup
Paste into the first cell and run:
import subprocess
import sys
subprocess.check_call([
sys.executable,
"-m",
"pip",
"install",
"-q",
"kubernetes",
])
from kubernetes import client, config
config.load_incluster_config()
api_client = client.ApiClient()
custom_api = client.CustomObjectsApi(api_client)
core_api = client.CoreV1Api(api_client)
auth_api = client.AuthorizationV1Api(api_client)
with open(
"/var/run/secrets/kubernetes.io/serviceaccount/namespace",
"r",
) as f:
NAMESPACE = f.read().strip()
print(f"SETUP_OK namespace={NAMESPACE}")
Expected result:
SETUP_OK namespace=<your-namespace>
Cell 2 – Check permissions
Paste into the second cell and run:
checks = [
("create", "kubeflow.org", "pytorchjobs", None),
("get", "kubeflow.org", "pytorchjobs", None),
("delete", "kubeflow.org", "pytorchjobs", None),
("list", "", "pods", None),
("get", "", "pods", None),
("get", "", "pods", "log"),
("list", "", "events", None),
]
denied = []
for verb, group, resource, subresource in checks:
review = client.V1SelfSubjectAccessReview(
spec=client.V1SelfSubjectAccessReviewSpec(
resource_attributes=client.V1ResourceAttributes(
namespace=NAMESPACE,
verb=verb,
group=group,
resource=resource,
subresource=subresource,
)
)
)
result = auth_api.create_self_subject_access_review(review)
allowed = bool(result.status.allowed)
name = resource if subresource is None else f"{resource}/{subresource}"
print(f"{verb:7} {name:20} {'OK' if allowed else 'DENIED'}")
if not allowed:
denied.append(f"{verb} {name}")
if denied:
raise PermissionError(
"Missing permissions: " + ", ".join(denied)
)
print("RBAC_OK")
Expected result:
create pytorchjobs OK
get pytorchjobs OK
delete pytorchjobs OK
list pods OK
get pods OK
get pods/log OK
list events OK
RBAC_OK
If any permission returns DENIED, stop the test.
Cell 3 – Create the Gloo PyTorchJob
Paste into the third cell and run:
import time
from copy import deepcopy
JOB_NAME = f"gloo-cpu-test-{int(time.time())}"
training_code = r"""
import os
from datetime import timedelta
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
def log(message):
print(message, flush=True)
rank = int(os.environ["RANK"])
world_size = int(os.environ["WORLD_SIZE"])
log(f"[Rank {rank}] START world_size={world_size}")
try:
dist.init_process_group(
backend="gloo",
init_method="env://",
timeout=timedelta(seconds=180),
)
log(f"[Rank {rank}] GLOO_INIT_OK")
value = torch.tensor([float(rank + 1)])
dist.all_reduce(value, op=dist.ReduceOp.SUM)
expected = world_size * (world_size + 1) / 2
actual = value.item()
log(f"[Rank {rank}] ALL_REDUCE={actual}")
assert actual == expected, (
f"all_reduce={actual}, expected={expected}"
)
torch.manual_seed(1234)
model = torch.nn.Linear(1, 1)
model = DDP(model)
optimizer = torch.optim.SGD(
model.parameters(),
lr=0.01,
)
for epoch in range(3):
x = torch.tensor([[float(rank + 1)]])
target = 2.0 * x + 1.0
optimizer.zero_grad()
prediction = model(x)
loss = torch.nn.functional.mse_loss(
prediction,
target,
)
loss.backward()
optimizer.step()
dist.barrier()
log(
f"[Rank {rank}] "
f"EPOCH={epoch + 1} "
f"LOSS={loss.item():.6f}"
)
parameters = torch.cat([
parameter.detach().reshape(-1)
for parameter in model.module.parameters()
])
gathered = [
torch.zeros_like(parameters)
for _ in range(world_size)
]
dist.all_gather(gathered, parameters)
parameters_equal = all(
torch.allclose(
gathered[0],
item,
rtol=1e-5,
atol=1e-6,
)
for item in gathered[1:]
)
log(
f"[Rank {rank}] "
f"PARAMETERS_EQUAL={parameters_equal}"
)
assert parameters_equal
dist.barrier()
log(f"[Rank {rank}] GLOO_TEST_OK")
finally:
if dist.is_initialized():
dist.destroy_process_group()
"""
container = {
"name": "pytorch",
"image": "pytorch/pytorch:latest",
"imagePullPolicy": "IfNotPresent",
"command": ["python", "-u", "-c"],
"args": [training_code],
"env": [
{
"name": "OMP_NUM_THREADS",
"value": "1",
},
{
"name": "MKL_NUM_THREADS",
"value": "1",
},
{
"name": "PYTHONUNBUFFERED",
"value": "1",
},
{
"name": "TORCH_DISTRIBUTED_DEBUG",
"value": "DETAIL",
},
],
"resources": {
"requests": {
"cpu": "500m",
"memory": "1Gi",
},
"limits": {
"cpu": "500m",
"memory": "1Gi",
},
},
}
pod_template = {
"metadata": {
"annotations": {
"sidecar.istio.io/inject": "false",
}
},
"spec": {
"containers": [container],
},
}
job = {
"apiVersion": "kubeflow.org/v1",
"kind": "PyTorchJob",
"metadata": {
"name": JOB_NAME,
"namespace": NAMESPACE,
},
"spec": {
"pytorchReplicaSpecs": {
"Master": {
"replicas": 1,
"restartPolicy": "OnFailure",
"template": deepcopy(pod_template),
},
"Worker": {
"replicas": 2,
"restartPolicy": "OnFailure",
"template": deepcopy(pod_template),
},
}
},
}
custom_api.create_namespaced_custom_object(
group="kubeflow.org",
version="v1",
namespace=NAMESPACE,
plural="pytorchjobs",
body=job,
)
print(f"JOB_CREATED name={JOB_NAME}")
Expected result:
JOB_CREATED name=gloo-cpu-test-<number>
Cell 4 – Monitor the test
Paste into the fourth cell and run:
import time
label_selector = (
f"training.kubeflow.org/job-name={JOB_NAME}"
)
job_succeeded = False
job_failed = False
for attempt in range(60):
job_data = custom_api.get_namespaced_custom_object(
group="kubeflow.org",
version="v1",
namespace=NAMESPACE,
plural="pytorchjobs",
name=JOB_NAME,
)
conditions = job_data.get(
"status",
{},
).get(
"conditions",
[],
)
for condition in conditions:
if (
condition.get("type") == "Succeeded"
and condition.get("status") == "True"
):
job_succeeded = True
if (
condition.get("type") == "Failed"
and condition.get("status") == "True"
):
job_failed = True
pods = core_api.list_namespaced_pod(
namespace=NAMESPACE,
label_selector=label_selector,
).items
phases = {
pod.metadata.name: pod.status.phase
for pod in pods
}
print(
f"{attempt + 1}/60 "
f"pods={phases}"
)
if job_succeeded or job_failed:
break
time.sleep(5)
pods = core_api.list_namespaced_pod(
namespace=NAMESPACE,
label_selector=label_selector,
).items
markers = 0
for pod in sorted(
pods,
key=lambda item: item.metadata.name,
):
name = pod.metadata.name
logs = core_api.read_namespaced_pod_log(
name=name,
namespace=NAMESPACE,
container="pytorch",
)
print("\n" + "=" * 70)
print(name)
print("=" * 70)
print(logs)
if "GLOO_TEST_OK" in logs:
markers += 1
phases = [
pod.status.phase
for pod in pods
]
pods_ok = (
len(pods) == 3
and all(
phase == "Succeeded"
for phase in phases
)
)
print("\n" + "=" * 70)
print(f"PODS_OK={pods_ok}")
print(f"GLOO_TEST_OK={markers}/3")
print(f"PYTORCHJOB_SUCCEEDED={job_succeeded}")
if (
pods_ok
and markers == 3
and job_succeeded
):
print("PASS")
else:
print("FAIL")
Expected final result:
PODS_OK=True
GLOO_TEST_OK=3/3
PYTORCHJOB_SUCCEEDED=True
PASS
Expected log entries in each Pod:
GLOO_INIT_OK
ALL_REDUCE=6.0
PARAMETERS_EQUAL=True
GLOO_TEST_OK
Cell 5 – Delete the test
Paste into the fifth cell and run:
custom_api.delete_namespaced_custom_object(
group="kubeflow.org",
version="v1",
namespace=NAMESPACE,
plural="pytorchjobs",
name=JOB_NAME,
body=client.V1DeleteOptions(
propagation_policy="Foreground",
),
)
print(f"JOB_DELETED name={JOB_NAME}")
Expected result:
JOB_DELETED name=gloo-cpu-test-<number>
What to do next
After completing these Trainer scenarios, you can continue with related MLOps Studio articles.
For more information, see: