/ Модель

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

Контекст
40 960 токенов
Параметры
3,7 млрд
Лицензия
Apache 2.0
Архитектура
qwen3 · dense
Базовая модель
Qwen3-4B
Библиотека
transformers
Опубликована
27 окт 2026

qwen3-4b-midtrain-local-kv-per-document

Генерация текстаТекст → текст4 профессии
38скачиваний за 30 дней0лайковвеса обновлены27 окт 2026

Описание модели

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

Дообученная Qwen3-4B для генерации ответов в поисковых сценариях с найденными документами и локальным KV-вниманием.

Модель разработана автором репозитория lixiaochuan2020 на основе Qwen/Qwen3-4B и предназначена для генерации ответов в сценариях поиска по документам. Она прошла промежуточное обучение на корпусе поисковых траекторий, созданных моделью Qwen3-32B по вопросам NQ и HotpotQA с использованием поиска по wiki-18. В обучении применялось локальное KV-внимание по отдельным найденным документам: каждый фрагмент кодировался независимо, а последующая часть диалога могла обращаться ко всем фрагментам.

Это плотная причинная языковая модель семейства Qwen3 с 3,7 млрд параметров, поддерживающая диалоговую генерацию текста и контекст до 40 960 токенов. Карточка приводит результаты оценки на вопросах с поиском, включая наборы ID и OOD; в этих испытаниях применялись до 10 поисковых вызовов по wiki-18 с выдачей до пяти фрагментов за запрос.

Для воспроизведения обученного режима требуется специальная реализация local-KV из указанного в карточке приватного репозитория. Обычный вызов generate() и стандартные серверы vLLM или SGLang используют полное внимание, поэтому режим работы отличается от обученного; результаты оценки также показывают колебания качества между наборами. Веса опубликованы в формате safetensors и сохранены в float32; лицензия — Apache-2.0.

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

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

Ограничения

Для работы в обученном режиме требуется специальный код local-KV; стандартная генерация Transformers, vLLM и SGLang применяет полное внимание. Оценка проведена на поисковых бенчмарках с wiki-18, и качество различалось между наборами.

Публичные бенчмарки

Результаты из открытых лидербордов в сравнении с лидерами каталога

Публичных оценок пока нет

В подключённых источниках результатов этой модели не нашлось. Отсутствие оценки не значит, что модель хуже: её могли просто не проверять.

Источники: Hugging Face Leaderboards, Hugging Face Eval Results, Open LLM v2, MTEB, timm, Open ASR, EvalPlus, LLM Stats

Бенчмарки пользователейпока нет

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

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

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

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

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

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

    Модели ответят на каждую задачу, судья оценит ответы по шкале 0–100.

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

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

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

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

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

Открыть на Hugging Face

qwen3-4b-midtrain-local-kv-per-document

Qwen/Qwen3-4B mid-trained on a search-agent corpus written by a Qwen/Qwen3-32B teacher, with per-document local-KV attention: each retrieved passage is encoded on its own, as if its KV cache had been computed in advance. The full-attention baseline trained on the same corpus with the same settings is lixiaochuan2020/qwen3-4b-midtrain-baseline. RL from this model gave lixiaochuan2020/qwen3-4b-rl-local-kv-per-document.

Inference note. Plain model.generate() or a stock vLLM/SGLang server runs this model with full attention, which is not how it was trained. To run it as trained, use the patched code on branch claude/rl-grpo of ashmitkx/kv-midtrain (private repository):

  • Hugging Face eval: python -m kv_midtrain.evaluation.evaluate run ... --per_document (local-KV forward in src/kv_midtrain/training/local_kv.py).
  • SGLang rollouts: src/kv_midtrain/rl/local_kv/sglang_patch.py, applied by src/kv_midtrain/rl/site/sitecustomize.py with KV_LOCAL_KV=detached KV_LOCAL_KV_SPANS=document (prefill backend flex_attention, decode backend fa3, chunked prefill off).
  • vLLM: src/kv_midtrain/rl/local_kv/vllm_patch.py (attention backend FLEX_ATTENTION, VLLM_USE_V2_MODEL_RUNNER=0).
  • Passage boundaries: src/kv_midtrain/rl/local_kv/spans.py.

Access

Public: anyone can download it, no access request or login needed.

Weights

  • Saved dtype: float32 (as written by training). Load with dtype=torch.float32, or cast to bfloat16 for inference.
  • Branch main: the final checkpoint, step 4,763 of 4,763. Intermediate checkpoints, if added later, go on branches named step-<N>.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

repo = "lixiaochuan2020/qwen3-4b-midtrain-local-kv-per-document"
tokenizer = AutoTokenizer.from_pretrained(repo)
model = AutoModelForCausalLM.from_pretrained(repo, dtype=torch.float32)  # full attention; see the inference note

Mid-training data

A Qwen/Qwen3-32B teacher (thinking mode) answered NQ and HotpotQA training questions as a search agent, 4 times per question, using a wiki_search tool over wiki-18 (e5-base-v2, 5 passages per search, at most 10 searches, at most 16,384 tokens per trajectory). Trajectories were kept if they called at least one search and the Qwen3-32B answer judge marked the final answer correct. Gold answers were used only for that check, never as training text.

