07 · Preference tuning: DPO and KTO
A negative result. Trained on 437 pairs built from the SFT model's own mistakes, DPO lowered exact match on 500 test questions from 70.0% to 65.0%, a looser beta to 56.2% and KTO to 62.2%, and the answers a program can prove wrong did not fall.
- Part 3
- Beyond supervised
- Model
Qwen/Qwen2.5-1.5B-Instruct- Data
- Pairs built from the model’s own SQL answers, labelled by a program
- Hardware
- One T4, in Google Colab
An SFT model trained with lesson 4's recipe still misses. For a miss, saying which of two answers is worse is often cheaper than writing the best answer: a reviewer can mark "this one is wrong" in seconds, and a program can often do it for free. Preference tuning trains on that signal. DPO (direct preference optimisation) learns from pairs, a better answer and a worse one for the same prompt. KTO (Kahneman-Tversky optimisation) learns from single answers marked good or bad. This lesson runs both on the SQL task, starting from the SFT model and its own mistakes.
The result first, then how it was reached; the exact setup, time and cost are in How it was built at the end. It is a negative result: all three preference runs scored below the model they started from.
Preference tuning made the SFT model worse: exact match fell from 70.0% to 65.0% (DPO), 56.2% (DPO, loose) and 62.2% (KTO)
Four systems on the same 500 test questions, greedy decoding. Exact match carries its 95% interval; result match is exact or the same result on synthetic rows
1Others report gains from the step:
| Source | What the preferences were | What they report |
|---|---|---|
| Rogo, financial query expansion (OpenAI's preference fine-tuning, which uses DPO) | Pairs of preferred and non-preferred outputs; supervised training had missed unfamiliar expansions such as a missing growth metric | Accuracy on Rogo's own expert benchmark 75% → over 80% (provider-reported; model and data size not stated) |
| Taobao, TaoSR1 (e-commerce relevance, a closed in-house model) | The model's own samples after SFT: a correct sample against an incorrect one, and a stronger model's correct output where no sample was right | Macro F1 60.01 → 65.03 from the DPO stage; 67.12 after a GRPO stage (the paper's offline test set) |
| Heidi Health, clinical notes (on Fireworks AI) | Side-by-side evaluations, noisy, filtered with synthetic rewrites and an LLM judge | The SFT model beat the Gemini Flash tier and the preference-tuned one was preferred over the Gemini Pro tier in Heidi's own comparison (vendor-reported, no base model named) |
| Zephyr-7B (Hugging Face, Mistral-7B) | Ratings of four responses per prompt: the top one against a random other | MT-Bench 6.64 after SFT, 7.00 after SFT then DPO; 4.76 with DPO and no SFT |
This lesson's result is the opposite. On the 500 test questions every preference run scored below the SFT model on exact match. That is the finding, and the notebook measures enough to say what moved: a judge, the pairs it produced, the reward curves, the log-probabilities of the answers, and which test answers flipped.
1. Why not more SFT?
Supervised examples show one desired answer. Preference pairs express a comparison between two candidates for the same question. This is useful when the meaningful signal is which answer is better rather than a single exact string.
The SFT model here is lesson 4's recipe on 4,000 examples, half of that lesson's data: LoRA rank 16 on every linear layer, loss on the answer only. It took 7.5 minutes at a peak of 6.61 GB and scored 70.0% exact match (±4.0 points, the 95% interval) and 79.2% on result match, the share whose query is exact or returns the same rows as the gold query on synthetic data (section 2).
That leaves 150 test answers that are not exact. More SFT cannot say which of them are wrong, because SFT only has the gold query to imitate, and imitation treats a correct rewrite the same as a mistake. Rogo's post describes the same gap: supervised training struggled with query expansions it had not seen, and it reports that the pair-based step lifted accuracy on its own benchmark from 75% to over 80%. The signal preference tuning needs is cheap to collect, but only if something can say which answer is worse and be trusted when it does.
2. A program as judge
Lesson 4 found that most of the tuned model's misses were not clearly wrong: the same query written another way. If every non-exact answer is labelled "worse", preference tuning would train the model away from correct answers. The notebook's judge compares query results instead. For each question it builds the schema in memory, fills each table with 25 synthetic rows (22 random, 3 that carry the literals found in the gold query's WHERE clause), runs the gold query and the candidate, and gives one of five labels, tried in this order:
def judge(r, sql):
"""Label one cleaned answer for the example r (context, question, gold answer)."""
if not sql:
return "fails"
if normalise(sql) == normalise(r["answer"]):
return "exact" # equal to gold after normalising
if runs(r["context"], sql):
return "fails" # SQLite rejects it on the schema
con = synth_db(r["context"], r["answer"], zlib.crc32(r["question"].encode()))
gold_rows = run_rows(con, r["answer"])
if not any(v not in (None, 0) for row in gold_rows for v in row):
return "undetermined" # gold returns nothing informative here
got = run_rows(con, sql) # a failing run here is also "fails"
return "same result" if key(got, ordered) == key(gold_rows, ordered) else "wrong result"Only two labels can serve as a rejected answer: fails and wrong result. same result and undetermined are never used, so a correct paraphrase is never punished. "Same result" is evidence, not proof: two queries can agree on 25 rows. The audit measures how often that happens by damaging 300 validation gold queries in one small way each (a flipped comparison, MAX swapped with MIN, COUNT with SUM, a changed literal), which makes every one wrong by construction. 298 could be damaged.
The judge is rarely fooled (2.3%) and says nothing when unsure (17.4%); for the SFT model it can prove 13.8% of answers wrong
A: 298 gold queries damaged in one small way, so each is wrong by construction. B: how the same judge labels the SFT model's 500 greedy test answers
2The judge was fooled on 7 of 298 (2.3%), and said nothing on 52 (17.4%). Both numbers are for these damage types only. A fooled judge only loses a pair, because "same result" is never used as chosen or rejected, and the silence costs coverage in the same way. The mistake that would corrupt a pair is a correct answer labelled wrong, and this audit does not test that, since every damaged query is wrong by construction. Gold queries rewritten with other case and spacing were labelled exact 100 times in 100.
Applied to the SFT model's 500 test answers, the judge splits the 150 misses: 46 return the same result as the gold query, 35 cannot be judged, 67 return a different result and 2 do not run. Exact match says 70.0% correct, exact or same result says 79.2%, and 13.8% (69 answers) can be proven wrong. Heidi Health faced the same problem with human labels: its post reports that raw side-by-side preferences were noisy, with evaluators sometimes choosing responses that still contained hallucinations, and that success hinged on filtering them with synthetic rewrites and an LLM judge, and on larger batches.
3. Where pairs come from
The pairs come from the SFT model itself. For each of 2,000 new training questions (none of them among the 4,000 SFT examples) the model writes four answers at temperature 0.8, with no top-p, top-k or repetition penalty, so that the samples are draws from its own distribution. That was 8,000 answers in 6.6 minutes, each labelled by the judge. The last 200 questions are never trained on, as a held-out check.
# one pair per question that has at least one provably bad sample
bad = g[g["label"].isin(["fails", "wrong result"]) & (g["sql"] != "")]
rej = bad.iloc[rng.randrange(len(bad))] # rejected: a provably bad sample
good = g[g["label"] == "exact"]
# chosen: an exact sample, else the gold query
chosen = good.iloc[0]["sql"] if len(good) else r["answer"]Only 24.4% of questions gave a pair, and 35% of the chosen answers are the gold query, not something the model wrote
From 2,000 new training questions: 489 pairs, of which 52 are held out and 437 are trained on. Bars are shares of each group's total; counts in brackets
3Most samples are good (72.5% exact) and most questions have an exact sample (85.9%), which is why SFT works at all. Only 24.4% of questions have a provably bad sample, and that is what limits the data: 489 pairs, split into 437 to train on and 52 held out. The chosen answer is the model's own exact sample in 286 pairs and the gold query in 151, the cases where none of the four samples was exact. Those 151 are off-policy: the model would not have written them. The rejected answers are mostly wrong result (370 of 437) and mostly a wrong aggregate, operator or clause (208) or a wrong literal (113). The first three pairs the notebook prints show how small the difference between chosen and rejected often is: a misspelt name, a wrong literal, a quoted number.
How many match numbers have team europe listed as osku palermaa?
- Chosen
- SELECT COUNT(match_no) FROM table_19072602_2 WHERE team_europe = "Osku Palermaa"
- Rejected
- SELECT COUNT(match_no) FROM table_19072602_2 WHERE team_europe = "OSKU Palermoa"
Chosen is the model's own exact sample; rejected is labelled wrong result. It misspells the name, so its query matches no row.
Who had the high rebounds when the score was w 105–95 (ot) and Jason Kidd (8) had the high assists?
- Chosen
- SELECT high_rebounds FROM table_name_57 WHERE high_assists = "jason kidd (8)" AND score = "w 105–95 (ot)"
- Rejected
- SELECT high_rebounds FROM table_name_57 WHERE high_assists = "8" AND score = "w 105–95 (ot)"
Both from the model's own samples; rejected is labelled wrong result. It keeps only part of the value the column holds.
who had high rebounds at game 69?
- Chosen
- SELECT high_rebounds FROM table_27700375_10 WHERE game = 69
- Rejected
- SELECT high_rebounds FROM table_27700375_10 WHERE game = "Game 69"
Both from the model's own samples; rejected is labelled wrong result. It compares the column with text the column does not hold.
This is the recipe Taobao's TaoSR1 used for its DPO stage: sample several answers from the SFT model, and where some sample is correct pair it with an incorrect one; where none is, take a stronger model's correct output as the chosen answer. For those hard cases the gold query plays that role here. TaoSR1 reports that no sample out of five was correct for 13.7% of its instances, and that it curated about half of those into pairs. The paper does not state how many pairs it trained on.
For KTO the same samples are used without pairing: 2,000 answers from the training questions, 1,392 exact (good) and 608 provably bad, shuffled.
4. What DPO optimises
RLHF fits a reward model to preference pairs with the Bradley-Terry model, in which the chance that answer is preferred to depends on the difference of their rewards:
It then trains the policy to maximise reward while staying close to a reference policy , with a KL penalty of weight :
The optimum of that problem has a closed form, , which can be turned around to express the reward through the policy:
The Rafailov et al. paper (2023) puts this into Bradley-Terry. The term depends only on the prompt, so it cancels in the difference, and the reward model disappears. Fitting the result with a classifier gives the DPO loss, with the chosen and the rejected answer:
TRL logs for each answer as rewards/chosen and rewards/rejected, their difference as rewards/margins, and the share of pairs with a positive margin as rewards/accuracies. The gradient has a simple reading:
The weight is large for pairs the model currently ranks the wrong way and small for those it already separates. Each update raises the log-probability of the chosen answer and lowers that of the rejected one. Notice what the loss constrains: only the difference between the two log-ratios. Nothing in it holds the chosen answer's probability up, so both can fall as long as the rejected one falls further. Section 6 measures that.
The leash sets how far the optimum may sit from . A large makes the sigmoid saturate sooner, so the policy stops moving earlier; a small one lets it move further. The DPO paper used 0.1, and 0.5 for its summarisation task, where it did not meaningfully tune it. This lesson runs 0.1 and 0.02.
Which model is the reference? In TRL 0.19.1, when the model is a LoRA model and no reference is given, the reference is the same model with the adapter switched off. If the SFT adapter were still the trainable one, switching it off would give the base model, and the loss would measure drift from a model that has never seen SQL. The notebook merges the SFT adapter into the weights first and trains a fresh adapter on top, so that "adapter off" means the SFT model:
def load_sft():
"""The SFT model, adapter merged into the fp16 weights: the reference."""
base = AutoModelForCausalLM.from_pretrained(MODEL_ID, torch_dtype=DTYPE,
device_map={"": DEVICE})
return PeftModel.from_pretrained(base, "sft_adapter").merge_and_unload().eval()
# a NEW adapter on the merged model; with ref_model=None the reference is "adapter off"
adapter = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.0,
target_modules="all-linear", task_type="CAUSAL_LM")The cost of getting this wrong is measurable. On the 52 held-out pairs the mean log-probability of the chosen answers is −10.80 under the base model and −3.26 under the SFT model. With the base model as reference, the first step would see a chosen "reward" of 0.1 × 7.5 = 0.75 before any learning. Before training the notebook also evaluates once and asserts that every reward and margin is zero, which proves the policy equals the reference; the merged model gave identical greedy answers to the unmerged adapter on 64 test questions.
One detail a reader running the notebook will meet. TRL appends an end token to each completion, and the chat template already ends a completion with <|im_end|> and a newline, so each tokenised answer ends <|im_end|>, newline, <|im_end|>. The tail is identical on the chosen and the rejected answer and cancels in the loss. It does mean TRL's logged log-probabilities, about −28 for these chosen answers, are not comparable with the −3.26 above, which scores one end token; compare TRL's numbers only with each other.
The training used settings that DPO papers would not: a learning rate of 1e-4 for the LoRA adapter (an untuned guess; the papers cited here use 5e-7 to 1e-6 for full fine-tuning), 16 pairs per optimiser step and one pass over 437 pairs, which is 27 steps.
args = DPOConfig(
per_device_train_batch_size=4, gradient_accumulation_steps=4, # 16 pairs per step
num_train_epochs=1, learning_rate=1e-4,
lr_scheduler_type="cosine", warmup_ratio=0.1,
beta=0.1, loss_type="sigmoid", # the loss above
max_length=256, max_prompt_length=224, # every pair was filtered to fit
eval_strategy="steps", eval_steps=25, # held-out pairs scored every 25 steps
logging_steps=5, ...)5. Did DPO help?
No. Figure 1, at the top of the page, has the scores: on the 500 test questions DPO scored 65.0% exact against SFT's 70.0%, and 76.2% on result match against 79.2%. Read against the intervals, the aggregate difference is not conclusive on its own: the exact-match intervals are ±4.0 and ±4.2 points and they overlap, and the 3-point drop in result match is smaller than its interval (about ±3.6 by the same formula). The paired counts are sharper, because they compare the same 500 questions:
DPO's net loss of 25 exact answers shows up as same-result and undetermined answers, not provable errors; the looser run and KTO added provable errors
Left: judge labels of the 500 test answers of each model. Right: answers whose exact-match status changed against SFT, fixed (not exact, then exact) and broken (exact, then not)
4DPO fixed 16 answers (not exact, then exact) and broke 41 (exact, then not), against SFT. Of the 57 that changed in either direction, 41 went the wrong way; if the changes were chance, about half would go each way, 28.5 ± 3.8. That is a small but real loss, not noise: 136 of the 500 greedy answers differ from the SFT model's, and more of them got worse than better.
What the 25-answer net loss in exact match turned into is the interesting part. Against SFT, DPO has 25 fewer exact answers and 10 more same result and 14 more undetermined answers, while the provably wrong answers (wrong result plus fails) go from 69 to 70. So DPO moved answers away from the gold query's exact text into other queries that the judge either confirms return the same rows (10 more) or cannot assess (14 more), and it did not reduce the mistakes the judge can prove. The causes confirm it: wrong aggregate, operator or clause stayed at 44 and wrong value or literal at 14, the two largest causes among the rejected answers it trained against (321 of 437). A look at the 41 broken answers would tell more, and the notebook does not print them; the third change in "Run it yourself" does.
The published gains do not contradict this. They measure different things on different setups, and this lesson did not test which differences matter. The DPO paper's headline is a judged win rate on summarisation with a GPT-J model: 61% against reference summaries, where PPO reached 57%. Zephyr's gain, 6.64 to 7.00 on MT-Bench, is a model-judged score for chat. TaoSR1's DPO stage lifted macro F1 from 60.01 to 65.03, with training that differs from this lesson in four documented ways: 500 steps at batch size 1,024 with a learning rate of 1e-6, a weight-0.5 SFT loss on the chosen answers added "to stabilize training", a stronger model's answers for the hard cases, and a much larger pair set. This lesson used 27 steps at batch size 16, a learning rate of 1e-4 and no auxiliary loss. Heidi's team reports a related sensitivity: raising the effective batch from 64k to 768k tokens moved the win rate over proprietary models from 48.0% to 51.3%. This lesson did not vary the batch, the learning rate or the auxiliary term.
6. What beta does
A second DPO run changes only , from 0.1 to 0.02, a leash five times looser. The theory says the policy should move further, and the logs say it did, though the reward numbers hide it: a reward is times a log-ratio, so a smaller makes the same movement look smaller.
Every run learned to separate its training answers: DPO's margin ended at 0.30 and 0.08, KTO's at 5.1
Reward = beta × log-ratio of the policy to the SFT model, logged every 5 optimiser steps. Blue: good or chosen answers. Orange: bad or rejected answers. Each panel has its own vertical scale
5At step 25 the held-out reward margin was 0.234 at = 0.1 and 0.060 at 0.02, which are log-ratio gaps of 2.34 and 3.0 nats (margin ÷ ). The looser run moved the gap about 28% further. In both runs the policy ranks held-out pairs mostly the right way, 73% and 67% of 52 pairs, which is within noise of each other at about ±12 points on that few pairs. The learning worked in the narrow sense: the pairs are separated, on training and on held-out pairs. What the test says is different.
Training pushed the rejected answers down by 2.6 and 3.3 nats and let the chosen answers slip by 0.3, so probability moved to answers in neither set
Mean log-probability of the 52 held-out answers, summed over the whole answer, before and after each DPO run. Higher is more likely
6The chosen answers did not rise. Their held-out log-probability fell by 0.3 nats in both runs, and the rejected ones fell by 2.6 and 3.3 nats. The gap grew only because the rejected answers fell much more. This is the likelihood displacement that DPO's loss permits: probability left the answers in the pairs and went elsewhere, to answers in neither set. The notebook does not measure where, and the test answers are the evidence.
At = 0.02 exact match fell to 56.2% (±4.3), 13.8 points below SFT and clear of the interval. 287 of the 500 answers are unchanged from SFT, 18 were fixed and 87 broken. Unlike the first run, the provably wrong answers rose here, from 69 to 87, with wrong aggregate, operator or clause going from 44 to 53 and wrong column or table from 0 to 7. Answer length did not drift, the classic sign of an over-optimised preference model: 24.6 and 24.3 tokens against SFT's 24.8. The movement is in which query is written, not how long it is.
7. No pairs? KTO
Often the signal is a thumbs up or down on one answer, not a comparison. KTO (Ethayarajh et al., 2024) trains on single answers marked desirable or undesirable. With the implicit reward and a reference point , an estimate of the KL divergence between policy and reference, the value of an answer follows prospect theory: gains and losses are measured from the reference point and valued by a saturating function.
The weights balance the two sides; the paper's rule is that should lie between 1 and 4/3. The notebook's 1,392 good and 608 bad answers give weights of 1.0 and 2.29, which makes the weighted counts equal. In TRL, is estimated from answers matched with the wrong prompts in the batch, clamped at zero, and the data must be shuffled first because the baseline is built from consecutive rows.
The paper's headline is that KTO matches or exceeds DPO from 1B to 30B parameters, and its Table 2 aligns Zephyr's SFT model on UltraFeedback: GSM8K 40.0 with DPO and 53.5 with KTO, 13.5 points more. It also reports matching DPO with up to 90% fewer desirable examples, and, for Mistral-7B on OpenAssistant, beating DPO with one output per input and 72% less data. No company case with KTO results turned up in the research for this lesson, so there is none here.
On the SQL task KTO did not help. Exact match fell to 62.2% (±4.3) and result match to 70.6%. The sharpest change is that answers that do not run went from 2 to 61, so only 87.8% of KTO's answers run (SFT: 99.6%). Its answers are also shorter, 21.8 tokens against 24.8. Against SFT it fixed 24 and broke 63. In figure 5, panel c, its reward margin reached 5.1 by step 125, about 17 times DPO's 0.30, with the bad answers pushed down to −3.2 and the good ones up to +1.9; panel f shows the KL reference point at zero from step 30. The notebook cannot separate the reasons for this result, because the run is not a controlled comparison with DPO: 125 steps and 2,000 answers against 27 steps and 874, no held-out evaluation, and the notebook does not print what the 61 failing answers look like.
8. What to keep
The preference runs were cheap to train, 2.1 minutes against SFT's 7.5, and every one of them cost exact-match points
Time and peak GPU memory of each phase on a T4, and exact match on the 500 test questions after it. Sampling the pairs took as long as training KTO
7On cost, preference tuning is not the problem. A DPO training took 2.1 minutes at a peak of 6.40 GB, less than the 7.5 minutes of SFT; KTO took 6.8 minutes and 7.97 GB, within the T4's 15.6 GB. Sampling the 8,000 answers took 6.6 minutes, and every adapter is 73.9 MB. Scoring a preference adapter loaded on the merged SFT model took about 204 ms per answer against 110 ms for the merged SFT model, because in that measurement the preference adapter is not merged. The cost is in the accuracy, and in the checking that tells you so.
The model to keep from this lesson is the SFT model. What to take from it:
| What you have | What to do | Why, from this lesson |
|---|---|---|
| A trusted way to say which of two answers is worse, and an SFT model whose samples differ in quality | DPO, with pairs from the model's own samples, beta 0.1 first | At beta 0.1 it left the proven-wrong count flat (69 → 70) but lowered exact match; audit the label, check the reference and compare paired answers on held-out questions before keeping it |
| Only good or bad marks on single answers | KTO | The paper reports it can match DPO with unpaired data; this lesson did not, and 61 answers stopped running |
| No SFT model yet | Train SFT first | Zephyr: 4.76 on MT-Bench with DPO alone, 6.64 with SFT alone, 7.00 with both |
| A program that scores each answer directly | Lesson 8, a score instead of pairs | A score computed for every sampled answer replaces the pair |
If you have a task like this one:
- Keep the SFT model until a paired comparison says otherwise. On the same 500 questions DPO fixed 16 answers and broke 41; compare fixed against broken on held-out questions before replacing a model.
- Audit the label before training. The judge here was fooled on 2.3% of damaged queries and silent on 17.4%, and both numbers were known before any training. A preference set is only as good as the program, or the people, that labelled it.
- Count the pairs before choosing the learning rate. Only 24.4% of questions had a provably bad sample, which gave 437 training pairs, 27 steps, and 151 chosen answers that are the gold query rather than the model's own.
- Judge the runs on generated answers, not on reward margins. Margins rose in every run and held-out pairs were ranked the right way 73% and 67% of the time, while exact match fell.
- Train SFT first. Zephyr reports 4.76 on MT-Bench with DPO alone, 6.64 with SFT alone and 7.00 with both.
- Next to try, not tested here: a learning rate of 1e-5 or lower for the adapter, since 27 steps at 1e-4 is far above the 5e-7 to 1e-6 the cited papers use for full fine-tuning.
- Next to try, not tested here: only the 286 pairs whose chosen answer is the model's own sample, with an auxiliary SFT loss on the chosen answer as TaoSR1 used.
- Next to try, not tested here: reading the 41 answers DPO broke and the 61 KTO answers that do not run, which the notebook does not print.
How it was built
| Item | Setting |
|---|---|
| Base model | Qwen/Qwen2.5-1.5B-Instruct, fp16; 1,562,179,072 weights with an adapter attached, 18,464,768 of them trainable |
| Data | sql-create-context, cleaned and split by table in lesson 3 (train 69,170, validation 3,817, test 3,923). SFT: 4,000 training examples and 200 validation examples, seed 42. Pairs: 2,000 other training questions, four samples each (8,000 answers), 489 pairs of which 437 train and 52 are held out (the last 200 questions). KTO: 2,000 labelled answers, 1,392 good and 608 bad |
| Test | 500 test questions, seed 42, the same for every system; exact match, result match (exact, or the same rows on synthetic data) and whether the query runs in SQLite |
| Judge | Five labels, compared on a synthetic database of 25 rows per table (22 random, 3 carrying the gold query's literals); audited on 298 damaged validation gold queries |
| Method, SFT | LoRA through TRL SFTTrainer: r=16, lora_alpha=32, lora_dropout=0.05, target_modules="all-linear", loss on the answer only |
| Method, DPO and KTO | A fresh LoRA adapter on the merged SFT model: r=16, lora_alpha=32, lora_dropout=0.0, target_modules="all-linear"; the reference is the model with the adapter off. DPO: loss_type="sigmoid", beta 0.1 and 0.02. KTO: loss_type="kto", beta 0.1, desirable_weight 1.0, undesirable_weight 2.29 |
| Training, SFT | 1 epoch, 250 steps, batch 8 × 2 accumulation = 16, learning rate 2e-4 with cosine decay and 3% warm-up, fp16, gradient checkpointing, max_length=256, seed 42 |
| Training, DPO | 1 epoch, 27 steps, batch 4 × 4 accumulation = 16 pairs, learning rate 1e-4 with cosine decay and 10% warm-up, fp16, gradient checkpointing, max_length=256, max_prompt_length=224, held-out pairs scored every 25 steps, seed 42 |
| Training, KTO | 1 epoch, 125 steps, batch 8 × 2 accumulation = 16, learning rate 1e-4 with cosine decay and 10% warm-up, fp16, gradient checkpointing, max_length=256, max_prompt_length=224, seed 42 |
| Decoding | Test answers: greedy, batches of 16, at most 128 new tokens, the zero-shot prompt. Pair samples: temperature 0.8, top_p=1.0, top_k=0, no repetition penalty, four per question, at most 96 new tokens |
| Hardware | One Tesla T4 (15.6 GB) on Google Colab; transformers 4.51.3, peft 0.15.2, trl 0.19.1, accelerate 1.6.0, datasets 3.6.0 |
Time and cost. SFT took 7.5 minutes at a peak of 6.61 GB; sampling the 8,000 answers took 6.6 minutes (peak memory not printed); each DPO training took 2.1 minutes at 6.40 GB; KTO took 6.8 minutes at 7.97 GB; the whole notebook took 32.6 minutes. Each saved adapter is 73.9 MB. Scoring takes 110 ms per answer for the merged SFT model and 204, 203 and 193 ms for DPO, looser DPO and KTO, whose adapters are loaded unmerged. Exact match, result match and the flips come from the 500 test questions; reward margins, ranking accuracy and log-probabilities come from the 52 held-out pairs; the judge audit comes from the damaged validation queries.
Run it yourself
The notebook runs on a free Colab T4 and takes 32.6 minutes in total: 7.5 for SFT, 6.6 for sampling, 2.1 for each DPO run and 6.8 for KTO, plus loading models and scoring four systems on 500 questions. Every size is one constant in the second code cell. The notebook's sections follow this page: 1 is the judge, 2 the SFT model in Why not more SFT?, 3 the pairs, 4 what DPO optimises, 5 and 6 the result and beta, 7 KTO, and 8 and 9 the comparison in What to keep. Three changes to try:
- Set
DPO_LR = 1e-5. The learning rate is the setting this lesson did not tune, and 27 steps at 1e-4 is a large move for a LoRA adapter. Do the 41 broken answers fall, and does the held-out accuracy keep its 73%? - Keep only the 286 pairs whose chosen answer is the model's own exact sample, dropping the 151 whose chosen answer is the gold query. Does exact match still fall, and does the number of provably wrong answers move?
- Print the 41 answers DPO broke next to the SFT answers for the same questions. Which part of the query changed: the column, the literal, the clause, or only the way it is written?
Lesson 8 drops the pairs: it trains on a score that a program computes for every sampled answer.
How is this page?
Last updated on