Run Python code as a MLOps Studio PyTorchJob

This guide explains how to package existing Python code as a PyTorchJob and run it inside the MLOps Studio cluster.

Introduction

One way to move Python code into MLOps Studio is to package it as a training job and run it inside the cluster.

This approach is useful when your code is already prepared as a script and you want to execute it in a more automated and repeatable way. Unlike an interactive notebook environment, a PyTorchJob is submitted to the cluster, scheduled as a workload, and then monitored until it completes.

Overview

In this article, you will run a Python script that verifies whether terratorch, geopandas, and PyTorch are working correctly inside a MLOps Studio job.

The workflow consists of the following steps:

  • prepare a Python script,

  • upload the script into a ConfigMap,

  • create a PVC for Python libraries,

  • run the code as a PyTorchJob,

  • monitor the job,

  • verify that it completed successfully.

The example installs required system and Python libraries inside the container before running the script. This makes the example useful for testing the execution model, but for production workloads you may prefer to prepare a custom image with the required dependencies already installed.

Prerequisites

Before starting, make sure that the following requirements are met.

No. 1 Access to the MLOps Studio workspace

You can sign in to the MLOps Platform and open your workspace.

See Access the MLOps Studio workspace.

No. 2 Existing namespace

A namespace has already been created.

See Create and manage a MLOps Studio namespace.

No. 3 kubeconfig and kubectl

You have downloaded kubeconfig for your namespace and configured kubectl on your local machine.

See Download and use kubeconfig for a MLOps Studio namespace.

No. 4 Available quota

Your namespace has enough CPU, memory, storage, and GPU quota for the workload that you want to run.

No. 5 Permission to create resources

You have permission to create ConfigMaps, PVCs, and PyTorchJob resources in your namespace.

No. 6 Required dependencies

You know which Python and system libraries your workload requires.

In this example, the workload uses terratorch, geopandas, and PyTorch. It also installs system libraries required by the Python packages used in the test.

Prepare the Python script

Create a local Python file named terra-test.py.

The example below verifies whether terratorch and geopandas are working correctly.

import sys
import importlib

def print_status(component, status, message=""):
    symbol = "✅" if status else "❌"
    print(f"{symbol} {component}: {message}")

print("--- Starting Environment Verification ---\n")

# --- 1. Verify GeoPandas ---
try:
    import geopandas as gpd
    from shapely.geometry import Point

    # Create a simple GeoDataFrame to test PROJ and GDAL backends
    d = {'col1': ['name1', 'name2'], 'geometry': [Point(1, 2), Point(2, 1)]}
    gdf = gpd.GeoDataFrame(d, crs="EPSG:4326")

    # Perform a coordinate transformation (tests PROJ)
    gdf_projected = gdf.to_crs("EPSG:3857")

    print_status("GeoPandas", True, f"Version {gpd.__version__} installed.")
    print(f"   > Test Operation: Successfully created and projected {len(gdf)} points.")

except ImportError:
    print_status("GeoPandas", False, "Module not found.")
except Exception as e:
    print_status("GeoPandas", False, f"Runtime Error: {e}")

print("-" * 30)

# --- 2. Verify PyTorch (Prerequisite for Terratorch) ---
try:
    import torch
    cuda_available = torch.cuda.is_available()
    device_name = torch.cuda.get_device_name(0) if cuda_available else "CPU only"

    print_status("PyTorch", True, f"Version {torch.__version__}")
    print(f"   > Compute Device: {device_name}")

except ImportError:
    print_status("PyTorch", False, "Module not found (Terratorch will fail).")

print("-" * 30)

# --- 3. Verify Terratorch ---
try:
    import terratorch
    # Check if we can access the model registry (confirms internal logic is working)
    from terratorch import BACKBONE_REGISTRY

    available_models = len(BACKBONE_REGISTRY)

    print_status("Terratorch", True, "Successfully imported.")
    print(f"   > Registry Check: Accessible ({available_models} backbones registered).")

except ImportError:
    print_status("Terratorch", False, "Module not found.")
except AttributeError:
    # Fallback if registry structure has changed in a specific version
    print_status("Terratorch", True, "Imported (Registry check skipped).")
except Exception as e:
    print_status("Terratorch", False, f"Runtime Error: {e}")

print("\n--- Verification Complete ---")

This script does not train a model. It is a verification workload that checks whether the container can import the required libraries and use the expected runtime environment.

Create a ConfigMap from the script

To run the script inside the cluster, upload it into a ConfigMap.

If the file is named terra-test.py, create the ConfigMap with kubectl:

kubectl create configmap terra-test --from-file=terra-test.py -n yourNamespace

Replace yourNamespace with your actual namespace.

The ConfigMap makes the script available inside the container that runs the PyTorchJob.

Prepare the PyTorchJob manifest

Create a file named script.yaml.

The YAML file below creates a 10 GiB PVC for Python libraries and then runs a PyTorchJob that executes the script stored in the ConfigMap.

Before using the manifest, replace the example values with values for your namespace and workload:

  • yourNamespace – namespace where the PVC and PyTorchJob will be created.

  • verify-geopandas-terratorch – name of the PyTorchJob.

  • terra-test – name of the ConfigMap that contains the Python script.

  • terra-test.py – name of the Python script executed inside the container.

  • pytorch/pytorch:2.1.0-cuda12.1-cudnn8-runtime – container image used by the job.

  • libgdal-dev libjpeg-dev libpng-dev – system libraries installed before the script runs.

  • terratorch geopandas – Python libraries installed before the script runs.

  • cpu, memory, and nvidia.com/gpu – resource limits requested by the job.

  • 10Gi – size of the PVC used for Python library caching.

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pip-cache-pvc
  namespace: yourNamespace  # REPLACE with your actual namespace
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
---

