Back to main
Unscripted Tech · Free mini-course

Fine-Tune Your First LLM

Understand the maths behind LoRA and QLoRA, and learn how to fine-tune a model yourself.

What exactly is fine-tuning?

Pre-training is the expensive part. A model reads an enormous amount of text and learns to predict the next word. That gives it grammar, facts and general reasoning patterns, but no particular job.

Fine-tuning starts from that pre-trained model and keeps training it, on a much smaller dataset, for one job: answer in your format, follow your style, handle your kind of question. You are not teaching it language again. You are adjusting behavior it already has.

The ideaConceptual sketch, not measured data
Large general-purpose modelSmall fine-tuned modelyour taskother tasksother tasks

This is why a smaller fine-tuned model can sometimes beat a much larger general one on a specific task. The large model spreads its capacity across everything. The small one has seen many examples of exactly your task and your output format. It is not guaranteed: it depends on the task, the data and the models, and outside that task the larger model usually stays ahead.

Why not train all the parameters?

  • Weights are just numbers. A model is a long chain of matrices. Each number in them is a weight (also called a parameter), and together they decide what the model outputs. TinyLlama, the model in this tutorial, has about 1.1 billion of them.
  • Training nudges those numbers. The model makes a prediction, a loss function measures how wrong it was, and every trainable weight is moved slightly in the direction that would have made it less wrong. Repeat thousands of times.
  • Full fine-tuning updates every weight. For each one, the GPU has to hold the weight itself, its gradient, and the optimizer's running statistics. With the common Adam optimizer that is roughly four numbers per weight.
Rough arithmetic. At 4 bytes per number, 1.1 billion weights is about 4.4 GB. Add a gradient and two Adam statistics per weight and you are near 4 × 4.4 = 17.6 GB before the model has processed a single example. A 7 billion parameter model lands around 112 GB by the same sum. The LoRA paper gives the extreme case: full fine-tuning of GPT-3 needed about 1.2 TB of GPU memory, against about 350 GB with LoRA.

Parameter-efficient fine-tuning (PEFT) is the family of methods that avoids this. Freeze the original weights, add a small number of new ones, and train only those. Frozen weights need no gradient and no optimizer state, so most of that memory bill disappears. LoRA is the most widely used PEFT method.

Understanding LoRA visually

Fine-tuning a weight matrix W really means learning a change to it. Call that change ΔW:

Wnew=W+ΔW

In full fine-tuning, ΔW is as big as W. LoRA (Low-Rank Adaptation) makes one bet: the change you need is much simpler than the matrix itself, so it can be built from two thin matrices multiplied together.

ΔW=BAB∈ℝd×r,A∈ℝr×k

W stays frozen. Only A and B are trained. The number r is the rank: the thin side of both matrices. Multiply a tall d × r matrix by a wide r × k one and you get a full d × k matrix, the same shape as W, so the two can be added. Move the slider and watch what rank does to the cost.

Try itOne 1,000 × 1,000 weight matrix
FROZENTRAINABLEW1,000 × 1,000+B1,000 × 8×A8 × 1,000
1,000,000original parameters (frozen)
16,000LoRA trainable parameters
98.4%fewer trainable parameters

1,000×8 + 8×1,000 = 16,000 trainable values, which is 1.6% of the matrix. The blue sliver in the bar is that share. With alpha = 16 (the value in my notebook), the update is scaled by 16/8 = 2.

At rank 8, a 1,000 × 1,000 matrix goes from 1,000,000 trainable values to 16,000. That is 98.4% fewer for this one matrix. The saving for a whole model depends on which layers you adapt.

The scaling factor

Real implementations do not add BA as is. They multiply it by α / r first, where α (alpha) is a number you choose:

h=Wx+αrBAxx is the layer's input, h is its output

Think of α / r as a volume knob for the adapter. Dividing by r keeps the size of the update roughly steady when you try a different rank, so you do not have to re-tune everything else each time.

Why is it called low-rank?

The rank of a matrix is, loosely, how many independent directions it contains. Because ΔW is built from an r-wide bottleneck, its rank can never exceed r, even though it has the full shape of W. With r = 8 the update can only move the weights along 8 independent directions. The LoRA paper's finding is that for adapting a pre-trained model, a small number of directions is often enough.

