Skip to content

About

QLoRA fine-tuning of SmolLM3-3B for text-to-SQL, with a measured negative result

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

30 Commits

Folders and files

Repository files navigation

Text-to-SQL with QLoRA: a measured negative result

I fine-tuned a small open model (SmolLM3-3B) with QLoRA on 5,000 examples from a public text-to-SQL dataset, then tested it on 20 questions about a supply-chain database it had never seen. The fine-tuned model scored worse than the untouched model. This repo documents the setup, the numbers, and what I found when I looked at the failures.

Results

Test set: 20 questions, graded by running the SQL and comparing the returned rows with a correct query. One run per version, greedy decoding, 4-bit model.

Version Passed (of 20) Wrong rows Crashed Prompt length
Zero-shot (untouched model) 8 9 3 ~285 tokens
Few-shot (3 worked examples in the prompt) 8 9 3 ~1,224 tokens
Fine-tuned (QLoRA, 5,000 examples, 1 epoch) 1 10 9 ~285 tokens

"Crashed" means the query raised an SQL error. "Wrong rows" means it ran but returned different rows than the correct query.

How to read these numbers

  • With 20 questions, each question is worth 5 percentage points. The gap between zero-shot and few-shot (none) is noise. The gap between either of them and the fine-tuned model (7 questions) is large enough that I believe it is real, but the sample is small.
  • The test set was frozen (git tag test-set-v1) before any model ran on it. I read the test replies only after the scores were known.
  • The fine-tuned model did learn its training task: it matched the correct SQL exactly on 163 of 200 held-out examples from the training dataset. It did not transfer to a database with six tables and 53 columns.

Task and data

Task: turn an English question into a SQLite query, given the table definitions.

Role Source License
Training b-mc2/sql-create-context: 78,577 (question, table definitions, SQL) rows. I used a random 5,000 for training and 200 held out for validation (seed 42). CC-BY-4.0
Exam database mindweave/purchasing-procurement-us, a synthetic procurement dataset (purchase orders, receipts, invoices, payments, suppliers). Built into a local SQLite file by src/build_eval_db.py. The data is not in this repo. CC-BY-NC-4.0, used here for non-commercial, educational purposes

The training rows show the model one to three small tables with only the columns each question needs. The exam shows all six tables (53 columns) in every prompt. I left out the companies table because it holds a single row. This gap between training and exam is the main finding of the project.

Exam questions. 8 dev questions (used for debugging and for the few-shot examples) and 20 test questions (used once per version). The questions and their correct SQL were drafted with help from an AI assistant (Claude). I ran every correct query against the database and checked each one against its English wording. The test set was fixed before any model ran on it (git tag test-set-v1).

Grading. The model's SQL and the correct SQL are both executed on the database, and the returned rows are compared:

  • Decimals are rounded to 2 places.
  • Row order matters only if the correct query has ORDER BY.
  • Duplicate rows count, and extra or missing columns count as a mismatch.
  • The model's SQL runs on a read-only connection with a 5-second time limit.
  • The SQL is pulled out of the reply first (code fences or surrounding text are removed).

Method

Item Setting
Model HuggingFaceTB/SmolLM3-3B (Apache 2.0), loaded in 4-bit NF4 with double quantization
Prompt A fixed system message, the instruction, the table definitions on one line in the training data's style, and the question. Thinking mode off.
Decoding Greedy (the same input always gives the same output), up to 200 new tokens
Zero-shot The prompt above, nothing else
Few-shot The same prompt, preceded by 3 solved examples taken from the dev set (spend_per_supplier, uninvoiced_pos, three_days_late). These come from the exam database, so this baseline has an advantage over the fine-tuned model.
QLoRA Rank 16, alpha 32, dropout 0.05, all linear layers. 30,228,480 trainable parameters (0.97% of 3.1B).
Training 5,000 examples, 1 epoch (313 steps), batch size 4 x 4 accumulation, learning rate 2e-4, 512 token limit, loss on the answer only. 19 minutes on a free Colab T4.
Training result Validation loss 0.051, 98.8% token accuracy on the 200 held-out training-set examples

Two details that cost debugging time:

  • SmolLM3's chat template stamps today's date into the default system prompt. A fixed system message removes it, so the baseline and fine-tuned runs use identical prompts.
  • The trainable adapter weights had to be cast to float32 to train in fp16 on a T4. Otherwise training crashed with a bfloat16 gradient-scaler error.

What went wrong

