Skip to Content
Recodocs

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.

15 min read
Part 2
Train
Model
Qwen/Qwen2.5-1.5B-Instruct
Data
The SQL splits from lesson 3
Hardware
One T4, in Google Colab
Open in ColabSaved with the outputs of a GPU run

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

1

Quality: how many answers run, and how many match exactly

% of 500 test questions

a
0%25%50%75%100%Zero-shot promptruns 96.2%58.4%Three-shot promptruns 96.0%59.4%Tuned (LoRA)runs 99.0%71.8%

Speed: milliseconds to generate one answer

Batches of 16, unmerged adapter for the tuned model

b
Zero-shot prompt114 msThree-shot prompt159 msTuned (LoRA)203 ms
Source: lesson notebook. Bars show the 95% interval, 1.96·√(p(1−p)/n) with n = 500. “Runs” means the query executes against the schema with empty tables.

Adapters 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
CompanyBase and adapterTraining dataBefore → afterWhat else they reportedStatus
KasistoGemma 3 12B
LoRA r=64, α=256, all 7 projections
98,648 banking QAProduction query resolution77.4%84.5%50%100%3,297 live queries over 7 months; training cost about $1,800Production
AmazonNova 2 Lite
LoRA r=32
2,000 catalogue examplesAttribute completeness, offline66%74.2%50%┆ Claude Sonnet 4.5 70.4% · 100%Won offline, lost the production A/B (59.1% vs 63.0%); cost down 98%A/B lost
BMWGemma 4 E4B
QLoRA, 4-bit NF4
Tens of thousands of judged pairsIncident title quality, 1–53.744.711.005.00Beat a prompted model about 4× larger; adapters “tens of megabytes”Pilot
ApoideaQwen2-VL-7B
QLoRA
A few thousand bank documentsTable structure score (TEDS)23.481.10.0100.0Banking statements and forms; base model scored 23.4Pilot
Sources: Kasisto and Backbase, FinRAG-12B (ACL 2026 Industry); Amazon Science, progressive fine-tuning for structured attribute generation; AWS for Industries, BMW on SageMaker AI; AWS Machine Learning blog, Apoidea Group with LLaMA-Factory. Each axis spans the metric’s full range. Company-reported.

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 W0W_0 with kk inputs and dd outputs, the layer computes

h=W0x+αr BAx,B∈Rd×r,  A∈Rr×k,  r≪min⁡(d,k)h = W_0 x + \frac{\alpha}{r}\, B A x, \qquad B \in \mathbb{R}^{d \times r},\; A \in \mathbb{R}^{r \times k},\; r \ll \min(d, k)

Only AA and BB are trained, so a layer learns r(d+k)r(d + k) numbers instead of dkdk. The rank rr sets how much the update can express, and α\alpha 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

3
x1,536W1,536 × 1,5362,359,296 weightsfrozen, fp16A 16 × 1,536 · randomB 1,536 × 16starts at zero× α / r = 32 / 16 = 249,152 trained weights (2.1%)+hStep 0B = 0, so h = Wx exactly:the adapter changes nothinguntil training moves it.After trainingh = Wx + 2·BAx. MergeW + 2·BA into one matrixand serving costs nothing.
Source: Hu et al., LoRA (2021), section 4.1; dimensions from the model's published configuration.

Two details explain why this is safe to start and cheap to finish. BB 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, W0+αrBAW_0 + \tfrac{\alpha}{r}BA 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

4
ModuleShape (in → out)LoRAshare10K100K1M10Mq_proj1,536 → 1,5362.36M49K2.1%k_proj1,536 → 256393K29K7.3%v_proj1,536 → 256393K29K7.3%o_proj1,536 → 1,5362.36M49K2.1%gate_proj1,536 → 8,96013.76M168K1.2%up_proj1,536 → 8,96013.76M168K1.2%down_proj8,960 → 1,53613.76M168K1.2%One layer46.79M frozen659K1.4%× 28 layers1.31B frozen in linear layers, plus 0.23B in the embedding (never adapted)18.46M1.2%
Source: arithmetic from the model's configuration (hidden 1,536; MLP 8,960; 2 key-value heads of 128). The notebook prints the same total from PEFT.

The 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)

5
1 MB10 MB100 MB1 GB10 GB0.1%1%10%100%of modelThe model itself in fp16: 3.1 GBFull fine-tune training state, 16 bytes per weight: 24.7 GB (lesson 2)1248163264128256LoRA rank rthis lesson: 74 MBAmazon’s rank: 148 MBKasisto’s rank: 295 MB4.6 MB1.18 GB
Source: arithmetic from the model configuration; the notebook measures the rank-16 file. LoRA paper (Hu et al., 2021, table 6): adapting GPT-3's query and value weights, “a rank as small as one suffices”.

This lesson uses the common first-run settings, and each one is a choice with a reason:

SettingValueWhat it does
r16Rank of each update; 74 MB of adapter for this model
lora_alpha32Scale of the update, α/r=2\alpha / r = 2; Kasisto used 256 / 64 = 4
lora_dropout0.05Drops 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_rate2e-4, cosine, 3% warm-upHigher than a full fine-tune's, because only new weights move; TRL's guide is about 1e-4, Amazon used 1e-5
Batch8 × 2 accumulation = 16Memory is set by the 8, the update by the 16
max_length256Covers over 99.9% of examples (lesson 3)
completion_only_lossTrueLoss 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:

ExampleTokensNo lossTrained onLesson 3: prompt / answer
0102703273 / 29
163432046 / 17
2116764079 / 37
3100643667 / 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

6
0.050.10100200300400500trainingvalidation
Source: lesson notebook. 15 minutes on a T4, about 1,089 padded tokens per second, peak 9.9 GB allocated.

The 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)

7
3596161■ exact match 359500 questionswrong aggregate, operator or clause61 (12.2%)other: same parts, written differently61 (12.2%)wrong value or literal14 (2.8%)does not run5 (1.0%)
Source: lesson notebook. Exact match is strict, so some misses are correct queries written another way.

Only 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 promptThree-shot promptLoRA adapter
Exact match on 50058.4%59.4%71.8%
Runs in SQLite96.2%96.0%99.0%
Time per answer114 ms159 ms203 ms unmerged
One-off costnonenone15 min on a free T4
What you shipa prompta prompt74 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 -100 labels 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

ToolchainChoose it when
TRL and PEFTYou want Python-level control over how examples, masks and adapters enter the trainer.
UnslothThe supported model and GPU path fit a memory-constrained notebook.
LLaMA-FactoryYou want a web interface to configure and launch a supported training recipe.
AxolotlYou want a versioned YAML recipe to launch repeatedly from the command line.

How it was built

ItemSetting
Base modelQwen/Qwen2.5-1.5B-Instruct, fp16, 1,543,714,304 weights
Datasql-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
Test500 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
MethodLoRA through TRL SFTTrainer: r=16, lora_alpha=32, lora_dropout=0.05, target_modules="all-linear", 18,464,768 trainable weights
Training1 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
DecodingGreedy, batches of 16; the tuned model gets the zero-shot prompt
HardwareOne 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:

  1. Set r=4 and then r=64, keeping lora_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?
  2. Set completion_only_loss=False and rerun the label check. How many tokens are now trained on, and what does it do to the score?
  3. Double N_TRAIN to 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