Files
561e9cf083 feat(docs): add dedicated documentation website (#3308)
* feat(docs): add initial documentation structure and configuration for Kubeflow Trainer

- Introduced .readthedocs.yaml for ReadTheDocs configuration.
- Created Makefile for building and serving documentation.
- Added Sphinx configuration in docs/conf.py.
- Established index.rst as the main entry point for documentation.
- Developed user guides for various frameworks including PyTorch, JAX, and DeepSpeed.
- Implemented custom CSS for documentation styling.
- Included a distributed data cache guide and a DeepSpeed integration guide.

This commit sets up the foundational documentation for the Kubeflow Trainer, enhancing accessibility and usability for users.

Signed-off-by: Sridhar1030 <[email protected]>

* feat(docs): update user guides and restructure documentation for Kubeflow Trainer

- Renamed and reorganized user guides to better serve different audiences: AI practitioners, cluster operators, and contributors.
- Added new sections for documentation on the Kubeflow Training Operator v1 and legacy guides.
- Enhanced descriptions to clarify the purpose and content of each guide, improving overall accessibility and usability.

Signed-off-by: Sridhar1030 <[email protected]>

* feat(docs): add comprehensive operator guides for Kubeflow Trainer

Signed-off-by: Sridhar1030 <[email protected]>

* feat(docs): enhance operator guides for Kubeflow Trainer

Signed-off-by: Sridhar1030 <[email protected]>

* fixed user-guides

Signed-off-by: Sridhar1030 <[email protected]>

* feat(docs): add initial API reference and contributor guides for Kubeflow Trainer

- Introduced API reference documentation for Python SDK and Kubernetes CRD types, including TrainJob, TrainingRuntime, and ClusterTrainingRuntime.
- Created contributor guides covering architecture, community, and contributing processes.
- Added legacy v1 documentation structure with sections for installation and user guides for various frameworks.
- Enhanced local execution documentation with updated examples.

This commit establishes a comprehensive documentation framework to support users and contributors of the Kubeflow Trainer.

Signed-off-by: Sridhar1030 <[email protected]>

* feat(docs): update user guides for distributed training frameworks

- Revised user guides for distributed training with Kubeflow Trainer, including JAX, PyTorch, MLX, DeepSpeed, and the data cache feature.
- Enhanced clarity and structure of documentation to improve user experience and accessibility.
- Added detailed instructions for using TrainJob with various frameworks, emphasizing configuration-driven training and runtime packages.
- Removed outdated content and streamlined sections for better readability.

This commit enhances the documentation framework, making it easier for users to implement distributed training solutions.

Signed-off-by: Sridhar1030 <[email protected]>

* refactor(docs): update index.rst and custom.css for improved documentation layout

- Replaced the old container structure with HTML for doc cards in index.rst, enhancing the visual presentation of quick links.
- Updated CSS styles for doc cards to improve interactivity and appearance, including hover effects and text decoration.
- Added an API Reference section to the documentation layout for better accessibility to technical details.

These changes aim to enhance the user experience and accessibility of the Kubeflow Trainer documentation.

Signed-off-by: Sridhar1030 <[email protected]>

* feat(docs): enhance documentation with new sidebar toggle and external link handling

- Added JavaScript functionality for a collapsible sidebar to improve navigation on larger screens.
- Implemented external link handling to open links in a new tab for better user experience.
- Updated CSS to accommodate new sidebar features and reduce whitespace in the content area.
- Included Sphinx documentation build artifacts in .gitignore for cleaner repository management.

These changes aim to improve the usability and accessibility of the Kubeflow Trainer documentation.

Signed-off-by: Sridhar1030 <[email protected]>

* added leagcy training docs

Signed-off-by: Sridhar1030 <[email protected]>

* refactor(docs): remove API reference section and update documentation layout

- Deleted the API reference section and related files to streamline the documentation.
- Updated index.rst to remove references to the API documentation.
- Enhanced CSS styles for doc cards to improve visual consistency and interactivity.

These changes aim to simplify the documentation structure and improve user navigation within the Kubeflow Trainer documentation.

Signed-off-by: Sridhar1030 <[email protected]>

* refactor(docs): remove CRD API reference generation and update Sphinx configuration

- Eliminated the CRD API reference generation from the Makefile and .readthedocs.yaml to simplify the build process.
- Updated Sphinx configuration to disable fail_on_warning, allowing builds to proceed despite warnings.
- Removed AutoAPI configuration from conf.py and related dependencies from requirements.txt to streamline documentation setup.

These changes aim to enhance the documentation build process and reduce complexity in the project structure.

Signed-off-by: Sridhar1030 <[email protected]>

* feat(docs): expand JAX and MPI user guides with detailed instructions

- Updated the JAX user guide to include comprehensive instructions for creating and monitoring JAX training jobs using the JAXJob custom resource.
- Enhanced the MPI user guide with additional metrics and Docker image building instructions, improving clarity and usability.
- Introduced a new section in the multi-cluster guide detailing the `MultiKueue` feature for efficient management of MPI jobs across clusters.

These changes aim to provide users with clearer guidance and enhance the overall documentation for distributed training frameworks in Kubeflow.

Signed-off-by: Sridhar1030 <[email protected]>

* feat(docs): enhance user guides with grid layout and sidebar improvements

- Introduced a grid layout for the BuiltinTrainer and local execution user guides, improving visual organization and accessibility.
- Added new sections for overview and backend options in the local execution guide, detailing how to run TrainJobs with different backends.
- Updated CSS to make the sidebar sticky during scrolling, enhancing navigation on larger screens.

These changes aim to improve the overall user experience and clarity of the documentation for Kubeflow Trainer.

Signed-off-by: Sridhar1030 <[email protected]>

* fix\(docs\):\ update\ dataset\ download\ instructions\ and\ improve\ links\ in\ user\ guides$'\n'$'\n'-\ Clarified\ that\ each\ rank\ in\ a\ multi-node\ TrainJob\ must\ download\ the\ dataset\ independently.$'\n'-\ Updated\ links\ in\ the\ local\ execution\ and\ Podman\ user\ guides\ to\ point\ directly\ to\ the\ relevant\ sections\ in\ the\ overview.$'\n'-\ Corrected\ the\ path\ for\ accessing\ the\ fine-tuned\ model\ in\ the\ BuiltinTrainer\ guide.$'\n'$'\n'These\ changes\ enhance\ the\ clarity\ and\ usability\ of\ the\ documentation\ for\ Kubeflow\ Trainer. (resolved the copliot reviews)

Signed-off-by: Sridhar1030 <[email protected]>

* docs: update extension framework guide and remove pod template documentation

- Added architecture diagrams to the Kubeflow Trainer Extension Framework guide for better visualization.
- Updated terminology in the index to reflect the transition from Pod Templates to Runtime Patches.
- Removed the outdated PodTemplate documentation to streamline the guides and focus on current practices.

These changes aim to enhance clarity and usability in the documentation for the Kubeflow Trainer.

Signed-off-by: Sridhar1030 <[email protected]>

* docs: update overview and add diagrams

Signed-off-by: Sridhar1030 <[email protected]>

* docs: update Sphinx configuration and improve link references

- Enabled fail_on_warning in Sphinx configuration to ensure builds fail on warnings, enhancing documentation quality.
- Updated links in user guides to point to the correct paths, improving navigation and clarity for users.

These changes aim to enhance the reliability and usability of the documentation for Kubeflow Trainer.

Signed-off-by: Sridhar1030 <[email protected]>

* fixed the MNIST link , updated local process backend to match the main documentation website

Signed-off-by: Sridhar1030 <[email protected]>

* fix(docs): add missing newline at end of file for pre-commit compliance

Signed-off-by: Sridhar1030 <[email protected]>

* fix(docs): remove trailing whitespace in podman guide

Signed-off-by: Sridhar1030 <[email protected]>

* fix(docs): format conf.py for black/flake8 compliance

Signed-off-by: Sridhar1030 <[email protected]>
Made-with: Cursor

* docs: update theme configuration and enhance CSS for improved navigation

- Updated the Furo theme options in `conf.py` to refine color variables for light and dark modes, enhancing visual consistency.
- Introduced a top navigation bar in the CSS with links to examples, GitHub, Slack, and the blog, improving accessibility and user experience.
- Expanded the CSS file to include a comprehensive color palette and responsive design adjustments for better usability across devices.

These changes aim to enhance the overall look and feel of the Kubeflow Trainer documentation, making it more user-friendly and visually appealing.

Signed-off-by: Sridhar1030 <[email protected]>

* fix(docs): wrap long lines in conf.py to satisfy E501 lint
Break announcement HTML string into concatenated short lines
to keep all lines under the 100-character limit.
Ref #3308

Signed-off-by: Sridhar1030 <[email protected]>

* docs: enhance theme configuration and update local execution guides

- Updated color variables in `conf.py` for improved light and dark mode support.
- Refined CSS styles to utilize new color variables, enhancing visual consistency across the documentation.
- Added architecture diagrams for Docker and Podman backends in their respective guides, clarifying the orchestration process.
- Improved the structure and clarity of the local execution documentation, including error handling and configuration examples.

These changes aim to enhance the overall user experience and visual appeal of the Kubeflow Trainer documentation.

Signed-off-by: Sridhar1030 <[email protected]>

* added homepage

Signed-off-by: Sridhar1030 <[email protected]>

* fixed routing

Signed-off-by: Sridhar1030 <[email protected]>

* Added remaining pages

Signed-off-by: Sridhar1030 <[email protected]>

* fix(docs): trim trailing whitespace for pre-commit

Signed-off-by: Sridhar1030 <[email protected]>

* fix(docs): add Kubeflow boilerplate header to conf.py

Required by the code-quality verify-boilerplate check added upstream.

Signed-off-by: Sridhar1030 <[email protected]>

* fix(docs): address PR review feedback

- Consolidate landing page: remove home.rst, migrate links to index.rst
- Vendor overview and data-cache images into docs/images/
- Fix apiVersion v2alpha1 → v1alpha1 in runtime-patches and megatron
- Add missing runtimes to supported-runtimes table
- Expand overview ecosystem list, remove phantom SDK bullet and stray emoji
- Replace hard-coded GitHub stats with ADOPTERS.md link
- Delete kueue.md stub, use external toctree link
- Fix torchtune overview link and wildcard import
- Fix xgboost typos and add distributed training example
- Replace vendored contributing/community with link-out stubs
- Add data-cache architecture diagrams
- Move top nav to Sphinx extension (docs/_ext/kubeflow_topnav/)
- Fix brokeGitHub line anchors in legacy fine-tuning reference
- Add missing import os in legacy getting-started

Signed-off-by: Sridhar1030 <[email protected]>

* docs(operator-guides): add torch envInjection section to ml-policy

Add documentation for torch.envInjection.targets in MLPolicy, allowing
PET_* env vars to be injected into init/sidecar containers.

Ref: kubeflow/website#4399, kubeflow/trainer#3417
Signed-off-by: Sridhar1030 <[email protected]>

---------

Signed-off-by: Sridhar1030 <[email protected]>

Co-authored-by: Hanzo Dev <[email protected]>
2026-06-18 14:29:04 +00:00

12 KiB

PyTorch on AMD ROCm Guide

This guide describes how to use TrainJob to train or fine-tune AI models with PyTorch on AMD ROCm GPUs on Kubernetes.


Prerequisites

Before exploring this guide, make sure to follow:


PyTorch on AMD ROCm Overview

PyTorch on AMD ROCm requires a different runtime environment than the default NVIDIA CUDA runtime. Specifically:

  • Image: You must use an AMD ROCm-compatible PyTorch image (e.g., rocm/pytorch:rocm7.1.1_ubuntu24.04_py3.12_pytorch_release_2.10.0).
  • Resources: You must request amd.com/gpu resources instead of nvidia.com/gpu.
  • Backend: PyTorch torch.distributed with the nccl backend works on ROCm via RCCL, AMD's drop-in NCCL replacement. No code changes are required.

:::{note} The built-in torch-distributed runtime is optimized for NVIDIA CUDA GPUs. For AMD ROCm workloads, you can override the runtime configuration using the Python SDK. :::


PyTorch Distributed Environment on ROCm

Your training script initializes torch.distributed the same way as with NVIDIA GPUs. ROCm exposes AMD GPUs through the CUDA API surface, so torch.cuda calls work without modification.

from kubeflow.trainer import TrainerClient, CustomTrainer
from kubeflow.trainer.options import kubernetes as k8s_options

def train_pytorch_rocm():
    import os
    import torch
    import torch.distributed as dist

    # Initialize distributed training — works identically on ROCm via RCCL.
    dist.init_process_group(backend="nccl")
    local_rank = int(os.environ["LOCAL_RANK"])

    # ROCm exposes AMD GPUs through the CUDA API surface.
    torch.cuda.set_device(local_rank)

    print(f"ROCm training on rank {dist.get_rank()} of {dist.get_world_size()}")
    print(f"Available AMD GPUs: {torch.cuda.device_count()}")
    print(f"Current device: {torch.cuda.current_device()}")

    dist.destroy_process_group()

client = TrainerClient()

# Define AMD GPU tolerations.
# Replace with your cluster's AMD GPU node configuration.
job_patch = k8s_options.RuntimePatch(
    training_runtime_spec=k8s_options.TrainingRuntimeSpecPatch(
        template=k8s_options.JobSetTemplatePatch(
            spec=k8s_options.JobSetSpecPatch(
                replicated_jobs=[
                    k8s_options.ReplicatedJobPatch(
                        name="node",
                        template=k8s_options.JobTemplatePatch(
                            spec=k8s_options.JobSpecPatch(
                                template=k8s_options.PodTemplatePatch(
                                    spec=k8s_options.PodSpecPatch(
                                        tolerations=[
                                            {
                                                "key": "amd.com/gpu",
                                                "operator": "Exists",
                                                "effect": "NoSchedule",
                                            },
                                        ],
                                    )
                                )
                            )
                        )
                    )
                ]
            )
        )
    )
)

# Create TrainJob
job_id = client.train(
    runtime="torch-distributed",
    trainer=CustomTrainer(
        func=train_pytorch_rocm,
        image="rocm/pytorch:rocm7.1.1_ubuntu24.04_py3.12_pytorch_release_2.10.0",
        num_nodes=2,
        resources_per_node={
            "amd.com/gpu": 1,
        },
    ),
    options=[job_patch],
)

# Wait until completion
client.wait_for_job_status(job_id)

# Logs are aggregated from node-0
print("\n".join(client.get_job_logs(name=job_id)))

End-to-end Training Example

The following example demonstrates how to train a simple CNN on the MNIST dataset using PyTorch DDP on AMD ROCm GPUs.

from kubeflow.trainer import TrainerClient, CustomTrainer
from kubeflow.trainer.options import kubernetes as k8s_options

def train_mnist_rocm():
    import os
    import torch
    import torch.distributed as dist
    import torch.nn as nn
    import torch.optim as optim
    from torch.nn.parallel import DistributedDataParallel as DDP
    from torch.utils.data import DataLoader
    from torch.utils.data.distributed import DistributedSampler
    import torchvision
    import torchvision.transforms as transforms

    # Initialize distributed training.
    dist.init_process_group(backend="nccl")
    local_rank = int(os.environ["LOCAL_RANK"])
    torch.cuda.set_device(local_rank)
    device = torch.device("cuda", local_rank)

    rank = dist.get_rank()
    world_size = dist.get_world_size()

    print(f"Process: {rank} of {world_size}")
    print(f"AMD GPU: {torch.cuda.get_device_name(local_rank)}")

    # Model definition.
    class CNN(nn.Module):
        def __init__(self):
            super().__init__()
            self.conv = nn.Sequential(
                nn.Conv2d(1, 32, 3, padding=1),
                nn.ReLU(),
                nn.MaxPool2d(2),
            )
            self.fc = nn.Sequential(
                nn.Linear(32 * 14 * 14, 128),
                nn.ReLU(),
                nn.Linear(128, 10),
            )

        def forward(self, x):
            return self.fc(self.conv(x).flatten(1))

    model = CNN().to(device)

    # Wrap model with DDP.
    # DDP synchronizes gradients across all ranks after each backward pass.
    model = DDP(model, device_ids=[local_rank])

    # Dataset — each worker gets a non-overlapping shard via DistributedSampler.
    transform = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize((0.1307,), (0.3081,)),
    ])

    dataset = torchvision.datasets.MNIST(
        root="/tmp/data", train=True, download=True, transform=transform
    )

    sampler = DistributedSampler(dataset, num_replicas=world_size, rank=rank)
    loader = DataLoader(dataset, batch_size=128, sampler=sampler)

    # Training setup.
    optimizer = optim.Adam(model.parameters(), lr=1e-3)
    criterion = nn.CrossEntropyLoss()

    # Training loop.
    for epoch in range(5):
        sampler.set_epoch(epoch)
        total_loss = 0.0

        for images, labels in loader:
            images, labels = images.to(device), labels.to(device)
            optimizer.zero_grad()
            loss = criterion(model(images), labels)
            loss.backward()
            optimizer.step()
            total_loss += loss.item()

        if rank == 0:
            print(f"Epoch {epoch}, Loss: {total_loss / len(loader):.4f}")

    dist.destroy_process_group()

