Chapter 6 · Post-training and Alignment 6.1
SFT Data: Construction and Quality Control
How to weigh the quantity and quality of SFT data and check it: measured effects of data size, label noise, the loss mask and mixed-in general data (Qwen2.5-0.5B on banking77), plus rule filters, near-duplicate removal and contamination checks on Alpaca, Alpaca-cleaned and Dolly.
After this page you will be able to
- Explain how one SFT example becomes a training signal: the prompt template, tokenization, the loss mask and the end-of-sequence token.
- Audit an instruction dataset in code: rule-based filters, exact and near-duplicate removal, test-set contamination checks, and length and padding statistics.
- Judge from experiments how data size, label noise, the loss mask and mixing in general data each matter, and know where to spend effort first.
- Set up a data-quality loop from sampling and cleaning through spot checks to evaluation feedback.
On this page
- The Short Version
- What SFT Teaches
- What One Example Looks Like in Training
- Experiments: Data Size, Label Noise, the Loss Mask and General Data
- First, measure how much nothing changes
- Data size: from 1 example per class to all of them
- Label noise: what wrong labels cost
- Does longer training memorize wrong labels?
- Does more data dilute wrong labels?
- The loss mask: should the prompt count in the loss
- Mixing in general data: can it hold off forgetting
- A Few Actual Outputs
- Audit: Three Public Instruction Datasets
- Rule filters: find the obviously bad examples first
- Near-duplicate removal and contamination checks
- Length, supervision ratio and padding
- Where the Data Comes From
- Building a Data-Quality Loop
- Common Problems and Diagnosis
- Summary and Exercises
- Quick self-test
- Further Reading
- FAQ
The Short Version
- The return on data diminishes quickly. Going from 1 to 20 examples per class lifts accuracy from 28.3% to 85.8%; going on to 50 per class (91.0%) and to all 10,003 examples (93.9%) adds only 4.0 and 2.1 percentage points per doubling of the data. With very little data the output format breaks first: at 1 example per class the valid-label rate is only 41.8%.
- The cost of wrong labels is roughly linear, shrinks in absolute terms with more data, and the model memorizes them if it trains long enough. With 10%, 20% and 40% of the labels replaced by a random class, accuracy falls to 82.4%, 77.7% and 69.2%, about 0.4 percentage points per 1% of wrong labels. On all the data, 20% wrong labels cost only 3.6 points of accuracy (8.1 at 20 per class), but the factor by which the error rate grows is almost the same (1.59 against 1.57). Back at 20 per class: after 3 epochs the model has learned the share of wrong labels, and its training loss sits near the floor of a model that knows the noise rate; after 10 epochs it has memorized all 308 relabeled training examples, its training loss is 0.0007, and test accuracy has fallen from 77.7% to 74.1%.
- Computing the loss on the whole sequence brought no benefit. Accuracy goes from 85.8% to 84.5%, and every step is about half again slower. This data (long prompts, short answers, few examples) is exactly the case where the literature says the gain is largest, and no gain shows up; but the metric and the scale differ, so this is not a refutation.
- Mixing in general instruction data did not improve the forgetting gauges and pulled the target task down. With 500 and 1,540 examples mixed in, WikiText-2 perplexity rises from 19.10 to 21.49 and 21.07, multiple-choice accuracy shows no clear change (72.8%, 71.5%, 71.7%), and target-task accuracy falls to 84.0% and 82.7%. The default configuration had not forgotten much to begin with, so there is little to protect; one possible reason is that long answers outweigh short ones in a loss averaged per token.
- Reading actual outputs: the classification adapter cannot say “none of these”, but it learned to stop when done. On out-of-scope inputs (baking sourdough, opening a savings account) the adapters still invent a string that looks like a label; on prompts in other formats the base model ran into the length limit three times while the default adapter stopped by itself on all four. Six prompts are examples, not a measurement.
- An audit takes three tools: rules, near-duplicate removal and spot checks. The original Alpaca has 8.6% of its examples hitting a rule, and Alpaca-cleaned removed the placeholders but has more refusal phrases; 2.5% of the banking77 test set has a near-duplicate in the training set, which moves accuracy by about 0.2 points; random batching wastes more than half of the positions on padding, and grouping by length leaves 5.8% (batch size 16).
These conclusions hold for this one model and this one task, and most settings were trained once (only the default configuration was repeated: with 3 other training seeds and 3 other data subsets, where the standard deviation across subsets is 0.80 percentage points). Each section says which findings are fairly solid and which are only observations.
What SFT Teaches
Pretraining teaches a model to continue text; SFT uses (instruction, answer) examples to turn it into a model that answers as requested. LIMA gives a representative view of what SFT actually teaches. Zhou et al. (2023) fine-tuned a 65B LLaMA on only 1,000 carefully selected examples, and in human evaluation its answers were equal to or preferred over GPT-4’s in 43% of cases. From this they proposed the “Superficial Alignment Hypothesis”: almost all of a model’s knowledge and ability is acquired in pretraining, and alignment mostly teaches which style and format to use when interacting with users.
The ablations in the same paper (7B model, scored 1 to 6 by ChatGPT) show that the quality and diversity of the data matter more than its quantity:
- With the same 2,000 examples, quality-filtered Stack Exchange data and unfiltered data differ by 0.5 points.
- Growing the quality-filtered Stack Exchange data from 2K to 32K examples (16 times) does not improve the score.
AlpaGasus (Chen et al., ICLR 2024) takes another route: ChatGPT scores each of the 52K Alpaca examples for accuracy and only the 9,229 examples scoring at least 4.5 are kept. The resulting model beats the Alpaca trained on all 52K in both GPT-4 judging and human evaluation, and the training time of the 7B model falls from 80 to 14 minutes (4 A100 80GB GPUs).
These conclusions depend on specific data, base models and judges and cannot be carried over to your task directly. So this page does it differently: with a small experiment that runs in a few minutes (the same setup as LoRA Fine-Tuning in Practice), it tests data size, label noise, the loss mask and mixing in general data one at a time, and then audits three popular public instruction datasets.
What One Example Looks Like in Training
In code, an SFT example is two equally long columns of tokens: the input ids and the labels. Positions that the model should not learn get the label -100, which PyTorch’s cross-entropy skips.
from datasets import load_dataset
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B")
data = load_dataset("PolyAI/banking77", split="train")
names = data.features["label"].names
PROMPT = ("Classify the customer message into one banking intent.\n"
"Message: {}\nIntent:")
row = data[0]
prompt = tok(PROMPT.format(row["text"]))["input_ids"]
answer = tok(" " + names[row["label"]])["input_ids"] + [tok.eos_token_id]
ids = prompt + answer
labels = [-100] * len(prompt) + answer # -100: no loss on the prompt
print(repr(row["text"]), "->", names[row["label"]])
print(f"{len(prompt)} prompt tokens, {len(answer)} answer tokens "
f"(supervised share {len(answer) / len(ids):.0%})")
print(f"{'position':>8} {'token':<12} {'label':>8}")
for pos in range(len(prompt) - 3, len(ids)):
print(f"{pos:>8} {tok.decode(ids[pos])!r:<12} {labels[pos]:>8}")
Output:
'I am still waiting on my card?' -> card_arrival
22 prompt tokens, 4 answer tokens (supervised share 15%)
position token label
19 '?\n' -100
20 'Intent' -100
21 ':' -100
22 ' card' 3701
23 '_arr' 11210
24 'ival' 3936
25 '<|endoftext|>' 151643
In this example:
- The whole prompt is labeled
-100. The model does not have to learn to “write the prompt”, only to “write the answer given the prompt”. Whether to also compute the loss on the prompt is tested below. - The answer is followed by an end-of-sequence token, and it counts in the loss. It is the only signal that teaches the model where to stop; leave it out and generation tends to run on.
- The supervision is sparse.
card_arrivalis split into 3 tokens, so with the end token there are 4 supervised positions, only 15% of the 26 tokens of the example. Every supervised token in SFT data deserves a check. - The prompt at inference must match the one in training. For the adapter trained with the default configuration, accuracy on the training prompt is 85.8%. With a different wording at inference (
Customer message: ...\nWhich banking intent is this? Answer:) it falls to 79.4%, and adding a single trailing space to the prompt gives 82.0% and drops the share of outputs that are one of the 77 class names from 98.5% to 95.9%. The template is part of the data and should be versioned together with it.
The widget below walks the printed sample token by token: toggle between answer-only loss and full-sequence loss and watch each position’s label flip from -100 to its real id — and how sparse the supervision is (4 of 26 tokens).
Experiments: Data Size, Label Noise, the Loss Mask and General Data
Each of the four questions below has been answered from experience by someone. Here each one is tested with a controlled experiment. The setup is the one from “The Setup: How to Measure a LoRA Run” in LoRA Fine-Tuning in Practice: the Qwen2.5-0.5B base model, banking77 (77 banking-support intents), the default LoRA (, , learning rate , all 7 linear layers adapted) and batch size 16. The model, the dataset licenses, the environment and the definitions of the metrics are on that page. Only a few points matter here:
- Target task: accuracy on the 3,080 test examples (greedy decoding; the output must equal the class name exactly). The valid-label rate is the share of outputs that are exactly one of the 77 class names.
- Forgetting probes: WikiText-2 perplexity (16.83 for the untuned base model) and ARC-Easy four-choice multiple-choice accuracy (72.4% for the base model).
- Default training data: 20 random examples per class, 1,540 in total, trained for 3 epochs (291 steps). Each experiment changes one factor.
- The subsets are nested: the 5-per-class subset is contained in the 10-per-class subset, which is contained in the 20-per-class subset, and so on. In the data-size comparison, the only difference is which examples were added.
First, measure how much nothing changes
Before reading the numbers below, look at how much the same configuration varies between runs; otherwise small differences get mistaken for findings. There are three sources:
- Different training seed, same data: 85.8%, 85.9%, 86.1%, a standard deviation of 0.18 percentage points.
- Different data subset, same training seed (three more random draws of 20 examples per class): 85.8% (default), 84.2%, 85.6%, 84.4%, a standard deviation of 0.80 percentage points, more than four times that of changing the training seed. The comparisons below all use the default subset, so a difference smaller than 1 percentage point may be just the luck of this subset.
- Sampling error of the test set itself: with 3,080 test examples and accuracy near 86%, the standard error is about 0.6 percentage points.
The conclusions below rely only on differences that are clearly larger than these.
Data size: from 1 example per class to all of them
First, “how many examples do I need”. The number of examples per class is swept from 1 to all of them (about 130; the classes differ in size). From 1 to 10 per class the number of steps is fixed at 150, since otherwise there would only be a few dozen steps and nothing would be learned (at 1 per class, 150 steps is 31 passes over the 77 examples). From 20 per class on, training runs for 3 epochs, so the number of steps grows with the data; the last row is all 10,003 training examples for 3 epochs (1,878 steps). The 50-per-class row has 3,826 examples rather than 3,850 because some classes have fewer than 50 examples in the training set.
| Examples per class | Training examples | Update steps | Accuracy | Valid-label rate | WikiText-2 perplexity | ARC-Easy (multiple choice) |
|---|---|---|---|---|---|---|
| 1 | 77 | 150 | 28.3% | 41.8% | 18.99 | 72.6% |
| 2 | 154 | 150 | 48.3% | 68.4% | 19.02 | 72.4% |
| 5 | 385 | 150 | 69.0% | 89.3% | 19.22 | 71.7% |
| 10 | 770 | 150 | 77.6% | 94.8% | 19.08 | 72.1% |
| 20 (default) | 1,540 | 291 | 85.8% | 98.5% | 19.10 | 72.8% |
| 50 | 3,826 | 720 | 91.0% | 99.6% | 19.46 | 71.8% |
| all (about 130) | 10,003 | 1,878 | 93.9% | 99.8% | 21.31 | 71.1% |
- Returns diminish, and quickly. Each doubling of the data adds 20.0 (1 to 2 per class), 8.5 (5 to 10), 8.2 (10 to 20), 4.0 (20 to 50, converted to a doubling) and 2.1 (50 to all, converted to a doubling) percentage points of accuracy. As an error rate: 14.2% at 20 per class, 9.0% at 50 per class and 6.1% with all the data. Across these seven points, every 2.5 times more data removes about a third of the errors, which is the shape of a power law (exponents between 0.4 and 0.65) and of the same kind as the loss falling with scale in Scaling Laws. Each point was trained once and the numbers of steps differ, so treat the exponent as a shape and do not extrapolate it to other tasks.
- With very little data, the output format breaks first. At 1 example per class the valid-label rate is only 41.8%: nearly six in ten outputs are not one of the 77 class names. The first 8 test examples all have the true label
card_arrival; the model trained on 1 example per class answerscard_located,card_not_received_by_card_accepter,card_not_arrival,card_arrival_hint,pending_card_arrival,getting_card,card_arrivalandcard_not_received. Only the seventh is correct and the other seven are not valid class names, yet each one looks like a class name. At 2 per class, onlycard_not_deliveryamong those 8 is invalid. These 8 belong to a single class and do not represent the whole test set, but the overall numbers point the same way: the share of errors that are invalid outputs falls from 81% at 1 per class to 11% at 20 per class and 3% with all the data. With little data, constraining the output to the 77 class names with constrained decoding (see Structured Output and Function Calling) should recover some of these errors; this page did not test it. - Forgetting hardly depends on data size, and may depend on the number of steps. WikiText-2 perplexity (16.83 for the base model) is 18.99 to 19.46 from 1 to 50 per class: 1 per class trained for only 150 steps is already as high as 20 per class trained for 291 steps, and training on all the data for 1,878 steps raises it to 21.31. ARC-Easy multiple choice stays between 71.1% and 72.8%, within the sampling error of about ±1 point (the base model scores 72.4% and the three seeds of the default configuration 71.4% to 72.8%). Data size and the number of steps are tied together here and cannot be separated: with all the data, the rise in perplexity could come from more data or from more steps, and this page did not rerun with the steps held fixed.
Label noise: what wrong labels cost
The method: replace the label of a random share of the training examples (10%, 20%, 40%) with another random class, keep everything else as in the default configuration, and leave the test set untouched. This is the simplest kind of “uniform noise”. Real annotation errors are mostly concentrated between neighboring classes (for example card_arrival and card_delivery_estimate), which is harder to cope with than this.
| Share of labels replaced at random | Accuracy | Valid-label rate | Mean loss, last 10 steps | WikiText-2 perplexity | ARC-Easy (multiple choice) |
|---|---|---|---|---|---|
| 0% | 85.8% | 98.5% | 0.0136 | 19.10 | 72.8% |
| 10% | 82.4% | 99.4% | 0.1919 | 19.84 | 71.8% |
| 20% | 77.7% | 99.5% | 0.2638 | 19.55 | 70.6% |
| 40% | 69.2% | 99.4% | 0.5120 | 19.57 | 70.5% |
- Accuracy falls roughly linearly with the noise rate, about 0.4 percentage points per 1% of wrong labels. With 10% of the labels wrong, accuracy drops from 85.8% to 82.4% (−3.3); with 20% to 77.7% (−8.1); with 40% to 69.2% (−16.6). Per 1% of noise that is 0.33, 0.41 and 0.42 points. Each rate was trained once, and the slope will change with the model, the task and the training length, so do not use it as a formula.
- Within 291 steps the model learned the share of wrong labels, without clearly memorizing which ones. The loss is averaged over supervised tokens, and an answer has 4.86 of them on average (a class name plus the end-of-sequence token, 3 at least and 10 at most), so the floor has to be converted to per-token units too. Imagine a model that recognizes the true class of every example and knows the noise process (a share of the labels is replaced uniformly by one of the other 76 classes). The lowest expected loss it can reach on an answer is , which is 0.76, 1.37 and 2.41 nats for of 10%, 20% and 40%; divided by 4.86 that is 0.16, 0.28 and 0.49 per token. The measured mean loss over the last 10 steps is 0.19, 0.26 and 0.51, about equal to the floor (the last 10 steps hold only 160 examples, of which 16 to 64 had their labels replaced, so that average fluctuates a lot). Sitting on the floor means the model learned that roughly this share of the labels is random; there is no evidence that it remembered which ones. Memorizing takes longer training, as the next section shows.
- The format is not damaged, and forgetting is not clearly worse. The valid-label rate is 99.4% to 99.5%, slightly higher than the 98.5% on clean data (the six runs of the default configuration with a different seed or data subset range from 98.2% to 98.7%; this page did not check why). Perplexity is 19.55 to 19.84 and multiple choice is 70.5% to 71.8%, which largely overlaps the range seen when the default configuration changes seed or data subset (perplexity 18.78 to 19.78, multiple choice 70.9% to 72.8%), so no conclusion is drawn from them. Noise mostly hurts the target task itself.
- The value of spot checks can be converted directly. 10% wrong labels cost about 3.3 points of accuracy. If you read 100 random examples and the defect rate is 10%, the chance of finding none is , less than 3 in 100,000. Reading 100 examples is enough to find a problem of this size, so the spot check in “Building a Data-Quality Loop” below is not a formality.
Does longer training memorize wrong labels?
In the previous section the loss sat near the floor, which means the model learned the share of wrong labels but had not yet remembered which examples were relabeled. To remember them it has to see them more often. Here the run with 20 examples per class and 20% wrong labels is trained for 10 epochs (970 steps, with the learning rate decaying to 0 over 970 steps) and compared with the clean-label run trained for 10 epochs (the experiment in LoRA Fine-Tuning in Practice).
There are two ways to tell that the labels were memorized. The first is the floor: a model that does not know which examples were relabeled cannot get a mean loss per supervised token below 0.28 on the training set (derived above); anything lower must use the specific fact that “these examples were relabeled”. The second is more direct: after training, let the model answer its own training examples, and look at the 308 relabeled ones, whether it outputs the wrong label from the training data or the true one, with the same number of untouched examples as a control. The 3-epoch row of the second table is the previous section’s run repeated unchanged, with the training examples tested in addition; training is deterministic, so its accuracy and loss are exactly the same as in the previous section.
| Setting | Update steps | Accuracy | Valid-label rate | Mean loss, last 10 steps | WikiText-2 perplexity | ARC-Easy (multiple choice) |
|---|---|---|---|---|---|---|
| Clean labels, 3 epochs (default) | 291 | 85.8% | 98.5% | 0.0136 | 19.10 | 72.8% |
| Clean labels, 10 epochs | 970 | 87.5% | 98.7% | 0.0003 | 19.98 | 71.9% |
| 20% wrong labels, 3 epochs | 291 | 77.7% | 99.5% | 0.2638 | 19.55 | 70.6% |
| 20% wrong labels, 10 epochs | 970 | 74.1% | 98.0% | 0.0007 | 22.15 | 69.8% |
| Setting | Relabeled rows: outputs the wrong training label | Relabeled rows: outputs the true label | Untouched rows: outputs the training label |
|---|---|---|---|
| 20% wrong labels, 3 epochs | 15.3% | 55.5% | 95.1% |
| 20% wrong labels, 10 epochs | 100.0% | 0.0% | 100.0% |
- The loss falls below the floor at the start of epoch 4 and ends near zero. With 20% wrong labels and 10 epochs, the mean loss in each epoch is 1.58, 0.54, 0.33, 0.18, 0.078, 0.040, 0.014, 0.0075, 0.0033 and 0.0010: the first three epochs are still above the floor (0.28), from epoch 4 on it is below, and the mean over the last 10 steps is 0.0007.
- Counting directly: not memorized after 3 epochs, fully memorized after 10. On the 308 relabeled training examples, the 3-epoch model outputs the wrong training label only 15.3% of the time, and the true label 55.5% of the time; the 10-epoch model outputs the wrong label on all 308 and the true label on none. On the untouched training examples the 3-epoch model is right 95.1% of the time and the 10-epoch model 100%. Memorizing 308 random labels takes only about 308 × log₂76 ≈ 1,900 bits of information, far less than the 8.8 million parameters of the LoRA adapter can hold, so the limit is how many times the model has seen them.
- The price of memorizing wrong labels shows up on the test set. With 10 epochs, accuracy falls from 77.7% at 3 epochs to 74.1%, perplexity rises from 19.55 to 22.15 and multiple choice falls from 70.6% to 69.8%; the clean-label runs go the other way, with 10 epochs more accurate than 3 (85.8% to 87.5%). Meanwhile the training loss of the run with wrong labels falls from 0.2638 to 0.0007, and the curve looks better and better. The data and settings are the same and only the number of epochs changes; the standard deviation across training seeds is only 0.18 percentage points, so the 3.6-point accuracy gap is far larger than it, though it is still a single run.
- So the training loss cannot be used alone to pick a model. When the data may contain wrong labels, watch the accuracy on a clean validation set; the training loss only keeps falling, including on the part that memorizes the wrong labels.
Does more data dilute wrong labels?
The method: train on all 10,003 examples (about 130 per class, 3 epochs, 1,878 steps), once with clean labels and once with 20% wrong labels, and compare with the two 20-per-class runs above; everything else is unchanged, except that the run with wrong labels uses training seed 1, for the reason given in the warning at the end of this section. Earlier work points in two opposite directions: Rolnick et al. (2017) found on image classification that with enough data a network still generalizes under a large share of wrong labels, while Zhang et al. (2017) found that a network can fit completely random labels. Their tasks and models differ from this page’s, so this section only records what was seen and does not test either claim.
| Setting | Training examples | Update steps | Accuracy | Mean loss, last 10 steps | WikiText-2 perplexity | ARC-Easy (multiple choice) |
|---|---|---|---|---|---|---|
| 20 per class, clean labels (default) | 1,540 | 291 | 85.8% | 0.0136 | 19.10 | 72.8% |
| 20 per class, 20% wrong labels | 1,540 | 291 | 77.7% | 0.2638 | 19.55 | 70.6% |
| All 10,003 examples, clean labels | 10,003 | 1,878 | 93.9% | 0.0027 | 21.31 | 71.1% |
| All 10,003 examples, 20% wrong labels | 10,003 | 1,878 | 90.3% | 0.2162 | 23.44 | 68.9% |
- With more data the absolute cost of wrong labels shrinks, while the factor by which the error rate grows barely changes. 20% wrong labels cost 8.1 percentage points of accuracy at 20 per class and 3.6 points on all the data (93.9% to 90.3%). But the clean error rate is lower to begin with: at 20 per class it rises from 14.2% to 22.3%, on all the data from 6.1% to 9.7%, a factor of 1.57 and 1.59. Each number comes from a single run, and the 20-per-class difference also has to be read against the 0.80-point standard deviation across data subsets, so the safe statement is that no shrinking of the factor was seen with more data, not that the wrong labels were diluted.
- All the data with 20% wrong labels is more accurate than clean data at 20 per class (90.3% against 85.8%). But it has 6.5 times the data and trains for 6.5 times as many steps (1,878 against 291), and the two are tied together. It cannot answer “label more noisy data, or clean up a small set”: that depends on the kind and rate of the noise and on what cleaning costs.
- The loss drops below the floor in epoch 3: the model starts to remember the relabeled examples. In the figure the run with wrong labels sits around 0.34 for the first two epochs, above the floor (0.28), because the model cannot yet recognize the true class of every example; in epoch 3 the mean loss is 0.225, and over the last 10 steps it is 0.2162, 23% below the floor. By the criterion of the previous section, that means it has started to use the specific fact of which examples were relabeled. After the same 3 epochs, the 20-per-class run ends at 0.2638, only 6% below the floor; the all-data run took 6.5 times as many steps and may remember more for that reason, but it is a single run, so do not read too much into it.
- The cost is not confined to the target task. WikiText-2 perplexity (base model 16.83) rises from 21.31 with clean labels to 23.44, and multiple choice falls from 71.1% to 68.9% (2,365 questions, a standard error of about 0.9 points for a single score). Both come from one run each, so treat them as observations.
The first time I trained on all the data with 20% wrong labels (training seed 0), the loss fell from about 0.36 to below 0.1 at the very start of epoch 3, then jumped to 0.9 around step 1,754 and stayed there to the end (the gray dotted line in the figure). I read the first as “the model memorized the wrong labels” and the second as training instability, and reran the same command: both runs ended with the same mean loss over the last 10 steps, 0.9378. The same seed gives the same result, so a rerun verifies nothing.
The real cause is that the script used seed 0 for two things: which examples get a wrong label, and how each epoch is shuffled. random.Random(0) always yields the same stream of random numbers. The stretch used to sample the 2,001 examples was used again almost verbatim by the epoch-3 shuffle (the two start only 47 numbers apart), so the relabeled examples were pushed to the end of that epoch: in the first 80% of positions only 3% to 4% of the rows have a wrong label (it should be 20%), in the last 20% it is 80% to 95%. The loss is low and then high simply because the batches first contain almost no wrong labels and then almost only wrong labels, and the final model was finished on a stretch of batches that were nearly all wrong labels.
After switching the training seed to 1, the share of wrong labels is about 20% in every epoch at every position; the table and the text use that rerun. The faulty run ended with accuracy 89.3% and perplexity 24.75, both worse than the rerun. I also checked the other runs on this page that have wrong labels or mixed-in data (the three noise rates at 20 per class and the two Alpaca mixes): none has such a concentration at any position in any epoch. Two lessons: when a curve changes abruptly, check the data order before explaining it with the model, and use independent random generators for sampling, corrupting and shuffling.
The loss mask: should the prompt count in the loss
By default only the answer counts in the loss (the example in the previous section). The alternative is to compute the loss over the whole sequence, prompt plus answer, so that the model also learns to “write the prompt”. Same 1,540 examples, only this one thing changed:
| Setting | Accuracy | Valid-label rate | WikiText-2 perplexity | ARC-Easy (multiple choice) |
|---|---|---|---|---|
| Loss on the response only (default) | 85.8% | 98.5% | 19.10 | 72.8% |
| Loss on the whole sequence | 84.5% | 98.3% | 19.83 | 71.0% |
- Computing the loss over the whole sequence did not raise accuracy; it is slightly lower. Accuracy goes from 85.8% to 84.5% (−1.3), the valid-label rate is 98.3%, WikiText-2 perplexity is 19.83 (19.10 by default) and multiple choice is 71.0% (72.8% by default). The accuracy difference is about 7 times the standard deviation across the three training seeds (0.18), but only 1.6 times the fluctuation when the data subset changes (standard deviation 0.80), so it may be just the luck of this subset and all that can be said is “no improvement, possibly slightly worse”. Perplexity and multiple choice are within the ranges above, and no conclusion is drawn from them.
- A plausible explanation is that the supervision gets diluted; this page did not verify it. The loss is the mean over all supervised positions in the batch. With the answer only, a batch of 16 has about 78 supervised tokens, all of them directly about “which class”; with the whole sequence it has about 500, and about 84% of those predict the prompt itself (the template and the user’s sentence), which does not directly help choose a class. The part of the gradient that concerns classification shrinks. The cost is real: the time per step rises from 0.35 s to 0.55 s, because the lm_head must produce logits for about 500 positions instead of about 78.
- This does not contradict Shi et al. (2024), and it does not test them either. They propose computing the loss on the instruction part too (Instruction Modelling) and find the gain largest when instructions are long and outputs short, or when there are few training examples. This data fits both (prompts average 27.1 tokens, answers 4.9, and there are only 20 examples per class), yet no gain shows up here. But they evaluate on 21 benchmarks, including NLP tasks (MMLU, TruthfulQA, HumanEval and others) and open-ended generation benchmarks (MT-Bench, AlpacaEval and others); this page measures exact-match accuracy of one small model on a classification task, so the metric, the scale and the training differ and neither result can overturn the other.
- In practice, computing the loss on the answer only is a fine default. If you want to try the whole sequence, compare on the metric you actually care about (for example scores on open-ended generation) and not only classification accuracy, and match the budget: computing the loss over the whole sequence makes every step slower.
Mixing in general data: can it hold off forgetting
Mixing some general instruction data into the target data is a common way to “prevent forgetting”. Here 500 or 1,540 examples are drawn at random from Alpaca-cleaned and mixed into the 1,540 banking examples (only examples without an extra input, answers cut to at most 200 tokens, the ### Instruction: and ### Response: template). Training is still 3 epochs, so the number of steps rises to 384 and 579; everything else is unchanged.
| Setting | Update steps | Accuracy | Valid-label rate | WikiText-2 perplexity | ARC-Easy (multiple choice) |
|---|---|---|---|---|---|
| No mixing (default) | 291 | 85.8% | 98.5% | 19.10 | 72.8% |
| Mix in 500 general instructions | 384 | 84.0% | 98.3% | 21.49 | 71.5% |
| Mix in 1,540 general instructions | 579 | 82.7% | 98.2% | 21.07 | 71.7% |
- Neither forgetting gauge improves. WikiText-2 perplexity rises from 19.10 to 21.49 and 21.07 (16.83 for the base model; the default configuration ranges from 18.78 to 19.78 across seeds and data subsets, so the rise exceeds the fluctuation); ARC-Easy multiple choice is 72.8%, 71.5% and 71.7%, within the sampling error of about ±1 point. The mixed runs take more steps than the default (384 and 579 against 291), and the previous section showed that more steps raise perplexity by themselves, so the effect of “the mixed-in data” and of “more steps” cannot be separated here. All that can be said is that on these two gauges no benefit from mixing in general data shows up.
- The default configuration had not forgotten much on these gauges to begin with. The base model’s multiple-choice accuracy is 72.4% and the default adapter’s is 72.8%, no drop; perplexity goes from 16.83 to 19.10. There is not much loss to protect, so the benefit of mixing cannot show. This is the result for a 0.5B model adapted on 1,540 classification examples for 291 steps; with longer training, a higher learning rate or a task farther from the pretraining distribution, forgetting is much heavier and the conclusion does not carry over.
- The target task got worse. Accuracy falls from 85.8% to 84.0% (−1.8) and 82.7% (−3.1), both an order of magnitude above the standard deviation across seeds (0.18); against the fluctuation across data subsets (standard deviation 0.80), −1.8 is 2.2 times that and −3.1 is 3.9 times, so the latter clearly exceeds the fluctuation and the former calls for caution. One possible reason is that the loss is averaged over supervised tokens: the mixed-in Alpaca answers average 129 to 131 supervised tokens (38.6% and 39.8% of them hit the 200-token cap), whereas a banking answer has 4.9. With 500 mixed-in examples the banking examples are 75.5% of the rows but only 10.4% of the supervised tokens; with 1,540 they are 50.0% of the rows and 3.6% of the supervised tokens. The target task’s share of the gradient is diluted, and accuracy drops with it. This is a plausible explanation only, and this page did not verify it; to check, average per example instead of per token, or weight the target data, and compare again.
A Few Actual Outputs
Beyond the numbers, here are the actual outputs for six prompts: greedy decoding, at most 24 new tokens, for the untuned base model, the default adapter and the two adapters trained with general data mixed in. Prompts 3 and 4 use this page’s classification template; the others are plain Q&A, free-text continuation and the ### Instruction format. Six prompts are a handful of examples, not a measurement; they are here only to show the shape of the behaviour.
| Prompt | Untuned base | Default adapter (no mixing) | Mix of 500 | Mix of 1,540 |
|---|---|---|---|---|
| Q&A format: capital of France | The capital of France is Paris. ↵ A single-select problem: Is the question answered in a satisfactory fashion? ↵ ↵ Available options: | Paris is the capital of France. ↵ A: ↵ paris | Paris | Paris is the capital of France. |
| Free text: one sentence about the ocean | The ocean is a vast and diverse body of water that covers approximately 71% of the Earth's surface. It | The ocean is a vast and mysterious body of water that covers approximately 71% of the Earth's surface. | The ocean is a vast and deep body of saltwater that covers approximately 70% of the Earth's surface, | The ocean is vast, deep, and filled with life. |
| This page’s classifier prompt, input: how to bake sourdough | Bread baking | bake_sourdough | bake_self_feeding_bread | bake_sourdough_bread |
| This page’s classifier prompt, input: open a savings account | Deposit | open_savings_account | open_savings_account | age_limit |
| Instruction format: capital of France | The capital of France is Paris. | The capital of France is Paris. | The capital of France is Paris. | The capital of France is Paris. |
| Instruction format: one sentence about the ocean | The ocean is a vast and complex system that encompasses the vast expanse of water that surrounds our planet. It is a | The ocean is a vast and complex system that encompasses the Earth's water, air, and sediment. | The ocean is a vast and mysterious body of water, teeming with life and providing a habitat for countless species. | The ocean is vast and deep, a vast expanse of blue, where life thrives and where the wind can rust |
- When the classification prompt gets an out-of-scope input, the adapters still emit a string that looks like a label. “How do I bake sourdough bread?” and “I would like to open a savings account.” are not among the 77 banking77 classes. The adapters answer
bake_sourdough,bake_self_feeding_bread,bake_sourdough_breadandopen_savings_account, all invented names that are not among the 77;age_limitis a real class, but unrelated to opening an account. Every training example has a label, so the model never saw “none of these” as an answer and has no way to say it. The 98.5% valid-label rate above only shows that the model behaves inside the distribution; it does not promise anything outside it. To make it decline, the training data needs declining examples (for instance anotherclass), or inference can constrain the output to the 77 names and add a confidence threshold; this page did not test either. - “Stop when done” carried over to other formats. Among the four non-classification prompts (1, 2, 5 and 6), the base model ran into the 24-token limit on three (prompt 2 stops at
...surface. It); the default adapter stopped by itself on all four; each of the two mixed adapters was cut off once. Training answers are always followed by the end-of-sequence token, so stopping became a habit. This is a side effect of fine-tuning, good or bad depending on the use: you need it for classification and it may be a problem for long-form generation. - For the instruction-format “capital of France”, all four models give the same words. The base model already handles that format and fine-tuning did not change it.
- The adapter with 1,540 examples mixed in wrote
where the wind can rustfor the instruction-format “ocean” sentence. The sentence is incoherent, and neither the base model nor the default adapter has that problem on the same prompt. One sample cannot show whether mixing in data hurts generation quality; it only reminds you not to rely on perplexity alone and to read outputs on your own evaluation set.
Audit: Three Public Instruction Datasets
Alpaca, Alpaca-cleaned and Dolly are the three public datasets most often used for SFT experiments. They differ in origin and character:
| Dataset | Examples | Source | License |
|---|---|---|---|
Alpaca (tatsu-lab/alpaca) | 52,002 | Generated by Stanford with OpenAI’s text-davinci-003, following the Self-Instruct recipe | CC BY-NC 4.0 |
Alpaca-cleaned (yahma/alpaca-cleaned) | 51,760 | A community-repaired version; its data card lists 10 kinds of fixed problems, including hallucinations, merged instructions, empty outputs and wrong answers | CC BY 4.0 |
Dolly (databricks/databricks-dolly-15k) | 15,011 | Written by Databricks employees, who were told not to draft with generative AI | CC BY-SA 3.0 |
The license is the first item of a data audit: before training a model for commercial use on data under a non-commercial license such as CC BY-NC, check the terms.
Rule filters: find the obviously bad examples first
The rules do not need to be clever; they need to be cheap and reproducible. The code below scans the three datasets with five rules, looks at how Alpaca and Alpaca-cleaned correspond, and draws a few random hits to read:
import random
import re
from collections import Counter
from datasets import load_dataset
def norm(s):
return re.sub(r"\s+", " ", s.strip().lower())
REFUSAL = re.compile(
r"as an ai( language)? model|as a language model|i'm sorry|i am sorry|"
r"i cannot|i can't|i'm not able|i am not able|i'm unable", re.I)
URL_ONLY = re.compile(r"^\s*(https?://\S+|www\.\S+)\s*$")
PLACEHOLDER = {"<noinput>", "<no input>", "no input", "noinput", "n/a",
"<no output>", "<picture attached>", "none"}
RULES = {
"empty output": lambda r: not r["output"].strip(),
"output <= 2 words": lambda r: len(r["output"].split()) <= 2,
"placeholder text": lambda r: (norm(r["output"]) in PLACEHOLDER
or norm(r["input"]) in PLACEHOLDER),
"input is only a URL": lambda r: bool(URL_ONLY.match(r["input"])),
"refusal-like phrase": lambda r: bool(REFUSAL.search(r["output"])),
}
def dolly():
ds = load_dataset("databricks/databricks-dolly-15k", split="train")
return [{"instruction": r["instruction"], "input": r["context"],
"output": r["response"], "category": r["category"]}
for r in ds]
sets = {
"alpaca": list(load_dataset("tatsu-lab/alpaca", split="train")),
"cleaned": list(load_dataset("yahma/alpaca-cleaned", split="train")),
"dolly": dolly(),
}
print(f"{'':24s}" + "".join(f"{k:>10s}" for k in sets))
print(f"{'rows':24s}" + "".join(f"{len(v):>10,}" for v in sets.values()))
flags = {k: {n: [f(r) for r in v] for n, f in RULES.items()}
for k, v in sets.items()}
for name in RULES:
print(f"{name:24s}" + "".join(f"{sum(flags[k][name]):>10,}" for k in sets))
print(f"{'any rule above':24s}" + "".join(
f"{sum(any(flags[k][n][i] for n in RULES) for i in range(len(v))):>10,}"
for k, v in sets.items()))
for k, v in sets.items():
seen, dup = set(), 0
for r in v:
key = norm(r["output"])
dup += key in seen
seen.add(key)
print(f"duplicate outputs, {k}: {dup:,}")
def keyed(rows):
out = {}
for r in rows:
out.setdefault((r["instruction"], r["input"]), set()).add(r["output"])
return out
a, c = keyed(sets["alpaca"]), keyed(sets["cleaned"])
shared = a.keys() & c.keys()
print(f"(instruction, input) shared by alpaca and cleaned: {len(shared):,}; "
f"outputs differ in {sum(a[k] != c[k] for k in shared):,}")
# a rule only produces candidates: read a random sample of what it flags
hits = [r for r in sets["alpaca"] if RULES["output <= 2 words"](r)]
random.Random(1).shuffle(hits)
for r in hits[:6]:
print(f"{r['instruction'][:50]!r} -> {r['output']!r}")
short = Counter(r["category"] for r in sets["dolly"]
if RULES["output <= 2 words"](r))
print("dolly, output <= 2 words by category:", dict(short.most_common(4)))
Output:
alpaca cleaned dolly
rows 52,002 51,760 15,011
empty output 28 0 0
output <= 2 words 3,694 1,058 780
placeholder text 538 18 1
input is only a URL 196 23 0
refusal-like phrase 119 945 24
any rule above 4,484 2,040 805
duplicate outputs, alpaca: 1,245
duplicate outputs, cleaned: 290
duplicate outputs, dolly: 75
(instruction, input) shared by alpaca and cleaned: 49,279; outputs differ in 47,447
'Create a password for the account with at least 8 ' -> 'Password123!'
'Provide the numeral form of the written number.' -> '770'
'Categorize the following text into one of the genr' -> 'Drama.'
'Categorize this sentence as either descriptive or ' -> 'Descriptive.'
'Categorize the following sentence as a given type.' -> 'Action.'
'Generate a new English word.' -> 'Frozbit'
dolly, output <= 2 words by category: {'open_qa': 393, 'closed_qa': 142, 'classification': 134, 'information_extraction': 72}
Reading the output line by line:
- The hits in the original Alpaca are mostly placeholders and very short outputs. Of 52,002 examples, 4,484 (8.6%) hit at least one rule: 28 have an empty output, 538 contain placeholders such as
<noinput>orN/A, and 196 have only a URL as input, so the model cannot see the page and can only make things up. In Alpaca-cleaned these fall to 0, 18 and 23, in line with the fixes listed on its data card. - Cleaning is not just “deleting the bad examples”. The two versions share 49,279 identical (instruction, input) pairs, and 47,447 of them have different output text; the average answer length goes from 56.9 tokens to 140.4 (see the length statistics below). Alpaca-cleaned is a different dataset, not a subset of Alpaca, so do not carry conclusions from Alpaca over without testing.
- Improving one dimension can worsen another. Refusal phrases (“I’m sorry”, “As an AI language model”) appear in 945 examples (1.8%) of Alpaca-cleaned against 119 in the original. Whether to control their share depends on whether you want your product to say such things.
- A rule hit is a candidate, not a verdict. In Dolly, the rule “output of at most 2 words” hits 780 examples, mostly from open QA (393), closed QA (142), classification (134) and information extraction (72), where a short answer is the correct form. Among the 6 randomly drawn Alpaca examples, some are reasonable short answers (
'Drama.','Descriptive.') and some have vague instructions ('Categorize the following sentence as a given type.'does not say which types). Rules narrow the range; a human reads before anything is deleted. - Repeated outputs. Rows whose output is identical to an earlier row (ignoring case and whitespace) number 1,245 in Alpaca, 290 in Alpaca-cleaned and 75 in Dolly. Many are short answers such as “Yes” or “True”, so you need the instruction to tell whether it is a real duplicate.
Near-duplicate removal and contamination checks
Exact deduplication misses repeats that change a few words. The usual tool is MinHash plus LSH (locality-sensitive hashing): cut the text into a set of word 3-grams, compress the set into a short signature with a family of hash functions, split the signature into bands and put them into buckets, and only compute the exact Jaccard similarity (intersection over union of the two sets) for pairs that fall into the same bucket. The implementation below is under 40 lines, and the same function serves three purposes: near-duplicates inside Dolly, 13-gram overlap between training text and test questions (the GPT-3 paper detected contamination with n-grams of 8 to 13 words, depending on the dataset), and near-duplicates between the banking77 training and test sets.
import re
import zlib
from collections import defaultdict
import numpy as np
from datasets import load_dataset
def words(text):
return re.findall(r"\w+", text.lower())
def shingles(text, k=3):
w = words(text)
return {zlib.crc32(" ".join(w[i:i + k]).encode())
for i in range(max(1, len(w) - k + 1))}
def near_duplicates(texts, threshold=0.8, bands=16, rows=4):
"""MinHash + LSH banding: pairs of texts with Jaccard >= threshold."""
rng = np.random.RandomState(0)
a = rng.randint(1, 1 << 30, bands * rows).astype(np.uint64)
b = rng.randint(0, 1 << 30, bands * rows).astype(np.uint64)
sets = [shingles(t) for t in texts]
buckets = defaultdict(list)
for i, s in enumerate(sets):
x = np.fromiter(s, dtype=np.uint64)[:, None]
sig = ((x * a + b) % np.uint64(4294967291)).min(axis=0)
for k in range(bands):
buckets[k, tuple(sig[k * rows:(k + 1) * rows])].append(i)
cand = set()
for ids in buckets.values():
if 1 < len(ids) <= 50: # skip giant buckets
cand |= {(i, j) for p, i in enumerate(ids) for j in ids[p + 1:]}
out = []
for i, j in cand:
jac = len(sets[i] & sets[j]) / len(sets[i] | sets[j])
if jac >= threshold:
out.append((i, j, jac))
return sorted(out)
def removable(n, pairs):
"""Rows to drop if one row is kept per cluster of near-duplicates."""
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for i, j, _ in pairs:
parent[find(i)] = find(j)
return sum(find(i) != i for i in range(n))
# 1. near-duplicate instructions inside one dataset
dolly = load_dataset("databricks/databricks-dolly-15k", split="train")
texts = [r["instruction"] + " " + r["context"][:200] for r in dolly]
pairs = near_duplicates(texts)
print(f"dolly: {len(pairs)} pairs with Jaccard >= 0.8, "
f"{removable(len(texts), pairs)} removable rows")
i, j, jac = next(p for p in pairs if p[2] < 1)
print(f" {jac:.2f} {texts[i][:70]}\n {texts[j][:70]}")
# 2. test questions that also appear in training text (13-gram overlap)
def ngrams(text, n=13):
w = words(text)
return {" ".join(w[i:i + n]) for i in range(len(w) - n + 1)}
arc = load_dataset("allenai/ai2_arc", "ARC-Easy", split="test")
index = defaultdict(set)
for q, r in enumerate(arc):
for g in ngrams(r["question"] + " " + " ".join(r["choices"]["text"])):
index[g].add(q)
train = load_dataset("yahma/alpaca-cleaned", split="train")
hit = set()
for r in train:
for g in ngrams(r["instruction"] + " " + r["input"] + " " + r["output"]):
hit |= index.get(g, set())
print(f"alpaca-cleaned vs ARC-Easy test: {len(hit)} of {len(arc)} questions")
# 3. the same near-duplicate check across a train/test split
bank = load_dataset("PolyAI/banking77")
tr, te = list(bank["train"]["text"]), list(bank["test"]["text"])
cross = [(i, j) for i, j, _ in near_duplicates(tr + te)
if i < len(tr) <= j]
print(f"banking77: {len({j for _, j in cross})} of {len(te)} test texts "
f"have a near-duplicate in train")
Output:
dolly: 1344 pairs with Jaccard >= 0.8, 325 removable rows
0.87 In the series A Song of Ice and Fire, who is the founder of House Kars
In the series A Song of Ice and Fire, who is the founder of House Tarl
alpaca-cleaned vs ARC-Easy test: 1 of 2376 questions
banking77: 77 of 3080 test texts have a near-duplicate in train
- Dolly has 1,344 near-duplicate pairs with Jaccard similarity of at least 0.8; keeping one example per cluster would remove 325 rows (2.2%). The printed sample is “In the series A Song of Ice and Fire, who is the founder of House …”: the two examples differ by one house name and their answers are different. Textual similarity is not redundancy: question templates each have their own answers. A safer approach to deduplication is to cap the number of examples per template cluster instead of keeping just one.
- Only 1 of the 2,376 ARC-Easy test questions has a 13-gram overlap with Alpaca-cleaned. That only shows nothing was copied in large blocks. Paraphrased or translated questions are invisible to 13-grams; to really prevent leakage, combine it with a private evaluation set and manual checks (see LLM Evaluation Methodology).
- 77 banking77 test examples (2.5%) have a near-duplicate in the training set, 7 of them verbatim. The adapter trained with the default configuration scores 93.5% on these 77 and 85.6% on the other 3,003. If those 77 were answered at only 85.6%, the overall accuracy would be about 0.2 points lower, less than the fluctuation between three random seeds. The effect is small, but you should know how many there are. Lee et al. (2022) found that over 4% of the text in the validation sets of common language-modeling datasets also appears in the training set, and that deduplication makes models regurgitate about ten times less training text.
Length, supervision ratio and padding
The compute bill of SFT is set by three numbers: how long the prompts and the answers are, how many tokens actually enter the loss, and how many positions in a batch are padding.
import random
from datasets import load_dataset
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B")
HEAD = ("Below is an instruction that describes a task{extra}. Write a "
"response that appropriately completes the request.\n\n"
"### Instruction:\n{instruction}\n\n")
P = HEAD.replace("{extra}", "") + "### Response:\n"
PI = (HEAD.replace("{extra}", ", paired with an input that provides further "
"context") + "### Input:\n{input}\n\n### Response:\n")
def lengths(rows):
prompts = [(PI if r["input"].strip() else P).format(**r) for r in rows]
enc = lambda texts: tok(texts, add_special_tokens=False)["input_ids"]
n_prompt = [len(x) for x in enc(prompts)]
n_resp = [len(x) + 1 for x in enc([r["output"] for r in rows])] # + EOS
return n_prompt, n_resp
def padding_share(lens, bs, grouped, seed=0):
idx = list(range(len(lens)))
random.Random(seed).shuffle(idx)
if grouped: # sort by length inside windows of 50 batches
idx = [i for s in range(0, len(idx), bs * 50)
for i in sorted(idx[s:s + bs * 50], key=lens.__getitem__)]
batches = [idx[s:s + bs] for s in range(0, len(idx) - bs + 1, bs)]
real = sum(lens[i] for b in batches for i in b)
total = sum(max(lens[i] for i in b) * bs for b in batches)
return 1 - real / total
for name in ("tatsu-lab/alpaca", "yahma/alpaca-cleaned"):
rows = list(load_dataset(name, split="train"))
n_prompt, n_resp = lengths(rows)
lens = [p + r for p, r in zip(n_prompt, n_resp)]
print(f"{name}: prompt {sum(n_prompt) / len(rows):.1f} tokens, "
f"response {sum(n_resp) / len(rows):.1f} tokens, "
f"supervised share {sum(n_resp) / sum(lens):.3f}")
for bs in (16, 64):
print(f" batch {bs}: padding share random "
f"{padding_share(lens, bs, False):.3f}, length-grouped "
f"{padding_share(lens, bs, True):.3f}")
Output:
tatsu-lab/alpaca: prompt 46.7 tokens, response 56.9 tokens, supervised share 0.549
batch 16: padding share random 0.551, length-grouped 0.058
batch 64: padding share random 0.675, length-grouped 0.084
yahma/alpaca-cleaned: prompt 47.2 tokens, response 140.4 tokens, supervised share 0.748
batch 16: padding share random 0.576, length-grouped 0.033
batch 64: padding share random 0.641, length-grouped 0.048
- The longer the answers, the higher the supervision ratio. Alpaca’s answers average 56.9 tokens and only 54.9% of the tokens enter the loss; Alpaca-cleaned’s answers average 140.4 tokens and the ratio is 74.8%. With short answers, the template and the prompt use up half of the compute.
- Random batching wastes more than half of the positions on padding. At batch size 16, random batching is 55.1% padding, and at batch size 64 it is higher, 67.5%. Putting examples of similar length into the same batch (sort inside a window of 50 batches, then batch) leaves 5.8% and 8.4%. At batch size 16 the number of tokens processed per useful token drops from 2.2 to 1.06, about half the compute. The QLoRA paper also groups by length in its experiments, at the price of a loss curve that swings, because the length of the examples in a batch is no longer random.
Where the Data Comes From
Before auditing a dataset, ask who wrote it, because the source decides which defects it carries:
| Source | Examples | Strengths | Main risks | What to do |
|---|---|---|---|---|
| Written by people | Dolly (employee-written), LIMA (1,000 selected examples) | Quality and style are controllable | Expensive and slow, narrow coverage, authors differ in style | Write an annotation guideline first, double-check a sample, calibrate regularly |
| Business logs | Support conversations, search Q&A | The distribution closest to production | Privacy, the personal style of agents, wrong answers from the past | Anonymize, filter with rules, spot-check by hand, keep source tags |
| Generated by a strong model | Alpaca (text-davinci-003) | Cheap, large scale | Hallucinations and wrong answers, the teacher’s style leaks in, bound by the terms of service | Filter first (for example the score filter of AlpaGasus); where answers can be verified by a program, let the program check them; read the terms of use |
| Rewritten and expanded | The Self-Instruct recipe, rejection sampling | Fills edge cases and the long tail | Uniform phrasing, collapsing diversity | Deduplicate, cap each template cluster, mix in real data |
Self-Instruct (Wang et al., 2022) starts from a small set of human-written seed tasks, has the model generate new instructions, inputs and outputs, and filters out similar and low-quality ones; it is the blueprint for datasets like Alpaca. When synthetic data adds information, why training on a model’s own output loses the tail of the distribution, and how a verifier lets a model bootstrap are covered in Synthetic data and self-improvement.
Building a Data-Quality Loop
This pipeline works for any SFT dataset:
- Fix the acceptance criteria first. Write 10 to 20 “ideal answers” and say what counts as right and wrong. This is the seed of your future evaluation set.
- Split first, then clean. Divide training, validation and test sets by source or by conversation, and only then deduplicate. The banking77 example shows that once near-duplicates cross the split, test scores are inflated.
- Filter with rules, then deduplicate. Rules only narrow the range; read a sample of the hits before deciding whether to delete.
- Spot-check by hand. How many examples to read depends on what defect rate you want to show is below:
"""How many examples must a manual spot check read?"""
from math import comb, sqrt
from scipy.stats import beta
def clopper_pearson(k, n, alpha=0.05):
lo = 0.0 if k == 0 else beta.ppf(alpha / 2, k, n - k + 1)
hi = 1.0 if k == n else beta.ppf(1 - alpha / 2, k + 1, n - k)
return lo, hi
for n, k in [(50, 0), (100, 0), (100, 5), (300, 0), (300, 15), (1000, 50)]:
lo, hi = clopper_pearson(k, n)
print(f"read {n:4d}, bad {k:3d}: rate {k / n:5.1%}, "
f"95% CI [{lo:5.1%}, {hi:5.1%}]")
# smallest sample that proves "defect rate < 1%" when none is found
n = 1
while clopper_pearson(0, n)[1] >= 0.01:
n += 1
print("zero bad examples proves < 1% (95%) from n =", n)
Output:
read 50, bad 0: rate 0.0%, 95% CI [ 0.0%, 7.1%]
read 100, bad 0: rate 0.0%, 95% CI [ 0.0%, 3.6%]
read 100, bad 5: rate 5.0%, 95% CI [ 1.6%, 11.3%]
read 300, bad 0: rate 0.0%, 95% CI [ 0.0%, 1.2%]
read 300, bad 15: rate 5.0%, 95% CI [ 2.8%, 8.1%]
read 1000, bad 50: rate 5.0%, 95% CI [ 3.7%, 6.5%]
zero bad examples proves < 1% (95%) from n = 368
This uses the exact binomial interval (Clopper–Pearson). When the sample is small and defects are rare, the normal approximation produces conclusions like “0 defects, so the defect rate is exactly 0”; the exact interval does not. After reading 100 examples and finding no defect, the upper end of the two-sided 95% interval for the defect rate is still 3.6%; to show that the rate is below 1% you need to read 368 examples in a row with no defect. Reading 100 and finding 5 bad ones gives an interval of 1.6% to 11.3%; reading 1,000 and finding 50 narrows it only to 3.7% to 6.5%. For the meaning of confidence intervals see Evaluation Statistics. 5. Change one thing at a time, and version the data. Record the data file hash, the prompt template and the random seed, so that you can answer “did this improve because of the data or because of the seed?”. 6. Evaluate, read the failures, feed them back. The evaluation set does not take part in tuning; failures from production or evaluation are corrected by hand and added to the training set, while a version that never trains on them is kept for regression checks.
Common Problems and Diagnosis
| Symptom | Likely cause | First thing to do |
|---|---|---|
| Training loss is low but the output format in production is a mess | The inference prompt template differs from the training one | Build prompts with the same function and print the exact text that goes into the model in production |
| Answers get shorter and more alike | Short or templated answers dominate | Count answer lengths and sentence patterns, cap each template cluster |
| Generation does not stop | The end token is not in the labels, or was masked to -100 | Print the labels of one example and confirm the end token is in the loss |
| High on the dev set, worse in production | Near-duplicate leakage, or the dev set differs from the production distribution | Split before cleaning, build the evaluation set from production samples |
| General ability drops clearly | Learning rate or epochs too large, data too narrow | Lower the learning rate, train fewer epochs; before mixing in general data, check it on your own forgetting metric (in the experiments above it did not help) |
| More data brings no gain | The data is homogeneous and the bottleneck is quality or the annotation guideline | Spot-check the wrong examples and add data by error type instead of adding volume |
| The same configuration gives very different results twice | Random seed or data subset | Use at least 3 seeds or 3 data subsets, report the mean and the range |
Summary and Exercises
Key points:
- An SFT example is a prompt, an answer and an end-of-sequence token: the prompt’s labels are
-100, while the answer and the end token count in the loss. The supervision is sparse (in banking77 the answer is only about 15% of the tokens), so every supervised token deserves a check, and the prompt template at inference must match training: on this page a reworded prompt lowers accuracy from 85.8% to 79.4%. - The return on data size diminishes quickly: each doubling of the data adds 8.2 percentage points of accuracy from 10 to 20 examples per class, 4.0 from 20 to 50 and 2.1 from 50 to all; the error rate fell from 14.2% to 6.1% with 6.5 times the data.
- With very little data the output format breaks first: at 1 example per class, 58% of the outputs are not a valid class name. With more data, the errors are almost all confusions between neighboring classes.
- Label noise: every 1% of wrong labels costs about 0.4 percentage points; with more data the absolute cost shrinks (3.6 points for 20% wrong labels on all the data, 8.1 at 20 per class) while the factor by which the error rate grows barely changes. After 3 epochs the training loss sits near the floor of a model that knows the noise rate; after 10 epochs it is below the floor, all 308 relabeled examples are memorized, and test accuracy falls by 3.6 points, so the training loss cannot be used alone to pick a model.
- Computing the loss on the whole sequence brings no gain on a classification task with long prompts, short answers and few examples (accuracy goes from 85.8% to 84.5%) and makes every step about half again slower, so the default is to compute the loss on the answer only; if you want to try it, compare on the metric you care about.
- Mixing in general instruction data is not a free way to prevent forgetting: the default configuration barely forgets (multiple choice 72.8%, base model 72.4%), perplexity is higher after mixing in 500 or 1,540 examples, and target-task accuracy falls by 1.8 and 3.1 percentage points. With a loss averaged per token, long answers outweigh short ones: with 500 mixed-in examples the banking examples are 75.5% of the rows but only 10.4% of the supervised tokens.
- In an audit, a rule hit is only a candidate: read before you delete. Alpaca and Alpaca-cleaned are two different datasets, so conclusions about one do not carry over to the other. Near-duplicate removal (MinHash plus LSH) and contamination checks belong after the split; 2.5% of the banking77 test set has a near-duplicate in the training set.
- The quality loop: split first, then clean; how many examples a spot check reads depends on the defect-rate bound you want to prove (100 clean examples still leave an upper bound of 3.6%); change one thing at a time and version the data; fix the failures found in evaluation and feed them back.
- The compute bill: putting examples of similar length in the same batch cuts the padding share from 55.1% to 5.8%, at the price of batches whose length is no longer random, so the loss curve swings.
Quick self-test
1. In an SFT example, which positions should have the label -100 (not counted in the loss)?
- The prompt (instruction, input and template)
- The first token of the answer
- The end-of-sequence token after the answer
- All positions; the model learns to answer from the prompt alone
The prompt is labeled
-100; the answer and the end token count in the loss. The end token is the only signal that teaches the model where to stop, and leaving it out or masking it makes generation tend to run on. In this page’s example,card_arrivalplus the end token gives 4 supervised positions, only 15% of the 26 tokens of the example.
2. Accuracy is 85.8% at 20 examples per class, 91.0% at 50 and 93.9% with all the data (about 130 per class). Which statement about data size fits these numbers best?
- Accuracy is proportional to data size; one more doubling adds another 8 points
- The return on each doubling shrinks: 8.2 points from 10 to 20 per class, about 4.0 points per doubling from 20 to 50, and about 2.1 points per doubling from 50 to all
- Beyond 50 per class, data size no longer affects accuracy
- Data size only affects training time, not accuracy
The error rate makes it clearer: 14.2%, 9.0%, 6.1%. Every 2.5 times more data removes about a third of the errors. Each point was trained once and the numbers of steps differ, so the shape of the curve is a useful guide, but do not extrapolate the exponent to other tasks.
3. With 20% of the training labels replaced by a random other class and 10 epochs of training, the training loss falls to 0.0007, far below the 0.28 floor of a model that knows the noise rate. What does that mean?
- The model learned well, and test accuracy will be high too
- The model memorized which examples were relabeled, and test accuracy will suffer
- The floor is wrong; wrong labels do not raise the loss
- The learning rate is too small and the model is not trained yet
The noise is random and cannot be inferred from the content of an example, so a model that does not know which examples were relabeled cannot go below the floor on the training set. 0.0007 means it used the specific fact that “these examples were relabeled”: all 308 relabeled examples came out with the wrong label. The price shows on the test set: accuracy falls from 77.7% at 3 epochs to 74.1%, while the clean-label runs go the other way, with 10 epochs more accurate than 3. A loss below the floor is a sign of memorized noise, not of good learning.
4. After mixing 500 or 1,540 Alpaca-cleaned instructions into the 1,540 banking-intent examples (the number of steps rises to 384 and 579), which statement matches the experiments on this page?
- WikiText-2 perplexity and ARC-Easy accuracy both improve clearly, and target-task accuracy stays the same
- Neither forgetting gauge improves (perplexity rises from 19.10 to 21.49 and 21.07, multiple choice stays between 71.5% and 72.8%), and target-task accuracy falls to 84.0% and 82.7%
- Target-task accuracy rises clearly, because the general data acts as a regularizer
- The output format is damaged and the valid-label rate drops below 50%
The valid-label rate is still 98.3% and 98.2%, so the format is intact. The loss is averaged over supervised tokens, and the mixed-in Alpaca answers average 129 to 131 supervised tokens against 4.9 for a banking-intent answer: with 500 mixed-in examples the banking examples are 75.5% of the rows but only 10.4% of the supervised tokens. This is one possible reason the target task got worse; this page did not verify it. The default configuration had not forgotten much to begin with (multiple choice 72.8%, base model 72.4%), so there was little for the mixing to protect.
5. You read 100 random training examples and find no defect at all. What can you conclude?
- The defect rate is exactly 0
- The two-sided 95% exact interval for the defect rate is 0 to 3.6%, so a rate near 3% cannot be ruled out
- The defect rate is below 1%
- Nothing; spot checks are pointless
With zero defects, the exact binomial (Clopper-Pearson) upper bound is , about 3.6% for . To show the rate is below 1% you must read 368 examples in a row without finding a defect. The normal approximation would conclude “the defect rate is exactly 0” here, which is why spot checks should use the exact interval.
6. 77 banking77 test examples (2.5%) have a near-duplicate in the training set, 7 of them verbatim. The default adapter scores 93.5% on these 77 and 85.6% on the other 3,003. How much does this leak affect the overall accuracy of 85.8%?
- About 8 percentage points
- About 0.2 percentage points, less than the spread between three random seeds, but you should know how many there are, which is why you split before deduplicating
- None; a near-duplicate is not leakage
- About 2.5 percentage points
If those 77 were answered at only 85.6%, the overall accuracy would be lower by percentage points. The effect is small because the share is small; with a large share (for instance a paraphrased copy of the whole training set inside the test set), the inflation would be far bigger.
Exercises:
- To show the defect rate is below 2% (the upper bound of the two-sided 95% exact interval below 2%), how many examples must you read in a row without finding a defect? Apply the method that gives 368 for 1% in the text.
- This page’s noise floor per answer is (in nats), where 76 is the number of other classes. Compute for , then convert it to a floor per supervised token (an answer has 4.857 supervised tokens on average); if the task has only 30 classes, what replaces 76 in the formula?
- With 500 Alpaca-cleaned examples mixed in, the banking examples are of the rows. A banking answer has 4.857 supervised tokens on average (including the end token) and a mixed-in answer has 128.9. Work out the share of supervised tokens that belongs to the banking examples. To make the banking examples half of the supervised tokens, by what weight must each of their supervised tokens be multiplied?
Reference answers
- With zero defects, the upper bound of the two-sided 95% Clopper-Pearson interval is . Require it to be below 0.02: , that is , so at least 183 examples in a row. The 1% case works the same way: , hence 368.
- With : and , so nats; divided by 4.857 the floor per supervised token is about 0.085. The training loss is averaged per supervised token, so that is the number to compare it with, not itself. With 30 classes a wrong label is replaced by one of the other 29, so 76 becomes 29.
- The banking examples have supervised tokens in total and the Alpaca answers have , so the banking share is , matching the text. For the two sides to be half each, the weight satisfies , so . This is the weight under a loss averaged per token; if you average per example instead, every example has the same weight and no such compensation is needed.
Further Reading
-
Data quality and quantity: Zhou et al., LIMA: Less Is More for Alignment; Chen et al., AlpaGasus: Training A Better Alpaca with Fewer Data.
-
Where the data comes from: Wang et al., Self-Instruct: Aligning Language Models with Self-Generated Instructions; the data cards of the three datasets: Alpaca, Alpaca-cleaned and Dolly.
-
Loss over the prompt: Shi et al., Instruction Tuning With Loss Over Instructions.
-
Label noise: Zhang et al., Understanding deep learning requires rethinking generalization (networks can fit random labels); Rolnick et al., Deep Learning is Robust to Massive Label Noise (enough data dilutes wrong labels); Northcutt et al., Pervasive Label Errors in Test Sets Destabilize Machine Learning Benchmarks (annotation errors in common test sets).
-
Deduplication and leakage: Lee et al., Deduplicating Training Data Makes Language Models Better.
-
Data and environment used in the experiments: banking77 (Casanueva et al., Efficient Intent Detection with Dual Sentence Encoders); the hyperparameter experiments in the same setup are in LoRA Fine-Tuning in Practice.
-
Related pages on this site: Training Pipeline, Preference Optimization, LLM Evaluation Methodology, Evaluation Statistics; paper walkthroughs: InstructGPT and LoRA.
-
The same recipe in robotics: behavior cloning is supervised learning on demonstrations; see the paper breakdown of Diffusion Policy.
-
Deduplication and quality filtering of pretraining corpora (how MinHash parameters are chosen, the cost and bias of training a classifier on LLM labels): see the FineWeb breakdown.
-
Chung et al., Scaling Instruction-Finetuned Language Models (FLAN) (2022): one of the founding instruction-tuning papers, where multi-task fine-tuning sharply improved zero- and few-shot ability.
-
Lambert et al., Tulu 3 (2024): a systematic report of an open post-training recipe (SFT + DPO + reinforcement learning with verifiable rewards), with auditable data mixing and evaluation.
FAQ
- How much data does SFT need?
- It depends on the task, but the return diminishes quickly. Measured here with Qwen2.5-0.5B on banking77 (77-class intent classification): accuracy is only 28.3% at 1 example per class, 69.0% at 5, 85.8% at 20, 91.0% at 50 and 93.9% with all 10,003 examples. Each doubling of the data adds less: 8.2 percentage points from 10 to 20 per class, 4.0 from 20 to 50, 2.1 from 50 to all. This is one 0.5B model, one classification task and one run per point, so do not carry the numbers over to other tasks; the steep-then-flat shape is the useful part.
- What happens when the SFT data contains wrong labels?
- They lower accuracy on the target task, and with enough training the model memorizes them. Here the training labels were replaced by a random other class: 10%, 20% and 40% wrong labels take accuracy from 85.8% to 82.4%, 77.7% and 69.2%, about 0.4 percentage points per 1% of noise. On all 10,003 examples, 20% wrong labels take accuracy from 93.9% to 90.3%: the absolute loss is smaller, but the factor by which the error rate grows is similar (1.59 against 1.57). Back at 20 per class: after 3 epochs the training loss sits near the floor of a model that knows the noise rate, so the model has learned the share of wrong labels; after 10 epochs all 308 relabeled training examples are memorized, the training loss is 0.0007, and test accuracy falls from 77.7% to 74.1%. If you read 100 random examples and the defect rate is 10%, the chance of finding none is below 3 in 100,000, so a spot check easily finds a problem of that size.
- Should the loss also be computed on the prompt during SFT?
- By default only the answer (response) counts in the loss, and the prompt's labels are set to -100. Shi et al. (2024) found that computing the loss on the instruction too can work better when instructions are long and outputs short, or when there are very few examples. This page tested one such case (banking77 classification, prompts averaging 27.1 tokens, answers 4.9, 20 examples per class): with the loss on the answer only, accuracy is 85.8%; on the whole sequence it is 84.5%, with every step about half again slower. One experiment cannot overturn that paper (the task and the model size differ), but it shows this is not a free lunch, so compare on your own metric.
- Does mixing in general instruction data stop a fine-tuned model from forgetting?
- Not necessarily. This page mixed 500 or 1,540 general instructions into 1,540 classification examples: WikiText-2 perplexity rose from 19.10 to 21.49 and 21.07, multiple-choice accuracy showed no clear change, and target-task accuracy fell to 84.0% and 82.7%. One possible reason is that the loss is averaged per token, so long answers outweigh short ones (with 500 mixed-in examples the banking examples are 75.5% of the rows but only 10.4% of the supervised tokens). The model had not forgotten much with the default configuration to begin with (multiple choice 72.8%, base model 72.4%), so there was little to protect; cases with heavy forgetting (longer training, a higher learning rate, a task far from the pretraining distribution) need their own measurement.
- How do I check the quality of an instruction dataset?
- Check the license first, then scan with cheap rules (empty outputs, placeholders, very short outputs, refusal phrases, repeated outputs); a rule hit is only a candidate, so read it before deleting. Next use MinHash with LSH to find near-duplicates, check 13-gram overlap with the evaluation sets, and finally compute lengths, the supervision ratio and padding. This page's audit of Alpaca: 4,484 of 52,002 examples (8.6%) hit at least one rule; Alpaca-cleaned removed the placeholders and empty outputs but raised refusal phrases from 119 to 945 examples. How many examples a spot check reads depends on the defect-rate bound you want to prove: 100 clean examples still leave a 95% upper bound of 3.6%.