/ Модель

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

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

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

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

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

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

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

Это дообученная методом GRPO модель поискового агента на базе Qwen3-4B, созданная lixiaochuan2020. Она обучалась отвечать на вопросы по найденным фрагментам Википедии, вызывая инструмент wiki_search; обучение с подкреплением ориентировано на правильность итогового ответа. Архитектура — плотная авторегрессионная Qwen3ForCausalLM, около 3,7 млрд параметров, контекст до 40 960 токенов. Веса сохранены в формате safetensors и dtype float32; лицензия Apache-2.0.

Особенность обучения — локальное внимание per-document local-KV: фрагменты поиска обрабатываются отдельно, а последующий текст может учитывать все найденные фрагменты. Для корректного соответствия обучению README требует специальный патч для SGLang, vLLM или кода оценки; стандартный model.generate() и обычные серверы используют полное внимание. Модель предназначена для агентного поиска и ответов на вопросы, а не для самостоятельного поиска без настроенного инструмента и нужного формата промпта. Основное описание и примеры ориентированы на английские поисковые бенчмарки; качество на других языках не установлено.

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

  • ответы на вопросы с поиском по фрагментам Википедии
  • многошаговый поиск для вопросов по нескольким источникам
  • эксперименты с RL-обучением поисковых агентов
  • оценка агентных ответов на наборах вопросов HotpotQA и NQ

Ограничения

Обычный Transformers generate() и стандартные серверы vLLM/SGLang применяют полное внимание вместо использованного при обучении local-KV; для соответствующего режима нужны специальные патчи и настройки. README описывает поиск через конкретный инструмент wiki_search и не подтверждает качество на языках помимо английского.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Открыть на Hugging Face

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

GRPO search-agent RL, with per-document local-KV attention in both rollouts and training, from the mid-trained lixiaochuan2020/qwen3-4b-midtrain-local-kv-per-document (Qwen/Qwen3-4B mid-trained on Qwen/Qwen3-32B search trajectories with the same attention). Each retrieved passage is encoded on its own, as if its KV cache had been computed in advance. The full-attention baseline with the same RL is lixiaochuan2020/qwen3-4b-rl-baseline.

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. Load with dtype=torch.float32, or cast to bfloat16 for inference.
  • Branch main: the policy after RL step 300 of 300, converted from the miles FSDP checkpoint to Hugging Face format.
  • Conversion check against the starting model: same 4,022,468,096 parameters, all finite, relative L2 change of the weights 0.0214
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

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

Starting model

lixiaochuan2020/qwen3-4b-midtrain-local-kv-per-document: Qwen/Qwen3-4B mid-trained for 1 epoch (4,763 steps, 8 packed rows of 18,432 tokens per step, trajectories up to 16,384 tokens) on 297,720 judged-correct search-agent trajectories written by a Qwen/Qwen3-32B teacher with wiki-18 search. Muon for the decoder-layer matrices and AdamW for the rest, learning rate 2e-5, cosine schedule, warmup 0.03, float32 weights with bf16 compute, FlexAttention with per-document local-KV attention and detached passage K/V. Details are on its card.

RL data

ItemValue
Question poolSearch-R1 nq_hotpotqa_train
Training questions32,000
HotpotQA questions16,524
NQ questions15,476

The RL questions are a random sample (seed 0) of the pool after removing questions in the AFM SFT data and questions asked more than once. None is a mid-training question or an eval question. Gold answers are used only by the reward.

Reward

1 when Qwen/Qwen3.5-9B (no thinking, temperature 0) judges the rollout's final answer correct against the gold answers, otherwise 0.

  • Final answer: in the last assistant turn, after the reasoning, the content of the last <answer> or <final_answer> tag, otherwise the last paragraph.
  • No answer (reward 0): the reasoning was not closed, the last turn still calls a tool, or the answer is empty or over 50 words.
  • Judge prompt: the question, the gold answers and the final answer; the judge decides whether the answer refers to the same thing as any gold answer (wording, formatting and aliases do not matter; a different entity, date or number, or a list of several candidates, is incorrect) and replies Correct or Incorrect.

RL config

SettingValue
Frameworkmiles (FSDP training, SGLang rollouts)
AlgorithmGRPO
Starting model and KL referencelixiaochuan2020/qwen3-4b-midtrain-local-kv-per-document
RL steps (rollout steps)300
Prompts per step56
Samples per prompt16
Optimizer steps per RL step4
Rollout temperature1.0
New tokens per turn4,096
Max context (tokens)16,384
Max searches per rollout10
Searchwiki_search over wiki-18, e5-base-v2, top 5 passages
KL loss coefficient0.001
KL estimatorlow-variance KL (low_var_kl)
Clip ε0.2
Entropy coefficient0
OptimizerAdam
Adam β10.9
Adam β20.999
Learning rate1e-6
Warmup (optimizer steps)40
Scheduleconstant
Weight decay0
Max gradient norm1.0
GPUs for training and rollouts (colocated)7
GPUs for search and the reward judge1

Attention

Per-document local-KV attention in both rollouts and training:

  • 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.
  • 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.
  • Rollouts: SGLang with the local-KV prefill (flex_attention backend), fa3 decode, chunked prefill off, so a tool turn is never split.
  • Training: FlexAttention with the local-KV mask; passage K/V are detached, as in mid-training, so the loss on later tokens does not train how passages are encoded.

Prompt format

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

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 or RL 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: vLLM 0.24 (kv_midtrain.evaluation.vllm_generate), batched over all open conversations; Local mode runs through the local-KV vLLM patch. Checked against the PyTorch loop used for the mid-trained models on the Qwen3-1.7B local-KV mid-trained model (ID questions, 3 samples each): judged accuracy differs by +0.010 (CI −0.005 to +0.026) in Full mode and +0.002 (CI −0.011 to +0.016) in Local mode.
  • 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.5040.6990.6720.6550.6310.6780.852
Local0.5580.6940.6620.6600.6370.6840.949

OOD search:

ModeBamboogleFEVERMuSiQuePopQAAccuracyCI lowCI highAnswer rate
Full0.6480.9270.3670.5930.6310.6010.6600.873
Local0.6800.9330.4230.5700.6470.6180.6740.978

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

DatasetProblemsAccuracyBoxed answer rate
GSM8K test1,3190.9370.995
MATH-5005000.9240.980

Training run

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

Related models

ModelTrainingAttention in training
lixiaochuan2020/qwen3-4b-midtrain-baselinemid-trainingfull
lixiaochuan2020/qwen3-4b-midtrain-local-kv-per-documentmid-training; starting model of this oneper-document local-KV
lixiaochuan2020/qwen3-4b-rl-baselineGRPO from the mid-trained baselinefull
lixiaochuan2020/qwen3-4b-rl-local-kv-per-document (this model)GRPO from the mid-trained local-KV modelper-document local-KV

Collection: kv-midtrain.

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

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

GPU в ailist

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

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

Подбираем GPU…

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

0 моделей