Training a model
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.
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.
| Step | What happens | Numbers |
|---|---|---|
| Forward pass | the model guesses | |
| Loss | how wrong: | |
| Gradient | ||
| Update | ||
| Check | new guess, new loss | 7.6 → loss 5.76 |
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). . Correct token at 0.9 → 0.105 (good); at 0.1 → 2.30 (bad).the probability the model gave the correct tokenp = 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: . B starts at zero, so training starts from the original model.the original weights, frozentwo small trained matrices; only these changerank, 16 in Tezscaling, 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:
| Level | What changes | Cost | Me? |
|---|---|---|---|
| Pretraining | All weights, learned from trillions of tokens | Thousands of GPUs, months | No. Qwen did this. |
| Full fine-tuning | All 4B weights, on task data | About 60+ GB GPU memory for a 4B model (weights, gradients, Adam states) | No |
| QLoRA fine-tuning | Base frozen in 4-bit; small LoRA adapters trained | One 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.
- Userthe request plus a description of the tablefiliallar bo'yicha jami qarz
- Modelreturns a plan, never numbers{"tool": "group_and_total", "group_by": ["filial"], "column": "qarz", "agg": "sum"}
- DuckDBcomputes the real totals: numbers are computed, never generated
Measure before training
Design the data: plan first, request second
- 118 synthetic domain tablesloans, sales, payroll, cash, retail ...
- 2Headers renamed like real Excelcodes, "G1", "column 1", Cyrillic
- 3Plan generatorbuilds a VALID plan from the tabletraining/plans.py
- 4Teacher model phrases the requestGemma, local: uz-Latin, uz-Cyrillic, ru, en, mixed; short and long; typos
- 5Execute the plan in DuckDBwith the real tools; keep the row only if it runs
- 6Roundtrip checka checker model reads ONLY the request and writes its own plan; keep the row only if both give the same result table
- 7Coverage gateslength mix, tool mix, column-name styles compared with the tests
- 8ExportChatML train.jsonl
Format of one training row
{"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\", ...}"}
]}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.Training run: my real config
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
Make it run on a laptop
Evaluate by execution
Results and the guard
| Model | Tools | Right / 1,410 | Silent wrong | Should-ask caught / 162 |
|---|---|---|---|---|
| tez8 | 15 | 1,066 | 138 | 143 |
| tez17 (product) | 19 | 1,298 | 55 | 147 |
| tez18 | 19 | 1,287 | 61 | 142 (rejected) |
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.