apiVersion: "kubeflow.org/v1"
kind: PyTorchJob
metadata:
  name: verify-geopandas-terratorch
  namespace: yourNamespace # REPLACE with your actual namespace
spec:
  pytorchReplicaSpecs:
    Master:
      replicas: 1
      restartPolicy: OnFailure
      template:
        spec:
          containers:
            - name: pytorch

              image: pytorch/pytorch:2.1.0-cuda12.1-cudnn8-runtime
              env:
                - name: PYTHONPATH
                  value: "/mnt/libs"

              command:
                - "/bin/bash"
                - "-c"
                - |
                  echo "--- 1. System Setup ---"
                  export DEBIAN_FRONTEND=noninteractive
                  export TZ=Etc/UTC
                  apt-get update && apt-get install -y libgdal-dev libjpeg-dev libpng-dev # ADD different system libraries if needed
                  pip config set global.cache-dir /mnt/libs
                  echo "--- 2. Installing Dependencies ---"
                  pip install terratorch geopandas # ADD different python libraries if needed

                  echo "--- 3. Running Verification ---"
                  python /var/script/terra-test.py # REPLACE with the actual name of your script inside the container

              resources:
                limits:
                  nvidia.com/gpu: 1
                  memory: "16Gi"
                  cpu: "2"

              volumeMounts:
                - name: script-volume
                  mountPath: /var/script
                - name: pip-libs-volume
                  mountPath: /mnt/libs
                - name: dshm-volume
                  mountPath: /dev/shm

          volumes:
            - name: script-volume
              configMap:
                name: terra-test # REPLACE with the actual name of your ConfigMap containing the Python script
            - name: pip-libs-volume
              persistentVolumeClaim:
                claimName: pip-cache-pvc
            - name: dshm-volume
              emptyDir:
                medium: Memory

The manifest contains two resources:

  • PersistentVolumeClaim named pip-cache-pvc, used for Python library caching.

  • PyTorchJob named verify-geopandas-terratorch, used to run the Python verification script.

Apply the manifest

Save the YAML file and apply it with kubectl:

kubectl apply -f script.yaml -n yourNamespace

Replace yourNamespace with your actual namespace.

The cluster creates the PVC first, then starts the PyTorchJob.

Monitor the job

To monitor the job, inspect the PyTorchJob resource with kubectl:

kubectl describe pytorchjob verify-geopandas-terratorch -n yourNamespace

A successful run may contain status information similar to the example below:

Name:         verify-geopandas-terratorch
Namespace:    yourNamespace
API Version:  kubeflow.org/v1
Kind:         PyTorchJob

Status:
  Completion Time:  2026-02-18T11:58:26Z
  Conditions:
    Last Transition Time:  2026-02-18T11:50:39Z
    Last Update Time:      2026-02-18T11:50:39Z
    Message:               PyTorchJob verify-geopandas-terratorch is created.
    Reason:                PyTorchJobCreated
    Status:                True
    Type:                  Created

    Last Transition Time:  2026-02-18T11:52:03Z
    Last Update Time:      2026-02-18T11:52:03Z
    Message:               PyTorchJob verify-geopandas-terratorch is running.
    Reason:                PyTorchJobRunning
    Status:                False
    Type:                  Running

    Last Transition Time:  2026-02-18T11:58:26Z
    Last Update Time:      2026-02-18T11:58:26Z
    Message:               PyTorchJob verify-geopandas-terratorch is successfully completed.
    Reason:                PyTorchJobSucceeded
    Status:                True
    Type:                  Succeeded

  Replica Statuses:
    Master:
      Succeeded:  1

The most important part is the final condition:

Reason:                PyTorchJobSucceeded
Status:                True
Type:                  Succeeded

This confirms that the job completed successfully.

Check the job pods

You can also list the pods in the namespace:

kubectl get pods -n yourNamespace

Look for a pod created for the PyTorchJob.

To inspect the pod logs, first identify the pod name, then run:

kubectl logs <pod-name> -n yourNamespace

Replace <pod-name> with the actual pod name.

The logs should show the system setup, dependency installation, and verification output from the Python script.

Adjust the job for your own workload

The example is designed to verify the runtime environment. For your own workload, adjust the manifest before applying it.

The most common changes are:

  • change the namespace,

  • change the job name,

  • change the ConfigMap name,

  • change the script name,

  • use another container image,

  • add or remove system libraries,

  • add or remove Python packages,

  • adjust CPU, memory, and GPU limits,

  • change the PVC size.

For example, if your script does not require GPU access, remove this part from the manifest:

nvidia.com/gpu: 1

If your script requires more memory, adjust the memory limit:

memory: "32Gi"

If you already have a custom image with all dependencies installed, you can remove the package installation commands and use your own image instead.

Clean up resources

After testing, remove the resources that you no longer need.

Delete the PyTorchJob:

kubectl delete pytorchjob verify-geopandas-terratorch -n yourNamespace

Delete the ConfigMap:

kubectl delete configmap terra-test -n yourNamespace

Delete the PVC if you no longer need the cached Python libraries:

kubectl delete pvc pip-cache-pvc -n yourNamespace

Warning

Deleting the PVC removes the data stored in it. Delete it only if you are sure that the cached libraries or other stored files are no longer needed.

What to do next

After verifying that your Python code can run as a PyTorchJob, you can adapt the same structure for your own workload.

For production workloads, consider preparing a dedicated container image with the required system and Python dependencies already installed. This makes jobs faster to start and easier to reproduce.