ItemValue
Questions answered128,875
Trajectories kept297,720
Supervised (assistant) tokens243.78M
Tool-result (passage) tokens314.24M
Total tokens684.86M

The loss covers assistant tokens only.

Mid-training config

SettingValue
Base modelQwen/Qwen3-4B
Optimizer for decoder-layer weight matricesMuon
Optimizer for embeddings and normsAdamW
Learning rate2e-5
Schedulecosine
Warmup (fraction of steps)0.03
Epochs1
Steps4,763
Packed row length (tokens)18,432 (padding-free; each trajectory attends only to itself)
Max trajectory length (tokens)16,384
Rows per step8
GPUs8
Weight decay0
Max gradient norm1.0
Weightsfloat32
Computebf16 autocast
Attention kernelFlexAttention
Gradient checkpointingon
Seed42

Attention

  • Each retrieved passage, from its Doc k(Title: token through its final newline, is its own document. Its tokens attend only to earlier tokens of the same passage: not to the conversation before the search, and not to the other passages.
  • Passage K/V are detached: the loss on later tokens does not train how passages are encoded.
  • The tool-turn wrapper tokens (<|im_start|>user\n<tool_response>\n before the passages and </tool_response><|im_end|>\n after them) attend normally.
  • Every token after the tool turn attends to all passages.
  • Passages keep their absolute positions in the sequence.

Prompt format

Qwen3 chat template with one tool, wiki_search, called in Qwen3's <tool_call> format. Each tool result lists the top 5 wiki-18 passages as Doc k(Title: …) text lines. The system prompt and tool schema used in training are SYSTEM_PROMPT and TOOLS in src/kv_midtrain/data_loading/afm_mhqa.py of ashmitkx/kv-midtrain (private repository).

Evaluation

  • ID search: 1,200 held-out questions (HotpotQA dev 720, NQ test 240, 2WikiMultihopQA dev 240), 3 samples each. None is a mid-training question.
  • OOD search: 1,025 questions (Bamboogle 125, FEVER 300, MuSiQue 300, PopQA 300), 1 sample each.
  • Search settings: the training system prompt, a Question: … user message and the wiki_search tool; temperature 0.7, top-p 0.95, 4,096 new tokens per turn, up to 10 wiki-18 searches, top-5 passages.
  • Generation: a PyTorch loop over the Hugging Face model (kv_midtrain.evaluation.evaluate), one token per forward pass; Local mode uses the local-KV forward of src/kv_midtrain/training/local_kv.py.
  • Modes: Full is standard attention. Local is per-document local-KV attention, as in training (see Attention).
  • Math: GSM8K test and MATH-500, one sample per problem with thinking, no tools; temperature 0.6, top-p 0.95, top-k 20, up to 16,384 tokens.
  • Judge: Qwen/Qwen3.5-9B (no thinking, temperature 0) gets the question, the dataset's gold answers and the extracted final answer, and replies Correct or Incorrect. Search: the content of the last <answer> or <final_answer> tag after the reasoning, otherwise the last paragraph; there is no answer when the reasoning was not closed or the last turn calls a tool. Math: the last \boxed{} after the reasoning. A missing answer, or one over 50 words, counts as incorrect.
  • Columns: source columns and Accuracy are the share of rollouts judged correct (Accuracy over all rollouts of the group); CI low and CI high come from 2,000 bootstrap resamples of questions; Answer rate is the share of rollouts with a final answer.

ID search:

Mode2WikiMultihopQAHotpotQANQAccuracyCI lowCI highAnswer rate
Full0.5350.6100.5970.5930.5690.6160.946
Local0.4850.5560.5930.5490.5250.5740.966

OOD search:

ModeBamboogleFEVERMuSiQuePopQAAccuracyCI lowCI highAnswer rate
Full0.5760.9070.3030.4870.5670.5370.5970.963
Local0.5920.9100.2630.4630.5510.5200.5820.978

Math (no passages, so Full and Local are the same):

DatasetProblemsAccuracyBoxed answer rate
GSM8K test1,3190.9010.954
MATH-5005000.8640.932

Training run

W&B: local-KV-per-document (project cxcscmu/kv-midtrain-qwen3-4b, run id qwen3-4b-midtrain-muon-local_kv_per_document_detached).

Related models

ModelTrainingAttention in training
lixiaochuan2020/qwen3-4b-midtrain-baselinemid-trainingfull
lixiaochuan2020/qwen3-4b-midtrain-local-kv-per-document (this model)mid-trainingper-document local-KV
lixiaochuan2020/qwen3-4b-rl-baselineGRPO from the mid-trained baselinefull
lixiaochuan2020/qwen3-4b-rl-local-kv-per-documentGRPO from this modelper-document local-KV

Collection: kv-midtrain.

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

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

GPU в ailist

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

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

Подбираем GPU…

Класс архитектуры
Qwen3ForCausalLM
Ревизия весов
0967f1e

0 моделей