Now for the main goal of this course. Fine-tuning a language model, to write the answers we want. Let's start with the most direct way, full fine-tuning, and see what it costs.
Here's a tiny training loop, written by hand. We count the trainable parameters. The Adam W optimizer will update every one of them. We repeat one example, eight times, as a batch. Each step computes the loss, runs backward, and updates the weights. Finally, we count how many numbers Adam has stored. Run it. All one hundred and thirty four million parameters are trainable. The loss falls quickly. And Adam stores two hundred and sixty nine million extra numbers. Exactly two for every parameter, just like our memory rule said.
app.pypython
import time, torchfrom transformers import AutoTokenizer, AutoModelForCausalLMname = "HuggingFaceTB/SmolLM2-135M-Instruct"tok = AutoTokenizer.from_pretrained(name)model = AutoModelForCausalLM.from_pretrained(name)trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)print(f"Trainable parameters: {trainable:,}")optimizer = torch.optim.AdamW(model.parameters(), lr=2e-5)batch = tok(["Is Dune in stock? Yes, we have 3 copies."] * 8, return_tensors="pt")start = time.time()for step in range(1, 4): loss = model(**batch, labels=batch["input_ids"]).loss loss.backward(); optimizer.step(); optimizer.zero_grad() print(f"step {step}: loss {loss.item():.3f}")print(f"Time per step: {(time.time() - start) / 3:.1f} s")saved = sum(v.numel() for s in optimizer.state.values() for v in s.values() if v.dim())print(f"Numbers stored by Adam: {saved:,}")
Output
Trainable parameters: 134,515,008
step 1: loss 4.685
step 2: loss 3.849
step 3: loss 3.190
Time per step: 0.6 s
Numbers stored by Adam: 269,030,016
For our small model, that's fine. But remember the calculator. For an eight billion parameter model, the same loop needs over a hundred gigabytes of memory. And every fine-tuned copy is a full sized model to store. Ten customers, ten full copies.
Let's recap. Full fine-tuning updates every parameter. Adam stores two extra numbers for each one. It works for small models, but gets very expensive for big ones. Next, how labels work when a model learns to write.