You have probably asked a chatbot to write SQL and got back something that looks right, uses a column that doesn’t exist, and fails. In this tutorial you fix that for your database: you fine-tune a small open model on your Mac so it learns your tables and your style of query. Training took about two minutes on our MacBook, the result is an 11 MB file, and on our test set the model went from 34% to 96% correct answers. No cloud, no API key, no GPU rental.
You will also see where fine-tuning stops working, because our first attempt taught us that the hard way.
What you will build
A tiny text-to-SQL model for a sample shop database (customers, products, orders). You ask a question in plain English, the model writes a SQLite query, and Python runs it. A scoring script runs every answer against the real database, so you get a real accuracy number, not a vibe.
Here is the real before-and-after from our run:

And one question side by side, from ask.py:
$ uv run python ask.py "What is the cheapest kitchen product?" --base
SQL: SELECT p.name FROM products AS p JOIN orders AS o ON p.id = o.product_id ORDER BY o.order_date ASC LIMIT 1
('Wall Clock',)
$ uv run python ask.py "What is the cheapest kitchen product?"
SQL: SELECT name FROM products WHERE category = 'kitchen' ORDER BY price ASC LIMIT 1;
('Coffee Mug',)
The base model returned a wall clock. The fine-tuned one got the coffee mug, which really is the cheapest kitchen item (9.50).
What you need
- A Mac with Apple Silicon (M1 or later). MLX is Apple’s machine learning framework and runs only on Apple Silicon. On Windows or Linux, see the FAQ.
- RAM: we measured a peak memory footprint of about 2.2 GB while training (
/usr/bin/time -l). That should fit on an 8 GB Mac, but we only tested on a 36 GB M3 Pro. - Disk: about 280 MB for the model weights, 11 MB per adapter, about 1 GB more if you fuse the model (step 7).
- Time: 20-30 minutes. Training itself took 109 seconds for us.
- Cost: free. The model is Qwen2.5-0.5B-Instruct (Apache 2.0), downloaded from Hugging Face without an account.
- Software: uv (a fast Python installer). Our versions: macOS 27.2.1, Python 3.12.11, uv 0.7.13, mlx 0.32.5, mlx-lm 0.32.2.
Step 1: Create the project
mkdir mlx-finetune && cd mlx-finetune
uv init --python 3.12 --bare
uv add mlx-lm
mkdir data
Check it worked:
uv run python -c "import mlx_lm, mlx.core as mx; print(mlx_lm.__version__, mx.__version__)"
0.32.2 0.32.5
We pinned Python 3.12 to stay on a well-supported version. Our Mac’s default was Python 3.14, which we did not test with MLX.
Step 2: Make a sample database
Save this as make_db.py. It creates shop.db with 20 customers, 12 products and 300 orders from 2025. Swap in your own database later.
"""Create a small SQLite shop database to train and test against."""
import random
import sqlite3
from datetime import date, timedelta
random.seed(7)
db = sqlite3.connect("shop.db")
db.executescript("""
DROP TABLE IF EXISTS customers;
DROP TABLE IF EXISTS products;
DROP TABLE IF EXISTS orders;
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, city TEXT, joined DATE);
CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, category TEXT, price REAL);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, product_id INTEGER,
quantity INTEGER, order_date DATE);
""")
first = ["Asha", "Ben", "Chen", "Dina", "Eli", "Fatima", "Gopal", "Hana", "Ivan", "Jade",
"Kofi", "Lena", "Mateo", "Nora", "Omar", "Priya", "Quinn", "Rosa", "Sami", "Tara"]
cities = ["Chennai", "London", "Berlin", "Toronto", "Austin", "Lagos", "Sydney", "Madrid"]
for i, name in enumerate(first, 1):
joined = date(2024, 1, 1) + timedelta(days=random.randint(0, 700))
db.execute("INSERT INTO customers VALUES (?,?,?,?)", (i, name, random.choice(cities), joined.isoformat()))
products = [("Desk Lamp", "home", 24.0), ("Coffee Mug", "kitchen", 9.5), ("Chef Knife", "kitchen", 48.0),
("Yoga Mat", "fitness", 30.0), ("Dumbbell Set", "fitness", 85.0), ("Notebook", "office", 4.0),
("Desk Chair", "office", 140.0), ("Throw Pillow", "home", 18.0), ("Water Bottle", "fitness", 15.0),
("Stand Mixer", "kitchen", 210.0), ("Wall Clock", "home", 35.0), ("Gel Pens", "office", 7.5)]
for i, (n, c, p) in enumerate(products, 1):
db.execute("INSERT INTO products VALUES (?,?,?,?)", (i, n, c, p))
for i in range(1, 301):
d = date(2025, 1, 1) + timedelta(days=random.randint(0, 364))
db.execute("INSERT INTO orders VALUES (?,?,?,?,?)",
(i, random.randint(1, 20), random.randint(1, 12), random.randint(1, 5), d.isoformat()))
db.commit()
for t in ("customers", "products", "orders"):
print(t, db.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0], "rows")
uv run python make_db.py
customers 20 rows
products 12 rows
orders 300 rows
Step 3: Write the training data
Fine-tuning learns from examples: a question in, the SQL you want out. Writing 600 by hand is no fun, so make_data.py uses templates: 18 question types, each with four phrasings and slots for names, cities, months and so on.
The trick that keeps the test honest: the last phrasing of each template never goes into training. The test set only uses those held-out phrasings, so the model has to cope with wording it has never seen.
Each line in the files is one chat in the format mlx-lm expects: a system message with the schema, the user’s question, and the assistant’s SQL.
"""Generate question -> SQL training data for shop.db.
Each template has several phrasings. The LAST phrasing of every template is kept
out of training and only used in test.jsonl, so the test checks wording the
model has never seen.
"""
import json
import random
import sqlite3
random.seed(42)
db = sqlite3.connect("shop.db")
names = [r[0] for r in db.execute("SELECT name FROM customers")]
cities = sorted({r[0] for r in db.execute("SELECT city FROM customers")})
cats = sorted({r[0] for r in db.execute("SELECT category FROM products")})
prods = [r[0] for r in db.execute("SELECT name FROM products")]
months = {"January": "01", "February": "02", "March": "03", "April": "04", "May": "05", "June": "06",
"July": "07", "August": "08", "September": "09", "October": "10", "November": "11", "December": "12"}
SCHEMA = """You write SQLite queries for this database. Reply with one SQL query only.
customers(id, name, city, joined)
products(id, name, category, price)
orders(id, customer_id, product_id, quantity, order_date)"""
J_CUST = "FROM orders o JOIN customers c ON o.customer_id = c.id"
J_PROD = "FROM orders o JOIN products p ON o.product_id = p.id"
TEMPLATES = [
(["Which customers live in {city}?", "List the customers from {city}.",
"Show me everyone based in {city}.", "Who are our customers in {city}?"],
"SELECT name FROM customers WHERE city = '{city}';"),
(["How many customers are in {city}?", "Count the customers from {city}.",
"Number of customers living in {city}?", "What's the customer count for {city}?"],
"SELECT COUNT(*) FROM customers WHERE city = '{city}';"),
(["What products are in the {cat} category?", "List all {cat} products.",
"Show the {cat} items.", "Which items do we sell under {cat}?"],
"SELECT name FROM products WHERE category = '{cat}';"),
(["Which products cost less than {x} dollars?", "List products under ${x}.",
"Show items priced below {x}.", "What can I buy for less than {x} dollars?"],
"SELECT name, price FROM products WHERE price < {x};"),
(["What is the most expensive {cat} product?", "Priciest item in {cat}?",
"Which {cat} product has the highest price?", "Top-priced product in the {cat} range?"],
"SELECT name FROM products WHERE category = '{cat}' ORDER BY price DESC LIMIT 1;"),
(["How many units has {name} ordered in total?", "Total quantity bought by {name}?",
"Sum of items {name} has ordered?", "How many items did {name} buy altogether?"],
f"SELECT SUM(o.quantity) {J_CUST} WHERE c.name = '{{name}}';"),
(["How many orders were placed in {month}?", "Count the orders from {month}.",
"Number of orders in {month} 2025?", "How busy was {month}? Give the order count."],
"SELECT COUNT(*) FROM orders WHERE order_date LIKE '2025-{mm}-%';"),
(["How much revenue did the {prod} bring in?", "Total sales for {prod}?",
"What did we earn from the {prod}?", "Revenue generated by {prod}?"],
f"SELECT SUM(o.quantity * p.price) {J_PROD} WHERE p.name = '{{prod}}';"),
(["Who are the top {n} customers by units ordered?", "Show the {n} customers who bought the most items.",
"List our {n} biggest buyers by quantity.", "Top {n} customers ranked by number of units?"],
f"SELECT c.name, SUM(o.quantity) AS units {J_CUST} GROUP BY c.name ORDER BY units DESC LIMIT {{n}};"),
(["Which customers joined in {y} or later?", "List customers who signed up since {y}.",
"Show customers that joined from {y} onwards.", "Who became a customer in {y} or after?"],
"SELECT name FROM customers WHERE joined >= '{y}-01-01';"),
(["What is the revenue for each category?", "Show total sales per category.",
"Break down revenue by product category.", "How much did every category earn?"],
f"SELECT p.category, SUM(o.quantity * p.price) AS revenue {J_PROD} GROUP BY p.category ORDER BY revenue DESC;"),
(["Which products has {name} bought?", "List the items {name} ordered.",
"What did {name} purchase?", "Show every product {name} has ever ordered."],
f"SELECT DISTINCT p.name FROM orders o JOIN products p ON o.product_id = p.id "
f"JOIN customers c ON o.customer_id = c.id WHERE c.name = '{{name}}';"),
(["What is the average price of {cat} products?", "Average {cat} price?",
"Mean price for items in {cat}?", "On average, what does one {cat} product cost?"],
"SELECT AVG(price) FROM products WHERE category = '{cat}';"),
(["How many orders has {name} placed?", "Count {name}'s orders.",
"Number of orders from {name}?", "How often has {name} ordered from us?"],
f"SELECT COUNT(*) {J_CUST} WHERE c.name = '{{name}}';"),
(["Least expensive item in {cat}?", "Which {cat} product has the lowest price?",
"Lowest-priced thing we sell in {cat}?", "What is the cheapest {cat} product?"],
"SELECT name FROM products WHERE category = '{cat}' ORDER BY price ASC LIMIT 1;"),
(["How many products are in the catalog?", "Count all products.",
"Total number of items we stock?", "How many products do we sell?"],
"SELECT COUNT(*) FROM products;"),
(["City with the largest number of customers?", "Where do most of our customers live?",
"Name the city that has the most customers.", "Which city has the most customers?"],
"SELECT city FROM customers GROUP BY city ORDER BY COUNT(*) DESC LIMIT 1;"),
(["What is the largest quantity in a single order?", "Biggest order size by units?",
"Max quantity anyone ordered at once?", "What was the biggest single order by quantity?"],
"SELECT MAX(quantity) FROM orders;"),
]
def slots():
month = random.choice(list(months))
return dict(city=random.choice(cities), cat=random.choice(cats), x=random.choice([10, 20, 25, 40, 50, 100]),
name=random.choice(names), month=month, mm=months[month], prod=random.choice(prods),
n=random.choice([3, 5, 10]), y=random.choice([2024, 2025]))
def example(q, sql):
return {"messages": [{"role": "system", "content": SCHEMA},
{"role": "user", "content": q},
{"role": "assistant", "content": sql}]}
def make(n, test):
rows = []
for _ in range(n):
phr, sql = random.choice(TEMPLATES)
s = slots()
q = phr[-1] if test else random.choice(phr[:-1])
rows.append(example(q.format(**s), sql.format(**s)))
return rows
if __name__ == "__main__":
for split, n, test in [("train", 600, False), ("valid", 60, False), ("test", 70, True)]:
with open(f"data/{split}.jsonl", "w") as f:
for r in make(n, test):
f.write(json.dumps(r) + "\n")
print(split, n)
uv run python make_data.py
train 600
valid 60
test 70
The seed is fixed, so you get the same files every time (we checked the MD5 of test.jsonl across two runs).
Step 4: Measure the base model first
Before you train anything, find out how bad the starting point is. evaluate.py asks the model each test question, runs its SQL on shop.db, and compares the rows with the rows from the correct query. Row order and duplicate rows are ignored, and floats are rounded to 2 decimals.
"""Score a model on data/test.jsonl by running its SQL against shop.db.
Usage: uv run python evaluate.py [--adapter adapters]
"""
import argparse
import json
import re
import sqlite3
import time
from mlx_lm import generate, load
MODEL = "mlx-community/Qwen2.5-0.5B-Instruct-4bit"
p = argparse.ArgumentParser()
p.add_argument("--adapter", default=None)
p.add_argument("--show", type=int, default=3, help="print this many examples")
args = p.parse_args()
model, tok = load(MODEL, adapter_path=args.adapter)
db = sqlite3.connect("shop.db")
def run(sql):
rows = db.execute(sql).fetchall()
return sorted({tuple(round(v, 2) if isinstance(v, float) else v for v in r) for r in rows})
def clean(text):
text = re.sub(r"```(?:sql)?", "", text).strip()
return text.split(";")[0].strip() + ";"
tests = [json.loads(line) for line in open("data/test.jsonl")]
ok = runs = 0
fails = []
start = time.time()
for i, t in enumerate(tests):
msgs, gold = t["messages"][:2], t["messages"][2]["content"]
prompt = tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
raw = generate(model, tok, prompt=prompt, max_tokens=120)
sql = clean(raw)
try:
got = run(sql)
runs += 1
match = got == run(gold)
except Exception as e:
got, match = f"ERROR: {e}", False
ok += match
if not match:
fails.append((msgs[1]["content"], sql))
if i < args.show:
print(f"Q: {msgs[1]['content']}\n model: {sql}\n {'PASS' if match else 'FAIL'}\n")
n = len(tests)
print(f"SQL that runs: {runs}/{n}")
print(f"Correct answers: {ok}/{n} ({100 * ok / n:.0f}%)")
print(f"Time: {time.time() - start:.0f}s")
for q, sql in fails[:5]:
print(f" missed: {q}\n {sql}")
uv run python evaluate.py
The first run downloads the model (about 280 MB). Our output (first examples cut for space):
Q: Revenue generated by Dumbbell Set?
model: SELECT SUM(T2.quantity * T2.price) AS Revenue FROM orders AS T1 JOIN products AS T2 ON T1.product_id = T2.id WHERE T2.name = 'Dumbbell Set';
FAIL
Q: Show every product Quinn has ever ordered.
model: SELECT p.name FROM products AS p JOIN orders AS o ON p.id = o.product_id JOIN customers AS c ON o.customer_id = c.id WHERE c.name = 'Quinn';
PASS
Q: How busy was June? Give the order count.
model: SELECT MAX(T2.quantity) AS order_count FROM orders AS T1 INNER JOIN customers AS T2 ON T1.customer_id = T2.id WHERE T2.joined = '2021-01-01' AND T1.order_date = '2021-01-01';
FAIL
...
SQL that runs: 57/70
Correct answers: 24/70 (34%)
Time: 10s
So the base model writes SQL that runs only 57 times out of 70 and gets the right answer 24 times. Look at “How busy was June?”: it joined orders to customers, took the MAX of a column that isn’t there, and filtered on dates in 2021. It knows SQL; it doesn’t know your data.
Step 5: Fine-tune with LoRA
LoRA (low-rank adaptation) doesn’t change the model’s 494 million weights. It trains a small set of extra weights, an adapter, that sits beside the frozen model. That’s why it is fast and light enough for a laptop.
uv run mlx_lm.lora --model mlx-community/Qwen2.5-0.5B-Instruct-4bit \
--train --data data --mask-prompt \
--iters 300 --batch-size 4 --learning-rate 1e-4 \
--steps-per-report 50 --steps-per-eval 100 \
--adapter-path adapters
What the flags do:
--data datareadstrain.jsonlandvalid.jsonlfrom the folder.--mask-promptcomputes the loss only on the assistant’s SQL, not on the schema and question. You want it to learn to answer, not to repeat the prompt.--iters 300 --batch-size 4means 1,200 examples seen, so two passes over the 600 training rows.
Our real output:
Loading pretrained model
Loading datasets
Training
╭─ mlx_lm.lora ────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ model mlx-community/Qwen2.5-0.5B-Instruct-4bit │
│ type lora · 16 layers · rank 8 │
│ dataset data │
│ optimizer adam · lr 1.0e-04 │
│ batch · iters 4 · 300 │
│ max seq 2,048 │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
Trainable parameters: 0.594% (2.933M/494.033M)
iter train_loss tok/s tokens
1 val 1.952 2.40s
50 0.314 ▼ 283 4.5k
100 val 0.010 2.37s
100 0.031 ▼ 276 8.9k
save 0000100_adapters.safetensors
150 0.004 ▼ 296 13.6k
200 val 0.000 2.36s
200 0.000 ▼ 293 18.3k
save 0000200_adapters.safetensors
250 0.000 ▼ 277 22.7k
300 val 0.000 2.57s
300 0.000 ▼ 260 27.1k
save 0000300_adapters.safetensors
train ██████████████████████████████ 100% · 300/300
Only 0.594% of the parameters are trained. The validation loss (val) drops from 1.952 to 0.000, which tells you the model has learned this data very well. Hold that thought for the troubleshooting section.
The adapter is saved in adapters/adapters.safetensors (11 MB), with checkpoints every 100 steps.
Step 6: Test the fine-tuned model
Same script, same 70 questions, now with the adapter:
uv run python evaluate.py --adapter adapters
Q: Revenue generated by Dumbbell Set?
model: SELECT SUM(o.quantity * p.price) FROM orders o JOIN products p ON o.product_id = p.id WHERE p.name = 'Dumbbell Set';
PASS
Q: Show every product Quinn has ever ordered.
model: SELECT DISTINCT p.name FROM orders o JOIN products p ON o.product_id = p.id JOIN customers c ON o.customer_id = c.id WHERE c.name = 'Quinn';
PASS
Q: How busy was June? Give the order count.
model: SELECT COUNT(*) FROM orders WHERE order_date LIKE '2025-06-%';
PASS
SQL that runs: 70/70
Correct answers: 67/70 (96%)
Time: 11s
missed: How often has Ben ordered from us?
SELECT DISTINCT p.name FROM orders o JOIN products p ON o.product_id = p.id JOIN customers c ON o.customer_id = c.id WHERE c.name = 'Ben';
missed: How many items did Eli buy altogether?
SELECT COUNT(*) FROM orders o JOIN customers c ON o.customer_id = c.id WHERE c.name = 'Eli';
missed: How often has Fatima ordered from us?
SELECT DISTINCT p.name FROM orders o JOIN products p ON o.product_id = p.id JOIN customers c ON o.customer_id = c.id WHERE c.name = 'Fatima';
From 24 to 67 correct, and every query now runs. The three misses are instructive: “How often has Ben (and Fatima) ordered” was read as “what has Ben ordered”, and “How many items did Eli buy altogether” counted orders instead of summing quantities. Those were held-out phrasings, and both are genuinely close to other question types.

To try your own questions, save this as ask.py:
"""Ask the model a question and run the SQL it writes against shop.db.
Usage: uv run python ask.py "Which city has the most customers?"
uv run python ask.py "..." --base (no adapter, for comparison)
"""
import argparse
import sqlite3
from mlx_lm import generate, load
from make_data import SCHEMA
p = argparse.ArgumentParser()
p.add_argument("question")
p.add_argument("--base", action="store_true")
args = p.parse_args()
adapter = None if args.base else "adapters"
model, tok = load("mlx-community/Qwen2.5-0.5B-Instruct-4bit", adapter_path=adapter)
msgs = [{"role": "system", "content": SCHEMA}, {"role": "user", "content": args.question}]
prompt = tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
sql = generate(model, tok, prompt=prompt, max_tokens=120).strip()
print("SQL:", sql)
try:
for row in sqlite3.connect("shop.db").execute(sql).fetchall()[:10]:
print(" ", row)
except sqlite3.Error as e:
print(" error:", e)
uv run python ask.py "Which city has the most customers?"
SQL: SELECT city FROM customers GROUP BY city ORDER BY COUNT(*) DESC LIMIT 1;
('London',)
Step 7: Fuse the adapter and serve it like an API
To use the model from other apps, fuse the adapter into the base model and start mlx-lm’s OpenAI-compatible server:
uv run mlx_lm.fuse --model mlx-community/Qwen2.5-0.5B-Instruct-4bit \
--adapter-path adapters --save-path fused --dequantize
uv run mlx_lm.server --model ./fused --port 8089
--dequantize stores the fused weights at full 16-bit precision, so the fused folder is 953 MB. In a second terminal, save the request as ask.json:
{"messages":[{"role":"system","content":"You write SQLite queries for this database. Reply with one SQL query only.\ncustomers(id, name, city, joined)\nproducts(id, name, category, price)\norders(id, customer_id, product_id, quantity, order_date)"},{"role":"user","content":"How many orders were placed in August?"}],"temperature":0,"max_tokens":100}
curl -s localhost:8089/v1/chat/completions -H 'Content-Type: application/json' -d @ask.json
The reply’s message content was:
SELECT COUNT(*) FROM orders WHERE order_date LIKE '2025-08-%';
Running that in sqlite3 shop.db returned 27. Any tool that speaks the OpenAI chat API can now point at http://localhost:8089/v1.
How LoRA fine-tuning works

