Skip to content

Training a model

Chapter 4 3 code blocks 2261 words

One training step, step by step

Say this

Take a batch, run the forward pass, compute the loss, backpropagate to get gradients, let the optimizer update the weights, zero the gradients. For an embedding model: a batch of N query–positive pairs, a similarity matrix divided by a temperature, and cross-entropy where the right answer for each query is its own positive.

python5 lines
q, p   = model(queries), model(passages)    # normalized vectors
scores = q @ p.T / tau                       # N x N, tau ≈ 0.02-0.05
loss   = cross_entropy(scores, arange(N))    # diagonal = correct pair
loss.backward()                              # gradients for every weight
optimizer.step(); optimizer.zero_grad()      # AdamW update, reset

Example project

I ran exactly this loop when I trained my CRNN OCR model from scratch (CTC loss) and the Tez LoRA fine-tune (cross-entropy on the next token, only the LoRA weights trainable). Describe one of them as your real example.

If they push

  • Bigger batches mean more in-batch negatives, which makes contrastive training stronger.

How training actually works: loss, gradient, backprop

Say this

The loss is one number for how wrong the model is. For an LLM it's cross-entropy, the negative log of the probability the model gave the correct next token. The gradient tells, for every weight, which direction increases the loss and how strongly. Backpropagation computes all those gradients in one backward pass using the chain rule: start at the loss and go back layer by layer, each layer multiplying the incoming gradient by its own local derivative. Then the optimizer moves each weight against its gradient. I used AdamW at learning rate 2e-4 with warmup, which adapts the step size per weight. In my Tez fine-tune I accumulated gradients over 16 examples per step, computed the loss only on the answer tokens, and with LoRA the gradients flowed through the frozen 4-bit base but only updated the small adapter matrices. Training loss went down to about 0.04 per token, and I watched validation loss for overfitting.

The loop in one sentence: guess → measure how wrong → find which way each weight should move → move it a little → repeat.

A tiny example you can do by hand. A "model" with one weight: prediction = w × x. Input x = 2, correct answer = 10, start with w = 3, learning rate 0.05.

StepWhat happensNumbers
Forward passthe model guesses3×2=6
Losshow wrong: (guess−answer)2(6−10)2=16
Gradient∂L∂w=2·(guess−answer)·x2·(−4)·2=−16
Updatew←w−η·∂L∂w3−0.05·(−16)=3.8
Checknew guess, new loss7.6 → loss 5.76
w←w−η·∂L∂w
ηlearning rate (lr), 0.05 in this example
∂L∂wthe gradient: step against it to lower the loss
∂L∂w=2·(guess−answer)·x
∂L∂whow much the loss changes when w moves a little
xthe input

The gradient is negative, meaning "a bigger w lowers the loss", so w goes up. Repeat and w approaches 5, where the loss is 0. A real model does exactly this for billions of weights at once.

What each part really is

  • Loss (cross-entropy): at each position the model gives a probability to every token in its vocabulary (about 151k for Qwen). L=−logpcorrect. Correct token at 0.9 → 0.105 (good); at 0.1 → 2.30 (bad).
    L=−logpcorrect
    pcorrectthe probability the model gave the correct token
    −logp = 1 gives loss 0; as p gets small the loss grows fast
  • Gradient: "which way and how much" for every weight.
  • Backpropagation: the network is functions inside functions, so the chain rule applies. The forward pass saves each layer's outputs; the backward pass starts at the loss and goes toward the input, each layer multiplying the gradient from above by its own local derivative. One backward pass, about 2× the cost of a forward pass, gives every gradient.
  • Optimizer (AdamW): keeps running averages of each weight's gradients (momentum) and of their squares, so every weight gets its own step size, plus weight decay.
  • Learning rate: too big and the loss jumps and explodes; too small and training crawls. A short warmup, then a decay.

Example project

  • Accumulation: 16 examples go forward one at a time, their gradients are summed, then one AdamW step. That's an effective batch of 16 that fits in 16 GB.
  • Loss only on the answer (train_on_responses_only): the system prompt and request add no loss; only the JSON plan tokens do.
  • LoRA: gradients flow back through the frozen 4-bit base (its activations are needed), but only the LoRA matrices A and B are updated, about 0.5% of the parameters.
  • lr 2e-4, 3% warmup, 1 epoch. Training loss about 0.044 per token (tez8, steps 301–400). 5% of rows held out for validation.

