CoolFace
Modelpublic

A-Kishore/llama-3.2-3b-text2sql

sourceHugging Faceapache-2.0updated 3mo agoView on Hugging Face
0likes8downloads
Model Card

๐Ÿ”ฎ Llama-3.2-3B-Instruct Text-to-SQL

A fine-tuned version of `unsloth/Llama-3.2-3B-Instruct-bnb-4bit` for generating SQL queries from natural language questions and database DDL schemas.

![License: Apache 2.0](https://opensource.org/licenses/Apache-2.0) ![Finetuned with Unsloth](https://github.com/unslothai/unsloth)


Model Summary

AttributeValue
Base Modelunsloth/Llama-3.2-3B-Instruct-bnb-4bit
TaskText-to-SQL (natural language โ†’ SQL)
Fine-Tuning MethodLoRA (PEFT) via Unsloth + TRL
Training Datasetgretelai/synthetic_text_to_sql (50k samples)
Trainable Parameters~0.75% of base model
Export FormatMerged FP16 (merged_16bit)
LicenseApache-2.0 + Meta Llama 3 Community License
DeveloperA-Kishore

Evaluation Results

Evaluated on the first 200 samples of the gretelai/synthetic_text_to_sql test split using greedy decoding. ROUGE F-measures reported.

ModelROUGE-1ROUGE-2ROUGE-L
Base Model (unsloth/Llama-3.2-3B-Instruct-bnb-4bit)0.29080.20160.2651
Fine-Tuned (A-Kishore/llama-3.2-3b-text2sql)0.84860.72320.8151
Improvement+191.82%+258.73%+207.47%

Metric interpretation:

  • โ€”ROUGE-1 (unigram overlap) reflects accurate retrieval of schema identifiers and SQL keywords.
  • โ€”ROUGE-2 (bigram overlap) captures structural alignment of consecutive SQL constructs (e.g. GROUP BY, ORDER BY).
  • โ€”ROUGE-L (longest common subsequence) tracks overall query flow including nested clauses and join ordering.
Note: ROUGE measures lexical overlap, not SQL executability. A query may score slightly lower due to stylistic differences (alias names, join ordering) while still being functionally equivalent. See Limitations.

How to Use

The model weights are fully merged in 16-bit precision and load with standard transformers or unsloth.

Prompt Format

Always use this exact template โ€” the model was trained on it:

###TASK
Generate the SQL query to answer the following question

### Database Schema
{sql_context}

### Question
{sql_prompt}

### SQL Query

(a) Standard transformers

python
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

model_name = "A-Kishore/llama-3.2-3b-text2sql"

tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype=torch.float16,
    device_map="auto"
)

prompt = """###TASK
Generate the SQL query to answer the following question

### Database Schema
{sql_context}

### Question
{sql_prompt}

### SQL Query
"""

sql_context = "CREATE TABLE employees (id INT, name TEXT, department TEXT, salary REAL);"
sql_prompt = "What is the average salary per department?"

inputs = tokenizer(
    prompt.format(sql_context=sql_context, sql_prompt=sql_prompt),
    return_tensors="pt"
).to("cuda")

outputs = model.generate(
    **inputs,
    max_new_tokens=150,
    use_cache=True,
    pad_token_id=tokenizer.eos_token_id
)

result = tokenizer.decode(outputs[0], skip_special_tokens=True)
sql = result.split("### SQL Query")[-1].strip()
print(sql)
# SELECT department, AVG(salary) FROM employees GROUP BY department;

(b) Unsloth Fast Inference

python
import torch
from unsloth import FastLanguageModel

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name="A-Kishore/llama-3.2-3b-text2sql",
    max_seq_length=768,
    dtype=torch.float16,
    load_in_4bit=False,
)
FastLanguageModel.for_inference(model)

prompt = """###TASK
Generate the SQL query to answer the following question

### Database Schema
{sql_context}

### Question
{sql_prompt}

### SQL Query
"""

sql_context = "CREATE TABLE employees (id INT, name TEXT, department TEXT, salary REAL);"
sql_prompt = "What is the average salary per department?"

inputs = tokenizer(
    prompt.format(sql_context=sql_context, sql_prompt=sql_prompt),
    return_tensors="pt"
).to("cuda")

outputs = model.generate(
    **inputs,
    max_new_tokens=150,
    temperature=None,
    do_sample=False,
    pad_token_id=tokenizer.eos_token_id
)

result = tokenizer.decode(outputs[0], skip_special_tokens=True)
sql = result.split("### SQL Query")[-1].strip()
print(sql)

Training Details

Dataset

LoRA Configuration

ParameterValue
Rank (r)16
Alpha (lora_alpha)16
Target Modulesq_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj
Biasnone

LoRA freezes the base model weights and injects trainable rank-decomposition matrices into all attention and MLP projections. Only ~0.75% of parameters are updated, dramatically reducing VRAM usage and preventing catastrophic forgetting.

Hyperparameters

ParameterValue
Optimizerpaged_adamw_8bit
Learning Rate2e-4
LR Schedulerlinear
Warmup Steps5
Epochs1
Per-Device Batch Size8
Gradient Accumulation1
Max Sequence Length768
Sequence PackingTrue
Mixed Precisionfp16
Experiment TrackingWeights & Biases

Training was accelerated using the unsloth library, which provides optimized GPU kernels for 4-bit quantized training (~2ร— faster than standard configurations).


Repository

Training and evaluation code: a-kishore-dev/llama-text2sql-finetune

Notebooks included:

  • โ€”Text_to_SQL_Finetuning.ipynb โ€” dataset prep, LoRA config, training, export
  • โ€”evaluate_model.ipynb โ€” ROUGE evaluation comparing base vs fine-tuned

Limitations

  • โ€”SQL executability: ROUGE is a lexical proxy. High ROUGE does not guarantee a query will execute or return logically correct results. A query with different aliases or reordered joins may score lower despite being equivalent.
  • โ€”Out-of-distribution schemas: Performance degrades on high-cardinality databases, deeply nested subqueries, or DDL patterns that diverge significantly from the training distribution.
  • โ€”Single epoch: The model was trained for one epoch on 50k samples. Further training may improve generalization.

License

The model adapter is released under Apache 2.0. The underlying base model is governed by the Meta Llama 3 Community License Agreement. Users must comply with both.


Acknowledgements

  • โ€”Unsloth โ€” optimized kernels for 4-bit training and sequence packing
  • โ€”Hugging Face โ€” trl (SFTTrainer) and transformers
  • โ€”Meta AI โ€” Llama 3.2 open weights
  • โ€”Gretel AI โ€” synthetic Text-to-SQL dataset

Author

A-Kishore ยท GitHub ยท HuggingFace