One common misreading: A and B are not rows or columns picked out of W. They are brand-new matrices. Their shapes exist only so that BA comes out the same shape as W.

How does training start without breaking the model?

In the paper, A starts as small random numbers and B starts as all zeros. So BA is zero at step one and the model behaves exactly like the original. Training then moves it away from zero only as far as the data pushes it.

After training you can also merge the adapter in by computing W + BA once and storing it. The merged model runs at the same speed as the original.

Where does LoRA attach inside the model?

LoRA can go on any linear layer. The classic setup, used in most of the paper's experiments and in my notebook, targets the attention layers' query and value projections: q_proj and v_proj. The token embeddings, the key projections and everything else stay exactly as pre-trained. Modern setups often add the other attention and MLP projections too, for more capacity at a higher cost.

QLoRA and quantization

LoRA shrinks what you train. It does nothing about the frozen base model, which still has to sit in GPU memory. Quantization shrinks that part: store each weight with fewer bits.

A weight is normally a 32-bit or 16-bit floating point number. Quantizing to 4 bits means each weight can only be one of 16 values instead of billions. You lose a little precision and save a lot of space.

One weight, three sizesEach square is one bit
  • FP3232 bits · 4 bytes per weight
  • FP1616 bits · 2 bytes per weight
  • 4-bit4 bits · half a byte per weight
Memory calculatorWeight storage only
Model size (parameters)
Weight precision
≈ 0.55 GB
1.1B weights × 4 bits ÷ 8 = 0.55 billion bytes (4-bit)
  • FP324.40 GB
  • FP162.20 GB
  • 8-bit1.10 GB
  • 4-bit0.55 GB

This is only the space the weights take. Real training needs more on top: activations for every example in the batch, gradients, optimizer state, the adapters themselves, and framework overhead. Treat the number as a floor, not a budget.

QLoRA puts the two ideas together. Load the base model in 4-bit and freeze it. Attach normal LoRA adapters, which stay in regular precision. During training, gradients flow back through the frozen 4-bit weights and update only the adapters.

Two separate things. 4-bit quantization is how you store the base model. LoRA is how you train. Loading a model in 4-bit is not fine-tuning on its own.
Advanced: what is NF4?

With only 16 possible values, where you place them matters. Spacing them evenly wastes most of them, because a trained network's weights are not spread evenly: they cluster around zero in a bell-curve shape. NF4 (4-bit NormalFloat) places its 16 values to match that bell curve, with more of them near zero where most weights live. The QLoRA paper introduces it as a data type designed for normally distributed weights.

The weights are stored in 4-bit but the maths is done in a higher precision. They are converted on the fly for each calculation. In my notebook that is the bnb_4bit_compute_dtype = torch.float16 setting.

Advanced: what is double quantization?

Quantizing weights in blocks leaves behind a few extra numbers per block, the quantization constants, needed to convert back. Across billions of weights those add up. Double quantization quantizes those constants as well. The QLoRA paper reports a saving of about 0.37 bits per parameter, roughly 3 GB on a 65 billion parameter model.

My notebook uses NF4 but does not switch double quantization on. In the bitsandbytes config it is a separate option, bnb_4bit_use_double_quant.

Hands-on: fine-tune TinyLlama

This walks through my notebook cell by cell. It loads TinyLlama (1.1 billion parameters) in 4-bit, attaches LoRA adapters, and trains them on 200 grade-school maths word problems. Because the base model is 4-bit and frozen, this is a QLoRA-style setup.