client = TrainerClient()

# Define AMD GPU tolerations.
job_patch = k8s_options.RuntimePatch(
    training_runtime_spec=k8s_options.TrainingRuntimeSpecPatch(
        template=k8s_options.JobSetTemplatePatch(
            spec=k8s_options.JobSetSpecPatch(
                replicated_jobs=[
                    k8s_options.ReplicatedJobPatch(
                        name="node",
                        template=k8s_options.JobTemplatePatch(
                            spec=k8s_options.JobSpecPatch(
                                template=k8s_options.PodTemplatePatch(
                                    spec=k8s_options.PodSpecPatch(
                                        tolerations=[
                                            {
                                                "key": "amd.com/gpu",
                                                "operator": "Exists",
                                                "effect": "NoSchedule",
                                            },
                                        ],
                                    )
                                )
                            )
                        )
                    )
                ]
            )
        )
    )
)

job_id = client.train(
    runtime="torch-distributed",
    trainer=CustomTrainer(
        func=train_mnist_rocm,
        image="rocm/pytorch:rocm7.1.1_ubuntu24.04_py3.12_pytorch_release_2.10.0",
        num_nodes=2,
        resources_per_node={
            "amd.com/gpu": 1,
        },
    ),
    options=[job_patch],
)

client.wait_for_job_status(job_id)
print("\n".join(client.get_job_logs(name=job_id)))

