Skip to Content
Recodocs

03 · Prepare the data

Six questions to ask of a training set before any GPU time is spent. 1,667 of 78,577 gold queries fail to run, and a random split lets a model-free copy score 30 to 60 times higher than a split by table.

13 min read
Part 1
Decide
Model
Qwen/Qwen2.5-1.5B-Instruct
Data
sql-create-context: 78,577 questions, tables and SQL queries
Hardware
One T4, in Google Colab
Open in ColabSaved with the outputs of a GPU run

Lesson 2 chose the model for this part of the course, Qwen2.5-1.5B-Instruct. Lesson 4 will fine-tune it. This lesson prepares what it will learn from, and the published cases are clear that this step decides more than the model does:

Two companies found the training data, not the model, set the result

Published comparisons where the model was held fixed and the data changed or was audited

1

DoorDash: a fine-tuned reranker at AUC 0.56; 19 of 35 labels wrong

Natural-language search relevance: model AUC (0.5 = random), and an audit of 35 human labels

a
0.560.5 random1.0 perfect■ 19 wrong ■ 16 right, after cross-functional adjudication“The model architecture wasn’t the problem; the labels were.”

Intercom: the same model, two training sets, 27 points apart

Qwen3 14B issue extractor fine-tuned two ways, downstream answer rate %

b
0%20%40%60%GPT-4.1 prompted: 63.3%Hard cases only36.4%Broader data63.4%
Sources: DoorDash engineering, LLM-as-a-judge for natural language search; Intercom Fin research, David vs Goliath.

DoorDash fine-tuned a Qwen3 reranker on human relevance labels and got an AUC of 0.56, which it called "barely above random". Rather than try a bigger model, it audited the labels: of 35 cases reviewed, the human rating was wrong in 19. Intercom trained the same model twice on two selections of its data and got answer rates 27 points apart. In both cases the model was not the problem.

The result comes first, and the exact setup, time and cost are in How it was built at the end.

The task

From here to lesson 4 the course trains one behaviour: turn a question about a table into the SQL that answers it. It is a real fine-tuning job. AT&T fine-tuned an 8-billion-parameter SQL model for its campaign analytics, according to an H2O.ai customer story, and the business cases list several more. It also meets lesson 1's three conditions: a program can check the output (does the query run, does it match), the prompted baseline can be measured before training (lesson 4 does it first), and a team has reason to own the model, since its schemas and questions describe its business.

The data is sql-create-context: 78,577 questions, each with the CREATE TABLE statement for its table and the gold SQL query, built from the public WikiSQL and Spider datasets (CC BY 4.0). One example:

{
  "question": "How many heads of the departments are older than 56 ?",
  "context": "CREATE TABLE head (age INTEGER)",
  "answer": "SELECT COUNT(*) FROM head WHERE age > 56"
}

The lesson asks six questions of this data, in the order a careful team would, and answers each with a measurement from the notebook.

1. Is every label right?

DoorDash needed people to check its labels, because relevance is a judgement. A SQL label can be checked by a program, for nothing: build the table from its CREATE TABLE statement in an empty SQLite database and run the query.

def runs(context, sql):
    """Return None if the query runs against the schema, or the SQLite error message."""
    con = sqlite3.connect(":memory:")
    try:
        for statement in context.split(";"):
            if statement.strip():
                con.execute(statement)   # create the table(s)
        con.execute(sql)                 # run the gold query against them
        return None
    except sqlite3.Error as e:
        return str(e)
    finally:
        con.close()

One gold query in 47 does not run against its own table

1,667 of 78,577 gold SQL queries fail in SQLite, by kind, with a real example of each

2
Example from the dataSyntax error1,221WHERE crowd > 26 OFFSET 063the number 26,063 split at its commaUnknown column185no such column: TYPEa column the schema does not defineTable defined twice137table customers already existsthe schema itself is brokenUnknown function90rating / SHARE(18 - 49)text from a cell parsed as a functionOther34
Source: lesson notebook, every query executed against its CREATE TABLE statement in an empty SQLite database.

Four gold queries from the 1,667 that fail, each run against its own CREATE TABLE in an empty SQLite database (the error SQLite reports, then the gold query as the notebook prints it)

Syntax error
near "OFFSET": SELECT COUNT(election) FROM table_name_14 WHERE inhabitants < 16 OFFSET 170
Syntax error
near "OFFSET": SELECT artist FROM table_name_87 WHERE peak_position < 2 AND sales > 200 OFFSET 000
Syntax error
near "AS": SELECT MAX(10 AS _c_pts) FROM table_25887826_17 WHERE total_pts = 39
Syntax error
near "$_per_capita_": SELECT COUNT(tourism_receipts__2011___us) AS $_per_capita_ FROM table_18524_6 WHERE tourism_receipts__2003___a