How to read the code blocks. A green “From my notebook” tag means the code is copied unchanged from the notebook in the repository. An orange “Extra” tag means I added it for this page and it is not in the repository.
  1. Step 1: Prerequisites

    • Basic Python. You do not need prior machine learning experience.
    • A Google account, to use Google Colab. Nothing gets installed on your own machine.
    • A GPU runtime. The notebook was run on a Colab T4 GPU, which has 16 GB of memory. Colab's free tier usually offers one, though availability varies.
  2. Step 2: Set up the environment

    Open the notebook in Colab, then go to Runtime → Change runtime type and pick T4 GPU. The 4-bit loading in step 5 needs a CUDA GPU and will not work on a CPU runtime.

  3. Step 3: Install the dependencies

    Five libraries do the work. transformers loads the model and runs training. peft adds LoRA. bitsandbytes does the 4-bit quantization. accelerate places the model on the GPU. datasets downloads the training data.

    From my notebookCell 2
    !pip install -q -U "bitsandbytes>=0.46.1" transformers accelerate peft datasets
    

    In the notebook this cell sits after the imports. On a fresh runtime, run it first so the imports pick up the updated versions.

  4. Step 4: Import the libraries

    Everything used later is imported here: the model and tokenizer loaders, the training classes, the quantization config, and the LoRA pieces from PEFT.

    From my notebookCell 1
    import torch
    
    from datasets import load_dataset
    from transformers import AutoTokenizer, AutoModelForCausalLM, TrainingArguments, Trainer, BitsAndBytesConfig
    
    from peft import LoraConfig, get_peft_model, TaskType
    
  5. Step 5: Load the base model and tokenizer

    This downloads TinyLlama and loads it in 4-bit instead of its usual 16-bit, so it takes far less GPU memory. The tokenizer is the piece that turns text into the token IDs the model works with, and back again.

    From my notebookCell 3
    model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
    
    bnb_config = BitsAndBytesConfig(
        load_in_4bit = True,
        bnb_4bit_quant_type = 'nf4',
        bnb_4bit_compute_dtype = torch.float16
    )
    
    model = AutoModelForCausalLM.from_pretrained(
        model_name,
        quantization_config = bnb_config,
        device_map = 'auto',
        trust_remote_code = True
    )
    
    tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
    
    • load_in_4bit = TrueStore every base weight in 4 bits. This is the memory saving.
    • bnb_4bit_quant_type = 'nf4'Use the NF4 data type from the QLoRA paper for those 4 bits.
    • bnb_4bit_compute_dtypeDo the actual calculations in 16-bit floats, converting on the fly.
    • device_map = 'auto'Let the library put the model on the available GPU.

    The download is about 2.2 GB, which matches the calculator above: 1.1 billion weights at 16 bits each.

  6. Step 6: Configure LoRA

    This is where the adapters are created. get_peft_model freezes the base model and inserts a pair of A and B matrices next to each targeted layer.

    From my notebookCell 4
    lora_config = LoraConfig(
        r = 8,
        lora_alpha = 16,
        target_modules = ['q_proj', 'v_proj'],
        lora_dropout = 0.05,
        bias = 'none',
        task_type = TaskType.CAUSAL_LM
    )
    
    model = get_peft_model(model, lora_config)
    
    • r = 8The rank. Each adapter is 8 wide, as in the slider above.
    • lora_alpha = 16The scaling number. The update is multiplied by 16 / 8 = 2.
    • target_modulesAdapt only the query and value projections in each attention layer. Everything else stays frozen.
    • lora_dropout = 0.05Randomly drop 5% of adapter inputs during training to reduce memorizing.
    • bias = 'none'Do not train any bias terms.
    • task_type = CAUSAL_LMTell PEFT this is a next-token-prediction model.
    How small is the adapter? The adapter file saved in the repository contains 1,126,400 trainable values. TinyLlama has 1,100,048,384. That is about 0.10% of the model, in a file of about 4.5 MB.
    Check the maths: where 1,126,400 comes from

    TinyLlama has 22 layers with a hidden size of 2,048. In each layer:

    • q_proj is 2,048 × 2,048, so its adapter is 8×2,048 + 2,048×8 = 32,768.
    • v_proj is 256 × 2,048 (TinyLlama uses fewer value heads than query heads), so its adapter is 8×2,048 + 256×8 = 18,432.
    • Per layer that is 51,200. Times 22 layers: 51,200 × 22 = 1,126,400.

    You can ask PEFT for this number yourself right after cell 4:

    Extra, not in my notebookOptional check
    model.print_trainable_parameters()
    
  7. Step 7: Prepare the dataset

    The training data is GSM8K, a set of grade-school maths word problems with worked answers. The notebook takes only the first 200 of its 7,473 training examples to keep the run short.

    From my notebookCell 5
    data = load_dataset('openai/gsm8k', 'main', split='train[:200]')
    

    Next, every example is rewritten into one fixed template and converted to tokens. The template is what teaches the model the pattern: after ### Response: comes an answer.

    From my notebookCell 6
    def tokenize(batch):
        texts = [
            f"### Instruction:\n{inst}\n### Response:\n{out}"
            for inst, out in zip(batch['question'], batch['answer'])
        ]
    
        tokens = tokenizer(
            texts,
            padding = 'max_length',
            truncation = True,
            max_length = 256,
            return_tensors = 'pt'
        )
    
        tokens['labels'] = tokens['input_ids'].clone()
    
        return tokens
    
    • max_length = 256Every example is cut or padded to exactly 256 tokens, so they can be stacked into batches.
    • labels = input_idsThe target is the text itself. The model is trained to predict each next token, and the loss measures how wrong those predictions are.
    From my notebookCell 7
    tokenized_data = data.map(tokenize, batched=True, remove_columns=data.column_names)
    

    map runs that function over all 200 examples and drops the original text columns, leaving only what the trainer needs.

    One thing to know. Because the labels are a straight copy of the padded input, the padding tokens count toward the loss too. Padding is easy to predict, so it pulls the loss number down. Keep that in mind when you read the loss in step 9.
  8. Step 8: Set the training hyperparameters

    TrainingArguments holds every setting for the run, and Trainer ties the model, the settings and the data together. Each value is explained in the hyperparameter reference below.

    From my notebookCell 8
    training_args = TrainingArguments(
        output_dir = './tinyllama-lora-tuned',
        per_device_train_batch_size = 4,
        gradient_accumulation_steps = 4,
        learning_rate = 1e-3,
        num_train_epochs = 50,
        fp16 = True,
        logging_steps = 20,
        save_strategy = 'epoch',
        report_to = 'none',
        remove_unused_columns = False,
        label_names = ["labels"]
    )
    
    • batch size 4 × accumulation 4Four examples at a time on the GPU, with the weights updated every four batches. That behaves like a batch of 16 without needing the memory for one.
    • num_train_epochs = 50Fifty passes over the 200 examples. 200 ÷ 16 rounds up to 13 updates per pass, so 13 × 50 = 650 steps.
    • fp16 = TrueUse 16-bit maths during training, which is faster and lighter on a T4.
    • logging_steps = 20Print the loss every 20 steps so you can watch it fall.
    • save_strategy = 'epoch'Write a checkpoint to the output folder after every pass.
    From my notebookCell 9
    trainer = Trainer(
        model = model,
        args = training_args,
        train_dataset = tokenized_data,
        processing_class = tokenizer
    )
    
  9. Step 9: Train

    One line starts the run. Only the LoRA matrices change; the 1.1 billion base weights are never touched.

    From my notebookCell 10
    trainer.train()
    
    My runTraining loss by step
    0.00.51.01.52.002004006001.930.028

    650 steps took about 20 minutes on the T4. The logged loss fell from 1.93 to 0.028. Your numbers will differ a little from run to run.

    A low loss here is not proof the model got better at maths. Fifty passes over 200 examples gives the model every chance to memorize them, and the padding effect from step 7 lowers the number further. The only real test is questions it has never seen.
  10. Step 10: Save the trained adapters

    save_pretrained on a PEFT model writes only the adapter, not the base model. That is why the result is a few megabytes instead of gigabytes. The tokenizer is saved next to it so the folder is self-contained.

    From my notebookCell 11
    model.save_pretrained("./tinyllama-lora-tuned-adapter-math")
    tokenizer.save_pretrained("./tinyllama-lora-tuned-adapter-math")
    

    Colab deletes its files when the session ends, so the last cell copies the adapter folder to Google Drive. It will ask for permission to access your Drive.

    From my notebookCell 12
    # Colab runtimes are temporary — copy the adapter to Drive so it isn't lost on disconnect
    from google.colab import drive
    drive.mount('/content/drive')
    
    import shutil
    shutil.copytree(
        './tinyllama-lora-tuned-adapter-math',
        '/content/drive/MyDrive/tinyllama-lora-tuned-adapter-math',
        dirs_exist_ok=True
    )
    
  11. Step 11: Load the fine-tuned model and test it

    This step is not in my repository. The notebook stops after saving the adapter. The code below is the standard PEFT way to load an adapter and generate text. I added it for this page and have not included any output, because I have not run it as part of the notebook.

    Loading works in two layers, mirroring how training worked: first the same frozen 4-bit base model, then the saved adapter on top. The prompt must use the same ### Instruction / ### Response template as the training data, or the adapter will not recognize the pattern it learned.

    Extra, not in my notebookLoad and generate
    from peft import PeftModel
    
    # Start from a clean copy of the frozen 4-bit base model
    base = AutoModelForCausalLM.from_pretrained(
        model_name,
        quantization_config = bnb_config,
        device_map = 'auto'
    )
    
    # Attach the saved adapter on top of it
    tuned = PeftModel.from_pretrained(base, "./tinyllama-lora-tuned-adapter-math")
    tuned.eval()
    
    # Use the exact prompt format the adapter was trained on
    prompt = "### Instruction:\nA shop has 20 apples and sells 7. How many remain?\n### Response:\n"
    inputs = tokenizer(prompt, return_tensors='pt').to(tuned.device)
    
    with torch.no_grad():
        output = tuned.generate(**inputs, max_new_tokens=150, do_sample=False)
    
    print(tokenizer.decode(output[0], skip_special_tokens=True))
    

    To judge the result fairly, try questions from GSM8K's separate test split (1,319 problems the model never trained on), and run the same prompts through the plain base model to compare.

