/ Модель

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

Контекст
8 192 токена
Лицензия
Apache 2.0
Архитектура
querylm_nanochat · dense
Библиотека
transformers
Опубликована
19 ноя 2026

querylm-dclm-400m

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

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

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

Базовая англоязычная модель на 400 млн параметров, обученная продолжать текст и формировать поисковые запросы для внешнего ретривера.

QueryLM 400M (DCLM-Edu) — базовая языковая модель Kausp11, обученная с нуля на текстах веба из DCLM-Edu. Это каузальная плотная модель в стиле nanochat с архитектурой NanochatForCausalLM: 14 слоёв, ширина 1 280, 10 голов внимания и контекст 4 095 токенов. В README указано 401,2 млн параметров; число сохранённых параметров выше из-за value embeddings. Модель использует токенизатор SmolLM2, расширенный до словаря из 49 156 токенов.

Во время предобучения в текстовые последовательности добавлялись блоки поиска: модель училась формировать поисковые запросы и продолжать текст с учётом переданных извлечённых фрагментов. Она не генерирует сами фрагменты: вызывающая система должна выполнить поиск и вставить результаты в контекст. Модель также можно использовать для обычного продолжения текста. Это базовый чекпойнт без формата чата; для диалогового применения автор указывает на отдельную дообученную версию. Основной язык данных — английский.

Модель предназначена для исследований обучения языковых моделей с поиском во время предобучения, а не для готового продукта. В README предупреждают, что она не проходила обучение безопасности и отказам, может уверенно выдавать ложные сведения и зависит от качества и безопасности переданных поисковых результатов. Для загрузки репозитория выполняется Python-код из него. Лицензия — Apache-2.0.

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

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

Ограничения

Это базовая модель без чат-формата и обучения безопасности; она может уверенно генерировать ложные сведения. Для поиска требуется внешний ретривер, а модель воспринимает переданные фрагменты, в том числе ошибочные или вредоносные, как контекст.

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

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

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

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

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

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

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

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

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

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

Открыть на Hugging Face

QueryLM 400M (DCLM-Edu), base model

A 400M-parameter language model trained from scratch on DCLM-Edu web text in which search blocks were inserted during pretraining: at points where a lookup would help predict what comes next, the training text contains a search query followed by a retrieved passage. The model learned to write the queries and to use the passages; the passages themselves were never a prediction target.

This is the base model (pretraining only). The chat fine-tuned version is Kausp11/querylm-dclm-400m-sft-search. A compute-matched Standard baseline (same architecture and compute, plain text without search blocks) exists but is not published in this set yet.

Stagebase model (pretraining only; no chat format)
Architecturenanochat-style decoder: 14 layers, width 1,280, 10 heads, feed-forward 5,120, head dim 128, context 4,095 tokens
Parameters401.2M reported (842.2M stored, including value embeddings)
Loads withtransformers + trust_remote_code=True (the repo ships modeling_nanochat.py)

How to use

The model can be used without search like any causal language model. To let it search: open a search block, let it write the query, run your own retriever, insert the result, and let it continue.

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

repo = "Kausp11/querylm-dclm-400m"
tok = AutoTokenizer.from_pretrained(repo)
# trust_remote_code runs modeling_nanochat.py from this repo; pin `revision=` to a commit you have read.
model = AutoModelForCausalLM.from_pretrained(repo, trust_remote_code=True, torch_dtype=torch.bfloat16).eval()

Q_OPEN, Q_CLOSE = tok.convert_tokens_to_ids("<WEB_QUERY>"), tok.convert_tokens_to_ids("</WEB_QUERY>")

def my_search(query: str) -> str:
    """Replace with your retriever (BM25 index, web search API, ...). Return one short passage."""
    return "Canberra is the capital city of Australia. It was founded in 1913 and is the country's largest inland city."

@torch.no_grad()
def generate(text, max_new_tokens, stop_id=None, allow_search=True):
    x = tok(text, add_special_tokens=False, return_tensors="pt")
    kw = {} if allow_search else {"bad_words_ids": [[Q_OPEN]]}
    out = model.generate(**x, max_new_tokens=max_new_tokens, do_sample=False,
                         eos_token_id=stop_id, pad_token_id=tok.eos_token_id, **kw)
    return tok.decode(out[0, x.input_ids.shape[1]:], skip_special_tokens=True)

# Base model: it continues text. Few-shot examples set the question-answer format.
shots = ("Question: Who wrote the novel Pride and Prejudice?\nAnswer: Jane Austen\n\n"
         "Question: What is the chemical symbol for gold?\nAnswer: Au\n\n")
