Zum Inhalt springen

Lektion 18 · Fine-tuning

Fine-tune Llama with LoRA and QLoRA

Learn how LoRA adapters work, see real TRL and PEFT code for a Llama fine-tune with QLoRA, choose settings and avoid common training failures.

Training every weight of a large model needs a lot of memory. LoRA (low-rank adaptation) freezes the original weights and trains small extra matrices instead. QLoRA also loads the frozen base model in 4 bits. These methods make fine-tuning realistic on far smaller hardware, though you still need a suitable GPU for practical speed.

The idea of LoRA

For a large weight matrix W, LoRA learns two thin matrices A and B, and uses W + B × A (with a scaling factor). The width of the thin part is the rank, r. Because r is small, the number of trained values is tiny compared with W. For the theory, see LoRA and PEFT.

Python Count trainable values with and without LoRA

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The 4096 size is only an example matrix. The result of training is an adapter: a small set of files that is meant to be used with the base model it was trained on.

Real training code

The following uses Hugging Face's TRL and PEFT libraries with bitsandbytes for 4-bit loading. Run it on a machine with a supported GPU. Check the current documentation, because arguments change between releases.

Python
import torch
from datasets import load_dataset
from peft import LoraConfig
from transformers import BitsAndBytesConfig
from trl import SFTConfig, SFTTrainer

model_id = "meta-llama/Llama-3.2-1B-Instruct"

data = load_dataset("json", data_files={"train": "train.jsonl", "eval": "validation.jsonl"})

quantization = BitsAndBytesConfig(          # the "Q" in QLoRA
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
)

lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
                  target_modules="all-linear", task_type="CAUSAL_LM")

config = SFTConfig(
    output_dir="llama-support-lora",
    num_train_epochs=3,
    per_device_train_batch_size=4,
    gradient_accumulation_steps=4,
    learning_rate=1e-4,
    max_length=1024,
    eval_strategy="epoch",
    logging_steps=10,
)

trainer = SFTTrainer(
    model=model_id,
    args=config,
    train_dataset=data["train"],
    eval_dataset=data["eval"],
    peft_config=lora,
    quantization_config=quantization,
)
trainer.train()
trainer.save_model()

These numbers are starting points, not recommendations proven for your task. Remove quantization_config for plain LoRA. Passing quantization_config straight to SFTTrainer needs a recent TRL release; if your version rejects it, follow that version's documentation for loading a 4-bit model. Other tools, such as Unsloth, offer similar workflows. The code was not run for this tutorial, so expect to adjust it to your library versions.

Settings that matter

Setting Meaning Watch for
r Adapter capacity Too low underfits; high costs more
learning_rate Step size Too high can ruin behavior
num_train_epochs Passes over the data Too many can overfit
Batch size and accumulation Memory against stable updates Out-of-memory errors
max_length Longest example in tokens Longer ones are cut

Check the last row carefully. TRL's SFT configuration documents a default max_length of 1024 tokens, and longer sequences are truncated. Measure your examples with the real tokenizer first.

Read the loss curves

Training loss usually falls. Validation loss tells you about new data. If training loss keeps falling while validation loss rises, the model is overfitting. Stop earlier, add varied data or reduce epochs.

Python Stand-in: find the best epoch from losses

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Loss is only a signal. Always also read real outputs and score them on your test set.

Common failures

  • Wrong chat format at training or serving, which leads to odd replies.
  • Endless output because the end-of-turn token is not learned or not set as a stop.
  • Out of memory: reduce batch size or max_length, use 4-bit loading or a smaller model.
  • No improvement: check labels, data volume and whether the task needs facts instead.
  • Loss of general skills after aggressive training. Test beyond your new task.

Fine-tuning can weaken a model's safety behavior, even with harmless-looking data. Run safety tests again after every training run.

Reproducibility

Record the base model revision, dataset version or hash, library versions, all settings and the random seed. Without this record you cannot explain why a later model behaves differently.

Choosing where to train

Fine-tuning needs much more memory than running a model, because the trainer stores gradients and other state. A small model with LoRA or QLoRA fits on far smaller hardware than full training, but the exact need depends on the model, sequence length and batch size. You can use your own GPU or rent one by the hour from a cloud provider. If you rent, check the current price on the provider's page, shut the machine down when you finish and think about where your training data is copied.

Start with a smoke test

Before a long run, train on a handful of examples for a few steps. Confirm that the data loads, that the loss is a normal number, that the model saves and that you can load the adapter and generate text. Then overfit on a tiny set on purpose: a healthy setup should be able to memorize ten examples. If it cannot, look for a format or configuration error before spending time on the full data.

Compare settings carefully

Change one setting per run and keep a table of settings and results. Choose between runs with the validation set, and save the test set for the final check. If two runs are close, collect more evaluation examples instead of trusting a difference of one or two answers.

Saving and organizing runs

Give each run its own output folder with a clear name. Save the configuration next to the adapter, together with the validation results and a few sample outputs. Delete failed checkpoints you no longer need, because they take disk space, and protect the ones trained on sensitive data. An adapter learned from private text can reveal parts of it, so give it the same access rules as the data.

Before you celebrate

Load the saved adapter in a fresh process and generate a few replies. This confirms that what you saved is what you trained, with the right tokenizer and template. Then move on to a full evaluation.

What an adapter cannot do. An adapter cannot fix an unclear task or wrong labels, and it does not remove the base model's license conditions. Treat it as one part of the system.

Read before you run. Understand every argument in your training script. If you cannot explain a setting, look it up in the library documentation first, because a silent default can change the result of a long run.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. What does LoRA mainly train?

    The base stays frozen and the low-rank matrices learn.
  2. 2. What does QLoRA add?

    Quantizing the base saves memory during training.
  3. 3. Training loss falls while validation loss rises. What does this suggest?

    The model fits the training data while getting worse on unseen data.

Summary

  • LoRA trains small adapters; QLoRA also quantizes the base while training.
  • TRL and PEFT offer a common code path.
  • Watch truncation, learning rate and validation loss.
  • Record everything and retest safety after training.

Next: Evaluate and Ship a Fine-tuned Llama

Dein Fortschritt wird in diesem Browser gespeichert. Kein Konto nötig.