Skip to content

Commit 8531d67

Browse files
committed
feat: support LoRA training and conversion using NNX and Qwix
1 parent 2d739e9 commit 8531d67

27 files changed

Lines changed: 1711 additions & 281 deletions

File tree

docs/_static/js/editable_commands.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,16 @@ document.addEventListener('DOMContentLoaded', () => {
1616
"<DATASET_PATH>",
1717
"<GCS_BUCKET>",
1818
"<HF_CKPT_PATH>",
19+
"<HF_LORA_ADAPTER_PATH>",
1920
"<HF_MODEL>",
2021
"<HF_TOKEN>",
2122
"<IMAGE_NAME>",
2223
"<LAZY_LOAD>",
24+
"<LEARNING_RATE>",
25+
"<LORA_ALPHA>",
26+
"<LORA_RANK>",
27+
"<LORA_RESTORE_PATH>",
28+
"<MAX_TARGET_LENGTH>",
2329
"<MODEL_NAME>",
2430
"<NUM_SLICES>",
2531
"<POD_NAME>",

docs/tutorials/post_training_index.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ MaxText was co-designed with key Google led innovations to provide a unified pos
2626
- **SFT (Supervised Fine-Tuning)**
2727
- [SFT on Single-Host TPUs](https://maxtext.readthedocs.io/en/latest/tutorials/posttraining/sft.html)
2828
- [SFT on Multi-Host TPUs](https://maxtext.readthedocs.io/en/latest/tutorials/posttraining/sft_on_multi_host.html)
29+
- **LoRA (Low-Rank Adaptation)**
30+
- [LoRA on Single-Host TPUs](posttraining/lora.md)
2931
- **Multimodal SFT**
3032
- [Multimodal Support](https://maxtext.readthedocs.io/en/latest/tutorials/posttraining/multimodal.html)
3133
- **Reinforcement Learning (RL)**
@@ -68,6 +70,7 @@ posttraining/sft_on_multi_host.md
6870
posttraining/rl.md
6971
posttraining/rl_on_multi_host.md
7072
posttraining/knowledge_distillation.md
73+
posttraining/lora.md
7174
posttraining/multimodal.md
7275
posttraining/full_finetuning.md
7376
posttraining/gepa_optimization.md
Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
<!--
2+
Copyright 2023–2026 Google LLC
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
https://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
-->
16+
17+
# LoRA Fine-tuning on single-host TPUs
18+
19+
**Low-Rank Adaptation (LoRA)** is a Parameter-Efficient Fine-Tuning (PEFT) technique designed to optimize large language models while minimizing resource consumption.
20+
21+
Unlike traditional full-parameter fine-tuning, LoRA:
22+
23+
- **Freezes the pre-trained model weights**, preserving the original knowledge.
24+
- **Injects trainable rank decomposition matrices** into the Transformer layers.
25+
26+
This approach **greatly reduces the number of trainable parameters** required for downstream tasks, making the process faster and more memory-efficient.
27+
28+
This tutorial provides step-by-step instructions for setting up the environment and performing LoRA fine-tuning on a Hugging Face dataset using MaxText.
29+
30+
We use [Tunix](https://github.com/google/tunix), a JAX-based library, to power these post-training tasks.
31+
32+
In this tutorial we use a single host TPU VM such as `v6e-8/v5p-8`. Let's get started!
33+
34+
## Setup environment variables
35+
36+
Login to Hugging Face. Provide your access token when prompted:
37+
38+
```bash
39+
hf auth login
40+
```
41+
42+
Set the following environment variables before running LoRA Fine-tuning.
43+
44+
```sh
45+
# -- Model configuration --
46+
export MODEL_NAME=<MODEL_NAME> # e.g., 'gemma3-4b'
47+
48+
# -- MaxText configuration --
49+
export BASE_OUTPUT_DIRECTORY=<GCS_BUCKET> # e.g., gs://my-bucket/my-output-directory or /path/to/my-output-directory
50+
export RUN_NAME=<RUN_NAME> # e.g., $(date +%Y-%m-%d-%H-%M-%S)
51+
export STEPS=<STEPS> # e.g., 1000
52+
export PER_DEVICE_BATCH_SIZE=<BATCH_SIZE_PER_DEVICE> # e.g., 1
53+
export LORA_RANK=<LORA_RANK> # e.g., 16
54+
export LORA_ALPHA=<LORA_ALPHA> # e.g., 32.0
55+
export LEARNING_RATE=<LEARNING_RATE> # e.g., 3e-6
56+
export MAX_TARGET_LENGTH=<MAX_TARGET_LENGTH> # e.g., 1024
57+
58+
# -- Dataset configuration --
59+
export DATASET_NAME=<DATASET_NAME> # e.g., openai/gsm8k
60+
export TRAIN_SPLIT=<TRAIN_SPLIT> # e.g., train
61+
export HF_DATA_DIR=<DATASET_PATH> # e.g., main
62+
export TRAIN_DATA_COLUMNS=<DATA_COLUMNS> # e.g., ['question','answer']
63+
64+
# -- LoRA Conversion configuration (Optional) --
65+
export HF_LORA_ADAPTER_PATH=<HF_LORA_ADAPTER_PATH> # e.g., 'username/adapter-name'
66+
```
67+
68+
## Customizing Trainable Layers (Optional)
69+
70+
By default, MaxText determines which layers to apply LoRA to based on the model's architecture by reading `src/maxtext/configs/post_train/lora_module_path.yml`.
71+
72+
If you need to fine-tune specific components (e.g., targeting only Attention layers to optimize memory usage), you can override these defaults through the following hierarchy:
73+
74+
### Configuration Hierarchy
75+
76+
1. **Command Line Argument**: Pass the `lora_module_path` argument directly in your training command. This is the most flexible way for experimental iterations.
77+
2. **Task-Specific Config (`sft.yml`)**: Define the `lora_module_path` parameter in `src/maxtext/configs/post_train/sft.yml` to set a persistent configuration for your SFT runs.
78+
3. **Global Defaults**: Automatic detection via the model-to-regex mapping defined in `lora_module_path.yml`.
79+
80+
## Get your model checkpoint
81+
82+
This section explains how to prepare your model checkpoint for use with MaxText. You have two options: using an existing MaxText checkpoint or converting a Hugging Face checkpoint.
83+
84+
### Option 1: Using an existing MaxText checkpoint
85+
86+
If you already have a MaxText-compatible model checkpoint, simply set the following environment variable and move on to the next section.
87+
88+
```sh
89+
export MAXTEXT_CKPT_PATH=<CKPT_PATH> # e.g., gs://my-bucket/my-model-checkpoint/0/items or /path/to/my-model-checkpoint/0/items
90+
```
91+
92+
### Option 2: Converting a Hugging Face checkpoint
93+
94+
Refer to the steps in [Hugging Face to MaxText](https://maxtext.readthedocs.io/en/maxtext-v0.2.1/guides/checkpointing_solutions/convert_checkpoint.html#hugging-face-to-maxtext) to convert a hugging face checkpoint to MaxText. Make sure you have the correct checkpoint files converted and saved. Similar as Option 1, you can set the following environment and move on.
95+
96+
```sh
97+
export MAXTEXT_CKPT_PATH=<CKPT_PATH> # e.g., gs://my-bucket/my-model-checkpoint/0/items or /path/to/my-model-checkpoint/0/items
98+
```
99+
100+
## Run a Fresh LoRA Fine-Tuning on Hugging Face Dataset
101+
102+
Once your environment variables and checkpoints are ready, you can start the LoRA fine-tuning process.
103+
104+
Execute the following command to begin training:
105+
106+
```sh
107+
python3 -m maxtext.trainers.post_train.sft.train_sft \
108+
run_name="${RUN_NAME?}" \
109+
base_output_directory="${BASE_OUTPUT_DIRECTORY?}" \
110+
model_name="${MODEL_NAME?}" \
111+
load_parameters_path="${MAXTEXT_CKPT_PATH?}" \
112+
hf_path="${DATASET_NAME?}" \
113+
train_split="${TRAIN_SPLIT?}" \
114+
hf_data_dir="${HF_DATA_DIR?}" \
115+
train_data_columns="${TRAIN_DATA_COLUMNS?}" \
116+
steps="${STEPS?}" \
117+
per_device_batch_size="${PER_DEVICE_BATCH_SIZE?}" \
118+
max_target_length="${MAX_TARGET_LENGTH?}" \
119+
learning_rate="${LEARNING_RATE?}" \
120+
enable_nnx=True \
121+
pure_nnx_decoder=True \
122+
enable_lora=True \
123+
lora_rank="${LORA_RANK?}" \
124+
lora_alpha="${LORA_ALPHA?}"
125+
```
126+
127+
Your fine-tuned model checkpoints will be saved here: `$BASE_OUTPUT_DIRECTORY/$RUN_NAME/checkpoints`.
128+
129+
## (Optional) Resume from a previous LoRA checkpoint
130+
131+
If you want to resume training from a previous run or further fine-tune an existing LoRA adapter, you can specify the LoRA checkpoint path.
132+
133+
### Step 1: Convert HF LoRA adapter to MaxText format
134+
135+
If your LoRA adapter is currently in Hugging Face format, you must convert it to MaxText format before it can be loaded. Use the integrated conversion utility:
136+
137+
```sh
138+
python3 -m maxtext.checkpoint_conversion.to_maxtext \
139+
model_name="${MODEL_NAME?}" \
140+
hf_lora_adapter_path="${HF_LORA_ADAPTER_PATH?}" \
141+
base_output_directory="${BASE_OUTPUT_DIRECTORY?}/converted_adapter" \
142+
hardware=cpu skip_jax_distributed_system=True
143+
```
144+
145+
### Step 2: Set the restore path
146+
147+
Point `LORA_RESTORE_PATH` to the converted MaxText adapter directory (the directory containing the `0/items` or Orbax files).
148+
149+
- **load_parameters_path**: Points to the frozen base model weights (the original model).
150+
- **lora_restore_path**: Points to the previous LoRA adapter weights you wish to load.
151+
152+
```sh
153+
export LORA_RESTORE_PATH=<LORA_RESTORE_PATH> # e.g., gs://my-bucket/run-1/checkpoints/0/items or /path/to/run-1/checkpoints/0/items
154+
```
155+
156+
### Step 3: Run LoRA Fine-Tuning with the Restore Path
157+
158+
Once your environment variables and checkpoints are ready, you can start the LoRA fine-tuning process.
159+
160+
Execute the following command to begin training:
161+
162+
```sh
163+
python3 -m maxtext.trainers.post_train.sft.train_sft \
164+
run_name="${RUN_NAME?}" \
165+
base_output_directory="${BASE_OUTPUT_DIRECTORY?}" \
166+
model_name="${MODEL_NAME?}" \
167+
load_parameters_path="${MAXTEXT_CKPT_PATH?}" \
168+
lora_restore_path="${LORA_RESTORE_PATH?}" \
169+
hf_path="${DATASET_NAME?}" \
170+
train_split="${TRAIN_SPLIT?}" \
171+
hf_data_dir="${HF_DATA_DIR?}" \
172+
train_data_columns="${TRAIN_DATA_COLUMNS?}" \
173+
steps="${STEPS?}" \
174+
per_device_batch_size="${PER_DEVICE_BATCH_SIZE?}" \
175+
max_target_length="${MAX_TARGET_LENGTH?}" \
176+
learning_rate="${LEARNING_RATE?}" \
177+
enable_nnx=True \
178+
pure_nnx_decoder=True \
179+
enable_lora=True \
180+
lora_rank="${LORA_RANK?}" \
181+
lora_alpha="${LORA_ALPHA?}"
182+
```
183+
184+
Your fine-tuned model checkpoints will be saved here: `$BASE_OUTPUT_DIRECTORY/$RUN_NAME/checkpoints`.
185+
186+
## (Optional) Convert Fine-tuned LoRA to Hugging Face Format
187+
188+
After completing the fine-tuning process, your LoRA weights are stored in MaxText/Orbax format. To use these weights with the Hugging Face ecosystem (e.g., for inference or sharing), convert them back using the `to_huggingface.py` script.
189+
190+
```sh
191+
python3 -m maxtext.checkpoint_conversion.to_huggingface \
192+
model_name="${MODEL_NAME?}" \
193+
lora.lora_restore_path="${BASE_OUTPUT_DIRECTORY?}/${RUN_NAME?}/checkpoints/<STEPS>/model_params" \
194+
base_output_directory="${BASE_OUTPUT_DIRECTORY?}/hf_lora_adapter" \
195+
lora.lora_rank="${LORA_RANK?}" \
196+
lora.lora_alpha="${LORA_ALPHA?}"
197+
```
198+
199+
- `lora.lora_restore_path`: Point this to the specific checkpoint directory (e.g., `.../checkpoints/1000/items`) that you want to export.
200+
- `base_output_directory`: The local or GCS directory where the Hugging Face `adapter_model.safetensors` and `adapter_config.json` will be saved.
201+
- `lora.lora_rank` / `lora.lora_alpha`: Must match the values used during the training phase to ensure the `adapter_config.json` is generated correctly.

pytest.ini

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ addopts =
1414
--ignore=tests/unit/gemma3_layers_test.py
1515
--ignore=tests/unit/gpt_vs_reference_test.py
1616
--ignore=tests/unit/llama4_layers_test.py
17+
--ignore=tests/unit/hf_checkpoint_conversion_test.py
1718
--ignore=tests/unit/yarn_vs_reference_test.py
1819
--ignore=tests/unit/moba_vs_reference_test.py
1920
--ignore=tests/unit/offline_engine_test.py

src/dependencies/requirements/base_requirements/tpu-post-train-requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ google-cloud-storage
1010
google-tunix
1111
gspread
1212
hypothesis
13+
ijson
1314
ipykernel
1415
ipywidgets
15-
ijson
1616
llguidance
1717
loguru
1818
lxml
@@ -21,6 +21,7 @@ openai
2121
openai-harmony
2222
papermill
2323
partial-json-parser
24+
peft
2425
perfetto
2526
prometheus-fastapi-instrumentator
2627
py-cpuinfo

0 commit comments

Comments
 (0)