04 · Your first fine-tune: SFT with LoRA
Measure the strongest prompt first, then train a LoRA adapter on Qwen2.5-1.5B with TRL. On 500 held-out questions exact match rose from 59.4% to 71.8%, in 15 minutes on a free T4, for a 74 MB file.
- Part 2
- Train
- Model
Qwen/Qwen2.5-1.5B-Instruct- Data
- The SQL splits from lesson 3
- Hardware
- One T4, in Google Colab
Lessons 1 to 3 settled three things: the task (a question about a table in, one SQLite query out), the model (Qwen2.5-1.5B-Instruct) and the data (sql-create-context, cleaned and split by table). This lesson trains. It changes no weight of the model; it adds a small set of new ones beside them, with a method called LoRA, and measures what that bought against the cheapest alternative, a better prompt.
The result first, then how it was reached; the exact setup, time and cost are in How it was built at the end.
Training moved exact match from 59.4% with the best prompt to 71.8%, on the same 500 held-out questions
Qwen2.5-1.5B-Instruct on a Colab T4, greedy decoding; the tuned model gets the zero-shot prompt
1Quality: how many answers run, and how many match exactly
% of 500 test questions
aSpeed: milliseconds to generate one answer
Batches of 16, unmerged adapter for the tuned model
bAdapters like this one are how most published fine-tunes are done today. Four companies that reported their settings and results:
Four companies trained adapters, not models; three kept the gain, one lost it in production
Published LoRA and QLoRA fine-tunes: base model, adapter settings, training data, and the result before (○) and after (●) training
2| Company | Base and adapter | Training data | Before → after | What else they reported | Status |
|---|---|---|---|---|---|
| Kasisto | Gemma 3 12B LoRA r=64, α=256, all 7 projections | 98,648 banking QA | 3,297 live queries over 7 months; training cost about $1,800 | Production | |
| Amazon | Nova 2 Lite LoRA r=32 | 2,000 catalogue examples | Won offline, lost the production A/B (59.1% vs 63.0%); cost down 98% | A/B lost | |
| BMW | Gemma 4 E4B QLoRA, 4-bit NF4 | Tens of thousands of judged pairs | Beat a prompted model about 4× larger; adapters “tens of megabytes” | Pilot | |
| Apoidea | Qwen2-VL-7B QLoRA | A few thousand bank documents | Banking statements and forms; base model scored 23.4 | Pilot |
Three things in that table carry through this lesson. The base models are small, 4 to 12 billion parameters, and the training sets are thousands of examples, not millions. Every result is a before and after on a fixed test, so each company measured the untrained model first. And Amazon's adapter beat a frontier model offline and then lost the production A/B test, which is why this lesson's result is described as what it is, a score on 500 held-out questions, and lesson 11 is about what else a release needs.
1. The baseline to beat
Lesson 1's rule: before training, measure the best result you can get without it, on the same examples you will score the tuned model on. The notebook draws 500 questions from lesson 3's test split, which shares no table with the training data, and scores two prompts:
- zero-shot: lesson 3's system prompt, the schema and the question;
- three-shot: the same, after three solved training examples written as earlier turns of the conversation. Showing the model the format is the cheapest rival to training, so it is the one to beat.
Two measures are used. Runs: the generated query executes in SQLite against the schema. It needs no gold answer, but the tables are empty, so it shows the query is valid, not that it is right. Exact: the query equals the gold query once case, white space, a trailing semicolon and the quote character are normalised. It is strict, and its misses are read in section 5.
The untuned model is already good at SQL. Zero-shot, 96.2% of its queries run and 58.4% match exactly. Three examples add one point, 59.4%, well inside the ±4.3-point uncertainty of a 500-question test, and make every answer 45 ms slower because the prompt is longer. Its misses show why prompting stalls:
gold : SELECT MAX(year) FROM table_name_85 WHERE points < 0
model: SELECT MAX(year) FROM table_name_85 WHERE points <= 0
gold : SELECT AVG(acc_bal), acc_type FROM customer WHERE credit_score < 50 GROUP BY acc_type
model: SELECT acc_type, AVG(acc_bal) AS avg_balance FROM customer WHERE credit_score < 50 GROUP BY acc_type;The first is a wrong answer. The second is a right answer in a different house style: columns in another order, an alias, a semicolon. A prompt can ask for a style, but it cannot show the thousands of small conventions a team's queries follow. Learning those from examples is what supervised fine-tuning does, and lesson 1 put this kind of job, a behaviour a program can check, at the top of its list.
2. How LoRA trains
Keep the base weights fixed and learn a smaller correction to their behaviour. LoRA is a parameter-efficient way to train that correction, not a way to guarantee that the corrected model will generalise.
A full fine-tune updates every weight. Lesson 2 measured what that costs: about 16 bytes of GPU memory per parameter once gradients and optimizer state are counted, 9.9 GB for a 0.5-billion-parameter model, out of reach for 1.5 billion on a T4. LoRA (low-rank adaptation, Hu et al., 2021) freezes the weights and learns a correction to each layer instead, written as the product of two thin matrices.
For a frozen weight with inputs and outputs, the layer computes
Only and are trained, so a layer learns numbers instead of . The rank sets how much the update can express, and scales it.
LoRA leaves the weight alone and learns a thin detour beside it, which starts at zero
One attention projection of Qwen2.5-1.5B (q_proj, 1,536 → 1,536) with a rank-16 adapter; shapes drawn to scale on the long side
3Two details explain why this is safe to start and cheap to finish. starts at zero, so at the first step the adapter adds nothing and the model behaves exactly like the one measured in section 1; training moves it only as far as the data pushes. And after training, is one ordinary matrix of the original shape, so the adapter can be merged into the model and served at no extra cost (lesson 12).
The update is small but it touches every layer. With target_modules="all-linear", PEFT adds a pair to all seven projections in each of the 28 layers: four in attention and three in the MLP, the block where most of the weights are. Kasisto adapted the same seven in its banking model.
all-linear puts 18.5 million trainable weights beside 1.31 billion frozen ones, three-quarters in the MLP
Weights per module in one of Qwen2.5-1.5B's 28 layers: frozen matrix (grey) and rank-16 LoRA pair (blue), log scale; right, the LoRA share
4The notebook's count agrees: 18,464,768 trainable parameters, 1.20% of the base model's 1.54 billion. Gradients and optimizer state now exist for 18 million numbers, not 1.5 billion, which is where lesson 2's memory saving comes from. The embedding and the output head stay frozen; all-linear leaves the output layer out by design.
How large should the rank be? The LoRA paper found that adapting GPT-3's attention weights, "a rank as small as one suffices", and published fine-tunes use small ranks: 32 at Amazon, 64 at Kasisto. Rank buys capacity linearly in size:
Doubling the rank doubles the adapter; at rank 16 it is 2% of the model, at 256 it is 38%
Adapter file size by LoRA rank for Qwen2.5-1.5B with all-linear, float32 weights, MB (left, log) and as a share of the fp16 model (right)
5This lesson uses the common first-run settings, and each one is a choice with a reason:
| Setting | Value | What it does |
|---|---|---|
r | 16 | Rank of each update; 74 MB of adapter for this model |
lora_alpha | 32 | Scale of the update, ; Kasisto used 256 / 64 = 4 |
lora_dropout | 0.05 | Drops 5% of the adapter's inputs in training, a light guard against memorising |
target_modules | "all-linear" | All seven projections in every layer, not the output head |
learning_rate | 2e-4, cosine, 3% warm-up | Higher than a full fine-tune's, because only new weights move; TRL's guide is about 1e-4, Amazon used 1e-5 |
| Batch | 8 × 2 accumulation = 16 | Memory is set by the 8, the update by the 16 |
max_length | 256 | Covers over 99.9% of examples (lesson 3) |
completion_only_loss | True | Loss on the answer only (lesson 3) |
In code, the whole training run is a configuration and a trainer. TRL's SFTTrainer reads lesson 3's prompt–completion records, builds the chat template, masks the prompt and wraps the model in the adapter:
lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
target_modules="all-linear", task_type="CAUSAL_LM")
config = SFTConfig(
output_dir="sft-out",
per_device_train_batch_size=8, gradient_accumulation_steps=2, # effective batch 16
num_train_epochs=1, learning_rate=2e-4, lr_scheduler_type="cosine", warmup_ratio=0.03,
fp16=True, bf16=False, # a T4 has no bfloat16
gradient_checkpointing=True, # recompute activations to save memory
gradient_checkpointing_kwargs={"use_reentrant": False},
max_length=256, # lesson 3: covers over 99.9% of examples
completion_only_loss=True, # no loss on the prompt
logging_steps=25, eval_strategy="steps", eval_steps=200,
save_strategy="no", report_to="none", seed=42,
)
trainer = SFTTrainer(model=model, args=config, train_dataset=train_ds, eval_dataset=val_ds,
processing_class=tok, peft_config=lora)
trainer.train()3. Check what the loss sees
Lesson 3 measured that without a mask, 97% of the training signal would go into predicting prompts. A configuration flag is a claim; the notebook checks it by collating four training examples exactly as the trainer will and counting the labels set to -100, which the loss ignores:
| Example | Tokens | No loss | Trained on | Lesson 3: prompt / answer |
|---|---|---|---|---|
| 0 | 102 | 70 | 32 | 73 / 29 |
| 1 | 63 | 43 | 20 | 46 / 17 |
| 2 | 116 | 76 | 40 | 79 / 37 |
| 3 | 100 | 64 | 36 | 67 / 33 |
Each count differs from lesson 3's by three tokens, and the notebook asserts the reason. TRL 0.19.1 ends the prompt before the <|im_start|>assistant header, so those three tokens are trained on; lesson 3 counted them as prompt. The text the loss actually sees for example 0:
<|im_start|>assistant
SELECT name FROM table_name_9 WHERE year > 2001 AND length = "52 x 20 mins"<|im_end|>That costs nothing, since the chat template writes the header at generation time anyway. The point of the check is that a silent mismatch here, a mask that covers nothing or everything, trains without an error and only shows as a worse model.
4. Train
8,000 of the 69,170 training examples, one pass, 500 optimizer steps. Training time is set by tokens, so the notebook counts them first: 738,225 real tokens, about 954,000 once each batch is padded to its longest example. At the measured 1,089 padded tokens per second, the run took 14.6 minutes on a Colab T4, with 9.9 GB of GPU memory at its peak.
Loss fell fastest in the first hundred steps; validation loss ended at 0.023
Mean loss per answer token by optimizer step (effective batch 16), log scale; training loss every 25 steps, validation on 500 examples
6The curve starts where lesson 3 left it. Before training, lesson 3 measured the model's loss on answer tokens at 0.28 per token; the first 25 steps here average 0.16, and by step 100 it is 0.04. Most of what the run teaches is learned in the first fifth of it: the conventions of the dataset, which are the same in every example. The rest is slow, and the validation loss, on 500 examples from tables the model never trained on, was still falling at step 400 (0.032 to 0.023). It does not rise, so the run is not memorising; more data or a second pass would likely still help, and that is a measured next step rather than a default.
5. What training changed
The notebook saves the adapter, frees the training model, loads the saved files on a fresh copy of the base model and generates the same 500 answers with the zero-shot prompt. What is scored is exactly what would be deployed.
Figure 1, at the top of the page, is this section's result. Exact match rose 12.4 points over the best prompt, from 59.4% to 71.8%. The intervals do not overlap, so on this test the difference is real. Queries that fail to run fell from about 1 in 25 to 1 in 100. Panel b is the cost the table hides: the unmerged adapter makes each answer slower, 203 ms against 114 ms, because every layer now does two extra matrix products. Merging removes it, and lesson 12 measures that.
Where are the 141 remaining misses?
Of the 141 misses only 5 are broken SQL; most use a different clause or write the same query another way
Every tuned-model answer on 500 test questions, put in one cause by rules tried in order (top); the misses ranked (below)
7Only 5 do not run. The rest split into two kinds that need different responses. Some are wrong: a select list that drops the grouped column (AVG(Price), AVG(Score) without Appelation), or a query against a table the schema does not have. Others are the right query in another form, which exact match cannot see. In the notebook's sample of five misses, three are the gold query with a number written in quotes, year = "1990" for year = 1990, which gives the same answer whenever the column holds that value. Two of the tuned model's misses, as the notebook prints them:
What was the score in 1990?
- Gold
- SELECT score FROM table_name_85 WHERE year = 1990
- Tuned
- SELECT score FROM table_name_85 WHERE year = "1990"
Right in another form: the quoted number returns the same rows whenever the column holds that value.
What are the average price and score of wines grouped by appelation?
- Gold
- SELECT AVG(Price), AVG(Score), Appelation FROM WINE GROUP BY Appelation
- Tuned
- SELECT AVG(Price), AVG(Score) FROM WINE GROUP BY Appelation
Wrong: it drops the column the rows are grouped by.
So 71.8% is a floor on the true accuracy, and the honest next measurement is execution accuracy: run both queries on tables that contain data and compare the results. That is lesson 11's job, and Amazon's reversal is the reason it matters.
6. What to keep
The adapter directory holds a 73.9 MB weights file and a configuration that names its base model, Qwen/Qwen2.5-1.5B-Instruct. That is the whole product of the run: the 3.1 GB model it modifies is downloaded unchanged from the Hub. BMW described its adapters the same way, "tens of megabytes against a base model of tens of gigabytes", and the consequence is practical: one copy of the base model in memory can serve many adapters, one per task or customer, and swapping one is loading a small file.
| Zero-shot prompt | Three-shot prompt | LoRA adapter | |
|---|---|---|---|
| Exact match on 500 | 58.4% | 59.4% | 71.8% |
| Runs in SQLite | 96.2% | 96.0% | 99.0% |
| Time per answer | 114 ms | 159 ms | 203 ms unmerged |
| One-off cost | none | none | 15 min on a free T4 |
| What you ship | a prompt | a prompt | 74 MB beside the base model |
Kasisto's numbers show the same trade at production scale: a 12-billion-parameter model, 98,648 examples, about $1,800 of training, and 7.1 more points of customer queries resolved over 3,297 live queries.
If you have a task like this one:
- Measure the strongest prompt first, on the exact questions you will score the tuned model on. Here three examples were worth one point, inside the noise, so training had a clear bar to beat.
- Check the loss mask before training. Count the
-100labels on a few collated examples; a wrong mask trains without an error. - Start at rank 16 on all linear layers with a learning rate around 2e-4; change rank only if the result is short and the validation loss has flattened.
- Read the misses before calling the number final. Exact match undercounts a model that writes the same query differently; score by execution before a release (lesson 11).
- Next to try, not tested here: a second epoch or 16,000 examples, since validation loss was still falling at step 400.
Biderman and colleagues found that low-rank LoRA learned less than full fine-tuning on their coding and maths tasks and preserved more pre-existing capabilities. On their instruction mixture, LoRA matched full fine-tuning on several reported benchmarks. If a SQL adapter misses its target, measure both held-out SQL and the capabilities the base must retain before deciding whether to increase rank or update more weights. Biderman et al., LoRA Learns Less and Forgets Less
Choose a toolchain
| Toolchain | Choose it when |
|---|---|
| TRL and PEFT | You want Python-level control over how examples, masks and adapters enter the trainer. |
| Unsloth | The supported model and GPU path fit a memory-constrained notebook. |
| LLaMA-Factory | You want a web interface to configure and launch a supported training recipe. |
| Axolotl | You want a versioned YAML recipe to launch repeatedly from the command line. |
How it was built
| Item | Setting |
|---|---|
| Base model | Qwen/Qwen2.5-1.5B-Instruct, fp16, 1,543,714,304 weights |
| Data | sql-create-context, cleaned and split by table in lesson 3 (train 69,170, validation 3,817, test 3,923); 8,000 training and 500 validation examples sampled with seed 42 |
| Test | 500 test questions, seed 42, the same for every system; exact match after normalising case, white space, a trailing semicolon and quote characters, plus whether the query runs in SQLite on the empty schema |
| Method | LoRA through TRL SFTTrainer: r=16, lora_alpha=32, lora_dropout=0.05, target_modules="all-linear", 18,464,768 trainable weights |
| Training | 1 epoch, 500 optimizer steps, batch 8 × 2 accumulation = 16, learning rate 2e-4 with cosine decay and 3% warm-up, fp16, gradient checkpointing, max_length=256, loss on the answer only, seed 42 |
| Decoding | Greedy, batches of 16; the tuned model gets the zero-shot prompt |
| Hardware | One Tesla T4 (15.6 GB) on Google Colab; transformers 4.51.3, peft 0.15.2, trl 0.19.1 |
Time and cost. The 8,000 examples hold 738,225 tokens, about 953,928 once batches are padded. Training took 14.6 minutes including two validation passes, about 1,089 padded tokens per second, with 9.87 GB of GPU memory allocated at its peak (15.22 GB reserved). Scoring the 500 questions takes 114 ms per answer zero-shot, 159 ms three-shot and 203 ms with the unmerged adapter, so one to two minutes per system (derived). The saved adapter is 73.9 MB beside a 3,087 MB base model.
Run it yourself
The notebook runs in about 25 minutes on a free Colab T4, 15 of them training, and saves the adapter to ./adapter. Its sections follow this page: 1 is the baseline, 2 the training setup and the loss-mask proof, 3 and 4 the result and its misses, 5 the comparison in What to keep. Three changes to try:
- Set
r=4and thenr=64, keepinglora_alpha = 2 * r. Does exact match move by more than the ±4-point interval, and what happens to the adapter's size and the training time? - Set
completion_only_loss=Falseand rerun the label check. How many tokens are now trained on, and what does it do to the score? - Double
N_TRAINto 16,000. The validation loss was still falling at step 400; does exact match follow it?
Next to try
Sweep the learning rate at a fixed rank before interpreting a weak fit as a capacity problem. This applies Raschka’s advice to check learning rate and alpha when training is unstable. Hold adapter placement, scaling, data and scoring fixed. With the rate chosen, compare standard LoRA with DoRA by enabling use_dora=True in PEFT. DoRA learns weight magnitude separately from direction. Check held-out SQL and memory under the same settings. Raschka’s rank and alpha guide · DoRA paper · PEFT settings
Lesson 5 keeps everything here and changes one thing: it quantises the frozen weights to 4 bits, so the same adapter can be trained on a model several times larger on the same GPU.
How is this page?
Last updated on