/ Модель

Характеристики

Контекст
32 768 токенов
Параметры
1,5 млрд
Лицензия
Apache 2.0
Архитектура
qwen2 · dense
Базовая модель
Qwen2.5-1.5B-Instruct
Библиотека
transformers
Опубликована
25 авг 2026

qwen2.5-1.5b-sql-qlora-merged

Генерация текстаТекст → текст3 профессии

Компактная модель Qwen2.5, дообученная для преобразования английских вопросов и схем таблиц в запросы SQLite.

43скачиваний за 30 дней0лайковвеса обновлены25 авг 2026

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Тесты пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь.

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Текст» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы. Опубликованный результат появится на этой странице.

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

blaze-star выпустил компактную языковую модель Qwen2.5-1.5B-Instruct, дообученную методом QLoRA и опубликованную со слитыми fp16-весами. Она преобразует вопрос на естественном английском языке и явно переданную схему CREATE TABLE в один запрос SQLite; в карточке описано обучение на датасете b-mc2/sql-create-context и тестирование на отложенной выборке. Модель имеет плотную архитектуру Qwen2, содержит 1,5 млрд параметров и поддерживает контекст до 32 768 токенов.

Модель рассчитана на генерацию SQL для небольших схем с одной таблицей. Автор сообщает о точном совпадении 74,8% на тесте из 1 000 примеров и отдельно предупреждает, что эта метрика чувствительна к стилю запроса и не проверяет его фактическое выполнение. Модель обучалась для английского языка и диалекта SQLite; результаты не следует напрямую переносить на крупные многотабличные хранилища. Сгенерированный SQL нужно проверять и безопасно валидировать перед использованием. Лицензия — Apache-2.0.

Сценарии применения

  • генерация SQLite-запроса по вопросу на английском языке
  • поиск данных в небольшой таблице по текстовому запросу
  • создание SQL-запросов для прототипа аналитического интерфейса

Ограничения

Обучена для английского языка, диалекта SQLite и небольших схем с одной таблицей; качество на крупных многотабличных базах не установлено. Оценка точного совпадения чувствительна к стилю SQL, а запросы не проверялись исполнением; перед использованием их следует валидировать.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

qwen2.5-1.5b-sql-qlora-merged

Merged fp16 weights of Qwen/Qwen2.5-1.5B-Instruct, QLoRA-fine-tuned for text-to-SQL: given a CREATE TABLE schema and a natural-language question, emit a single SQLite query.

The LoRA adapter alone is at blaze-star/qwen2.5-1.5b-sql-qlora.

Results

Held-out test split, 1,000 examples never seen in training.

ModelExact matchToken F1Format compliance
Base, 0-shot (4-bit)49.7%0.92526.7%
Base, 3-shot (4-bit)52.3%0.92199.3%
QLoRA fine-tuned74.8%0.97399.9%
Delta vs 0-shot+25.1 pts+0.049+73.2 pts

Fine-tuning improved exact match by +25.1 points (49.7% -> 74.8%), a +51% relative gain.

Usage

The model expects the chat template with this system prompt — it was trained with it, and accuracy drops without it.

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained("blaze-star/qwen2.5-1.5b-sql-qlora-merged", dtype=torch.float16, device_map="auto")
tok = AutoTokenizer.from_pretrained("blaze-star/qwen2.5-1.5b-sql-qlora-merged")
SYSTEM = ("You are a text-to-SQL engine. Given a SQLite schema and a question, reply with a "
          "single SQL query that answers the question. Output only the SQL query: no "
          "explanation, no comments, no markdown code fences.")

schema = "CREATE TABLE head (age INTEGER)"
question = "How many heads of the departments are older than 56?"

messages = [
    {"role": "system", "content": SYSTEM},
    {"role": "user", "content": f"Schema:\n{schema}\n\nQuestion: {question}\n\nSQL:"},
]
prompt = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
ids = tok(prompt, return_tensors="pt").to(model.device)
out = model.generate(**ids, max_new_tokens=96, do_sample=False)
print(tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True))
# SELECT COUNT(*) FROM head WHERE age > 56

Use greedy decoding (do_sample=False). Sampling hurts exact match on this task.

What the metric actually measures

Primary metric is normalized exact match against the dataset's reference SQL: lowercased, whitespace collapsed, " unified to ', backticks/brackets stripped, spacing normalized around operators and punctuation. It is strict — a semantically equivalent query that differs in alias naming (AS p vs AS T1) or literal quoting (= '15' vs = 15) counts as a miss.

That strictness is the point, but it must be read correctly: the base model already produces largely correct SQL content (token F1 0.925 before any training). Much of the headroom is conformance to this dataset's canonical SQL style, which is exactly what task-specific fine-tuning buys you. To keep that claim honest this project reports three separate baselines rather than one:

