File size: 7,082 Bytes
14f5f1d cb304e8 14f5f1d cb304e8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | ---
language:
- en
license: apache-2.0
base_model: Qwen/Qwen2.5-Coder-1.5B-Instruct
tags:
- text-to-sql
- sql
- qwen
- qwen2.5-coder
- onnx
- onnxruntime-genai
- int4
- slm
datasets:
- trl-lab/SQaLe-text-to-SQL
pipeline_tag: text-generation
library_name: onnxruntime-genai
---
# π§ Qwen2.5-Coder-1.5B-Instruct Text-to-SQL (ONNX GenAI INT4)
This repository hosts an optimized, fine-tuned **Text-to-SQL** Small Language Model (SLM) based on [`Qwen/Qwen2.5-Coder-1.5B-Instruct`](https://huggingface.co/Qwen/Qwen2.5-Coder-1.5B-Instruct).
Fine-tuned on the [`trl-lab/SQaLe-text-to-SQL`](https://huggingface.co/datasets/trl-lab/SQaLe-text-to-SQL) dataset using QLoRA and exported to **ONNX Runtime GenAI (INT4)** for ultra-low latency, CPU/edge execution with negligible RAM and VRAM footprint.
---
## π Model Highlights
- **Base Architecture**: `Qwen2.5-Coder-1.5B-Instruct`
- **Fine-Tuning Technique**: QLoRA (Rank `r=64`, Alpha `128`, Targets: `q, k, v, o, gate, up, down` projections)
- **Quantization & Format**: ONNX Runtime GenAI (INT4 / DirectML / CPU / CUDA compatible)
- **Model Size**: ~980 MB (INT4 quantized `model.onnx.data`)
- **Primary Use Case**: Precise schema-aware Natural Language to SQL query translation for enterprise databases, analytical engines, and autonomous multi-agent pipelines.
---
## π οΈ Quickstart & Inference
### 1. Installation
```bash
pip install onnxruntime-genai huggingface_hub
```
### 2. Download and Run Inference
```python
import os
import onnxruntime_genai as og
from huggingface_hub import snapshot_download
# 1. Download model from Hugging Face Hub
REPO_ID = "spcv/qwen2.5_coder_text2sql_onnx"
model_dir = snapshot_download(repo_id=REPO_ID)
# 2. Load the ONNX model and tokenizer
model = og.Model(model_dir)
tokenizer = og.Tokenizer(model)
# 3. Define the Database Schema & Question
schema = """
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100),
created_at TIMESTAMP
);
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT REFERENCES customers(customer_id),
order_date DATE,
total_amount DECIMAL(10, 2),
status VARCHAR(20)
);
"""
question = "Find the total amount spent by customer with email 'jane.doe@example.com' on completed orders."
# 4. Construct Prompt using the Qwen ChatML Template
system_prompt = (
"You are an expert SQL query writer. Follow these rules strictly:\n"
"1. Only use tables and columns that exist in the provided schema.\n"
"2. Use correlated subqueries or JOINs when a value must be derived from another table.\n"
"3. Use IS NULL / IS NOT NULL for null checks, never != '' or = ''.\n"
"4. Use the correct aggregation: SUM for totals, COUNT for row counts, AVG for averages.\n"
"5. Write syntactically valid SQL: WHERE must come after all JOINs.\n"
"6. Return only the SQL query with no explanation or markdown."
)
user_content = f"### Database Schema\n{schema.strip()}\n\n### Question\n{question}\n\n### SQL Query"
prompt = (
f"<|im_start|>system\n{system_prompt}<|im_end|>\n"
f"<|im_start|>user\n{user_content}<|im_end|>\n"
f"<|im_start|>assistant\n"
)
# 5. Tokenize and Generate
tokens = tokenizer.encode(prompt)
params = og.GeneratorParams(model)
params.set_search_options(max_length=512, temperature=0.1, top_p=0.9)
params.input_ids = tokens
generator = og.Generator(model, params)
generated_tokens = []
while not generator.is_done():
generator.compute_logits()
generator.generate_next_token()
new_token = generator.get_next_tokens()[0]
generated_tokens.append(new_token)
output_sql = tokenizer.decode(generated_tokens)
print("Generated SQL:\n", output_sql.strip())
```
---
## π― Prompt & Chat Template Structure
The model follows standard **ChatML** format with structured instructions:
```text
<|im_start|>system
You are an expert SQL query writer. Follow these rules strictly:
1. Only use tables and columns that exist in the provided schema.
2. Use correlated subqueries or JOINs when a value must be derived from another table.
3. Use IS NULL / IS NOT NULL for null checks, never != '' or = ''.
4. Use the correct aggregation: SUM for totals, COUNT for row counts, AVG for averages.
5. Write syntactically valid SQL: WHERE must come after all JOINs.
6. Return only the SQL query with no explanation or markdown.<|im_end|>
<|im_start|>user
### Database Schema
[DDL / Schema definition]
### Question
[User Question in Natural Language]
### SQL Query<|im_end|>
<|im_start|>assistant
```
---
## ποΈ Training & Fine-Tuning Details
### Hyperparameters
| Parameter | Value |
|---|---|
| **Base Model** | `Qwen/Qwen2.5-Coder-1.5B-Instruct` |
| **Dataset** | `trl-lab/SQaLe-text-to-SQL` |
| **Training Framework** | Hugging Face `trl` (`SFTTrainer`) + `peft` |
| **LoRA Rank ($r$)** | `64` |
| **LoRA Alpha ($\alpha$)** | `128` |
| **LoRA Target Modules** | `q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj` |
| **Learning Rate** | `5e-5` (Cosine schedule, 5% warmup) |
| **Precision** | `bfloat16` / `NF4` 4-bit base loading |
| **Export Toolchain** | `onnxruntime-genai.models.builder` (`-p int4`, `-e cpu/cuda`) |
---
## π Leaderboard & Benchmark Results
The model was empirically benchmarked on **15-table E-Commerce production schemas** and multi-table natural language query benchmarks running locally via ONNX Runtime GenAI on CPU.
### Performance Summary
| Model Variant / Pipeline | Execution Accuracy (EX) | Execution Validity Rate | Avg CPU Latency | Model Size |
|---|:---:|:---:|:---:|:---:|
| **`spcv` Optimized ONNX Pipeline** | **95.00%** (19/20) | **100.00%** (20/20) | **3,570 ms** | **~980 MB** (INT4) |
| **`spcv` Original Merged PyTorch Base** | **40.00%** (8/20) | **80.00%** (16/20) | **6,596 ms** | **3.08 GB** (FP16) |
### Benchmark Methodology
1. **Execution Accuracy (EX)**: Evaluates semantic equivalence by populating SQLite in-memory tables with mock enterprise data and verifying if `PRED_SQL` produces identical output rows/columns to `GOLD_SQL`.
2. **Schema Complexity**: 15 interconnected production tables (`users`, `orders`, `products`, `shipments`, `payments`, `reviews`, `support_tickets`, etc.).
3. **Query Diversity**: Evaluates `JOIN` depth (up to 4 tables), nested aggregation (`SUM`, `AVG`, `COUNT`), date arithmetic (`datetime('now', '-30 days')`), subqueries (`NOT IN`), and conditional filtering (`CHECK` constraints).
---
## π Capabilities Breakdown
- **Single & Multi-table JOINs**: Correctly resolves foreign keys and table references.
- **Aggregations & Filtering**: Accurately computes `SUM`, `COUNT`, `AVG`, `GROUP BY`, and `HAVING` clauses.
- **Subqueries & CTEs**: Handles nested filtering and window functions where supported.
- **Dialect Support**: Standard ANSI SQL / SQLite / PostgreSQL / MySQL compliant syntax.
---
## π License & Attribution
- Base model licensed under **Apache 2.0** by the Qwen Team / Alibaba Cloud.
- Distributed by **spcv** for high-precision local Text-to-SQL intelligence.
|