ROCm Specific Configurations

Resources

AMD ROCm GPUs are exposed in Kubernetes via the AMD GPU device plugin. Specify amd.com/gpu in resources_per_node to request AMD GPU devices:

Resource Description
amd.com/gpu AMD GPU device managed by the AMD GPU Operator. Set the value to match the number of GPUs per node on your hardware (e.g., 8 for MI300X nodes).

Node Selector (optional)

In mixed clusters (AMD and NVIDIA GPU nodes), add a node_selector to ensure pods schedule exclusively on AMD GPU nodes. The AMD GPU Operator labels GPU nodes by default:

Label Value
amd.com/gpu.present true

Tolerations

Depending on your cluster configuration, AMD GPU nodes may have a NoSchedule taint. Add the following toleration if your nodes are tainted:

Toleration Key Toleration Operator Toleration Effect
amd.com/gpu Exists NoSchedule

Environment Variables

Common ROCm environment variables you may need to configure:

Variable Description
HIP_VISIBLE_DEVICES Controls which AMD GPUs are visible to the process. Equivalent to CUDA_VISIBLE_DEVICES on NVIDIA.
NCCL_SOCKET_IFNAME Specifies the network interface RCCL uses for inter-node communication (e.g., eth0).
HSA_FORCE_FINE_GRAIN_PCIE Set to 1 to enable fine-grain PCIe memory, which can improve performance in some multi-GPU configurations.