BaselineExact matchFormat complianceWhat it controls for
4-bit, 0-shot49.7%26.7%matched conditions — same quantization the adapter trains on
4-bit, 3-shot52.3%99.3%isolates output formatting from SQL convention
fp16, 0-shot57.3%99.4%strongest untrained configuration

The 3-shot baseline is the important control. Three in-context examples raise format compliance to 99.3% — the model stops wrapping output in markdown fences almost entirely — yet exact match moves only to 52.3%. Formatting was therefore not the bottleneck, and gains above that line are genuine SQL-convention learning, not prompt-format cleanup.

Both models receive an identical prompt and identical output post-processing (fence stripping, leading-prose removal, first-statement extraction), so neither is advantaged by the harness. Secondary metrics: order-insensitive token F1 over SQL tokens (partial credit) and format compliance (fraction of raw generations that were already bare SQL).

Data and leakage control

b-mc2/sql-create-context — natural-language question + CREATE TABLE schema -> SQLite query.

The 78,577 raw rows are deduplicated on a SHA-1 of the normalized (question, schema) pair (4 exact duplicates dropped), shuffled with seed 42, and then test is carved off first, before val and train. Splits: 12,000 train / 750 val / 1,000 test.

Split disjointness is asserted at build time and recorded in data/split_report.json:

{"train_test_overlap": 0, "val_test_overlap": 0, "train_val_overlap": 0}

prepare_data.py raises if any of these is non-zero, so a leaking split cannot be trained on. The test split was used only by evaluate.py, never by train.py.

Training

Base modelQwen/Qwen2.5-1.5B-Instruct
MethodQLoRA — frozen 4-bit NF4 base (double quant, bf16 compute) + LoRA adapters
LoRAr=16, alpha=32, dropout=0.05, on q,k,v,o,gate,up,down_proj
Trainable params18.5M of 1.56B (1.18%)
Optimizerpaged AdamW 8-bit, lr 0.0002, cosine schedule, 3% warmup, grad-clip 0.3
Effective batch32 (16 x 2 accumulation)
Epochs2
Max seq len512 tokens (observed mean 125, max 254)
Losscross-entropy on the SQL completion only — prompt tokens masked to -100
Hardware1x NVIDIA A100-SXM4-80GB
Wall time11.7 min
Peak VRAM (training)30.96 GB

Loss is computed only on the assistant turn, so the model is never rewarded for reproducing the schema or the question.

loss curves

Quantization: latency, VRAM, and quality

Merged fp16 model re-quantized with bitsandbytes and benchmarked on the same A100. Latency is a single request generating exactly 64 tokens (20 runs after 3 warmups); quality is exact match on the first 300 test examples.

PrecisionWeights VRAMPeak VRAMLatency (bs=1, 64 tok)Decode tok/sBatch-16 tok/sExact match
fp163.09 GB3.3 GB1862.4 ms34.4436.576.7% (n=300)
8bit1.8 GB2.1 GB27963.2 ms2.316.775.3% (n=300)
4bit1.16 GB1.54 GB2320.7 ms27.6369.275.3% (n=300)

Limitations

  • Single-table, synthetic-ish schemas. sql-create-context schemas are small CREATE TABLE statements derived from WikiSQL/Spider. Performance will not transfer directly to large multi-table production warehouses.
  • Exact match is style-sensitive. A correct query written in a different but valid style scores zero. Token F1 is reported alongside for this reason.
  • No execution-based evaluation. Queries are compared as strings, not run against a database, so semantic equivalence is undercounted.
  • 4-bit inference costs accuracy. The base model loses ~8 points of exact match going from fp16 to 4-bit (57.3% -> 49.7%); see the quantization table for the fine-tuned model's own fp16/8-bit/4-bit spread.
  • English only, and the model emits SQLite dialect.

Intended use

Converting natural-language questions into SQLite queries over small, explicitly-provided schemas — a component inside a larger system that supplies the schema and validates or sandboxes the generated query. Do not execute generated SQL against a production database without validation; the model can emit syntactically valid queries that are semantically wrong.

Training code

Full, reproducible pipeline: https://github.com/harshb20/qwen2.5-1.5b-sql-qlora

Citation

@misc{qwen25-1.5b-sql-qlora,
  title  = {QLoRA text-to-SQL fine-tune of Qwen2.5-1.5B-Instruct},
  author = {harshb20},
  year   = {2026},
  url    = {https://github.com/harshb20/qwen2.5-1.5b-sql-qlora}
}

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · transformers

Можно запустить

Подбираем GPU…

Класс архитектуры
Qwen2ForCausalLM
Ревизия весов
e4fb20f

0 моделей