Understanding hyperparameters

Hyperparameters are the settings you choose before training. There is no single correct set: good values depend on the model, the dataset and the hardware. The values shown are what my notebook uses, as a starting point to experiment from, not a recommendation.

LoRA rank

r · notebook uses 8

The inner size of the A and B matrices. It caps how complex the learned change can be.

Increase itMore trainable parameters and more room to learn the task, but a bigger adapter, more memory, and more room to memorize a small dataset.
Decrease itA smaller, cheaper adapter. Too low and it may not have the capacity to learn the behavior you want.

LoRA alpha

lora_alpha · notebook uses 16

A scaling number. The update is multiplied by alpha / r before it is added to the frozen weights.

Increase itThe adapter's change counts for more. Acts a bit like raising the learning rate for the adapter, and can make training unstable.
Decrease itThe adapter has a gentler effect. The model stays closer to the original and may under-learn the task.

LoRA dropout

lora_dropout · notebook uses 0.05

During training, randomly zeroes a fraction of the values going into the adapter, so it cannot lean on any single one.

Increase itStronger protection against overfitting, useful on small datasets. Too high and learning slows down or stalls.
Decrease itFaster fitting to the training data, with less protection against memorizing it.

Target modules

target_modules · notebook uses ['q_proj', 'v_proj']