Each is a conversion artefact: a number split at its comma, or a column name the converter turned into SQL. The notebook prints the first 110 characters of the query.

Running a query on empty tables does not prove it is correct, but a query that fails cannot be. Of 78,577 gold queries, 1,667 fail. Most are damage from converting the original data: in "WHERE crowd > 26 OFFSET 063" a crowd of 26,063 was split at its comma, and the second half became an OFFSET clause. Others reference columns the schema does not define, or come with a schema that defines the same table twice.

A model trained on these learns to write SQL that does not run, and nothing in the training loss would say so. They are dropped rather than repaired, because a repair is a guess at what the author meant. The rule generalises: when a program can check a label, check every label before training, not a sample after.

When no program can check a label, a label can be made correct by construction instead. NVIDIA trained its Nemotron 3.5 Parse document model partly on pages it rendered itself: charts drawn from known series and values, HTML tables with known rows and headers, and pages of known text, so every target is exact and the model learns to reverse the rendering. The open releases are large, 9.98 million charts, 1 million tables and 7.9 million multilingual pages (NVIDIA, 2026; company-reported). The cost is realism: rendered pages are cleaner than scans, so a set of real documents is still needed to test on.

Stanford’s Alpaca team reported generating 52,000 instructions and answers for less than US$500 in API costs by expanding a human-written seed set with Self-Instruct. Databricks reported collecting more than 15,000 Dolly records from employees who followed category-specific examples and guidelines and were told to avoid generative AI. For SQL, use a human-written specification to define the intended result, then run generated labels against independent fixtures before admitting them to the training set. Stanford Alpaca report · Databricks Dolly dataset card

2. Duplicates and contradictions?

An exact duplicate is trained on twice and, if it falls on both sides of a split, tests itself. A contradiction, the same question about the same table with two different answers, teaches the model that both are right. This dataset is clean on both counts: no exact duplicates, and one contradictory pair in 78,577.

It does repeat questions: "how many users are there?" appears with several different tables, 299 questions in all. Those stay, because the answer depends on the table, and that is exactly what the model must learn to read.

3. Will the split tell the truth?

A held-out test is useful because it asks whether the model can solve a new example. Splitting near-duplicates across train and test can turn memorisation into apparent skill.

A held-out set is only honest if nothing in it was effectively seen in training. In this dataset questions come in groups about the same table: a WikiSQL table has three or four questions on average. A random split puts one in training and its sibling in test. The notebook measures whether that matters with a baseline that has no model at all: for each test question, find the most similar training question and copy its SQL. If the copied query has exactly the right shape (the same columns, functions and operators, with the literal values removed), the test set is rewarding memory of the training set.

def copy_baseline(train_idx, test_idx):
    """Copy the SQL of each test question's nearest training question; score the query shape."""
    vec = TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True).fit(text[train_idx])
    nn = NearestNeighbors(n_neighbors=1, metric="cosine").fit(vec.transform(text[train_idx]))
    _, near = nn.kneighbors(vec.transform(text[test_idx]))
    copied = answers[train_idx][near[:, 0]]
    return np.mean([shape(a) == shape(b) for a, b in zip(copied, answers[test_idx])])

A random split rewards copying: a model-free baseline scores 30 to 60 times higher

Copy the SQL of the most similar training question: test examples where the query shape is exactly right, %, three random seeds

3
0%2%4%6%Same table, random splitSplit 15.2%0.1%62.7%Split 25.8%0.1%64.2%Split 34.7%0.2%64.4%split by tablerandom split
Source: lesson notebook, 25,121 examples whose table is named; shape = the query with literal values removed. Right column: share of test questions whose nearest training question is about the same table.

Under a random split, copying gets the shape exactly right for 4.7 to 5.8% of test questions, because for nearly two in three of them the nearest training question is about the same table. Split by table, so that every question about a table lands on one side, and copying drops to 0.1 to 0.2%. Nothing about the data changed; only which examples were allowed to sit next to each other. A fine-tuned model can exploit the same shortcut, and its score would rise with nothing learned.

The remedy is to split by the unit that repeats. Here that is the table; elsewhere it is the customer, the document, the conversation or the day. WikiSQL's re-anonymised table names (table_name_31 is reused for unrelated tables) carry no identity, so those examples are treated as groups of one.

How big should the test set be? Big enough that its error bars are smaller than the difference you want to claim. The standard error of an accuracy pp measured on nn examples is

