* 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.8 KiB
How to Fine-Tune LLMs with Kubeflow
Overview of the LLM fine-tuning API in the Training Operator
:::{admonition} Old Version :class: warning This page is about Kubeflow Training Operator V1, for the latest information check the Kubeflow Trainer V2 documentation.
Follow this guide for migrating to Kubeflow Trainer V2. :::
This page describes how to use a train API from the Training Python SDK that simplifies the ability to fine-tune LLMs with distributed PyTorchJob workers.
If you want to learn more about how the fine-tuning API fits in the Kubeflow ecosystem, head to the explanation guide.
Prerequisites
You need to install the Training Python SDK with fine-tuning support to run this API.
How to use the Fine-Tuning API?
You need to provide the following parameters to use the train API:
- Number of PyTorch workers and resources per workers.
- Trainer parameters.
- Dataset parameters.
- Pre-trained model parameters.
For example, you can use the train API to fine-tune the BERT model using the Yelp Review dataset from HuggingFace Hub with the code below:
import transformers
from peft import LoraConfig
from kubeflow.training import TrainingClient
from kubeflow.storage_initializer.hugging_face import (
HuggingFaceModelParams,
HuggingFaceTrainerParams,
HuggingFaceDatasetParams,
)
TrainingClient().train(
name="fine-tune-bert",
# BERT model URI and type of Transformer to train it.
model_provider_parameters=HuggingFaceModelParams(
model_uri="hf://google-bert/bert-base-cased",
transformer_type=transformers.AutoModelForSequenceClassification,
),
# Use 3000 samples from Yelp dataset.
dataset_provider_parameters=HuggingFaceDatasetParams(
repo_id="yelp_review_full",
split="train[:3000]",
),
# Specify HuggingFace Trainer parameters. In this example, we will skip evaluation and model checkpoints.
trainer_parameters=HuggingFaceTrainerParams(
training_parameters=transformers.TrainingArguments(
output_dir="test_trainer",
save_strategy="no",
eval_strategy="no",
do_eval=False,
disable_tqdm=True,
log_level="info",
),
# Set LoRA config to reduce number of trainable model parameters.
lora_config=LoraConfig(
r=8,
lora_alpha=8,
lora_dropout=0.1,
bias="none",
),
),
num_workers=4, # nnodes parameter for torchrun command.
num_procs_per_worker=2, # nproc-per-node parameter for torchrun command.
resources_per_worker={
"gpu": 2,
"cpu": 5,
"memory": "10G",
},
)
After you execute train, the Training Operator will orchestrate the appropriate PyTorchJob resources to fine-tune the LLM.
Dataset and Model Parameter Classes
HuggingFaceModelParams
Description
The HuggingFaceModelParams dataclass holds configuration parameters for initializing Hugging Face models with validation checks.
| Attribute | Type | Description |
|---|---|---|
model_uri |
str |
URI or path to the Hugging Face model (must not be empty). |
transformer_type |
TRANSFORMER_TYPES |
Specifies the model type for various NLP/ML tasks. |
access_token |
Optional[str] (default: None) |
Token for accessing private models on Hugging Face. |
num_labels |
Optional[int] (default: None) |
Number of output labels (used for classification tasks). |
Supported Transformer Types (TRANSFORMER_TYPES)
| Model Type | Task |
|---|---|
AutoModelForSequenceClassification |
Text classification |
AutoModelForTokenClassification |
Named entity recognition |
AutoModelForQuestionAnswering |
Question answering |
AutoModelForCausalLM |
Text generation (causal) |
AutoModelForMaskedLM |
Masked language modeling |
AutoModelForImageClassification |
Image classification |
Example Usage
from transformers import AutoModelForSequenceClassification
from kubeflow.storage_initializer.hugging_face import HuggingFaceModelParams
params = HuggingFaceModelParams(
model_uri="bert-base-uncased",
transformer_type=AutoModelForSequenceClassification,
access_token="huggingface_access_token",
num_labels=2 # For binary classification
)
HuggingFaceDatasetParams
Description
The HuggingFaceDatasetParams class holds configuration parameters for loading datasets from Hugging Face with validation checks.
| Attribute | Type | Description |
|---|---|---|
repo_id |
str |
Identifier of the dataset repository on Hugging Face (must not be empty). |
access_token |
Optional[str] (default: None) |
Token for accessing private datasets on Hugging Face. |
split |
Optional[str] (default: None) |
Dataset split to load (e.g., "train", "test"). |
Example Usage
from kubeflow.storage_initializer.hugging_face import HuggingFaceDatasetParams
dataset_params = HuggingFaceDatasetParams(
repo_id="imdb", # Public dataset repository ID on Hugging Face
split="train", # Dataset split to load
access_token=None # Not needed for public datasets
)
HuggingFaceTrainerParams
Description
The HuggingFaceTrainerParams class is used to define parameters for the training process in the Hugging Face framework. It includes the training arguments and LoRA configuration to optimize model training.
| Parameter | Type | Description |
|---|---|---|
training_parameters |
transformers.TrainingArguments |
Contains the training arguments like learning rate, epochs, batch size, etc. |
lora_config |
LoraConfig |
LoRA configuration to reduce the number of trainable parameters in the model. |
Example Usage
from transformers import TrainingArguments
from peft import LoraConfig
from kubeflow.storage_initializer.hugging_face import HuggingFaceTrainerParams
trainer_params = HuggingFaceTrainerParams(
training_parameters=TrainingArguments(
output_dir="results",
learning_rate=2e-5,
num_train_epochs=3,
per_device_train_batch_size=8,
),
lora_config=LoraConfig(
r=8,
lora_alpha=16,
lora_dropout=0.1,
bias="none",
),
)
S3DatasetParams
Description
The S3DatasetParams class is used for loading datasets from S3-compatible object storage. It includes validation checks to ensure proper configuration.
| Parameter | Type | Description |
|---|---|---|
endpoint_url |
str |
URL of the S3-compatible storage service. |
bucket_name |
str |
Name of the S3 bucket containing the dataset. |
file_key |
str |
Key (path) to the dataset file within the bucket. |
region_name |
str, optional |
The AWS region of the S3 bucket (optional). |
access_key |
str, optional |
The access key for authentication with S3 (optional). |
secret_key |
str, optional |
The secret key for authentication with S3 (optional). |
Implementation Details
The S3DatasetParams class includes validation checks to ensure required parameters are provided and the endpoint URL is valid. The actual dataset download is handled by the S3 class which uses boto3 to interact with the S3-compatible storage.
Example Usage
from kubeflow.storage_initializer.s3 import S3DatasetParams
s3_params = S3DatasetParams(
endpoint_url="https://s3.amazonaws.com",
bucket_name="my-dataset-bucket",
file_key="datasets/train.csv",
region_name="us-west-2",
access_key="YOUR_ACCESS_KEY",
secret_key="YOUR_SECRET_KEY"
)
Using custom images with Fine-Tuning API
Platform engineers can customize the storage initializer and trainer images by setting the STORAGE_INITIALIZER_IMAGE and TRAINER_TRANSFORMER_IMAGE environment variables before executing the train command.
For example: In your python code, set the env vars before executing train:
...
os.environ['STORAGE_INITIALIZER_IMAGE'] = 'docker.io/<username>/<custom-storage-initiailizer_image>'
os.environ['TRAINER_TRANSFORMER_IMAGE'] = 'docker.io/<username>/<custom-trainer_transformer_image>'
TrainingClient().train(...)
Next Steps
Run the example to fine-tune the TinyLlama LLM
Check this example to compare the create_job and the train Python API for fine-tuning BERT LLM.
Understand the architecture behind train API.