Skip to content
All guides

Guide · Train

Fine-tuning an open model with LoRA and QLoRA

When fine-tuning beats prompting and retrieval, how to prepare the data and the baseline, and a Hugging Face TRL recipe for QLoRA on Qwen3.5-9B on one 24 GB GPU, through the eval gate to serving with vLLM.

Suraj Malthumkar15 min readFacts, prices and versions checked November 23, 2026

Fine-tuning changes a model's weights so it does one job your way: your output format, your labels, your tone, your domain vocabulary. In our model lifecycle it is step 3. Data and a baseline evaluation come before it; reinforcement learning and the eval gate come after.

Versions

Training code was checked against TRL 1.18.2, PEFT 0.22.0, Transformers 5.24.0 and Datasets 5.2.0, the current releases on 23 November 2026. We ran the Python end to end on CPU with a tiny test model of the same architecture; the 4-bit path needs a CUDA GPU, and the GPU settings are sized, not benchmarked. Serving with vLLM 0.34.0 needs its own environment, because vLLM 0.34.0 requires Transformers 5.16.1 or later but older than 5.23. Pin versions: these libraries rename arguments between minor releases.

Climb the ladder one rung at a time

Each rung costs more to build and maintain than the one below it. Move up only when the cheaper option has measurably failed on your test set.

RungWhat it fixesWhat it does not fix
1. PromptingInstructions, output format, a few worked examplesBehavior the model will not hold across thousands of inputs
2. Retrieval (RAG)Facts the model lacks, facts that change, citationsOutput style, task skill
3. Fine-tuning (SFT)Format, tone, labels, domain patterns; a small model doing one narrow job wellFacts that change every week; skills the model lacks entirely
4. Reinforcement learningCorrectness you can check automaticallyAnything you cannot score

Fine-tuning earns its place for consistent structured output at volume, for a small self-hosted model that must match a large API model on one narrow task, or for behavior easier to show in a thousand examples than to describe. Changing knowledge belongs in retrieval.

Measure a baseline before you train

Score these on the same held-out test set, with the same harness:

  • the base model you plan to fine-tune, with your best prompt;
  • the same model with retrieval, if facts matter for the task;
  • the API model you would otherwise use.

Record the task metric, cost per thousand requests and p95 latency for each. These are the numbers the fine-tuned model must beat at the eval gate. If prompting or retrieval already clears the bar, ship that. In our lifecycle, this is where we stop and say so.

Prepare the data

Use chat messages in JSONL

One example per line, each a messages list of role and content pairs. This ChatML-style format is the de facto standard across training tools, and TRL reads it directly. The running example here, and in the reinforcement fine-tuning guide, extracts invoice fields into JSON:

{"messages": [{"role": "system", "content": "Extract the invoice fields as JSON."}, {"role": "user", "content": "Invoice INV-2291 from Acme Supplies. Total due: USD 1,240.00."}, {"role": "assistant", "content": "{\"vendor\": \"Acme Supplies\", \"invoice_number\": \"INV-2291\", \"total\": 1240.0, \"currency\": \"USD\"}"}]}

How much data you need

Unsloth recommends a bare minimum of 100 rows for reasonable results, and more than 1,000 for better ones. It also stresses that results depend heavily on data quality (Unsloth datasets guide). Clean, consistent labels matter more than raw count.

Clean it, strip personal data, deduplicate

  • Fix or drop wrong examples. The model learns your mistakes as faithfully as your good answers.
  • Remove personal data the task does not need: names, emails, phone numbers, account numbers. Run a detector, review a sample by hand, and swap values for consistent placeholders. Fine-tuned weights can memorize training text, and European regulators have said a model trained on personal data is not automatically anonymous (EDPB Opinion 28/2024).
  • Deduplicate exact and near-duplicate rows. Duplicates overweight some patterns and leak across splits.
  • Read the rendered template. Render one example with apply_chat_template and read it; special tokens and thinking blocks hide silent bugs.

