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.
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.
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:
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 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.
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:
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.
- FP3232 bits · 4 bytes per weight
- FP1616 bits · 2 bytes per weight
- 4-bit4 bits · half a byte per weight
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.
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.
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.
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.
Step 3: Install the dependencies
Five libraries do the work.
transformersloads the model and runs training.peftadds LoRA.bitsandbytesdoes the 4-bit quantization.accelerateplaces the model on the GPU.datasetsdownloads the training data.From my notebookCell 2!pip install -q -U "bitsandbytes>=0.46.1" transformers accelerate peft datasetsIn the notebook this cell sits after the imports. On a fresh runtime, run it first so the imports pick up the updated versions.
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 1import torch from datasets import load_dataset from transformers import AutoTokenizer, AutoModelForCausalLM, TrainingArguments, Trainer, BitsAndBytesConfig from peft import LoraConfig, get_peft_model, TaskTypeStep 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 3model_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.
Step 6: Configure LoRA
This is where the adapters are created.
get_peft_modelfreezes the base model and inserts a pair ofAandBmatrices next to each targeted layer.From my notebookCell 4lora_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_projis 2,048 × 2,048, so its adapter is 8×2,048 + 2,048×8 = 32,768.v_projis 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 checkmodel.print_trainable_parameters()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 5data = 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 6def 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 tokensmax_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 7tokenized_data = data.map(tokenize, batched=True, remove_columns=data.column_names)mapruns 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.Step 8: Set the training hyperparameters
TrainingArgumentsholds every setting for the run, andTrainerties the model, the settings and the data together. Each value is explained in the hyperparameter reference below.From my notebookCell 8training_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 9trainer = Trainer( model = model, args = training_args, train_dataset = tokenized_data, processing_class = tokenizer )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 10trainer.train()My runTraining loss by step650 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.Step 10: Save the trained adapters
save_pretrainedon 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 11model.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 )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/### Responsetemplate as the training data, or the adapter will not recognize the pattern it learned.Extra, not in my notebookLoad and generatefrom 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
testsplit (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 8The inner size of the A and B matrices. It caps how complex the learned change can be.
LoRA alpha
lora_alpha · notebook uses 16A scaling number. The update is multiplied by alpha / r before it is added to the frozen weights.
LoRA dropout
lora_dropout · notebook uses 0.05During training, randomly zeroes a fraction of the values going into the adapter, so it cannot lean on any single one.
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.
Learning rate
learning_rate · notebook uses 1e-3How big a step the optimizer takes each time it updates the adapter weights.
Batch size
per_device_train_batch_size · notebook uses 4How many examples the GPU processes at once.
Epochs
num_train_epochs · notebook uses 50How many times training passes over the whole dataset.
Gradient accumulation
gradient_accumulation_steps · notebook uses 4Adds up gradients over several small batches before making one update. Batch size 4 with 4 accumulation steps behaves like a batch of 16.
Full fine-tuning vs LoRA vs QLoRA
| Full fine-tuning | LoRA | QLoRA | |
|---|---|---|---|
| Trainable parameters | All of them (100%) | Only the adapters, usually well under 1% | Only the adapters, same as LoRA |
| GPU memory | Highest: weights, a gradient for every weight, and optimizer state for every weight | Lower: the full-precision base model is still loaded, but gradients and optimizer state exist only for the adapters | Lowest: the base model is stored in 4-bit, plus the small adapters |
| Computational cost | Highest per step | Lower: far fewer weights to update | Similar to LoRA, with some extra work to de-quantize weights on the fly |
| Training approach | Update the original weights directly | Freeze the original weights, train small A and B matrices beside them | Quantize and freeze the original weights, then train LoRA adapters on top |
| Hardware | Large or multiple GPUs for anything beyond small models | A single GPU that can hold the base model | A single smaller GPU. The notebook here ran on a Colab T4 |
| Good for | Deep changes to a model when you have lots of data and compute | Task or style adaptation when the base model fits in memory | The 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
Unscripted Tech
My implementation, code and learning notes.
The notebook and notes this tutorial is built from.
Open ↗Video tutorialNeuralNine
The video tutorial that helped me learn the implementation.
“Fine-Tuning Local Models with LoRA in Python (Theory & Code)” by NeuralNine.
Open ↗Research paperOriginal LoRA paper
LoRA: Low-Rank Adaptation of Large Language Models.
Hu, Shen, Wallis, Allen-Zhu, Li, Wang, Wang and Chen, 2021.
Open ↗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.
More from me
AI Stickman Videos
One prompt that installs Stickman Video Director and renders your first video.
Read more →Free guideThe Context Kit
Four markdown files that stop your AI coding agent from getting lost.
Read more →Free guideML Model That Can Smell
Set up OpenPOM and predict what any molecule smells like.
Read more →