Reusable ClusterTrainingRuntime

Instead of overriding the runtime configuration via the Python SDK for every TrainJob, cluster administrators can deploy a reusable ClusterTrainingRuntime for AMD ROCm GPUs. This simplifies the user experience by moving infrastructure-specific details out of the training script.

apiVersion: trainer.kubeflow.org/v1alpha1
kind: ClusterTrainingRuntime
metadata:
  name: torch-rocm-distributed
  labels:
    trainer.kubeflow.org/framework: torch
spec:
  mlPolicy:
    numNodes: 2
    torch:
      numProcPerNode: auto
  template:
    spec:
      replicatedJobs:
        - name: node
          template:
            metadata:
              labels:
                trainer.kubeflow.org/trainjob-ancestor-step: trainer
            spec:
              template:
                spec:
                  tolerations:
                    - key: "amd.com/gpu"
                      operator: "Exists"
                      effect: "NoSchedule"
                  containers:
                    - name: node
                      image: rocm/pytorch:rocm7.1.1_ubuntu24.04_py3.12_pytorch_release_2.10.0
                      resources:
                        limits:
                          amd.com/gpu: 1

Users can then submit TrainJobs referencing this runtime without specifying the image, resource limits, or tolerations:

job_id = client.train(
    runtime="torch-rocm-distributed",
    trainer=CustomTrainer(
        func=train_mnist_rocm,
    ),
)

Next Steps