Hold out a test set and keep it clean

  • Split before you augment or generate synthetic data, and generate only from the training split.
  • Split by group, not by row. All examples from one customer, document or ticket thread go to the same split.
  • Deduplicate across splits after normalizing whitespace and case.
  • Keep three splits: train; validation, for choosing checkpoints and hyperparameters; and test, scored once per candidate at the eval gate.
  • Freeze and version the test set so scores stay comparable.

LoRA, QLoRA or full fine-tuning

  • Full fine-tuning updates every weight and holds gradients and optimizer state for all of them. Axolotl lists about 61 GiB peak memory for a full vision-and-text fine-tune of Qwen3.5-9B (Axolotl Qwen3.5 examples).
  • LoRA freezes the base weights and trains small low-rank adapters on chosen layers, saved as a small file you can swap at serving time.
  • QLoRA is LoRA on a base model stored in 4-bit NF4. It cuts memory again, at some cost in speed.

Thinking Machines' LoRA Without Regret (September 2025) is the clearest recent evidence on when LoRA is enough:

  • On small-to-medium instruction-tuning and reasoning datasets, LoRA performs the same as full fine-tuning. On datasets that exceed its capacity, it underperforms.
  • Apply it to all layers, especially the MLP layers. Attention-only LoRA significantly underperforms.
  • The best LoRA learning rate was consistently about 10x the full fine-tuning rate.
  • LoRA is less tolerant of large batch sizes than full fine-tuning.
  • LoRA uses slightly more than two-thirds of the FLOPs of full fine-tuning per pass.

For a narrow task with a few thousand examples, start with LoRA. Keep full fine-tuning for very large datasets or continued pretraining.

Unsloth publishes minimum VRAM for its own trainer (Unsloth requirements):

Model sizeQLoRA (4-bit)LoRA (16-bit)
7B5 GB19 GB
8B6 GB22 GB
9B6.5 GB24 GB
14B8.5 GB33 GB
27B22 GB64 GB
32B26 GB76 GB
70B41 GB164 GB

Unsloth calls these absolute minimums, measured with its own optimizations. Plain Transformers and PEFT need more, and longer sequences add activation memory, so a 9B model on a 24 GB card points to QLoRA.

Worked example: QLoRA on Qwen3.5-9B with TRL

The model is Qwen3.5-9B, released under Apache-2.0. Two details shape the script:

  • It is a vision-language model whose language layers mix Gated DeltaNet linear attention with standard attention. We put adapters on the language model's main linear projections only: 200 modules and about 40M trainable parameters, 0.42% of the model.
  • It thinks by default, writing a reasoning block before the answer. Extraction needs direct answers, so the script turns thinking off during training, and you do the same at inference.

We sized the settings for one 24 GB GPU such as an L4 or A10G. If you run out of memory, halve per_device_train_batch_size and double gradient_accumulation_steps.

pip install "trl==1.18.2" "peft==0.22.0" "transformers==5.24.0" "datasets==5.2.0" "bitsandbytes==0.50.2" torchvision pillow
pip install flash-linear-attention

Qwen3.5's processor needs torchvision and Pillow even for text-only training, so install the torchvision build that matches your PyTorch. Without flash-linear-attention, Transformers warns that it falls back to a much slower reference implementation of the Gated DeltaNet layers.

import torch
from datasets import load_dataset
from peft import LoraConfig
from transformers import BitsAndBytesConfig
from trl import SFTConfig, SFTTrainer
 
MODEL = "Qwen/Qwen3.5-9B"
 
raw = load_dataset(
    "json",
    data_files={"train": "data/train.jsonl", "validation": "data/val.jsonl"},
)
 
def to_prompt_completion(example):
    messages = example["messages"]
    return {
        "prompt": messages[:-1],      # system and user turns: no loss here
        "completion": messages[-1:],  # the assistant answer: loss is computed here
        "chat_template_kwargs": {"enable_thinking": False},
    }
 