SE=p (1−p)n\text{SE} = \sqrt{\frac{p\,(1 - p)}{n}}

The test set's size sets the smallest difference you can claim

Standard error of an accuracy near 50%, in percentage points, against test-set size

4
024601,0002,0003,0004,000100: ±5.0500: ±2.21,000: ±1.63,923: ±0.8this test set
√(p(1−p)/n) at p = 0.5. A difference smaller than about twice the standard error of each score is not evidence.

At 100 examples a score near 50% is uncertain by five points either way; at 3,923, the test set here, by less than one. Shopify's Flow team evaluated its fine-tuned agent offline on 300 hand-crafted examples, enough to see a large effect but not to separate two candidates a few points apart. Lesson 4 will compare a prompted and a fine-tuned model, so this test set is sized for differences of two or three points.

78,577 examples in, 76,910 kept, split by table into train, validation and test

Every example accounted for; whole tables go to one side of the split

5
Train 69,170Validation 3,817Test 3,923Dropped: query fails 1,667
Source: lesson notebook. Exact duplicates: 0. Same question and table with two different queries: 1 pair.

4. How long are the examples?

Lesson 2 showed that activation memory grows with sequence length. So the maximum length in training should cover the data and no more, measured with the tokenizer of the model you will train, on the complete formatted example.

Almost every example fits in 256 tokens; a 128-token cap would cut 3.7%

Tokens per formatted example in the Qwen2.5 chat template, 8-token bins; 76,910 examples

6
05k10k15ktruncated by a 128 cap: 3.7%median 91p99 148cap 25664128192256320
Source: lesson notebook. Median 91, 99th percentile 148, 99.9th 193, longest 469 (two examples, beyond the axis).

The median example is 91 tokens and 99.9% are under 193. A cap of 256 truncates 4 examples of 76,910; a cap of 128 would cut 3.7%, and a truncated example teaches the model to stop mid-query. Lesson 4 trains with a maximum length of 256.

5. What does the model see?

A model never sees a JSON record. It sees one string in its chat template, split into tokens. Each example is written in the conversational prompt–completion form that TRL's SFTTrainer reads, with the system and user turns as the prompt and the SQL as the completion:

SYSTEM = "You write SQLite queries. Answer with one SQL query and nothing else."

def messages(row):
    return {
        "prompt": [
            {"role": "system", "content": SYSTEM},
            {"role": "user",
             "content": f"Schema:\n{row['context']}\n\nQuestion: {row['question']}"},
        ],
        "completion": [{"role": "assistant", "content": row["answer"]}],
    }

What the model sees: 80 tokens, of which 20 are the answer

One training example in the Qwen2.5 chat template, split into its tokens. Grey: prompt, label −100, no loss. Blue: answer, trained on

7
<|im_start|>system⏎You write SQLite queries. Answer with one SQL query and nothing else.<|im_end|>⏎<|im_start|>user⏎Schema:⏎CREATE TABLE candidate_assessments (candidate_id VARCHAR, asessment_outcome_code VARCHAR)⏎⏎Question: Find id of candidates whose assessment code is "Pass"?<|im_end|>⏎<|im_start|>assistant⏎SELECT candidate_id FROM candidate_assessments WHERE asessment_outcome_code = "Pass"<|im_end|>⏎
Source: lesson notebook, Qwen2.5 tokenizer. ⏎ marks a newline. Across all 76,910 examples the prompt is 72% of the tokens.

The prompt carries everything the model needs: the instruction, the schema and the question. The answer is the short blue run at the end. Across the dataset the prompt is 72% of the tokens.

6. Where is the loss computed?

Supervised fine-tuning lowers the model's negative log-likelihood of target tokens, and every token in the sequence can be a target. A mask decides which ones are:

L(θ)=−1∑tmt∑tmt log⁡pθ ⁣(xt∣x<t),mt={1xt is part of the answer0otherwise\mathcal{L}(\theta) = -\frac{1}{\sum_t m_t} \sum_{t} m_t \,\log p_\theta\!\left(x_t \mid x_{<t}\right), \qquad m_t = \begin{cases} 1 & x_t \text{ is part of the answer} \\ 0 & \text{otherwise} \end{cases}

Without the mask, every prompt token is a target too, and the model is trained to reproduce instructions and schemas it will always be given. The notebook measures what that would cost, by running the untouched model over 256 training examples and splitting its loss between prompt and answer tokens:

Without a mask, 97% of the training signal goes to copying the prompt back

The untouched Qwen2.5-1.5B on 256 training examples: prompt (grey) against answer (blue)

8
Share of tokensprompt 71%answer 29%Share of an unmasked lossprompt 97%answer 3%
Source: lesson notebook. Mean loss per token: prompt 4.08, answer 0.28.

The result is lopsided. The untouched model already finds the SQL answers easy to predict, at 0.28 per token, because once it has read a schema and a question the query follows closely. The prompt is the opposite: at 4.08 per token, a question and a schema are hard to predict before they are given, and they always will be. Without a mask, 97% of the training signal would go into that impossible part, and the 3% left over is the behaviour the run exists to teach.

In code, the mask is a label of -100, which PyTorch's cross-entropy ignores:

input_ids = prompt_ids + answer_ids
labels = [-100] * len(prompt_ids) + answer_ids   # no loss on the prompt

TRL's SFTTrainer builds these labels itself for data in prompt–completion form, which is why the notebook saves the splits that way. Lesson 4 loads them and trains.

What to keep

If you have a task like this one:

  • Check every label a program can check, before training. Here that is one run per query against its own schema; it found 2.1% failing, and none of them would show up in a training loss.

  • Split by the unit that repeats, then size the test set. The table is the unit here; a random split let copying score up to 5.8% on query shape against 0.2% by table. A test set of 3,923 has a standard error of 0.8 points at 50% accuracy, so a two to three point difference is visible.

  • Write the data in the model's own chat template and set the maximum length from the data. A cap of 256 truncates 0.01% of examples; a cap of 128 would cut 3.68%.

  • Train on the answer only. The prompt is 71% of tokens and 97% of an unmasked loss on 256 examples; with the mask, 13 of the 64 tokens in the first example are trained on.

  • Drop a failing label rather than repair it. A repair is a guess at what the author meant.

  • Next to try, not tested here: repair the failing queries instead of dropping them, and see whether a model trained on the repaired set scores differently.

  • Next to try, not tested here: check labels that run but return the wrong rows, by executing them against populated tables.

  • Next to try, not tested here: train once with the mask and once without, and compare the scores; this lesson measured only where the loss would go.

How it was built

ItemSetting
Base modelQwen/Qwen2.5-1.5B-Instruct, used for tokenizing and for one forward-pass loss measurement (no training)
Datasql-create-context, pinned to commit 9d80a6a118b838d9defc3798d659a54a2ac2ff37: 78,577 rows; 1,667 dropped (gold query fails); 0 exact duplicates; 76,910 kept
SplitsBy table (whole groups to one side, 5% of groups to test, 5% to validation): train 69,170, validation 3,817, test 3,923. Seed 42. Names of the form table_name_N are treated as groups of one
Test3,923 examples for the lesson 4 comparison; this lesson measures its standard error (0.8 points at 50%)
ChecksLabel check: every gold query run in SQLite with :memory:. Leakage: TF-IDF (1 to 2-grams, sublinear) nearest neighbour, cosine, on the 25,121 examples whose table is named, 90/10 split, seeds 0, 1, 2
FormatConversational prompt-completion; system prompt "You write SQLite queries. Answer with one SQL query and nothing else."; Qwen2.5 chat template
LengthMeasured on the full formatted example: median 91, p90 114, p99 148, p99.9 193, maximum 469 tokens
Loss maskingLabel -100 on prompt tokens; measured on 256 training examples (seed 42): prompt 71% of tokens, loss 4.08 per prompt token against 0.28 per answer token
HardwareFree Colab T4; transformers 4.51.3, accelerate 1.6.0; model loaded in float16

Time and cost. The notebook runs in about five minutes end to end on a T4 and saves three files of 69,170, 3,817 and 3,923 examples. Nothing is trained and no paid model is called. The notebook does not print a time or peak memory for each phase. The leakage numbers come from the 25,121 named-table examples, the length and loss numbers from the 76,910 kept examples (the loss from a sample of 256 of them), and the standard-error figures are the formula at p = 0.5.

Run it yourself

The notebook runs in about five minutes on a free Colab T4 and saves sql_train.jsonl, sql_validation.jsonl and sql_test.jsonl. Its sections follow the page: section 1 is Is every label right?, 2 is Duplicates and contradictions, 3 is Will the split tell the truth? and the test-set size, 4 is How long are the examples?, 5 is What does the model see? and 6 is Where is the loss computed?. Three changes to try:

  1. Keep the 1,667 failing queries and count how many land in the test set. What would they do to a model's measured accuracy?
  2. Split at random instead of by table, and rerun the copy baseline on the saved files.
  3. Change the system prompt, and measure how the share of prompt tokens moves.

How is this page?

Last updated on