Which layers get an adapter. The names must match the layer names inside the model you loaded.

Increase itAdding more layers (k_proj, o_proj, the MLP projections) gives more trainable parameters and more ways to adapt, at a higher memory and compute cost.
Decrease itFewer layers keeps the adapter small and light, which is why the notebook uses only the query and value projections.

Learning rate

learning_rate · notebook uses 1e-3

How big a step the optimizer takes each time it updates the adapter weights.

Increase itLearns faster, but the loss can jump around or blow up. Many LoRA setups start lower than this notebook does.
Decrease itSteadier training, but it needs more steps to get anywhere.

Batch size

per_device_train_batch_size · notebook uses 4

How many examples the GPU processes at once.

Increase itSmoother gradient estimates and faster epochs, but GPU memory use climbs with it.
Decrease itFits on smaller GPUs. Each update is noisier. This is the first thing to lower when you run out of memory.

Epochs

num_train_epochs · notebook uses 50

How many times training passes over the whole dataset.

Increase itMore chances to learn, and on a small dataset more chances to memorize it word for word.
Decrease itLess risk of overfitting and less time. Too few and the model has barely changed.

Gradient accumulation

gradient_accumulation_steps · notebook uses 4

Adds up gradients over several small batches before making one update. Batch size 4 with 4 accumulation steps behaves like a batch of 16.