If they push

  • Overfitting: validation loss rises while training loss falls. My Tez lesson: 39/40 on the tuning set had to be confirmed on held-out questions.
  • Vanishing / exploding gradients: multiplying many small or large numbers back through deep layers. Fixes: residual connections, normalization, gradient clipping.
  • Epoch / step / batch: one pass over all the data / one weight update / the examples used for one update.
  • Why the minus sign: the gradient points uphill, toward more loss, so we step the opposite way.
  • LoRA formula: y=Wx+αr·BAx. B starts at zero, so training starts from the original model.
    y=Wx+αr·BAx
    Wthe original weights, frozen
    B,Atwo small trained matrices; only these change
    rrank, 16 in Tez
    αscaling, 32 in Tez

First, name what kind of training it was

When asked "describe training a full model", be exact. There are three levels, and I did the third:

LevelWhat changesCostMe?
PretrainingAll weights, learned from trillions of tokensThousands of GPUs, monthsNo. Qwen did this.
Full fine-tuningAll 4B weights, on task dataAbout 60+ GB GPU memory for a 4B model (weights, gradients, Adam states)No
QLoRA fine-tuningBase frozen in 4-bit; small LoRA adapters trainedOne 16 GB GPU (my RTX 5070 Ti)Yes

The task: Tez is an offline Excel assistant for banks, where cloud AI is banned. The model reads a request in Uzbek (Latin or Cyrillic), Russian, English or a mix, plus a description of the table, and outputs a JSON plan of tool calls (19 tools: filter, group_and_total, top_n, make_chart, export_xlsx, …), or asks a question when the request is unclear. DuckDB executes the plan, so the model never does arithmetic.

  1. User
    the request plus a description of the table
    filiallar bo'yicha jami qarz
  2. Model
    returns a plan, never numbers
    {"tool": "group_and_total", "group_by": ["filial"], "column": "qarz", "agg": "sum"}
  3. DuckDB
    computes the real totals: numbers are computed, never generated
1

Measure before training

What
Test base models with no training, on the same task, executing their plans.
Result
On 40 test tasks on CPU: Qwen3.5-0.8B got 12, 1.5B-coder 17, 2B 20, 4B 34. Every model also turned "remove X" into "keep X", and none asked on unclear input.
Why
It shows whether training is needed and which base to train: the 4B, because it was the strongest that still runs on an office laptop CPU.
2

Design the data: plan first, request second

What
I had no real labelled bank requests, and couldn't use bank data. So I generated the data in reverse: make a correct plan first, then have a model write the request a person would type for it.
How
  1. 1
    18 synthetic domain tables
    loans, sales, payroll, cash, retail ...
  2. 2
    Headers renamed like real Excel
    codes, "G1", "column 1", Cyrillic
  3. 3
    Plan generator
    builds a VALID plan from the table
    training/plans.py
  4. 4
    Teacher model phrases the request
    Gemma, local: uz-Latin, uz-Cyrillic, ru, en, mixed; short and long; typos
  5. 5
    Execute the plan in DuckDB
    with the real tools; keep the row only if it runs
  6. 6
    Roundtrip check
    a checker model reads ONLY the request and writes its own plan; keep the row only if both give the same result table
  7. 7
    Coverage gates
    length mix, tool mix, column-name styles compared with the tests
  8. 8
    Export
    ChatML train.jsonl
Why
Starting from the plan guarantees the label is correct and executable. The roundtrip check throws away requests that don't actually say what the plan does. A teacher that leaves out "remove" or the save location gets rejected.
Special rows
Ask rows (unclear request → the right answer is a question) and cannot rows (the table has no such column → explain why), so the model learns not to guess.
Size
tez8: 19,886 rows. tez17 (the product): 38,258 rows.
3

Format of one training row