I read the fine-tuned model's replies after the test scores were known. Only these were read in full: the 7 questions the untouched model passed and the fine-tuned model failed, plus the fine-tuned dev replies. I did not read the zero-shot or few-shot test replies in full, so claims about them rest on the counts below.

Measured

1. The fine-tuned model copied the training data's habits. Counts of the 20 test queries each version wrote (crude text matches, so they show the habit is present, not that it caused a given failure):

Habit Zero-shot Few-shot Fine-tuned
Joins on company_id 4 0 12
T1/T2 table aliases 0 0 17
Double-quoted text values 0 0 7
3 or more joins in one query 0 0 3

company_id is the wrong link in this database. It holds one company, so every row shares the same value, and a join on it pairs every row with every other. The correct link is supplier_id = suppliers.id. The few-shot examples showed the correct link, and the few-shot model never used company_id.

2. Fine-tuning broke questions the original model got right. Seven questions passed zero-shot and failed fine-tuned. All seven correct answers use a single table. In all seven, the fine-tuned model wrote a query with extra joins:

Question What the fine-tuned query did
invoices_due_march_2025 Joined suppliers on company_id, filtered due_date = "March 2025"
average_line_quantity Joined goods_receipts and asked it for a quantity column it doesn't have
distinct_products_ordered Joined suppliers on product_id = id, added an unrequested filter
distinct_payment_terms A 9-table chain, including a table name that doesn't exist
suppliers_per_category Joined suppliers to itself on a column that doesn't exist
orders_above_average_total Joined suppliers on company_id inside the query and the subquery
highest_total_pos A 5-join chain with an invented status = "Active" filter (the reply also hit the 200-token limit)

Four of the seven crashed, and three returned wrong rows. The fine-tuned model also invented values that appear nowhere in the question or the data ("March 2025", "Active", and on dev "Not Invoiced" and "Delivered").

3. Few-shot examples helped on dev and did not help on test. On the five dev questions not used as examples, few-shot scored 4/5 against 2/5 for zero-shot. On the 20 test questions both scored 8/20. Four questions changed result between the two (two gained, two lost) and the changes cancelled. The two gained questions closely resemble the examples I put in the prompt.

4. The fine-tuned model passed one test question (earliest_latest_order, a MIN and MAX on one table) and none of the 6 plain single-table filters that zero-shot passed 3 of.

Hypothesis (not tested)

The training rows I inspected show only the tables a question needs, with trimmed columns. If that holds across the dataset, the model learned to use every table it is shown. The exam shows six tables per question, and most questions need one or two. This fits the seven cases above. I looked at only a handful of training rows and did not count how often answers use every table shown, so this is an explanation I could not confirm.

Not checked

  • Why few-shot lost two subquery questions that zero-shot passed.
  • Whether the cause is the training data or my settings (rank, learning rate, epochs, data size). I ran one training configuration.
  • Whether extra joins also cause the wrong rows in the fine-tuned model's other failures (e.g. through company_id duplicating rows). I did not run those queries to see what they return.

Limitations

The exam is small and the data is unusually uniform

  • 20 test questions. Each is worth 5 points, and categories hold 1 to 6 questions each, so per-category numbers are hints, not findings.
  • The database is synthetic and very regular. One company, one order line and at most one receipt per purchase order, one payment method (all 885 payments), no invoice that differs from its order, deliveries 0 to 3 days late and none early, 10 suppliers of which only 6 have orders. Total order values skip the range 5,000 to 6,000. 26 orders tie for the highest total. A text-to-SQL system is not properly tested by data this tidy.
  • Several questions can be passed with the wrong logic, because grading compares result rows and the data is uniform. The 17 unpaid invoices are exactly the invoices with no payment row and exactly those with status received. The 25 uninvoiced orders are exactly those with status sent. The 4 suppliers without orders are exactly the non-stock suppliers. Lateness never exceeds 3 days. A query using any of these shortcuts passes. The dev question unpaid_invoices was passed this way by the few-shot model.

Grading and question design

  • The grader is strict about columns. A query that returns an extra column is marked wrong even if its logic is right (this happened on the dev question suppliers_no_orders). I did not loosen the grader after seeing results.
  • The questions and their correct SQL were drafted with AI assistance. I ran each query and checked it against its wording, but I did not write every question from scratch.
  • One test question was reworded before any model ran (highest_total_pos, after I found 26 orders tie for the maximum). Two questions that match my aggregate definition (orders_in_2024, average_line_quantity) are labeled single_table. I left the file as frozen.
  • The test set is no longer clean for new experiments. It was used for all three versions and I read the replies. A second experiment would need a new test set.