data = raw.map(to_prompt_completion, remove_columns=raw["train"].column_names)
 
bnb = BitsAndBytesConfig(  # QLoRA: the frozen base weights are stored in 4-bit NF4
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_use_double_quant=True,
    bnb_4bit_compute_dtype=torch.bfloat16,
)
 
lora = LoraConfig(
    r=16,
    lora_alpha=32,
    lora_dropout=0.05,
    task_type="CAUSAL_LM",
    # The language model's main projections, Gated DeltaNet ones included.
    # "all-linear" would also wrap the vision encoder.
    target_modules=[
        "q_proj", "k_proj", "v_proj", "o_proj",
        "in_proj_qkv", "in_proj_z", "out_proj",
        "gate_proj", "up_proj", "down_proj",
    ],
)
 
args = SFTConfig(
    output_dir="out/qwen35-9b-qlora",
    model_init_kwargs={"dtype": torch.bfloat16},  # TRL loads in float32 otherwise
    max_length=2048,
    per_device_train_batch_size=2,
    gradient_accumulation_steps=8,  # 16 sequences per optimizer step
    num_train_epochs=2,
    learning_rate=2e-4,
    lr_scheduler_type="cosine",
    warmup_steps=0.05,  # under 1 means a fraction of total steps
    eval_strategy="steps",
    eval_steps=50,
    save_steps=50,
    logging_steps=10,
    report_to="none",
)
 
trainer = SFTTrainer(
    model=MODEL,
    args=args,
    train_dataset=data["train"],
    eval_dataset=data["validation"],
    peft_config=lora,
    quantization_config=bnb,  # delete this line for plain 16-bit LoRA
)
trainer.train()
trainer.save_model()  # saves the adapter, not a copy of the base model

What the choices do:

  • Prompt and completion. With data split this way, TRL computes the loss on the final assistant answer only. To train on every assistant turn of a multi-turn conversation, keep messages and set assistant_only_loss=True; TRL ships a patched Qwen3.5 training template for it.
  • The chat_template_kwargs column is passed to the chat template per example. With thinking off, the empty reasoning block lands in the prompt, so the model learns to answer directly.
  • Target modules. PEFT's "all-linear" is the right default for text-only models. On Qwen3.5 it would also wrap the vision encoder, so the list names the language model's main projections and skips the small in_proj_a and in_proj_b ones. Adding the Gated DeltaNet projections follows the advice in Axolotl's Qwen3.5 README.
  • Rank 16, alpha 32, learning rate 2e-4. A common start. TRL's docs suggest about 1e-4 for adapters and Axolotl's Qwen3.5 example uses 2e-4, so try both. The effective batch of 16 is modest because LoRA dislikes large batches.
  • Defaults. SFTConfig turns on gradient checkpointing and bf16. Packing stays off: Axolotl's notes say packing through Gated DeltaNet layers requires flash-linear-attention.

Choose the checkpoint by validation score, not by the last step. Validation loss rising while training loss falls means the model is memorizing.