make_data.pyturns templates into question/SQL chats and keeps one phrasing per template for testing.mlx_lm.loraloads the 4-bit base model and freezes it. It adds small trainable matrices to 16 layers (rank 8, the defaults shown in the training banner) and trains only those, about 2.9 million parameters.- The result is a separate adapter file.
load(model, adapter_path="adapters")stacks it on the base model at load time, so you can keep several adapters for different jobs and switch between them. evaluate.pyscores by running the SQL, which is the only check that counts: two queries can look different and return the same rows.
Troubleshooting: the mistakes we actually hit
The fine-tuned model got worse on new kinds of questions. Our first dataset had 14 question types. It scored 69 of 70 on its test, which felt great. Then we asked questions it had never seen a template for:
Q: Which city has the most customers?
base: SELECT city FROM customers GROUP BY city ORDER BY COUNT(*) DESC LIMIT 1 -> London (right)
tuned: SELECT c.name, SUM(o.quantity) AS units FROM orders o JOIN customers c ... LIMIT 1; -> ('Quinn', 66)
Q: How many products do we sell?
base: SELECT COUNT(id) FROM products -> 12 (right)
tuned: SELECT COUNT(*) FROM products WHERE price < 10; -> 3
The fine-tuned model forced every question into one of the shapes it had learned, and lost answers the base model got right. Training for fewer steps (we tried the 100-step checkpoint) did not fix it; it scored 59 of 70 and still got these wrong. What fixed it was data: we added four templates (cheapest item, product count, top city, largest order) and retrained. That is the version in this tutorial, and those four questions now come out right. Even then, questions outside all 18 types still fail:
Q: What was the total revenue in March?
tuned: SELECT SUM(o.quantity * p.price) FROM orders WHERE order_date LIKE '2025-03-%';
error: no such column: o.quantity
It glued two learned patterns together and forgot the join. The lesson: a fine-tuned small model is a specialist. Give it examples of every kind of question you will really ask, and keep a test set that you never train on.
Validation loss hits 0.000. That doesn’t mean the model is perfect. It means it has memorised this data. Templated data is very repetitive, so this happens fast. Trust the execution test, not the loss.
ollama create fails with unsupported MLX architecture: model "Qwen2ForCausalLM". We tried importing the fused folder into Ollama 0.40.19 and got this error (and --quantize q8_0 is not accepted either; that version lists int4, int8, nvfp4, mxfp4, mxfp8). We did not get the Ollama import working, so step 7 uses mlx_lm.server instead.
Scores look too low because of duplicates. In our first scoring version, a query without DISTINCT counted as wrong because it returned the same product twice. We changed evaluate.py to compare sets of rows. Decide what “correct” means for your use before you trust a number.
Make it yours
- Use your own database. Change
make_db.pyto copy your schema (or point at your real.dbfile), editSCHEMA, and write templates for the 20-30 questions people really ask. Keep the held-out last phrasing. - Try a bigger base model. Swap in
mlx-community/Qwen2.5-1.5B-Instruct-4bitin all three scripts and the training command. Compare the base score and the fine-tuned score with what you got here. (We did not run this one.) - Mix in real questions. Log real questions from your team, write the correct SQL for each, and add them to
train.jsonl. Real wording beats templates.
Challenge: build it for a database you use, then tell us in the comments what you taught it and what score you got before and after.
FAQ
Can I fine-tune an LLM on a MacBook Air with 8 GB? For a 0.5B model like this one, probably yes: we measured about 2.2 GB peak memory during training. We did not test on an 8 GB machine. For 7B models, guides commonly recommend 16 GB or more.
Do I need a GPU or a paid account? No. MLX uses the Apple Silicon GPU built into your Mac, and the model downloads from Hugging Face without logging in.
What about Windows or Linux? MLX is Apple-only. The same idea (LoRA on a small model, test by running the SQL) works with other tools such as Hugging Face PEFT on an NVIDIA GPU, but we did not run that here.
Should I fine-tune or just write a better prompt? Try the prompt first. Fine-tuning paid off here because the base model kept guessing wrong about the data (columns on the wrong table, dates in 2021) even with the schema in the prompt. If you only need the schema and a few examples, a longer prompt or a local RAG setup may be enough.
Summary
You built a database, generated 600 training examples with held-out wording for testing, measured the base model (24/70), trained a LoRA adapter in about two minutes, and measured again (67/70). You also saw the catch: the model only gets good at the kinds of questions you show it, so your data is the real product.
More hands-on local AI tutorials:
- Chat with your documents: local RAG with Ollama and Python
- Turn receipt photos into a spreadsheet with Ollama and Python
- OpenRouter for beginners: free models
Sources
- mlx-lm on GitHub (LoRA, fuse and server commands): https://github.com/ml-explore/mlx-lm, checked 2026-12-02
- Model card, mlx-community/Qwen2.5-0.5B-Instruct-4bit: https://huggingface.co/mlx-community/Qwen2.5-0.5B-Instruct-4bit, checked 2026-12-02
- Mac playbook, MLX LoRA requirements (16 GB+ guidance for 7B): https://svah-x.github.io/mac-playbooks/playbooks/mlx-lora, checked 2026-12-02
mlx_lm.lora --helpoutput from mlx-lm 0.32.2, run on 2026-12-02- All scores, timings and outputs in this post: our own runs on an M3 Pro MacBook Pro, macOS 27.2.1, 2026-12-02




Join the discussion