Experiment design

  • One training run, one configuration, one seed. I did not vary the data size, rank, learning rate or epochs, and did not rerun to check how much results change between runs. GPU training has some randomness that I did not measure.
  • One model. I did not test whether a stronger starting model would behave differently.
  • The few-shot baseline is lightly tuned. Three examples, chosen by me from the dev set, from the same database as the exam. I did not try other examples or counts.
  • Decoding limits. Greedy decoding with a 200-token cap. One fine-tuned reply was cut off by the cap.
  • Dev scores are not results. The few-shot dev numbers include questions similar to the prompt examples.
  • The environment is not fully pinned. Library versions are pinned, but I did not record the PyTorch or Python versions Colab used.

Scope

  • This is not a deployable system. A 3B model that returns wrong rows without any error is unsafe near real data. The exam data is licensed for non-commercial use.
  • The result applies to this setup: this model, this training data, this configuration, this database. It does not show that fine-tuning for text-to-SQL fails in general.

Repo layout

configs/qlora.yaml      training settings (LoRA rank, learning rate, data size)
data/exam/              dev.yaml (8 questions) and test.yaml (20 questions), with correct SQL
src/build_eval_db.py    downloads the Mindweave tables and builds the SQLite exam database
src/schema_text.py      turns the database into the one-line table definitions in the prompt
src/prompt.py           the single place the prompt (system message, instruction) is built
src/data.py             formats the training dataset with the same prompt
src/extract_sql.py      pulls the SQL out of a model reply
src/grader.py           runs two queries and compares the returned rows
src/eval_loop.py        question -> prompt -> model -> extract -> grade, for every question
src/train.py            QLoRA training script
src/validate_exam.py    runs every correct query and flags errors, empty results, duplicate ids
src/compare.py          side-by-side table of the three test runs
src/error_patterns.py   counts the failure habits in the table above
src/show_damage.py      prints the questions fine-tuning broke
results/                saved replies and verdicts for every run, plus the training log
notebooks/              exploration scripts, and colab_experiments.ipynb (see below)
tests/                  28 tests for the grader, extractor, prompt, data and loop code

How to reproduce

1. On any computer, no GPU: the exam, the tests, and the comparison

git clone https://github.com/stutigarg2k/qlora-text2sql.git
cd qlora-text2sql
python -m venv .venv
.venv\Scripts\activate        # Mac/Linux: source .venv/bin/activate
pip install -r requirements.txt
python src/build_eval_db.py   # downloads the Mindweave data, builds data/raw/supply_chain.db
python src/validate_exam.py   # every correct query should run and return rows
pytest                        # 28 tests
python src/compare.py         # reads the saved results in results/
python src/error_patterns.py
python src/show_damage.py

The saved model replies are in results/, so the comparison and error analysis work without a GPU.

2. On a GPU (I used a free Colab T4): training and the model runs

  1. Clone the repo and run pip install -r requirements-train.txt, then python src/build_eval_db.py.
  2. python src/train.py trains the adapter in about 19 minutes and writes outputs/adapter and results/train_log.json. Do not commit the adapter: it is 112 MB, over GitHub's 100 MB file limit, and it is the model that scored 1/20. Expect similar but not identical results on a rerun. I did not test how much a rerun varies.
  3. The zero-shot, few-shot and fine-tuned runs (load the model, generate, grade) are in notebooks/colab_experiments.ipynb. These cells are a record of what I ran, not a clean pipeline. They ran across several sessions, some were rerun, and the evaluation step is not yet a standalone script. The notebook uses the repo's src/ code for the prompt, extraction, grading and scoring.

Environment: Python 3.13 and a Colab T4 GPU. Library versions are pinned in requirements-train.txt. I did not record the PyTorch version.

Licenses and credits

  • Code in this repo: MIT.
  • Model: HuggingFaceTB/SmolLM3-3B, Apache 2.0.
  • Training data: b-mc2/sql-create-context, CC-BY-4.0. Credit to its author, b-mc2.
  • Exam database: mindweave/purchasing-procurement-us by Mindweave Technologies, CC-BY-NC-4.0, used for non-commercial educational purposes and not redistributed here. The MIT license of this repo does not apply to either dataset.

About

QLoRA fine-tuning of SmolLM3-3B for text-to-SQL, with a measured negative result

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages