# How LLM training and fine-tuning work

> How pre-training, mid-training, SFT, RLHF, DPO, RLVR, and LoRA adapters actually work, backed by a real fine-tuning vs prompting benchmark on 160 repo commits.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2026-11-25 | Topics: [AI](https://flaviocopes.com/tags/ai/) | Canonical: https://flaviocopes.com/llm-training-fine-tuning/

When you send a prompt to a modern language model and get a clean answer back, it is easy to think of the model as one finished artifact that simply "learned everything from the internet."

Under the hood, that assistant is the output of several distinct training phases stacked one on top of another. A raw model trained on internet text will not even answer your question reliably. Turning random numbers into a reliable coding partner or classifier takes pre-training, mid-training, supervised fine-tuning, and reinforcement learning, and then, for specialized developer tasks, parameter-efficient adapters like LoRA.

If you want to experience training a tiny model from scratch on your own Mac without writing Python, I covered that workflow in [How to build an LLM from scratch](https://flaviocopes.com/build-llm-from-scratch/) and [Build a language model on your Mac with Language Model Builder](https://flaviocopes.com/language-model-builder/). Here we zoom out to the complete modern training stack, look at the actual math and mechanics behind each stage, and run a real benchmark on 160 commits from this repository comparing full fine-tuning, four LoRA ranks, and prompting OpenAI's `gpt-4.1-mini`.

## Why a base model is not an assistant

A newly pretrained language model is called a **base model**.

Its only job is text completion. You hand it a sequence of tokens, and it predicts what tokens are most likely to follow based on the trillions of words it saw during pre-training.

Suppose you send a straightforward instruction to a base model:

```text
Prompt:
Write a Python function that parses a CSV file and returns a list of dictionaries.
```

An instruction-tuned assistant writes the function immediately. A base model often continues the prompt as if it were reading a homework sheet or a quiz:

```text
Base model completion:
2. Write a Python function that converts a list of dictionaries into a JSON string.
3. Explain the difference between csv.reader and csv.DictReader.
4. Bonus: handle UTF-8 BOM headers without crashing.
```

The base model is doing its job accurately. On the open web, a sentence starting with "Write a Python function that..." appears right next to numbered exercise lists far more often than it appears next to a clean answer. The model has no built-in notion of being a helpful assistant, stopping at the end of a turn, refusing a dangerous request, or returning strict JSON.

Yet the base model already holds almost all of the raw knowledge. It knows Python syntax, historical facts, HTTP status codes, and how to translate Italian to English. Everything that happens after pre-training reshapes *how* the model surfaces that knowledge and *how* it behaves in a conversation.

```mermaid steps
flowchart TD
  accTitle: Step 1 of 4 - Pre-training produces a base model
  accDescr: Raw text corpora feed next-token prediction to create a base completion model.
  A["Raw text corpus (trillions of tokens)"] --> B["Pre-training (next-token prediction)"]
  B --> C["Base model (text completion only)"]
%% step
flowchart TD
  accTitle: Step 2 of 4 - Mid-training extends context and sharpens quality
  accDescr: Mid-training extends the context window and anneals the base model on high-quality code and math.
  A["Base model (short context)"] --> B["Mid-training (RoPE scaling and annealing)"]
  B --> C["Annealed base model (long context)"]
%% step
flowchart TD
  accTitle: Step 3 of 4 - Post-training turns a base model into an assistant
  accDescr: Supervised fine-tuning and preference or verifiable RL turn the annealed base into a usable assistant.
  A["Annealed base model"] --> B["SFT (chat format and assistant masking)"]
  B --> C["RLHF, DPO, or RLVR (preferences and verifiers)"]
  C --> D["Assistant model (instruction following)"]
%% step
flowchart TD
  accTitle: Step 4 of 4 - LoRA adapts a frozen model to a narrow domain
  accDescr: A developer freezes the base or assistant weights and trains a small LoRA adapter on task data.
  A["Frozen model weights (W0)"] --> C["Merged output (W0 + delta W)"]
  B["Small LoRA adapter (task dataset)"] --> C
  C --> D["Domain-tuned model"]
```

You can think of the whole pipeline as a funnel. Pre-training burns almost the entire compute budget teaching the network how language, code, and world patterns fit together. Mid-training stretches its memory and polishes its sharpest skills. Post-training teaches it how to hold a conversation, follow instructions, and verify its own work. Finally, developer fine-tuning bends an already capable model toward a narrow taxonomy, format, or latency target.

## Stage 1: Pre-training

Pre-training starts with randomly initialized weights. Before step 1, the network outputs pure noise.

At every training step, the pipeline feeds a batch of token sequences into the Transformer. At every position in each sequence, the model outputs a vector of raw scores called logits, one score per token in its vocabulary (often 50,000 to 256,000 entries). A softmax function converts those logits into probabilities that sum to 1.0.

Because the training text already contains the real next token at every position, we get free supervision without a single human labeler. This is called causal language modeling, or next-token prediction.

### Cross-entropy loss in plain numbers

To measure how wrong a prediction is, training uses **cross-entropy loss**, written as `-ln(p)`, where `p` is the probability the model assigned to the actual next token.

Look at what that formula gives you for real probabilities:

```text
p = 1.00  ->  -ln(1.00) = 0.0000  (perfect confidence on the right token)
p = 0.50  ->  -ln(0.50) = 0.6931  (coin flip)
p = 0.25  ->  -ln(0.25) = 1.3863  (uniform guess across 4 classes)
p = 0.01  ->  -ln(0.01) = 4.6052  (confident in the wrong tokens)
```

Notice that `1.3863` value for four equally likely choices. Keep it in mind, because when we run our 4-class commit classifier later in this post, epoch 1 starts at a loss of `1.3819`. That number is simply the math telling us the untrained head is guessing nearly uniformly across the four classes.

For a real LLM with a 100,000-token vocabulary, random initialization assigns roughly `1 / 100,000` probability to every token, giving a starting loss near `ln(100000) = 11.51`. Backpropagation computes the gradient of that loss with respect to every weight in the network, and an optimizer (usually AdamW) nudges billions of parameters slightly in the direction that lowers the error. Repeat that update across trillions of tokens, and the loss drops below `2.0`. By predicting the next token accurately across enough text, the model is forced to build internal representations of grammar, logic, code structure, and factual relationships.

### Corpus curation, deduplication, and mixtures

Early language models threw massive web scrapes straight into training. Modern labs know that data quality beats raw volume every time. You can read a short primer on what goes into [training data](https://flaviocopes.com/ai-glossary/training-data/), and the engineering work behind it is huge.

Raw web crawls are full of cookie banners, SEO spam, machine-translated boilerplate, and the same license header copied across ten million pages. If a model sees the same paragraph 500 times, it memorizes that paragraph verbatim instead of generalizing, and it wastes expensive GPU cycles doing so.

Data pipelines clean the corpus in stages before a single GPU runs. First, language and heuristic filters drop garbled HTML, navigation chrome, and low-information pages. Next, exact and fuzzy deduplication (often using MinHash and Locality-Sensitive Hashing) collapses near-identical documents across the entire multi-terabyte scrape. After that, classifier-based filters score pages for educational depth and factual density, while scrubbing removes personal information like email addresses and API keys.

Finally, labs tune the **data mixture**. Rather than reflecting the raw proportions of the internet (which is mostly marketing copy and forum chatter), a good mixture deliberately upweights source code, mathematical derivations, technical documentation, books, and synthetic textbooks. Increasing the share of clean code even improves reasoning on non-coding benchmarks, because code enforces strict causal structure.

### Chinchilla scaling and inference-optimal over-training

For years, teams struggled to answer a basic budgeting question: given a fixed compute budget, should you train a bigger model on fewer tokens, or a smaller model on more tokens?

In 2022, DeepMind's Chinchilla paper gave a clean empirical rule. For **compute-optimal** training (reaching the lowest loss for a fixed FLOP budget), you should scale model parameters and training tokens together at roughly **20 tokens per parameter**. Under that rule, a 70-billion-parameter model is compute-optimal around 1.4 trillion tokens, and an 8-billion-parameter model around 160 billion tokens.

Almost nobody stops at Chinchilla anymore for small and medium models.

Chinchilla optimizes only for the one-time cost of training. It ignores the much larger cost of running inference for millions of users after launch. A 70B model might be cheaper to train to a target quality than an 8B model, yet serving that 70B model costs nearly 9x more per token forever.

So modern labs intentionally **over-train** smaller architectures. Instead of feeding an 8B model 160 billion tokens, labs feed it 10 to 15 trillion tokens, roughly 60x to 100x beyond the Chinchilla ratio. Training takes much longer, and loss improves more slowly near the end, but the resulting compact model fits on cheaper hardware and responds much faster in production.

### Why pre-training costs clusters and millions

Training a frontier model from scratch requires thousands of accelerators (such as H100 or B200 GPUs) wired together with high-bandwidth interconnects like InfiniBand and NVLink, running continuously for weeks or months.

At that scale, training is as much a distributed systems problem as a machine learning one. A single 70B or 400B model cannot fit in one GPU's memory, so engineers split the workload across three dimensions at once: data parallelism (different batches on different replicas), tensor parallelism (splitting individual matrix multiplications across GPUs inside one server), and pipeline parallelism (placing different Transformer layers on different machines).

Hardware fails constantly across thousands of GPUs. Silent data corruption, overheating chips, and dropped network links force labs to run automated health checks and asynchronous checkpointing so a crashed node does not wipe out a day of progress. Mixed-precision training (BF16 and FP8) doubles throughput while keeping FP32 master weights so tiny gradient updates do not vanish to zero.

Because of that cost and compute requirement, almost no product team pre-trains a foundation model from scratch. Downloading [open-weight models](https://flaviocopes.com/open-weight-models/) or calling an API lets you inherit millions of dollars of finished pre-training work in minutes.

## Stage 2: Mid-training

Between massive pre-training and chat post-training, modern labs added a distinct middle phase called **mid-training** (sometimes called continual pre-training or annealing).

Pre-training usually runs with short sequence lengths, such as 4,096 or 8,192 tokens. Standard self-attention compares every token against every preceding token, which means compute and memory grow quadratically with sequence length. Training on 128,000-token windows from step 1 would burn an absurd amount of compute just to learn basic English grammar.

Mid-training solves this efficiently after the base weights are already strong.

### Extending the context window with RoPE scaling

Most modern Transformers encode token positions using Rotary Position Embeddings (RoPE), which rotate query and key vectors at different frequencies depending on token distance. If a model only ever saw positions 0 through 8,191 during pre-training, feeding it position 50,000 causes those rotations to fall out of distribution, and output quality collapses.

During mid-training, engineers increase the RoPE base frequency (often called `rope_theta`, jumping from 10,000 to 500,000 or several million) or apply scaling methods like YaRN. They then continue next-token training for a few hundred billion tokens on genuinely long documents: whole code repositories concatenated with file paths, long scientific papers, legal filings, and full books. Because the model only needs to adapt its attention geometry rather than re-learn language, a few percent of the total pre-training compute is enough to unlock 128K or 1M token context windows.

### High-quality annealing

Mid-training also coincides with the **learning-rate cooldown** (annealing). During bulk pre-training, the learning rate stays relatively high so the model can cover huge ground quickly. In the final phase, labs decay the learning rate smoothly toward zero while swapping the data mixture from broad web text to their cleanest, densest data: curated math solutions, verified code repositories, structured reasoning traces, and high-signal technical writing.

That final polish produces disproportionately large gains on coding and reasoning benchmarks. Because the weights settle into a sharper minimum on clean data right before post-training begins, the model enters Stage 3 with stronger capabilities already in place.

## Stage 3: Post-training

At the end of mid-training, you have a smart, long-context base model that still acts like an autocomplete engine. **Post-training** turns it into an assistant that follows instructions, uses tools, admits when it does not know something, and reasons step by step.

### Supervised Fine-Tuning (SFT)

The first post-training step is Supervised Fine-Tuning. Here the training data switches from raw documents to structured conversations formatted with special role delimiters, known as a chat template:

```text
<|system|>
You are a concise coding assistant.
<|user|>
How do I list files modified in the last 24 hours with find?
<|assistant|>
Run: find . -type f -mtime -1
<|end|>
```

SFT still uses cross-entropy loss, with one important change: **assistant-only loss masking**.

During the forward pass, the model reads the entire conversation, including the system prompt and user message. When computing the loss, however, we mask out all system and user tokens (in PyTorch, setting their target labels to `-100`). Only the tokens generated by the assistant contribute gradients.

That masking keeps the model focused on predicting helpful answers rather than learning how to mimic user typos or generate follow-up questions. With anywhere from 10,000 to a couple million carefully written and curated dialogues, SFT teaches turn-taking, Markdown formatting, JSON tool calls, and clean stopping behavior.

### RLHF and reward models

SFT has a ceiling. Cross-entropy treats every deviation from one reference answer as an error, even when ten different phrasings are equally good. Worse, SFT gives almost no negative signal about *what not to do*: a subtle factual mistake or a slightly unhelpful tone looks nearly identical in token-level loss to a great answer.

Reinforcement Learning from Human Feedback (RLHF) fixes this by training on comparisons instead of single reference completions.

The classic RLHF pipeline runs in three steps. First, you generate multiple responses from the SFT model for the same prompt and ask human annotators (or stronger judge models) to pick which response is better, creating `(prompt, chosen, rejected)` pairs. Second, you train a separate **Reward Model** that takes a prompt and response and outputs a single scalar score, trained so `score(chosen) > score(rejected)`. Third, you optimize the assistant model (called the policy) with PPO (Proximal Policy Optimization) to generate responses that earn higher scores from the Reward Model.

Leaving PPO unchecked creates a classic failure called **reward hacking**. The model quickly discovers quirks in the Reward Model, such as writing overly long, sycophantic bullet lists or repeating flattering phrases that boost the score while making answers worse. To prevent the policy from drifting into nonsense, RLHF adds a **KL-divergence penalty** that punishes the model whenever its token probabilities wander too far from the original frozen SFT model.

### DPO (Direct Preference Optimization)

Classic PPO-based RLHF is notoriously finicky to run. You have to keep up to four large models in GPU memory at once: the active policy being trained, the frozen reference SFT model, the Reward Model, and a value/critic network for PPO variance reduction. Debugging unstable RL runs eats weeks of engineering time.

Direct Preference Optimization (DPO) mathematically rewrites the RLHF objective so you can skip the Reward Model and the PPO loop altogether.

Using a closed-form change of variables, DPO expresses the implicit reward directly in terms of the probability ratio between the active policy and the frozen reference model. You feed `(prompt, chosen, rejected)` pairs into a simple supervised-style training loop. The loss increases the likelihood of the `chosen` response relative to the reference model while pushing down the likelihood of the `rejected` response, scaled by a hyperparameter `beta` that controls how tightly the model stays anchored to the reference.

DPO is far simpler, cheaper, and easier to stabilize on modest hardware. Its main weakness is that standard DPO is **offline**: it only learns from the fixed pairs sitting in your dataset. Once the model changes, the dataset no longer reflects the mistakes the updated model currently makes. Online RL methods keep sampling fresh responses from the latest weights, which is why frontier labs still run online RL on top of or instead of DPO.

### RLVR and GRPO (verifiable rewards)

The biggest shift in modern post-training is **Reinforcement Learning with Verifiable Rewards (RLVR)**, often paired with an algorithm called **GRPO (Group Relative Policy Optimization)**.

Human preferences are noisy and expensive, and humans struggle to grade a 200-line algorithm or a tricky math proof accurately. For code, math, SQL, and formal logic, you do not need a human judge or a learned Reward Model. You have a deterministic verifier: a compiler, a unit test suite, or an exact mathematical checker.

GRPO makes online RL against verifiers much lighter than PPO by removing the separate critic network. For every prompt (say, a failing bug report with a test suite), the system samples a group of `G` candidate responses from the current policy, such as 8 or 16 complete reasoning-and-code rollouts. Every rollout runs against the verifier and gets an objective reward (`1` if all tests pass, `0` if anything fails, sometimes with small format bonuses).

GRPO then computes each rollout's advantage by subtracting the group's average reward and dividing by the group's standard deviation. Rollouts that solved the problem get reinforced; rollouts that failed get suppressed; and if all 16 rollouts pass or fail identically, the gradient signal is zero and the batch moves on.

Trained this way over hundreds of thousands of verifiable tasks, models spontaneously develop habits that look like careful engineering: breaking problems into sub-steps, checking edge cases, backtracking when a calculation looks wrong, and testing hypotheses before committing to an answer.

### Comparing the training stages

Each stage changes a different part of the system and demands a very different budget.

| Stage | Data shape | Training objective | Typical compute | What changes in the model |
| --- | --- | --- | --- | --- |
| Pre-training | Trillions of raw web, book, and code tokens | Next-token cross-entropy | Thousands of GPUs for weeks or months | World knowledge, syntax, coding and reasoning primitives |
| Mid-training | Hundreds of billions of long docs, clean code, and math | Next-token cross-entropy with RoPE scaling and LR decay | Small fraction (5% to 15%) of pre-training | Long context windows (128K+) and sharper technical accuracy |
| SFT | 10K to 2M `(prompt, response)` dialogues | Assistant-only masked cross-entropy | Hours to a few days on dozens of GPUs | Chat format, instruction following, tool-call syntax, stopping |
| RLHF (PPO) | Human-ranked `(prompt, chosen, rejected)` + online rollouts | Maximize learned reward minus KL penalty | Days on tens to hundreds of GPUs | Tone, helpfulness, safety boundaries, nuance |
| DPO | Offline `(prompt, chosen, rejected)` preference pairs | Closed-form preference log-ratio loss | Hours on 1 to 16 GPUs | Preference alignment without training a separate reward model |
| RLVR (GRPO) | Verifiable prompts with unit tests or exact graders | Group-relative advantage from verifier pass/fail | Days to weeks (rollout-bound) | Multi-step reasoning, self-correction, higher code/math pass rates |

## Practical fine-tuning: Full fine-tuning vs LoRA vs QLoRA

Unless you work at a frontier AI lab, you will not run pre-training or large-scale RLHF. What developers actually run in production is **fine-tuning**: taking an already post-trained model and adapting it to a specific task, taxonomy, or output style. For a quick glossary summary, see [fine-tuning](https://flaviocopes.com/ai-glossary/fine-tuning/).

When you fine-tune an open-weight model yourself (or submit a fine-tuning job to an API), the central architectural decision is how many parameters you update.

### Full fine-tuning and why memory explodes

**Full fine-tuning** unlocks every parameter in the model and updates all of them during backpropagation.

People often underestimate how much GPU VRAM full fine-tuning needs because they only count the size of the model file on disk. A 7-billion-parameter model stored in 16-bit precision (`BF16`, 2 bytes per parameter) takes about 14 GB to load for inference.

Training with the standard AdamW optimizer multiplies that footprint fast:

```text
7B model full fine-tuning memory (mixed precision + AdamW):
  BF16 model weights:             ~14 GB  (2 bytes/param)
  FP32 master weights copy:       ~28 GB  (4 bytes/param)
  Gradients (BF16/FP32):          ~14 to 28 GB
  AdamW optimizer states (m, v):  ~56 GB  (8 bytes/param in FP32)
  --------------------------------------------------------------
  Total before activations:       ~112 to 126 GB VRAM
```

Even with gradient checkpointing and sharded optimizers (like ZeRO or FSDP), full fine-tuning a 7B model demands multi-GPU or 80 GB datacenter hardware. Worse, every time you fine-tune that base model for a new customer or task, you end up storing and serving another full 14 GB copy of the weights.

### LoRA (Low-Rank Adaptation)

**LoRA** solves both the memory explosion and the deployment headache by exploiting an empirical property of neural networks: the weight *changes* needed to adapt a pretrained model to a new task have a very low intrinsic rank. You do not need to update every individual cell of a huge `4096 x 4096` weight matrix independently.

Instead of modifying a pretrained weight matrix `W0` (shape `d_in x d_out`), LoRA freezes `W0` completely. No gradients are stored for `W0`, and AdamW tracks zero optimizer states for it.

Next to `W0`, LoRA attaches two small, thin trainable matrices: `A` of shape `(d_in, r)` and `B` of shape `(r, d_out)`, where `r` is the **rank** (commonly 4, 8, 16, or 32). During the forward pass, the input `x` travels through both paths and their outputs are added together:

```text
h = x @ W0 + (alpha / r) * (x @ A @ B)
```

Look at the parameter reduction on a single `4096 x 4096` Transformer layer. The full matrix holds `16,777,216` parameters. A rank-16 LoRA adapter holds `4096 * 16 + 16 * 4096 = 131,072` parameters, just **0.78%** of the original layer.

```mermaid
flowchart TD
  accTitle: LoRA forward pass architecture
  accDescr: Input x splits between the frozen pretrained weight matrix W0 and the trainable low-rank A and B matrices scaled by alpha over r before summing into the output.
  X["Input vector x (dim d_in)"] --> W0["Frozen base weights W0 (no gradients)"]
  X --> A["Trainable matrix A (d_in x r, random init)"]
  A --> B["Trainable matrix B (r x d_out, zero init)"]
  B --> S["Scale by (alpha / r)"]
  W0 --> SUM["Element-wise sum (W0x + delta Wx)"]
  S --> SUM
  SUM --> OUT["Output vector h (dim d_out)"]
```

Four implementation details make LoRA work reliably in practice.

First, matrix `A` is initialized with small random Gaussian noise, while matrix `B` is initialized to all zeros. On training step 0, `A @ B` equals zero everywhere, so the model starts out producing the exact same outputs as the untouched pretrained model. If both `A` and `B` started with random values, the initial forward pass would inject random noise into every layer and destabilize early gradients.

Next, rank `r` sets the capacity of the adapter, and `alpha / r` sets the update scale. Simple formatting or classification tasks often converge at `r=8` or `r=16`, while learning a brand-new programming language or heavy style shift benefits from `r=32` or `r=64`. Many practitioners set `alpha = 2 * r` so the ratio stays fixed at `2.0` when experimenting with different ranks, avoiding a full learning-rate retune on every run.

Target module coverage matters too. The original 2021 LoRA paper only attached adapters to attention query and value projections (`q_proj`, `v_proj`). Later empirical work (including the QLoRA paper) showed that attaching LoRA to *all* linear layers in both attention and feed-forward MLP blocks (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`) matches full fine-tuning much more consistently across tasks.

Finally, LoRA adds zero inference latency overhead when merged. If you only need one adapted model, compute `W_merged = W0 + (alpha / r) * (A @ B)` offline and save a standard model with no extra operations at inference time. If you serve dozens of customers or tasks, keep one frozen `W0` loaded in VRAM and hot-swap tiny multi-megabyte adapter files per request.

### QLoRA (Quantized LoRA)

LoRA slashes optimizer and gradient memory, yet you still have to load the frozen base weights `W0` into memory. For a 70B model in BF16, the frozen base alone still takes 140 GB.

**QLoRA** fixes that bottleneck by quantizing the frozen base weights down to 4 bits using a data type called **NF4 (4-bit NormalFloat)**. Pretrained neural network weights tend to follow a zero-centered normal distribution. Standard 4-bit integers space their 16 quantization buckets evenly, wasting precision in the tails where few weights live. NF4 spaces its 16 buckets so each bin holds an equal share of a normal distribution, preserving far more accuracy at 4 bits.

QLoRA pairs NF4 with **double quantization** (quantizing the per-block scaling constants themselves, saving roughly 0.4 bits per parameter) and **paged optimizers** (using unified memory to spill temporary optimizer memory spikes to CPU RAM instead of crashing with an out-of-memory error). During each forward and backward step, a layer's NF4 weights dequantize on the fly to BF16 for the matrix multiplication, compute gradients, and immediately discard the temporary BF16 copy. Only the tiny BF16 LoRA adapters keep gradients and optimizer states.

With QLoRA, a 7B model fine-tunes comfortably inside 6 to 8 GB of VRAM, and a 70B model fits on a single 48 GB workstation GPU while recovering nearly the same accuracy as 16-bit LoRA.

## A real experiment: LoRA vs full fine-tuning vs prompting on 160 repo commits

Theory is nice, but fine-tuning choices get much clearer when you look at real training curves, exact parameter counts, and head-to-head accuracy against a prompted API model.

I pulled **160 real commit messages** from the Git history of `flaviocopes.com` and split them into **120 training commits** and **40 held-out test commits** across four balanced categories (30 training and 10 test commits per class):

- `apps` (Mac app pages, demo videos, downloads, app store metadata)
- `post` (blog posts, drafts, edits, article links)
- `courses_docs` (course schedules, newsletter lessons, project planning docs)
- `infra_fix` (SEO redirects, broken link fixes, site features, build scripts)

In this repository, commits usually carry a prefix like `apps:`, `post:`, `docs:`, `seo:`, `fix:`, or `feat:`. To make this a real classification test rather than a trivial regex match, we **stripped every prefix** before any model ever saw the text.

Here are eight real items from the 40-commit held-out test set, showing the original commit next to the stripped text the models actually received:

```text
Stripped input                                                             True class
------------------------------------------------------------------------------------------
add Vimeo demo video to rotating-shift-calendar-maker                      apps
redirect 32 unindexed old essays and fix links to them                     infra_fix
Clip Joiner plan, fifteen tutorials scheduled, 1.0.1 waiting for release   courses_docs
add Vimeo demo video to pdf-size-limit                                     apps
drop live links to the unpublished Agent SDK post                          infra_fix
add Theo's Antigravity Gemini subscription note to T3 Code guide           post
IBL day 13 to 17 emails scheduled in Sendy                                 courses_docs
announce AI Workshop Black Friday offer                                    infra_fix
```

Look closely at those examples. A few are obvious, like adding a Vimeo video to `pdf-size-limit`. Others are subtle repository conventions. "Clip Joiner plan, fifteen tutorials scheduled, 1.0.1 waiting for the release" mentions a Mac app, yet it was logged under `docs:` (`courses_docs`) because it updates a planning document. "drop live links to the unpublished Agent SDK post" mentions a blog post, yet it belongs to `infra_fix` (`fix:`). "announce AI Workshop Black Friday offer" was a `feat:` commit, placing it in `infra_fix`.

That ambiguity is exactly what real production classification looks like.

### Architecture and exact parameter math

Every commit string was embedded once with OpenAI's `text-embedding-3-small` model, producing a 1,536-dimensional vector per commit. All 160 commits combined used just **1,930 tokens** (about 12 tokens per commit), costing roughly **$0.0002 per 1,000 commits**.

On top of those 1,536-dimensional vectors, we built a 2-layer neural network (`1536 -> 256 -> 4` with a ReLU hidden layer and softmax cross-entropy loss) in pure NumPy, and trained it for 120 epochs in five modes: full fine-tuning, and LoRA adapters at ranks `r=2`, `r=4`, `r=8`, and `r=16`.

You can verify every parameter count by hand:

```text
Full fine-tuning (all weights trainable):
  W1 (1536 x 256) = 393,216
  b1 (256)        =     256
  W2 (256 x 4)    =   1,024
  b2 (4)          =       4
  Total           = 394,500 params  ->  770.5 KB in FP16

LoRA mode (W1 and b1 frozen; A and B wrap W1; linear head W2, b2 trainable):
  A (1536 x r) + B (r x 256) = (1536 + 256) * r = 1,792 * r
  Head W2 + b2               = 1,028
  r = 2   ->  1,792 *  2 + 1,028 =  4,612 params (1.17% of full,  9.0 KB FP16)
  r = 4   ->  1,792 *  4 + 1,028 =  8,196 params (2.08% of full, 16.0 KB FP16)
  r = 8   ->  1,792 *  8 + 1,028 = 15,364 params (3.89% of full, 30.0 KB FP16)
  r = 16  ->  1,792 * 16 + 1,028 = 29,700 params (7.53% of full, 58.0 KB FP16)
```

Seeing LoRA implemented in plain NumPy removes every bit of mystery about how gradients flow around a frozen weight matrix. Before looking at the full benchmark numbers, here is the core LoRA training loop using the exact `1536 -> 256 -> 4` dimensions, zero-initialized `B`, and `alpha / r` scaling:

```python
import numpy as np

def softmax(logits):
  shifted = logits - logits.max(axis=1, keepdims=True)
  exps = np.exp(shifted)
  return exps / exps.sum(axis=1, keepdims=True)

def cross_entropy(probs, y):
  return float(-np.log(probs[np.arange(len(y)), y] + 1e-12).mean())

def train_lora(X_train, y_train, X_val, y_val, W1_frozen, b1_frozen, rank=16, alpha=32.0, lr=0.05, epochs=120):
  rng = np.random.default_rng(42)
  d_in, d_hidden, n_classes = 1536, 256, 4
  scale = alpha / rank

  # Matrix A starts with small random values; matrix B starts at exact zero
  # so the adapter outputs zero delta on epoch 0.
  A = rng.normal(0.0, 0.02, size=(d_in, rank))
  B = np.zeros((rank, d_hidden))
  W2 = rng.normal(0.0, 0.02, size=(d_hidden, n_classes))
  b2 = np.zeros(n_classes)

  n = len(X_train)
  for epoch in range(1, epochs + 1):
    # Forward pass: frozen base path + scaled low-rank branch
    low_rank = X_train @ A
    pre_act = (X_train @ W1_frozen) + b1_frozen + scale * (low_rank @ B)
    hidden = np.maximum(0.0, pre_act)
    probs = softmax(hidden @ W2 + b2)

    # Backward pass: gradients only flow into W2, b2, A, and B (W1_frozen stays untouched)
    d_logits = probs.copy()
    d_logits[np.arange(n), y_train] -= 1.0
    d_logits /= n

    d_W2 = hidden.T @ d_logits
    d_b2 = d_logits.sum(axis=0)

    d_hidden = d_logits @ W2.T
    d_pre = d_hidden * (pre_act > 0.0)

    d_B = scale * (low_rank.T @ d_pre)
    d_A = scale * (X_train.T @ (d_pre @ B.T))

    # Parameter update
    A -= lr * d_A
    B -= lr * d_B
    W2 -= lr * d_W2
    b2 -= lr * d_b2

    if epoch in (1, 10, 30, 60, 120):
      val_pre = (X_val @ W1_frozen) + b1_frozen + scale * ((X_val @ A) @ B)
      val_probs = softmax(np.maximum(0.0, val_pre) @ W2 + b2)
      val_loss = cross_entropy(val_probs, y_val)
      val_acc = float((val_probs.argmax(axis=1) == y_val).mean() * 100.0)
      print(f'epoch {epoch:3d} | val_loss={val_loss:.4f} | val_acc={val_acc:.1f}%')

  return A, B, W2, b2
```

Notice how clean the gradient path is. `W1_frozen` participates in the forward pass to produce `pre_act`, yet we never compute `d_W1` and never touch `W1_frozen`. All of the adaptation happens inside `A` and `B`, multiplied by `scale = alpha / rank`.

### Running the benchmark and reading the numbers

Here is the terminal output from running all five training configurations alongside OpenAI `gpt-4.1-mini` (both zero-shot and 8-shot) on the exact same 40 held-out commits:

![Terminal output of the LoRA versus full fine-tuning and gpt-4.1-mini benchmark on 160 repository commits](https://flaviocopes.com/images/llm-training-fine-tuning/lora-training-run.webp)

Putting every measured run into one table makes the tradeoffs jump off the screen:

| Method | Trainable params | % of full | FP16 size | Final val loss | Held-out val acc | Latency / cost notes |
| --- | --- | --- | --- | --- | --- | --- |
| Full fine-tune | 394,500 | 100.00% | 770.5 KB | 0.5988 | 82.5% (33/40) | 1348.9 ms train; <1 ms local inference |
| LoRA (`r=2`) | 4,612 | 1.17% | 9.0 KB | 0.7911 | 65.0% (26/40) | 1892.8 ms train; <1 ms local inference |
| LoRA (`r=4`) | 8,196 | 2.08% | 16.0 KB | 0.7975 | 62.5% (25/40) | 1814.6 ms train; <1 ms local inference |
| LoRA (`r=8`) | 15,364 | 3.89% | 30.0 KB | 0.6692 | 72.5% (29/40) | 2218.2 ms train; <1 ms local inference |
| LoRA (`r=16`) | 29,700 | 7.53% | 58.0 KB | 0.6654 | 82.5% (33/40) | 3596.3 ms train; <1 ms local inference |
| `gpt-4.1-mini` (0-shot) | 0 | 0% | 0 KB | N/A | 45.0% (18/40) | 552.4 ms p50; 61.6 in tok; $0.0264 / 1k |
| `gpt-4.1-mini` (8-shot) | 0 | 0% | 0 KB | N/A | 55.0% (22/40) | 528.4 ms p50; 223.7 in tok; $0.0914 / 1k |

At rank `r=16`, LoRA matched full fine-tuning's **82.5%** held-out accuracy while training only **29,700 parameters** (7.53% of full, or **92.5% fewer** trainable parameters), shrinking the FP16 artifact from **770.5 KB** down to **58.0 KB**.

Looking at the epoch-by-epoch validation loss curves shows *how* LoRA learns differently from full fine-tuning:

![Chart showing trainable parameters, held-out validation accuracy, and epoch-by-epoch validation loss across full fine-tuning, LoRA ranks, and gpt-4.1-mini prompting](https://flaviocopes.com/images/llm-training-fine-tuning/lora-vs-prompting.webp)

Several real details in those curves are worth calling out directly.

First, look at epochs 1 through 30. Full fine-tuning starts moving immediately: validation loss drops from `1.3879` at epoch 1 to `1.3227` at epoch 10 (55.0% accuracy) and `1.0978` at epoch 30 (57.5%). Every LoRA run starts sluggishly by comparison. At epoch 10, all four LoRA ranks still sit at `17.5%` validation accuracy with loss hovering between `1.3961` and `1.3991`. That slow warm-up is a direct consequence of zero-initializing `B`: in the earliest steps, gradients have to pull `B` away from zero before the `A @ B` branch builds meaningful magnitude. Once `r=16` clears that warm-up, it accelerates fast, jumping from `40.0%` at epoch 30 to `60.0%` at epoch 60 (val loss `0.9320`) and reaching `82.5%` at epoch 120 (val loss `0.6654`).

Second, notice that `r=4` finished at `62.5%` (val loss `0.7975`), slightly behind `r=2` at `65.0%` (val loss `0.7911`). On a 40-commit test set, a single flipped prediction moves accuracy by `2.5%`. Whenever your evaluation set is small, always read validation loss alongside accuracy. Both `r=2` and `r=4` were clearly capacity-starved around `0.79` loss, whereas bumping rank to `r=8` dropped validation loss sharply to `0.6692` (72.5% accuracy), and `r=16` pushed accuracy to `82.5%` (`0.6654` loss).

Third, look honestly at the training wall-clock time: full fine-tuning finished in `1348.9 ms`, while LoRA took `1892.8 ms` to `3596.3 ms`. On a tiny 394K-parameter NumPy model running on CPU, splitting one matrix multiply into `x @ W1 + (x @ A) @ B` adds extra Python and small-array overhead. On a 7B or 70B LLM running on a GPU, the math flips completely: optimizer states and VRAM bandwidth dominate, so shrinking trainable parameters by 92%+ is what keeps the job inside GPU memory and speeds up multi-GPU gradient synchronization.

## Prompting vs few-shot vs RAG vs LoRA fine-tuning

The headline gap in our benchmark is dramatic: `gpt-4.1-mini` scored **45.0%** zero-shot (18/40) and **55.0%** with 8 few-shot examples (22/40), while the `r=16` LoRA classifier reached **82.5%** (33/40).

Cost and latency diverged even more sharply. Zero-shot prompting averaged **61.6 input tokens** and **1.1 output tokens** at **552.4 ms** median latency, costing roughly **$0.0264 per 1,000 commits**. Adding 8 few-shot examples (two per class) nearly quadrupled input tokens to **223.7** at **528.4 ms** median latency, lifting the cost to **$0.0914 per 1,000 commits**. Meanwhile, embedding the commit (~12 tokens) and running the 58.0 KB LoRA adapter locally took under **1 ms** after the embedding call and cost roughly **$0.0002 per 1,000 commits**, over 450x cheaper than 8-shot prompting.

So why did prompting lose by nearly 30 percentage points here?

Because our commit taxonomy encodes *private repository habits*, not universal world knowledge. Seeing `"Clip Joiner plan, fifteen tutorials scheduled, 1.0.1 waiting for the release"`, `gpt-4.1-mini` naturally guesses `apps`, because Clip Joiner is an app with a version number `1.0.1`. On `"drop live links to the unpublished Agent SDK post"`, it leans toward `post`. Given `"announce AI Workshop Black Friday offer"`, it has no way of knowing that site-wide feature banners live in `infra_fix` rather than `courses_docs`.

Eight examples in a prompt can only sketch the edges of four classes. One hundred twenty labeled examples converted into weight updates carve out the exact geometric boundaries of how *this* repository labels work.

### Why fine-tuning still loses for changing facts

It is tempting to look at that `82.5%` vs `55.0%` jump and conclude that fine-tuning beats prompting everywhere. That would be a serious mistake.

Fine-tuning excels at **stable patterns**: classification boundaries, house writing tone, domain jargon, strict JSON schemas, and compact model distillation. It is a poor mechanism for **mutable facts**.

If you fine-tune a model on your product documentation, pricing tiers, or customer records, three bad things happen right away:

- Updating a single changed fact requires re-running a training pipeline instead of updating a database row.
- The model blends old memorized facts with new ones and cannot cite which document a claim came from.
- Access control breaks, because every user who talks to the model shares the same baked-in weights.

For knowledge that changes weekly, daily, or per user, **RAG (Retrieval-Augmented Generation)** wins every time. Fetch the relevant chunks at query time, paste them into the context window with source IDs, and keep the weights clean.

### Choosing the right adaptation layer

| Approach | Setup effort | Inference latency | Cost at high volume | Updating facts | Style and taxonomy control | Best fit |
| --- | --- | --- | --- | --- | --- | --- |
| Zero-shot prompting | Minutes | Medium to high (API call) | Medium | Instant (edit prompt) | Moderate | Early prototypes, general reasoning, low volume |
| Few-shot prompting | Minutes to hours | Medium to high (more input tokens) | Higher (2x to 5x input tokens) | Instant (swap examples) | Good for clear patterns | Medium ambiguity where 5 to 10 examples cover edge cases |
| RAG + prompting | Hours to days | Medium (retrieval + LLM call) | Medium | Instant (re-index docs) | Depends on prompt | Changing docs, private knowledge bases, cited answers |
| LoRA fine-tuning | Days (data + eval + train) | Very low (small model or merged adapter) | Very low | Slow (retrain adapter) | High | High-volume classification, narrow formats, private taxonomies, local/offline models |
| Full fine-tuning | Days to weeks (multi-GPU) | Low (one merged checkpoint) | Low per token, high ops | Very slow | Maximum | New languages, deep domain pre-training, lab-scale post-training |

```mermaid
flowchart TD
  accTitle: Decision tree for choosing prompting, RAG, or fine-tuning
  accDescr: Follow questions about changing facts, prompt evaluation accuracy, and labeled data volume to choose between RAG, prompting, LoRA, or full fine-tuning.
  S["Start: task needs better LLM output"] --> Q1{"Does the task rely on fresh or changing facts?"}
  Q1 -->|"Yes"| RAG["Use RAG (keep facts in search, not weights)"]
  Q1 -->|"No"| Q2{"Do prompting, few-shot, and strict schemas pass your eval?"}
  Q2 -->|"Yes"| PROMPT["Stay on prompting (cheapest to maintain)"]
  Q2 -->|"No"| Q3{"Do you have 100+ clean examples and high volume or tight latency?"}
  Q3 -->|"No"| DATA["Collect real labeled data and build an eval set first"]
  Q3 -->|"Yes"| Q4{"Is this a brand-new language or deep domain shift?"}
  Q4 -->|"No"| LORA["Train a LoRA or QLoRA adapter"]
  Q4 -->|"Yes"| FULL["Consider continual pre-training or full fine-tuning"]
```

## Preparing real fine-tuning data

Every experienced ML engineer repeats the same lesson because teams keep re-learning it the hard way: **dataset quality beats clever hyperparameters every single time**. One hundred clean, consistent examples with unambiguous labels routinely outperform ten thousand messy scraped rows.

If you want to run a managed chat fine-tuning job (such as OpenAI's fine-tuning API) or train an open-weight instruct model with LoRA, your data is almost always stored as **JSONL** (JSON Lines), where each line is one complete conversation object containing a `messages` array.

From our exact 120 training commits, exporting to OpenAI's fine-tuning format produces a **120-line** file taking **30,524 bytes** (about 30.5 KB). Each line looks like this:

```json
{"messages":[{"role":"system","content":"Classify the repository commit message into one label: apps, post, courses_docs, or infra_fix. Reply with only the label."},{"role":"user","content":"add Vimeo demo video to rotating-shift-calendar-maker"},{"role":"assistant","content":"apps"}]}
{"messages":[{"role":"system","content":"Classify the repository commit message into one label: apps, post, courses_docs, or infra_fix. Reply with only the label."},{"role":"user","content":"redirect 32 unindexed old essays and fix links to them"},{"role":"assistant","content":"infra_fix"}]}
{"messages":[{"role":"system","content":"Classify the repository commit message into one label: apps, post, courses_docs, or infra_fix. Reply with only the label."},{"role":"user","content":"Clip Joiner plan, fifteen tutorials scheduled, 1.0.1 waiting for the release"},{"role":"assistant","content":"courses_docs"}]}
{"messages":[{"role":"system","content":"Classify the repository commit message into one label: apps, post, courses_docs, or infra_fix. Reply with only the label."},{"role":"user","content":"add Theo's Antigravity Gemini subscription note to T3 Code guide"},{"role":"assistant","content":"post"}]}
```

Before you upload a JSONL file or kick off a local GPU run, check four dataset basics.

### Deduplicate before splitting

Real production logs are full of near-duplicates. In our commit dataset, several Mac apps got similar demo video commits (`add Vimeo demo video to rotating-shift-calendar-maker`, `add Vimeo demo video to pdf-size-limit`). If exact duplicates appear in both your training split and your validation split, your validation score shoots up artificially while real-world accuracy stays flat. Deduplicate first, and when items belong to the same project or user session, split by group or timestamp so near-clones stay on one side of the split.

### Hunt for label leakage

Leakage is any accidental shortcut in the input that gives away the label during training yet will not exist in production. In our commit experiment, keeping the `apps:` or `docs:` prefix would have handed every model a 100% score without learning a single word of the commit description. In real apps, leakage sneaks in through timestamp formats, internal ticket IDs, boilerplate footers, or pre-sorted file names. Inspect 20 random training rows by eye and ask: "Could a dumb regex guess the label from a stray token?"

### Check class balance

In our experiment, all four classes had exactly 30 training rows and 10 test rows. Production datasets are rarely balanced. If 88% of your support logs fall into one category and 2% fall into a rare critical category, a model that predicts the majority class on every request scores 88% accuracy while missing 100% of the rare cases. Track per-class precision, recall, and a confusion matrix, and either stratify your split or rebalance the training set.

### Lock your held-out evaluation set

Never tune hyperparameters, prompts, or epochs directly on your final test set. Keep a small validation split to watch loss curves and pick a stopping epoch, and keep a separate held-out test split that you only evaluate once a candidate model looks ready. Whenever you fix bad labels in the training data, audit the test split with the exact same rubric so you are measuring real progress rather than label drift.

## Common fine-tuning failure modes

Fine-tuning modifies the model's weights directly, which introduces failure modes you never hit with pure prompting.

### Catastrophic forgetting

When you train hard on a narrow dataset, gradient updates push weights toward your task at the expense of capabilities the model already had. A general coding assistant fine-tuned exclusively on terse one-word classification labels can start answering normal user questions with broken fragments, forget how to format Markdown, or lose its refusal boundaries.

LoRA reduces catastrophic forgetting naturally because the frozen base weights remain intact and the adapter has limited capacity. Even with LoRA, keep your learning rate conservative, avoid training for excessive epochs, and if the adapted model still needs to handle general chat alongside your specialized task, mix 10% to 20% general instruction-following examples back into the fine-tuning dataset.

### Overfitting small datasets

With only a few hundred examples, a neural network has far more capacity than information. Left running too long, it memorizes the training rows word for word.

You can already see the early edge of that gap in our own `r=16` LoRA run. By epoch 120, training loss fell to `0.3086`, while validation loss settled at `0.6654`. That gap was still healthy because validation accuracy kept climbing to `82.5%`. Push that same run to 500 epochs, and training loss would drop below `0.02` while validation loss climbs back above `1.0` as the model over-commits to quirks in the 120 training commits.

Always log validation loss at regular intervals and save the checkpoint with the lowest validation loss (early stopping), rather than blindly taking the final epoch.

### Benchmark contamination

If your training data includes public benchmark questions (either accidentally scraped from the web or generated by a teacher model that memorized them), your evaluation numbers stop reflecting reality. This happens subtly in company repos too: developers export a CSV of past tickets, run a cleaning script, forget that an earlier version of the same tickets is sitting in the test fixture folder, and celebrate a jump from 70% to 98% that evaporates on day one in production. Hash-check every test input against your training set before trusting a single metric.

### Stale knowledge baked into weights

Fine-tuning freezes a snapshot of the world inside floating-point numbers. Suppose you fine-tune an open-weight model on your 2025 API specification so it stops making syntax mistakes. Six months later, you ship v2 of the API with renamed endpoints. Even when you paste the new v2 documentation into the system prompt, the fine-tuned weights actively fight the context and slip old v1 parameter names back into generated code.

Keep changing reference material outside the weights. Fine-tune on *how* to read documentation and format answers, and supply the latest documentation at runtime.

## How I would use it

Most developers reach for fine-tuning far too early.

If I were building a new AI feature for a web app or a Mac utility today, I would **not** start by training a LoRA adapter. For roughly 90% of real features, I would start with a capable API model, a tight system prompt, strict JSON schema outputs, and a repeatable evaluation script with 30 to 50 real test cases from the actual domain.

Prompting plus evals has a massive operational advantage. Iterating on a prompt takes thirty seconds. When a faster or cheaper model drops next month, I change one model string, re-run my eval script, and collect the upgrade for free. No GPU rentals, no dataset pipelines, no adapter versioning, and no risk of baking stale assumptions into weights.

I would only move to fine-tuning once my evaluation script proved a clear wall that prompting could not cross, or when unit economics made API prompting painful at scale. Specifically, I would use LoRA fine-tuning in three concrete situations:

- **High-volume routing and classification with a private taxonomy:** Exactly like the repository commit task in this post. If I needed to classify tens of thousands of incoming bug reports, site commits, or newsletter replies every month into custom internal buckets where 8-shot prompting still stalls around 55%, a tiny 58 KB LoRA adapter on embeddings (or a fine-tuned small open-weight model) cuts latency to milliseconds and drops cost by two orders of magnitude.
- **Replacing bloated few-shot prompts on a narrow, stable task:** When a production pipeline has to prepend 2,500 tokens of formatting rules and edge-case examples on every single API call just to get reliable output, baking those rules into a LoRA adapter removes the prompt tax and locks in consistent structure.
- **Distilling a frontier model into a small local or cheap model:** I would use a strong frontier model to generate and verify 500 to 2,000 clean `(input, output)` pairs for one repetitive job (such as structured metadata extraction or deterministic code transforms), audit a sample by hand, and LoRA fine-tune a small open-weight model to handle that job locally or at a fraction of the API cost.

And I would stay completely away from fine-tuning in a few clear poor-fit cases: anything driven by fast-changing documentation, pricing, or user-specific state (use RAG or SQL); low-volume tools where even an unoptimized API costs five dollars a month; early prototypes whose output schema changes every week; and any project where I have not built a clean held-out eval set yet. Without a held-out benchmark, fine-tuning just gives you a faster, more expensive way to guess whether the model got better.