Other tools that do the same job

  • Unsloth trains LoRA and QLoRA up to 2x faster with 70 to 80% less VRAM, as TRL's docs describe it, and also supports DPO, ORPO, KTO and GRPO. The VRAM table above is theirs.
  • Axolotl v0.21.1 (27 October 2026) runs from a YAML file, dropped FSDP1 for FSDP2 in v0.20, and ships Qwen3.5 configs. This snippet adapts its 27B QLoRA example (about 47 GiB peak in Axolotl's table, with sample packing on). The shipped file has no gate_proj and comments out the linear_attn lines; we added both, as its README describes:
base_model: Qwen/Qwen3.5-27B
chat_template: qwen3_5
load_in_4bit: true
adapter: qlora
lora_r: 16
lora_alpha: 32
lora_target_modules: [q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj, linear_attn.in_proj_qkv, linear_attn.in_proj_z, linear_attn.out_proj]
learning_rate: 0.0002
  • LlamaFactory v0.9.5 (30 May 2026) supports Qwen3.5, Qwen3.6, Gemma 4 and Transformers v5, and releases less often than the others.
  • torchtune is no longer actively maintained; its README says development wound down in 2025. Do not start new work on it.

Evaluate, then pass the eval gate

Score each candidate on the frozen test set with the baseline's harness:

  • Task metrics. For extraction: schema-valid rate, per-field accuracy, whole-record exact match. For classification: accuracy and per-class recall. For open-ended text: a rubric scored by people, or by a judge model you have checked against people.
  • General-ability regression. Run a fixed set of general prompts, plus any other tasks the model serves, on the base and tuned models. A narrow fine-tune can quietly degrade everything else.
  • Safety. Re-run refusal and jailbreak prompts, and probe for memorized training data by prompting with partial records.
  • The artifact you will ship. After QLoRA, evaluate the adapter on the 16-bit base, or the merged model, whichever you will serve. It is not bit-identical to the 4-bit model you trained against.
  • Cost and latency at your expected concurrency.

The gate: the candidate beats the baseline on the task metric by a margin fixed before training, and does not regress on general ability or safety beyond agreed thresholds. A candidate that fails goes back to data or training. Keep the eval report with the model version.

Serve the result

Merge the adapter into the weights

Load the base in 16-bit, apply the adapter, merge and save:

import torch
from peft import PeftModel
from transformers import AutoModelForImageTextToText, AutoProcessor
 
BASE = "Qwen/Qwen3.5-9B"
 
base = AutoModelForImageTextToText.from_pretrained(BASE, dtype=torch.bfloat16)  # 16-bit, not 4-bit
merged = PeftModel.from_pretrained(base, "out/qwen35-9b-qlora").merge_and_unload()
merged.save_pretrained("out/qwen35-9b-merged")
AutoProcessor.from_pretrained(BASE).save_pretrained("out/qwen35-9b-merged")

Serve it like any checkpoint, with vllm serve out/qwen35-9b-merged --host 127.0.0.1 --max-model-len 32768 in the serving environment below. A merged model has no adapter overhead, but every variant is a full copy of the weights.

Serve adapters with vLLM multi-LoRA

vLLM can load the base once and apply adapters per request. Install it in its own environment:

pip install "vllm==0.34.0"
vllm serve Qwen/Qwen3.5-9B \
  --host 127.0.0.1 \
  --max-model-len 32768 \
  --enable-lora \
  --max-lora-rank 16 \
  --max-loras 4 \
  --lora-modules invoice-extract=out/qwen35-9b-qlora

Clients pick the adapter by name in the model field:

curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "invoice-extract",
    "messages": [
      {"role": "system", "content": "Extract the invoice fields as JSON."},
      {"role": "user", "content": "Invoice INV-2291 from Acme Supplies. Total due: USD 1,240.00."}
    ],
    "chat_template_kwargs": {"enable_thinking": false}
  }'
  • --max-model-len caps the context. Qwen3.5-9B's native context is 262,144 tokens, which will not fit beside about 19 GB of bf16 weights on a 24 GB card.
  • --host 127.0.0.1 keeps the server local. With no host set, vLLM 0.34 listens on all interfaces, and it checks no API key unless you pass --api-key. To serve beyond the machine, follow the VPS guide.
  • --max-lora-rank must be at least your adapter's rank. In vLLM 0.34 it defaults to 16.
  • --max-loras is how many adapters can run in one batch. It defaults to 1.
  • vLLM 0.34 supports LoRA on Qwen3.5, including the Gated DeltaNet projections.
  • Runtime loading through /v1/load_lora_adapter needs VLLM_ALLOW_RUNTIME_LORA_UPDATING=True, and vLLM's docs warn against it in production unless the environment is isolated and fully trusted.