Increase itA larger effective batch without extra GPU memory, at the cost of fewer weight updates per epoch.
Decrease itMore frequent updates, each based on fewer examples.

Full fine-tuning vs LoRA vs QLoRA

Comparison of full fine-tuning, LoRA and QLoRA
Full fine-tuningLoRAQLoRA
Trainable parametersAll of them (100%)Only the adapters, usually well under 1%Only the adapters, same as LoRA
GPU memoryHighest: weights, a gradient for every weight, and optimizer state for every weightLower: the full-precision base model is still loaded, but gradients and optimizer state exist only for the adaptersLowest: the base model is stored in 4-bit, plus the small adapters
Computational costHighest per stepLower: far fewer weights to updateSimilar to LoRA, with some extra work to de-quantize weights on the fly
Training approachUpdate the original weights directlyFreeze the original weights, train small A and B matrices beside themQuantize and freeze the original weights, then train LoRA adapters on top
HardwareLarge or multiple GPUs for anything beyond small modelsA single GPU that can hold the base modelA single smaller GPU. The notebook here ran on a Colab T4
Good forDeep changes to a model when you have lots of data and computeTask or style adaptation when the base model fits in memoryThe same, when the base model would not otherwise fit

These are general tendencies, not benchmark results. Exact memory and speed depend on the model, the batch size, the sequence length and the libraries you use.

Common mistakes and fixes

CUDA out of memory

The model, the batch and the training state together need more GPU memory than you have.

  • Lower per_device_train_batch_size and raise gradient_accumulation_steps to keep the same effective batch.
  • Lower max_length so each example is shorter.
  • Make sure the base model really loaded in 4-bit, and restart the runtime to clear memory left over from earlier cells.
  • Use a smaller rank or fewer target modules.
Dataset formatting errors

The column names or the prompt template do not match what the code expects.

  • GSM8K has 'question' and 'answer' columns. For your own data, change the names inside tokenize() to match.
  • Print one formatted example before training and read it. Most formatting bugs are visible straight away.
  • Keep the template identical between training and inference, down to the line breaks.
Overfitting

Training loss keeps falling, but answers on new questions do not improve. The model is memorizing.

  • Use more examples, or train for fewer epochs.
  • Hold back a few examples the model never trains on and test with those.
  • Try a lower rank or a little more dropout.
Wrong target modules

PEFT raises an error saying the target modules were not found, because layer names differ between model families.

  • Run print(model) and look at the layer names. Llama-style models use q_proj and v_proj; other architectures use different names.
  • Copy the names exactly as printed.
Dependency conflicts

bitsandbytes, transformers, peft and accelerate change quickly and need compatible versions.

  • Run the install cell first, then restart the runtime before importing anything.
  • The notebook pins bitsandbytes to 0.46.1 or newer; its saved adapter was written by peft 0.20.0.
  • 4-bit loading through bitsandbytes needs a CUDA GPU. It will not work on a CPU-only runtime.
Poor answers after fine-tuning

Usually a prompt mismatch, too little data, or expecting more than a small model can do.

  • Prompt with the same ### Instruction / ### Response format used in training.
  • Check that you actually loaded the adapter on top of the base model.
  • A low training loss is not proof of good answers. Test on questions the model has not seen.
  • TinyLlama is a 1.1B model. Fine-tuning shapes its behavior; it does not make it a bigger model.

Resources and credits

Also worth reading: QLoRA: Efficient Finetuning of Quantized LLMs by Dettmers, Pagnoni, Holtzman and Zettlemoyer (2023), the source of NF4 and double quantization.

Credit where it is due. The LoRA and QLoRA methods belong to the authors of the papers above. The implementation approach comes from NeuralNine's video. My part is the notebook run, the notes and this explainer. The base model is TinyLlama 1.1B Chat and the dataset is GSM8K.

Unscripted Tech

Making complex tech simple.

cursor