How
json6 lines
{"messages": [
  {"role": "system",    "content": "tools: ...19 tool definitions...
                                     table: columns, types, sample values"},
  {"role": "user",      "content": "filiallar bo'yicha jami qarz"},
  {"role": "assistant", "content": "{\"tool\":\"group_and_total\", ...}"}
]}
Key setting
train_on_responses_only: true: the loss is computed only on the assistant's answer. The model learns to write plans, not to repeat the system prompt.
4

Training run: my real config

Config
matn6 lines
base: Qwen/Qwen3.5-4B       task: sft       format: chatml
quantization: 4bit (QLoRA)  max_length: 4096   val_split: 0.05
lora: r 16, alpha 32, dropout 0.05, attention projections
epochs: 1    lr: 2e-4    warmup: 3%
batch_size: 1 × gradient_accumulation 16  (= effective batch 16)
gradient_checkpointing: on          save every 200 steps
What happens in one step
16 examples pass forward one at a time (gradient accumulation, to fit in 16 GB) → cross-entropy on the next token, only over the answer tokens → backprop through the frozen 4-bit base into the LoRA matrices A and B only → AdamW updates about 0.5% of the parameters → repeat.
Why these choices
4-bit base + LoRA fits a 4B model on one 16 GB GPU. Gradient checkpointing trades compute for memory. One epoch because a second risked memorizing my generated style.
Time
About 13 hours per run, including merge, conversion and quantization.
5

Make it run on a laptop

How
Merge the LoRA adapter into the base weights → convert to GGUF (bf16) → quantize to Q4_K_M → run with llama.cpp on CPU. The tool JSON schemas become a GBNF grammar, so the model can only produce valid JSON with listed tool names and listed values.
Numbers
About 2.9 s per answer on 4 CPU threads, about 4.5 GB RAM (tez8 measurements).
A lesson
llama.cpp puts optional schema keys after required ones. That changed the key order the model was trained on and cost a 7-hour run. Now every key is required inside its schema, and I check the generated grammar against the training order.
6

Evaluate by execution

How
1,410 test requests: clean, noisy (typos), real public tables never seen in training, and fresh held-out sets kept sealed. Each answer's plan is executed and its result table compared with the expected one.
Metrics
Right, silent wrong (a plan that runs and looks right but gives a different result; the dangerous kind for a bank), and should-ask caught.
Discipline
Pass rules frozen before seeing results; same engine, grammar and machine for every model; one change per run; a control retrain to measure normal churn; bootstrap confidence intervals.
7

Results and the guard

Progress
ModelToolsRight / 1,410Silent wrongShould-ask caught / 162
tez8151,066138143
tez17 (product)191,29855147
tez18191,28761142 (rejected)
Guard
After the model: a confidence gate (mean token probability ≥ 0.94) and a validator with 5 checks, such as "empty result", "the filter kept every row" and "the grouping changed nothing". If held, the user is asked instead of getting a wrong number.
Honest point
tez18 had more data and got worse, so it was rejected. More rows don't automatically mean a better model; that's why the rules are frozen first.

The 90-second answer

Say this

"I didn't pretrain or fully fine-tune; I did QLoRA fine-tuning of Qwen3.5-4B for Tez, an offline Excel assistant for banks. The model turns a request in Uzbek, Russian or English into a JSON plan of tool calls, and DuckDB executes it, so numbers are never generated. First I measured base models: the 4B planned 34 of 40 correctly, smaller ones much fewer. With no real labelled data, I generated it in reverse: a generator makes a valid plan on fake bank tables, a local teacher model writes the request a person would type in several languages and styles, I execute the plan in DuckDB, and a second model must recover the same result from the request alone, otherwise the row is dropped. That gave 38,258 rows in ChatML. Training: 4-bit base, LoRA rank 16 on the attention projections, learning rate 2e-4, effective batch 16, one epoch, loss only on the answer tokens, on one 16 GB GPU, about 13 hours. Then I merge, convert to GGUF Q4_K_M and run on CPU with a grammar that forces valid JSON. I evaluate by executing plans on 1,410 requests: right answers went from 1,066 to 1,298 and silent wrong answers from 138 to 55 between tez8 and tez17."

Questions about this chapter?

The course, homework review and the other five books are in Uzbek. Questions in English are welcome on Telegram.

Write on Telegram Contents