prompt = shots + "Question: What is the capital of Australia?\n"

query = generate(prompt + "<WEB_QUERY>", max_new_tokens=24, stop_id=Q_CLOSE).strip()            # 1) the model writes the query
block = f"<WEB_QUERY>{query}</WEB_QUERY> <WEB_RESPONSE>{my_search(query)}</WEB_RESPONSE>"        # 2) you retrieve and insert the block
answer = generate(prompt + block + "\nAnswer:", max_new_tokens=16, allow_search=False)           # 3) the model continues
print("query :", query)
print("answer:", answer.split("\n")[0].strip())

Output of this exact script (CPU, bfloat16, torch 2.8.0, transformers 4.56.0, run 2026-11-19 on the files in this repo):

query : capital of Australia
answer: Canberra

The passage here is a fixed example string; the output shows the mechanics, not the model's accuracy.

Search-block format

Tokenid
<WEB_QUERY>49152
</WEB_QUERY>49153
<WEB_RESPONSE>49154
</WEB_RESPONSE>49155

Layout in the training text: …text<WEB_QUERY>query</WEB_QUERY> <WEB_RESPONSE>passage</WEB_RESPONSE> text continues…. The tokenizer is the SmolLM2 tokenizer plus these four tokens (vocabulary 49,156). The loss covered the text, the query and the query tags; the response tags and the passage carried no loss, so the model does not generate passages. The caller supplies them.

Training data

Pretraining: DCLM-Edu, annotated with search blocks by a fine-tuned annotator model (Gemma 4 E4B-it with a LoRA adapter). The annotator marks positions where a search would help (insertion probability at least 0.05, at least 40 characters apart) and writes a query of at most 24 tokens for each. Passages come from BM25 retrieval over the public Sphere web corpus and are shortened by extractive cleaning. An insertion is kept only if the passage overlaps the text that follows it in the document (ROUGE-1 F1 of at least 0.1 against the next 260 characters).

Training procedure

Pretraining optimizerMuon for matrix weights (peak LR 0.02828), AdamW for embeddings and output head
Batch256 sequences x 4,095 tokens = 1,048,320 tokens per update
Schedule40 warmup steps, constant, then linear decay to 5% of peak at the end
Pretraining budget10,100 updates; 10.6B tokens processed, of which 6.8B document tokens; 3.09e19 FLOPs; bf16 compute

Provenance

Checkpointrun dclm_nc_v1_d14_all_chin10k, step 10,100. The run branches at step 9,000 from a longer 400M run and decays the learning rate over steps 9,000 to 10,100; the schedule is finished
Initialised fromscratch
Codenanochat (upstream commit 92d63d4) with a local search-data branch
model.safetensors sha256b887209eaac5655008c7a9d5a3ab104cb4df5b3a52ce4f14013afc4a2432ec0e

Evaluation

Evaluation results will be added later.

Intended use and limitations

  • A research artifact for studying models that learn to search during pretraining. Not a product.
  • Base model: it continues text and has no chat format. For chat-style use see the fine-tuned version.
  • English web text only; no safety or refusal training of any kind. It will state false things fluently.
  • It searches usefully only when the caller runs the loop above. Passages are inserted verbatim into the context: whatever the retriever returns, the model conditions on, including wrong or adversarial text. The retrieval source is the caller's choice and responsibility.
  • Loading executes Python from this repository (modeling_nanochat.py). Read it or pin a revision.

License

Apache-2.0 (licence text in LICENSE). modeling_nanochat.py is adapted from nanochat, MIT License, Copyright (c) 2025 Andrej Karpathy (text in LICENSE-nanochat). Training text: DCLM-Edu (CC-BY-4.0). Retrieved passages used as masked context during pretraining come from Sphere (CC BY-NC 4.0); they are not part of this repo.

Citation

Paper: Search From the Start: Search-Native Pretraining for Language Models · Project page: https://kaustubhp11.github.io/querylm/

@article{ponkshe2026searchfromthestart,
  title   = {Search From the Start: Search-Native Pretraining for Language Models},
  author  = {Ponkshe, Kaustubh and Je, Gyung Hyun and Taga, Stefan and Raffel, Colin and Jaggi, Martin},
  journal = {arXiv preprint arXiv:2611.26809},
  year    = {2026}
}

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

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

GPU в ailist

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

Нельзя запустить

Модели нужен код из репозитория; запуск откроется после проверки совместимости.

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

0 моделей