This document is relevant for: Trn2, Trn3
Tutorial: Fine-tune a Hugging Face model with LoRA and TRL on Neuron#
This tutorial walks you through LoRA fine-tuning of the Hugging Face
Qwen/Qwen3-1.7B model on AWS Trainium with TorchNeuron and the TRL
SFTTrainer. You train a text-to-SQL adapter with tensor parallelism
across 4 NeuronCores. When you have completed it, you will have a LoRA adapter
saved on your Trainium instance.
Overview#
Supervised fine-tuning (SFT) with LoRA trains a small set of adapter weights
on top of a frozen base model. Hugging Face TRL provides SFTTrainer for
this workflow, and it runs on Neuron with the standard transformers and
peft APIs.
In this tutorial, you:
Convert a text-to-SQL dataset into the chat format that
SFTTraineruses.Load the model with a tensor-parallel plan across 4 NeuronCores.
Apply two Neuron-specific adjustments that make the run 2.8 times faster and make the adapter save correctly.
Launch the run with
torchrunand confirm that the adapter is saved.
Before you start#
This tutorial assumes that you have:
A working TorchNeuron environment. See Quickstart: Install and verify torch-neuronx.
Basic training on Neuron. See Tutorial: Train a simple model on Neuron.
Hugging Face
transformersand the basic idea of LoRA.
Model details#
Model:
Qwen/Qwen3-1.7B, a hybrid reasoning model with 28 decoder layers.Dataset:
fahmiaziz/text2sql-dataset, with 126,641 training rows and the columnsprompt,context, andanswer. The dataset has no test split.b-mc2/sql-create-contextalso works, because it has the same schema with the question in a column namedquestion.Method: LoRA with rank 32 and alpha 16 on all attention and MLP projections (
q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj).Parallelism: tensor parallelism of degree 4 on 4 NeuronCores.
Prerequisites#
A
trn2.3xlargeinstance or larger. The run uses one Trainium2 chip: 4 NeuronCores at the default LNC=2.torch-neuronxinstalled and verifiedHugging Face libraries, in the versions that this tutorial was tested with:
transformers5.14.1,trl1.10.0,peft0.19.1,accelerate1.15.0, anddatasets5.0.0Access to the Hugging Face Hub to download the model and the dataset
Prepare your environment#
Activate the virtual environment that has torch-neuronx, and install the
tested versions of the Hugging Face libraries:
pip install "transformers==5.14.1" "trl==1.10.0" "peft==0.19.1" "accelerate==1.15.0" "datasets==5.0.0"
Create a working directory. In the following steps, you create two files in
it: trl_lora_finetune.py (the training script) and
trl_lora_finetune.sh (the launcher).
mkdir -p ~/trl-lora && cd ~/trl-lora
Step 1: Convert the dataset to chat format#
In this step, you convert each text-to-SQL row into a system, user, and assistant conversation.
SFTTrainer can restrict the loss to the assistant tokens
(--assistant_only_loss true, set in the launch command in Step 5), but only
when the dataset is conversational. The text-to-SQL dataset stores plain
columns, so convert it to a messages column first. This conversion is also
required for the run to start (see Common issues).
Create trl_lora_finetune.py and add the imports and the dataset
conversion:
import os
import shutil
import torch
from accelerate import ParallelismConfig
from datasets import load_dataset
from transformers import AutoModelForCausalLM, Trainer
from trl import ModelConfig, ScriptArguments, SFTConfig, SFTTrainer, TrlParser, get_peft_config
# The two text-to-SQL datasets differ only in the name of the question column.
TEXT2SQL_QUESTION_COLUMNS = ("prompt", "question")
SQL_SYSTEM_PROMPT = (
"You are a SQL expert. Given a database schema and a question, respond with "
"a single SQL query that answers it. Output only the query."
)
def to_sql_messages(example, question_column):
answer = example["answer"].strip()
return {
"messages": [
{"role": "system", "content": SQL_SYSTEM_PROMPT},
{
"role": "user",
"content": (
f"{example[question_column].strip()}\n\n"
f"Schema:\n{example['context'].strip()}"
),
},
# An empty think block matches the Qwen3 chat template with
# enable_thinking=False, so training and serving use the same format.
{"role": "assistant", "content": f"<think>\n\n</think>\n\n{answer}"},
]
}
def prepare_dataset(dataset):
"""Convert a text-to-SQL dataset to conversational form. Others pass through."""
columns = dataset.column_names
question_column = next((c for c in TEXT2SQL_QUESTION_COLUMNS if c in columns), None)
if question_column is None or not {"context", "answer"} <= set(columns):
return dataset
return dataset.map(
to_sql_messages,
fn_kwargs={"question_column": question_column},
remove_columns=columns,
desc="Converting text-to-SQL rows to chat format",
)
Two details in the conversion are important:
The answer starts with an empty
<think>block. Qwen3 emits this block when it generates withenable_thinking=False. Without it, the trained format differs from the format the model is served with.The schema goes in the user turn. It changes on every row, so only the fixed instruction belongs in the system turn.
A dataset that is already conversational, such as trl-lib/Capybara,
passes through unchanged.
Step 2: Define the tensor-parallel plan and the trainer#
In this step, you define how the model weights are split across the 4 NeuronCores, and you define a trainer subclass for Neuron.
Add this code to trl_lora_finetune.py:
# colwise splits the output dimension, rowwise splits the input dimension.
TP_PLAN = {
"model.layers.*.self_attn.q_proj": "colwise",
"model.layers.*.self_attn.k_proj": "colwise",
"model.layers.*.self_attn.v_proj": "colwise",
"model.layers.*.self_attn.o_proj": "rowwise",
"model.layers.*.mlp.gate_proj": "colwise",
"model.layers.*.mlp.up_proj": "colwise",
"model.layers.*.mlp.down_proj": "rowwise",
}
class FastSFTTrainer(SFTTrainer):
"""SFTTrainer without the per-micro-batch entropy and token-accuracy metrics."""
def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
inputs.pop("_prediction_loss_only", None)
inputs["use_cache"] = False
return Trainer.compute_loss(
self, model, inputs, return_outputs=return_outputs, num_items_in_batch=num_items_in_batch
)
SFTTrainer.compute_loss makes a second pass over the logits on every
micro-batch to compute entropy and token accuracy. That pass is outside the
compiled region, so on Neuron each of its operations runs separately in eager
mode. FastSFTTrainer uses Trainer.compute_loss instead. The loss is
the same; only the entropy and mean_token_accuracy log fields are
removed.
Step 3: Add the Neuron-specific adjustments#
In this step, you add two functions that make tensor-parallel LoRA training fast and make the adapter save correctly on Neuron. Without them, the run is about 2.8 times slower and stops before it saves the adapter.
Add this code to trl_lora_finetune.py:
def make_shards_contiguous(model):
"""Repack rank-local weight shards into contiguous memory."""
repacked = 0
for param in model.parameters():
# For a sharded (DTensor) parameter, the rank-local shard must be contiguous.
local = param.to_local() if hasattr(param, "to_local") else param
if local.is_contiguous():
continue
with torch.no_grad():
# set_() keeps the DTensor wrapper and the parameter identity.
local.set_(local.detach().clone(memory_format=torch.contiguous_format))
repacked += 1
return repacked
def make_save_collective_safe(trainer):
"""Run the save on every rank so that the all-gathers match."""
real_save = trainer._save
def _save(output_dir=None, state_dict=None):
output_dir = output_dir or trainer.args.output_dir
discard = not trainer.args.should_save
if discard:
# Same code path and same collectives; the output is discarded.
output_dir = os.path.join(output_dir, f"_rank{trainer.args.process_index}_tmp")
real_save(output_dir, state_dict=state_dict)
if discard:
shutil.rmtree(output_dir, ignore_errors=True)
trainer._save = _save
trainer.save_model = lambda output_dir=None, _internal_call=False: _save(output_dir)
Contiguous shards. rowwise sharding slices the last dimension of a
weight, so each rank’s shard of o_proj and down_proj is a strided view
instead of its own buffer. The runtime then copies these shards on every graph
launch: 56 copies per micro-batch (28 layers x 2 weights). In the measured
run, these copies took 63% of the step time. The weights never change shape,
so one copy at setup removes the copies for the rest of the run.
Collective-safe save. Trainer.save_model saves only on rank 0. With
tensor parallelism, the save all-gathers the sharded adapter weights, and every
rank must join that collective. The other ranks skip the save, so the Neuron
runtime detects mismatched collectives and the run fails before rank 0 writes
the adapter. This function runs the save on every rank and discards the output
of the other ranks.
Step 4: Add the training flow#
In this step, you load the model with the tensor-parallel plan, build the trainer, and apply the adjustments.
Add this code to the end of trl_lora_finetune.py:
def main(script_args, training_args, model_args):
tp_size = int(os.environ.get("TP_SIZE", "1"))
tp_kwargs = {}
if tp_size > 1:
training_args.parallelism_config = ParallelismConfig(tp_size=tp_size)
tp_kwargs = {"tp_plan": TP_PLAN, "tp_size": tp_size}
model = AutoModelForCausalLM.from_pretrained(
model_args.model_name_or_path,
revision=model_args.model_revision,
dtype=torch.bfloat16 if training_args.bf16 else torch.float32,
low_cpu_mem_usage=True,
**tp_kwargs,
)
dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
train_dataset = prepare_dataset(dataset[script_args.dataset_train_split])
trainer = FastSFTTrainer(
model=model,
args=training_args,
train_dataset=train_dataset,
peft_config=get_peft_config(model_args),
)
trainable = sum(p.numel() for p in trainer.model.parameters() if p.requires_grad)
total = sum(p.numel() for p in trainer.model.parameters())
print(f"Trainable: {trainable:,} / {total:,} ({100 * trainable / total:.2f}%)", flush=True)
# Repack after PEFT wrapping, on the model that the runtime executes.
print(f"[repacked {make_shards_contiguous(trainer.model)} shards]", flush=True)
make_save_collective_safe(trainer)
trainer.train()
trainer.save_model(training_args.output_dir)
if __name__ == "__main__":
parser = TrlParser((ScriptArguments, SFTConfig, ModelConfig))
script_args, training_args, model_args, _ = parser.parse_args_and_config(
return_remaining_strings=True
)
main(script_args, training_args, model_args)
Apply make_shards_contiguous to trainer.model, not to model. The
trainer wraps the model with PEFT, and the runtime executes the wrapped model.
Note
This tutorial does not run evaluation. If you set --eval_strategy to a
value other than no, create the evaluation split with a fixed seed, for
example train_dataset.train_test_split(test_size=0.01, seed=training_args.seed).
Every rank must get the same split. Otherwise, the ranks run different
numbers of evaluation batches and stop at the metric all-reduce.
Step 5: Launch the fine-tuning run#
In this step, you create the launcher and start the run on 4 NeuronCores.
Create trl_lora_finetune.sh with this content:
#!/bin/bash
set -euo pipefail
export TP_SIZE=${TP_SIZE:-4}
NUM_PROC=${NUM_PROC:-4}
export OMP_NUM_THREADS=${OMP_NUM_THREADS:-$(( $(nproc) / NUM_PROC ))}
MODEL_NAME=${MODEL_NAME:-Qwen/Qwen3-1.7B}
DATASET_NAME=${DATASET_NAME:-fahmiaziz/text2sql-dataset}
OUTPUT_DIR=${OUTPUT_DIR:-Qwen3-1.7B-SFT-LoRA-sql}
MAX_SEQ_LENGTH=${MAX_SEQ_LENGTH:-512}
MAX_STEPS=${MAX_STEPS:-300}
torchrun --nproc_per_node="${NUM_PROC}" \
trl_lora_finetune.py \
--model_name_or_path "$MODEL_NAME" \
--dataset_name "$DATASET_NAME" \
--learning_rate 5.0e-4 \
--num_train_epochs 1 \
--max_steps "$MAX_STEPS" \
--packing false \
--pad_to_multiple_of "$MAX_SEQ_LENGTH" \
--max_length "$MAX_SEQ_LENGTH" \
--bf16 true \
--per_device_train_batch_size 4 \
--gradient_accumulation_steps 8 \
--loss_type nll \
--assistant_only_loss true \
--torch_compile \
--eos_token '<|im_end|>' \
--eval_strategy no \
--logging_steps 10 \
--dataloader_drop_last true \
--dataloader_num_workers 4 \
--save_steps 100 \
--save_total_limit 2 \
--warmup_steps 100 \
--weight_decay 0.01 \
--max_grad_norm 1.0 \
--use_peft true \
--lora_r 32 \
--lora_alpha 16 \
--lora_dropout 0.0 \
--lora_target_modules q_proj k_proj v_proj o_proj gate_proj up_proj down_proj \
--report_to none \
--output_dir "$OUTPUT_DIR"
Run it:
chmod +x trl_lora_finetune.sh
./trl_lora_finetune.sh
Notes on the settings:
NUM_PROCis 4 andTP_SIZEis 4, so the run uses one tensor-parallel group and no data parallelism. The effective batch size is 4 x 8 = 32 sequences per optimizer step.--pad_to_multiple_ofpads every sequence toMAX_SEQ_LENGTH, so the compiled graph sees one static shape. All rows of this dataset fit in 512 tokens, with a median of 148. A longer value adds only padding. For a dataset with longer rows, such astrl-lib/Capybara, setMAX_SEQ_LENGTH=1024.MAX_STEPS=300trains on 9,600 rows, which is about 0.076 epoch. For a full epoch, setMAX_STEPS=-1. A full epoch is about 3,957 steps, or about 4 hours at the measured step time.--save_steps 100writes a checkpoint (about 285 MB) every 100 steps, and--save_total_limit 2keeps the last two. A failure late in the run then does not lose all progress.OUTPUT_DIRis named for the dataset. TRL writes the adapter files directly into the output directory, so a shared name can overwrite an adapter from a different run.
The first steps are slower, because the Neuron compiler compiles the training graphs. Later steps reuse the compiled graphs.
Confirmation#
When the run starts, the script prints the trainable-parameter count and the number of repacked shards:
Trainable: ... / ... (...%)
[repacked ... shards]
A repacked count above zero confirms that make_shards_contiguous found and
fixed the strided rowwise shards.
During training, SFTTrainer logs the loss every 10 steps. The loss
decreases over the first few hundred steps.
When the run ends, confirm that the adapter is saved:
ls Qwen3-1.7B-SFT-LoRA-sql/
The directory contains adapter_model.safetensors and
adapter_config.json, and the checkpoint-* directories from the
periodic saves. Only one copy of the adapter is written; the other ranks’
temporary directories are removed.
Congratulations! You have fine-tuned Qwen3-1.7B with LoRA on AWS Trainium using TRL. If you encountered any issues, see the Common issues section below.
Benchmarks#
Step time with the settings in this tutorial (one Trainium2 chip, 4 NeuronCores, TP=4, effective batch 32, sequence length 512 for text2sql):
Without
make_shards_contiguous: 10.33 s/step.With
make_shards_contiguous: 3.67 s/step, 2.8 times faster.
Common issues#
ValueError from SFTTrainer when you use
--assistant_only_loss true: The dataset is not conversational.text2sql-datasethas a plain-stringpromptcolumn, not a list of messages. Convert the dataset withprepare_dataset(Step 1).KeyError: ‘completion’:
SFTTrainerroutes any row with a column namedpromptdown the prompt-completion path, which expects acompletioncolumn. Convert the dataset tomessages(Step 1).The run fails at save with “failed signature check from peer”: Only rank 0 ran the save, so the ranks ran mismatched collectives. The traceback points to a later
torch.distributed.barrier(), but the cause is the save. Applymake_save_collective_safe(Step 3).No adapter in the output directory after a run that seemed to finish: This is the same save issue. Rank 0 fails inside the all-gather before it writes any file. Apply
make_save_collective_safe(Step 3).Each step takes about 10 seconds instead of about 4: The
rowwiseshards are strided, and the runtime copies them on every graph launch. Applymake_shards_contiguoustotrainer.model(Steps 3 and 4).The run stops at the metric all-reduce during evaluation: The ranks created different evaluation splits. Create the split with a fixed seed (see the note in Step 4).
The model does not stop generating after the SQL query: The EOS token was not trained. Use the conversational format, which trains the EOS token, and keep
--eos_token '<|im_end|>'.
Clean up#
Stop the run with Ctrl+C if it is still running. To free disk space,
delete the checkpoints and keep only the final adapter:
rm -rf Qwen3-1.7B-SFT-LoRA-sql/checkpoint-*
Next steps#
Tutorial: Train with DDP, FSDP2, and DTensor on Neuron — Scale training across more NeuronCores and instances.
Further reading#
How to use torch.distributed on Neuron — Distributed training with torch-neuronx.
TRL SFTTrainer documentation — SFTTrainer options and dataset formats.
PEFT LoRA documentation — LoRA configuration options.
This document is relevant for: Trn2, Trn3