* 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]>
8.4 KiB
JAX Guide
This guide describes how to use TrainJob to train or fine-tune AI models with JAX.
Prerequisites
Before exploring this guide, make sure to follow the Getting Started guide to understand the basics of Kubeflow Trainer.
JAX Overview
JAX supports distributed and parallel computation through its
jax.distributed
module and Single Program, Multiple Data (SPMD) primitives such as pmap, pjit, and shard_map.
These APIs allow you to scale JAX workloads across multiple devices
and multiple nodes.
Kubeflow Trainer integrates with JAX by:
- Typically launching one worker Pod per JAX process (runtime dependent).
- Injecting the required JAX distributed environment variables.
- Providing consistent process indexing for distributed execution.
With Kubeflow Trainer, you can run:
- Multi-process CPU training
- Multi-GPU training using CUDA-enabled JAX
- Data-parallel and model-parallel JAX workloads
:::{note} The JAX runtime currently supports CPU and GPU workloads only.
TPU workloads are not supported because installing both jax[cuda]
and jax[tpu] in the same image leads to backend and plugin conflicts.
A separate TPU-specific runtime is required.
:::
JAX Runtime in Kubeflow Trainer
Kubeflow Trainer provides a built-in JAX distributed runtime named
jax-distributed.
This runtime:
- Uses the official NVIDIA JAX container image
- Requires no manual configuration of networking
Internally, the runtime maps:
- One Kubernetes Pod → one JAX process
- Multiple devices per Pod → local JAX devices
Get JAX Runtime Packages
Kubeflow Trainer includes a JAX runtime that uses the official NVIDIA JAX container image. This runtime provides native CPU and GPU support and comes with a curated set of pre-installed packages.
Run the following command to inspect the runtime packages:
from kubeflow.trainer import TrainerClient
TrainerClient().get_runtime_packages(
runtime="jax-distributed"
)
You should see the installed packages, for example:
Python: 3.10.12 (main, Feb 25 2026, 20:34:29) [GCC 11.4.0]
Package Version
------------------ -----------
...
Flax 0.11.2
jax 0.7.2
optax 0.2.4
...
JAX Distributed Environment
Your training script must explicitly initialize the JAX distributed runtime before performing any JAX computation.
from kubeflow.trainer import TrainerClient, CustomTrainer
def get_jax_dist():
import os
import jax
import jax.distributed as dist
# Initialize distributed JAX.
dist.initialize(
coordinator_address=os.environ["JAX_COORDINATOR_ADDRESS"],
num_processes=int(os.environ["JAX_NUM_PROCESSES"]),
process_id=int(os.environ["JAX_PROCESS_ID"]),
)
print("JAX Distributed Environment")
print(f"Local devices: {jax.local_devices()}")
print(f"Global device count: {jax.device_count()}")
import jax.numpy as jnp
x = jnp.ones((4,))
y = jax.pmap(lambda v: v * jax.process_index())(x)
print("PMAP result:", y)
client = TrainerClient()
# Create TrainJob
job_id = client.train(
runtime=client.get_runtime("jax-distributed"),
trainer=CustomTrainer(func=get_jax_dist),
)
# 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)))
Environment Variables Injected by the JAX Runtime
The jax-distributed runtime injects environment variables such as
| Variable | Description |
|---|---|
JAX_NUM_PROCESSES |
Total number of JAX processes |
JAX_PROCESS_ID |
Global process index (0-based) |
JAX_COORDINATOR_ADDRESS |
Address of the coordinator (process 0) |
Parallelism with JAX Primitives
Once initialized, you can use JAX SPMD primitives normally:
pmap— data-parallel executionpjit— explicit global shardingshard_map— low-level SPMD control
Kubeflow Trainer does not alter JAX semantics, it only provides the distributed execution environment.
:::{warning} All processes must call jax.distributed.initialize() exactly once and before any JAX computation. Failure to do so may result in deadlocks. :::
Scaling Semantics
In the JAX runtime:
num_nodescontrols the number of worker Pods- Typically one primary JAX process per worker Pod, depending on runtime implementation.
- All Pods run identical code
Results:
- 2 Pods
- 2 JAX processes
- Enabling a single global SPMD execution across processes.
Creating a TrainJob Example with Python SDK
Kubeflow Trainer provides a Python SDK that allows you to programmatically create and submit TrainJobs without writing YAML.
def train_mnist_jax():
import os
import jax
import jax.numpy as jnp
import jax.distributed as dist
import optax
from flax import linen as nn
from flax.training import train_state
import tensorflow_datasets as tfds
# Initialize distributed JAX
dist.initialize(
num_processes=int(os.environ["JAX_NUM_PROCESSES"]),
process_id=int(os.environ["JAX_PROCESS_ID"]),
coordinator_address=os.environ["JAX_COORDINATOR_ADDRESS"],
)
process_index = jax.process_index()
local_device_count = jax.local_device_count()
print("Process:", process_index)
print("Global devices:", jax.device_count())
print("Local devices:", jax.local_devices())
# Model definition
class CNN(nn.Module):
@nn.compact
def __call__(self, x):
x = nn.Conv(features=32, kernel_size=(3, 3))(x)
x = nn.relu(x)
x = nn.avg_pool(x, (2, 2), (2, 2))
x = x.reshape((x.shape[0], -1))
x = nn.Dense(128)(x)
x = nn.relu(x)
x = nn.Dense(10)(x)
return x
# Dataset
ds = tfds.load("mnist", split="train", as_supervised=True)
def preprocess(image, label):
image = jnp.array(image, dtype=jnp.float32) / 255.0
image = jnp.expand_dims(image, -1)
return image, label
ds = ds.map(preprocess).batch(128).prefetch(1)
ds = tfds.as_numpy(ds)
# Training setup
model = CNN()
rng = jax.random.PRNGKey(0)
params = model.init(rng, jnp.ones([1, 28, 28, 1]))["params"]
tx = optax.adam(1e-3)
state = train_state.TrainState.create(
apply_fn=model.apply,
params=params,
tx=tx,
)
# replicate state across local devices
state = jax.device_put_replicated(state, jax.local_devices())
# Training step
def loss_fn(params, batch):
images, labels = batch
logits = model.apply({"params": params}, images)
onehot = jax.nn.one_hot(labels, 10)
loss = optax.softmax_cross_entropy(logits, onehot).mean()
return loss
grad_fn = jax.value_and_grad(loss_fn)
@jax.pmap
def train_step(state, batch):
loss, grads = grad_fn(state.params, batch)
state = state.apply_gradients(grads=grads)
return state, loss
# Training loop
for epoch in range(5):
for images, labels in ds:
# shard batch per device
images = images.reshape(
(local_device_count, -1, 28, 28, 1)
)
labels = labels.reshape(
(local_device_count, -1)
)
state, loss = train_step(state, (images, labels))
if process_index == 0:
print(f"Epoch {epoch}, Loss: {loss.mean()}")
Create a TrainJob
- After defining the training function, create a TrainJob using the SDK.
from kubeflow.trainer import TrainerClient, CustomTrainer
job_id = TrainerClient().train(
runtime=TrainerClient().get_runtime("jax-distributed"),
trainer=CustomTrainer(
func=train_mnist_jax,
packages_to_install=[
"tensorflow-datasets",
"flax",
"optax",
],
num_nodes=2,
resources_per_node={
"gpu": 1,
},
),
)
Get the TrainJob Results
print("\n".join(TrainerClient().get_job_logs(name=job_id)))
Next Steps
- Check out the MNIST JAX example.
- Learn more about
TrainerClient()APIs in the Kubeflow SDK.