/ Модель

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

Контекст
512 токенов
Параметры
25,9 млн
Лицензия
Apache 2.0
Архитектура
bert · dense
Базовая модель
all-MiniLM-L6-v2
Библиотека
sentence-transformers
Опубликована
17 сен 2026

text2sql-schema-retriever-minilm

ЭмбеддингиТекст → embedding6 профессий

Англоязычный энкодер для ранжирования таблиц схемы базы данных по текстовому вопросу в конвейерах text-to-SQL.

239скачиваний за 30 дней0лайковвеса обновлены18 сен 2026

Бенчмарки

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Модель разработана Hari Krishna как дообученный энкодер предложений для поиска таблиц в схемах баз данных по вопросам на естественном языке в сценариях text-to-SQL. На вход она принимает текст вопроса и формирует векторы для сравнения с описаниями таблиц; ранжирование выполняется по косинусному сходству. Базовая архитектура — BERT из sentence-transformers/all-MiniLM-L6-v2, около 25,9 млн параметров, контекст до 512 токенов. Репозиторий содержит веса safetensors и квантированный до int8 экспорт ONNX для использования, в частности, с Transformers.js.

Модель дообучена контрастивным методом на парах вопросов и таблиц из обучающей части enterprise text-to-SQL benchmark. В описанной оценке она помещала все нужные таблицы в топ-3 для 96,3% тестовых вопросов; особенно полезна для предварительного отбора таблиц перед генерацией SQL. Модель рассчитана на английский язык. Лицензия — Apache-2.0.

Качество зависит от формулировок вопроса и текстовых описаний таблиц. В README отмечены ошибки, когда нужную таблицу можно распознать только по значениям данных или скрытым связям, не отражённым в схеме; результаты теста также не гарантируют качество на других базах данных и доменах.

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

  • поиск таблиц схемы по вопросу на естественном языке
  • отбор таблиц для передачи модели генерации SQL
  • ранжирование описаний таблиц по семантическому сходству с вопросом
  • поиск связанных таблиц для запросов, затрагивающих несколько таблиц

Ограничения

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

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

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

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

Также подходит для

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

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

Открыть на Hugging Face

Schema retriever for the enterprise text-to-SQL benchmark

Question in, the 12 tables of the schema ranked out. all-MiniLM-L6-v2 fine-tuned on question/table pairs from the train split, evaluated on the 453 test questions, whose SQL templates never appear in training. Two fine-tuning recipes were tried; the one at the root of this repo is the better of the two (contrastive), the other is under variants/.

Try it in the browser, against the un-tuned model.

Why

In the text-to-SQL project I measured that handing the SQL model a retrieved subset of the schema instead of the full schema made it worse: 50.99 % → 41.72 % execution accuracy for the fine-tuned model. I wrote that up as "retrieval hurt" and moved on, but that conflates two things: retrieval as an idea, and the particular retriever I used. This repo looks at the retriever on its own.

Numbers

"all in top k" is the fraction of test questions for which every table the gold SQL touches is inside the top k. That is the number that matters if you prune the schema before generation, because one missing table means the query cannot be right. recall@k is the softer per-table average.

retrieverrecall@1recall@3all in top 1all in top 3all in top 5MRR
BM25 over table docs0.6470.8250.4790.6620.7810.938
all-MiniLM-L6-v2, off the shelf0.6080.9200.4460.8120.9490.916
bge-small-en-v1.5, off the shelf0.5610.8160.4040.6750.8480.868
fine-tuned, in-batch negatives (MNRL)0.6530.9040.4810.7480.8190.944
fine-tuned, labelled contrastive0.7050.9800.5170.9630.9740.987

The labelled contrastive fine-tune beats the off-the-shelf model at every k, and the gap at top 3 (0.963 vs 0.812) is the one that matters for pruning.

The thing I got wrong first

My first attempt was the textbook recipe: MultipleNegativesRankingLoss, (question, table) pairs, other items in the batch as negatives. It improved recall@1 and MRR and made top-3 coverage worse (0.748 vs 0.812 off the shelf).

The reason is the corpus size. With 12 documents, a batch of 12 pairs has every table in it once, so for a question that needs orders and customers, the pair (q, orders) sees customers as a negative. The loss pulls the question toward its first table and pushes it away from its second. Exactly the wrong thing for multi-table questions, which are 46 % of the test set.

The second recipe labels pairs explicitly: every gold table is a positive, five sampled non-gold tables are negatives, OnlineContrastiveLoss, no in-batch negatives. Same base model, same data.

Fine-tuned model (contrastive), all gold tables in the top 3, by slice:

sliceall in top 3
difficulty:easy1.000
difficulty:enterprise0.952
difficulty:hard0.910
difficulty:medium1.000
difficulty:very_hard1.000
domain:catalogue1.000
domain:cross_domain1.000
domain:finance1.000
domain:hr1.000
domain:logistics0.895
domain:sales1.000

At exactly k = number of tables the question needs (the strictest reading): 1-table questions 0.951, 2-table questions 0.859, 3-table questions 0.852.

Remaining misses at top 3: 17 of 453, listed in misses_top3.json. Sixteen of them are the same failure: "List products held at Marseille" needs inventory and warehouses, but nothing in the question says "warehouse", a city name is doing that job, and the retriever has no way to know Marseille is a warehouse location rather than a customer or supplier one. That is a schema-knowledge problem, not an embedding problem, and the fix is probably to put example values into the table docs.

Training

  • base: sentence-transformers/all-MiniLM-L6-v2
  • documents: one short text per table, table <name>: columns <col, col, ...> plus the column comments from schema_context.txt; see table_docs.json. No synthetic descriptions.
  • MNRL variant: 4,551 pairs, batch 12 with the no-duplicates sampler, 3 epochs, 44.8 min on a laptop CPU
  • contrastive variant: 15,216 labelled pairs, batch 32, 2 epochs, margin 0.5, 99.4 min
  • lr 3e-5, 10 % warmup, seed 42 for both; evaluation is cosine similarity between the question and the 12 docs, no reranking

Use

from sentence_transformers import SentenceTransformer
import json
from huggingface_hub import hf_hub_download

repo = "hari-krishna-ai/text2sql-schema-retriever-minilm"
m = SentenceTransformer(repo)
docs = json.load(open(hf_hub_download(repo, "table_docs.json")))
tables = sorted(docs)
D = m.encode([docs[t] for t in tables], normalize_embeddings=True)
q = m.encode("Which suppliers ship products that are out of stock?", normalize_embeddings=True)
print(sorted(zip(D @ q, tables), reverse=True)[:5])

ONNX (int8) is in onnx/ for Transformers.js: pipeline('feature-extraction', repo, { dtype: 'q8' }) with pooling: 'mean', normalize: true.

Files

  • the shipped sentence-transformers model at the root (modules.json, 1_Pooling/, weights, tokenizer)
  • onnx/model_quantized.onnx – int8 export for Transformers.js (the fp32 weights are the safetensors at the root)
  • variants/mnrl/ – the other recipe, same layout minus ONNX
  • table_docs.json – the 12 documents, exactly as embedded
  • metrics.json, misses_top3.json, train.py

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

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

GPU в ailist

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

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

Подбираем GPU…

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

0 моделей