Adapters make lifecycle step 6 cheap: a new version takes a share of traffic under its own name, and rollback means routing back to the previous adapter.

What it costs

Our estimate, not a benchmark

  • Compute. LoRA costs about 4 × N × T FLOPs for N parameters and T training tokens: a forward pass, plus a backward pass with no weight gradients for the frozen base. Gradient checkpointing, which SFTConfig turns on, repeats the forward pass, so count about 6 × N × T. An 8B model on 10M tokens (5,000 examples of 1,000 tokens, two epochs) is about 4.8 × 10¹⁷ FLOPs.
  • Time. At a sustained 35 to 40 TFLOPS on one L4, about 3.3 to 3.8 hours. That is before QLoRA's dequantization overhead and the 9B model's extra 20% or so.
  • Money. An AWS g6.xlarge (one L4) lists at $0.805 an hour on demand in us-east-1 and $0.966 in Mumbai, so that is about $2.70 to $3.70 of GPU time.
  • The real budget. Sweeps, evaluation runs and failed attempts multiply that by 5 to 20. Engineering time costs more than the GPUs.

Managed services, with prices as listed on 23 November 2026:

ServiceWhat you getPrice
Together AISFT and DPO on open models, billed per 1M training tokens (dataset tokens × epochs, plus validation tokens)Up to 9B (Qwen3.5 0.8B to 9B, Llama 3.1 8B): SFT $0.34 to $0.38, DPO $0.84 to $0.94. 27B to 35B: SFT $1.05 to $1.16. Llama 3.3 70B: SFT $2.03 to $2.24. These models have a $4 minimum per job; larger ones have minimums of $6 to $60.
Google Vertex AIManaged SFT for Gemma 4, Qwen 3 to 3.8, Llama 3.x and 4 Scout, and others (Qwen 3.5 9B: full tuning only). You can export the tuned safetensors.Per training token (dataset tokens × epochs); we did not verify the rate
Amazon BedrockReinforcement fine-tuning, launched 3 Dec 2025 for Amazon Nova 2 Lite. gpt-oss-20b and Qwen3 32B were added on 17 Feb 2026 and are listed in US West (Oregon).$80 per training hour, then per-token inference and $1.95 per model per month for storage

Together's two price columns are not labeled LoRA or full, so we give the range. The 10M-token example would come to $3.40 to $3.80 there, so it is billed at the $4 minimum.

Avoid building on OpenAI fine-tuning: organizations that had never fine-tuned have been locked out since 7 May 2026, and job creation ends for everyone on 6 January 2027 (OpenAI deprecations). A fine-tune that lives only inside a vendor's API can be stranded; open safetensors weights plus the config that produced them are the hedge.

Check the license before you train

  • Apache-2.0 (Qwen3.5, Gemma 4, gpt-oss): include the license and any NOTICE file when you distribute. It grants no trademark rights.
  • Llama 4 Community License: a fine-tuned model you distribute must have "Llama" at the beginning of its name, and you must display "Built with Llama". Products with more than 700 million monthly active users need a separate license from Meta (Llama 4 license). For the multimodal Llama 4 models, the acceptable use policy says the license rights "are not being granted to you if you are an individual domiciled in, or a company with a principal place of business in, the European Union". It adds that the restriction "does not apply to end users of a product or service that incorporates any such multimodal models" (Llama 4 acceptable use policy).
  • Licenses differ by checkpoint, even within one vendor. Qwen3.8-27B is Apache-2.0, but Qwen3.8-Flash-Next uses a custom community license. Read the card of the exact checkpoint you train.
  • Your right to use the training data is a separate question from the model license. Settle it before training.

Sources

Fit check

Should you run your own model? Let's find out.

Sixty minutes on your workload, volumes and data rules. You leave with a recommendation, even when the answer is to stay on an API.