* 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]>
9.5 KiB
MLX Guide
This guide describes how to use TrainJob to train or fine-tune AI models with MLX.
Prerequisites
Before exploring this guide, make sure to follow the Getting Started guide to understand the basics of Kubeflow Trainer.
MLX Distributed Overview
MLX is a NumPy-like array framework designed for efficient and flexible machine learning, created by Apple machine learning researchers. The main differences between MLX and NumPy are:
-
Composable function transformations: MLX has composable function transformations for automatic differentiation, automatic vectorization, and computation graph optimization.
-
Lazy computation: Computations in MLX are lazy. Arrays are only materialized when needed.
-
Multi-device: Operations can run on any of the supported devices (CPU, GPU, etc.)
In Kubeflow Trainer, MLX distributed training is supported via the MPI backend which enables:
- Data Parallelism: The dataset is sharded across multiple devices, with each device processing a partition of the data and maintaining a copy of the model.
- Gradient Averaging: Gradients are computed locally and then averaged across all processes
using efficient communication primitives like
all_sum(). - Automatic Process Management: MLX handles process initialization and communication setup
through the
mlx.distributedmodule.
MLX with CUDA Backend
Kubeflow Trainer includes an MLX runtime called mlx-distributed.
This runtime installs the CUDA driver and mlx[cuda] package to enable MLX on distributed GPUs.
Currently, you can't use this runtime for non-GPU TrainJobs.
This setup is especially powerful: you can train or fine-tune models on a GPU cluster and then seamlessly evaluate them locally on an Apple silicon machine like in this MNIST example.
Get MLX Runtime Packages
MLX runtime comes with several pre-installed Python packages.
Run the following command to get a list of the available packages:
from kubeflow.trainer import TrainerClient
TrainerClient().get_runtime_packages(
runtime=TrainerClient().get_runtime("mlx-distributed")
)
You should see the installed packages, for example:
Python: 3.10.12 (main, May 27 2025, 17:12:29) [GCC 11.4.0]
Package Version
---------------------- -----------
...
mlx 0.28.0
mlx-cuda 0.28.0
mlx-data 0.1.0
mlx-lm 0.26.3
...
MLX Distributed Environment
Kubeflow Trainer uses the MPI-based runtime and mpirun launcher
to run MLX scripts on every training node. It automatically creates the OpenMPI hostfile to ensure
MLX can discover all MPI nodes, starts the OpenSSH server on the worker nodes, and configures
the distributed MLX environment:
mx.distributed.size()- Total number of processes across all MLX nodes.mx.distributed.rank()- Rank of the current process across all MLX nodes.
You can use these values to, for example, load different data shards on each process,
or evaluate your fine-tuned model only on the process with rank=0 (e.g., the master process).
You can access the distributed environment as follows:
from kubeflow.trainer import TrainerClient, CustomTrainer
def get_mlx_dist():
import mlx.core as mx
# Initialize MLX distributed backend.
dist = mx.distributed.init()
print("MLX Distributed Environment")
print(f"WORLD_SIZE: {dist.size()}")
print(f"RANK: {dist.rank()}")
print(f"Device: {mx.default_device()}")
# Create the TrainJob on 3 nodes.
job_id = TrainerClient().train(
runtime="mlx-distributed",
trainer=CustomTrainer(
func=get_mlx_dist,
num_nodes=3,
resources_per_node={
"gpu": 1,
},
),
)
# Wait for TrainJob to complete.
TrainerClient().wait_for_job_status(job_id)
# Since we launch MLX with `mpirun`, all logs should be consumed from the node-0.
print("\n".join(TrainerClient().get_job_logs(name=job_id)))
You should see the distributed environment as follows:
MLX Distributed Environment
WORLD_SIZE: 3
RANK: 0
Device: Device(gpu, 0)
Fine-Tune LLM with MLX and TrainJob
The following sections describe how to fine-tune Llama using MLX and Kubeflow Trainer.
Configure MLX Training Function
You can leverage the mlx-lm library to
fine-tune and evaluate LLMs. It provides builtin functions for rapid fine-tuning with Low-Rank
Adaptation (LoRA) as well as full model fine-tuning, with support for quantized models.
Wrap your MLX code inside a function and create a TrainJob with the CustomTrainer(). Your function
should handle the end-to-end MLX script including distributed fine-tuning and model evaluation.
:::{note} All necessary imports must be included inside the function body so that the TrainJob can recognize them on every training node. :::
Your training function might look like this:
def fine_tune_llama():
import types
import os
import mlx.core as mx
from mlx_lm.lora import train_model, CONFIG_DEFAULTS
from mlx_lm.tuner.datasets import load_dataset
from mlx_lm.utils import load
from mlx_lm.generate import generate
# Set parameters for the mlx-lm.
args = types.SimpleNamespace()
args.model = "meta-llama/Llama-3.2-3B-Instruct"
args.data = "mlx-community/WikiSQL"
args.train = True
# Set defaults for other required parameters.
for k, v in CONFIG_DEFAULTS.items():
if not hasattr(args, k):
setattr(args, k, v)
# Load pre-trained model and dataset, set your HF token.
os.environ["HF_TOKEN"] = "<YOUR_HF_TOKEN>" # Replace with your Hugging Face token.
model, tokenizer = load(args.model)
train_set, valid_set, _ = load_dataset(args, tokenizer)
# Start the Llama distributed fine-tuning.
train_model(args, model, train_set, valid_set)
# Evaluate the fine-tuned adapter.
dist = mx.distributed.init(strict=True, backend="mpi")
if dist.rank() == 0:
finetuned_model, finetuned_tokenizer = load(
args.model, adapter_path=args.adapter_path
)
# Pass prompt to the fine-tuned LLM.
print(
generate(
model=finetuned_model,
tokenizer=finetuned_tokenizer,
prompt="What is SQL?",
max_tokens=1000,
)
)
Create a TrainJob
After configuring the MLX training function, use the train() API to create a TrainJob:
from kubeflow.trainer import TrainerClient, CustomTrainer
job_id = TrainerClient().train(
runtime="mlx-distributed",
trainer=CustomTrainer(
func=fine_tune_llama,
num_nodes=2,
resources_per_node={
"gpu": 1,
},
),
)
Get the TrainJob Results
You can use the get_job_logs() API to see your TrainJob logs:
print("\n".join(TrainerClient().get_job_logs(name=job_id)))
:::{note} Since MLX training is launched via the mpirun command, all logs can be collected from node-0, which acts as the OpenMPI launcher. :::
You should see the fine-tuning results as follows:
Trainable parameters: 0.041% (1.311M/3212.750M)
Starting training..., iters: 1000
Node 0 of 2
Node 1 of 2
Calculating loss...: 100%|██████████| 25/25 [00:28<00:00, 1.13s/it]
Calculating loss...: 100%|██████████| 25/25 [00:28<00:00, 1.13s/it]
Iter 1: Val loss 2.935, Val took 28.274s
Iter 10: Train loss 2.687, Learning Rate 1.000e-05, It/sec 0.051, Tokens/sec 16.150, Trained Tokens 3137, Peak mem 8.008 GB
Iter 20: Train loss 2.010, Learning Rate 1.000e-05, It/sec 7.467, Tokens/sec 2425.386, Trained Tokens 6385, Peak mem 8.034 GB
Iter 30: Train loss 1.746, Learning Rate 1.000e-05, It/sec 7.789, Tokens/sec 2425.490, Trained Tokens 9499, Peak mem 8.469 GB
Iter 40: Train loss 1.737, Learning Rate 1.000e-05, It/sec 7.643, Tokens/sec 2533.776, Trained Tokens 12814, Peak mem 8.469 GB
...
SQL (Structured Query Language) is a programming language designed for managing and manipulating data stored in relational database management systems (RDBMS).
Gradient Averaging Patterns
MLX provides efficient gradient averaging utilities:
# Method 1: Using mx.distributed.all_sum directly.
averaged_grad = mx_dist.all_sum(gradient) / mx_dist.size()
# Method 2: Using mlx.nn.average_gradients (recommended).
import mlx.nn as nn
gradients = {"layer1": grad1, "layer2": grad2}
averaged_gradients = nn.average_gradients(gradients)
For more information, check the official MLX guides.
Next Steps
- Check out the distributed MNIST example with MLX.
- Follow the complete example to fine-tune Llama3.2 with MLX and Kubeflow Trainer.
- Explore the official MLX documentation.
- Learn more about
TrainerClient()APIs in the Kubeflow SDK.