Llama-3.2-1B-Instruct Text-to-SQL LoRA
an adapter for generating SQL queries from text
2 min readupdated
This LoRA (a lightweight add-on for a base model) is trained to turn a natural language question and an SQLite database schema into a ready-to-use SQL query. Built on top of unsloth/Llama-3.2-1B-Instruct using the gretelai/synthetic_text_to_sql dataset, the model contains 15.7 million trainable parameters. Compared to the base model, it generates working queries with significantly higher precision, raising execution accuracy from 50% to 84.4%. The adapter is useful for developers and analysts who need to quickly embed text-to-SQL generation interfaces.
Key features
- Based on the compact and efficient base model
unsloth/Llama-3.2-1B-Instruct. - Trained using a LoRA rank of r=32 on target modules
gate_proj,up_proj, anddown_proj. - Achieves a high valid SQL query rate of 96.88%.
- Optimized for working with SQLite database schemas.
What you can do
- Apply the model in chatbots and services for automatically translating user questions into SQL queries.
- Integrate the adapter into local analytical tools for working with SQLite databases.
- Test query generation to automate routine data extraction tasks.
Example
An example of usage with the transformers and peftizers libraries to generate an SQL query for a given table schema:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
BASE = "unsloth/Llama-3.2-1B-Instruct"
ADAPTER = "aayush0325/llama-3.2-1b-text2sql-lora-r32"
tokenizer = AutoTokenizer.from_pretrained(BASE)
model = AutoModelForCausalLM.from_pretrained(
BASE, dtype=torch.bfloat16, device_map="auto"
)
model = PeftModel.from_pretrained(model, ADAPTER).eval()
messages = [
{"role": "system", "content": "You are a SQL expert. Given a database schema and a question, respond with a single valid SQL query and nothing else."},
{"role": "user", "content": "### Schema (SQLite)\nCREATE TABLE staff (id INT, name TEXT, salary FLOAT);\n\n### Question\nWhat are the names of staff earning more than 50000?"},
]
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
with torch.no_grad():
out = model.generate(**inputs, max_new_tokens=256, do_sample=False)
print(tokenizer.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True))
Read more
DetailsBenchmarks: execution accuracy increased from 50.0% (base) to 84.38% (adapter), valid SQL rate reached 96.88%.
Hardware requirements: training was performed on a Modal L4 GPU (24 GB) in about 3 hours.
Limitations: trained on synthetic data from a single dataset; accuracy was tested strictly on SQLite with an exact string match requirement.










Comments