/ Модель

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

Контекст
8 192 токена
Параметры
140 млн
Лицензия
Apache 2.0
Архитектура
modernbert · dense
Базовая модель
mmBERT-small
Библиотека
transformers
Опубликована
8 окт 2026

ctxprune-small

Разметка токеновТекст → label8 профессий

Мультиязычная модель токен-классификации, которая сокращает выводы инструментов, журналы и документы для экономии контекста языковых моделей и ИИ-агентов.

116скачиваний за 30 дней0лайковвеса обновлены21 ноя 2026

Бенчмарки

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

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

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

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

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

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

ctxprune-small — дообученная мультиязычная модель для сжатия контекста, разработанная для подготовки вывода инструментов, журналов и документов перед передачей ИИ-агенту или языковой модели. Она оценивает токены и помогает удалять менее важные фрагменты, сохраняя текст и идентификаторы настолько, насколько позволяет выбранный бюджет. Модель основана на энкодере mmBERT-small с двухклассовой головой токен-классификации; содержит 140,5 млн параметров, поддерживает контекст до 8192 токенов и распространяется в форматах Safetensors и ONNX.

Модель обучена на примерах вывода инструментов, исходного кода, веб-текстов и диалогов. В оценке на вопросах по сжатым фрагментам она сохраняла около половины токенов; точность ответов при этом снизилась с 91,8% на исходном тексте до 68,8%. Результаты на обычных длинных документах сопоставимы с LLMLingua-2-large, а мультиязычная веб-проза оказалась слабой областью. Сжатие неизбежно теряет информацию; режим force_protected сохраняет идентификаторы, но может снизить качество ответов. Лицензия модели — Apache-2.0; базовая модель mmBERT-small указана с лицензией MIT.

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

  • сжатие вывода командной строки перед передачей агенту программирования
  • сокращение журналов для анализа языковой моделью
  • уменьшение размера ответов MCP-инструментов
  • сжатие фрагментов документов перед ответом на вопрос
  • сохранение идентификаторов и путей при сокращении текста

Ограничения

Сжатие теряет информацию: при сохранении 50% токенов точность ответов в описанной оценке снизилась примерно с 92% до 69%. На мультиязычной веб-прозе результаты слабее, а для обычных длинных документов преимущество перед LLMLingua-2-large не показано.

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

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

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

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

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

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

Открыть на Hugging Face

ctxprune-small: context compression for AI agents

Cuts tool outputs, logs and documents to about half before an LLM reads them, without mangling IDs.

real run: a 704-character failing test log pruned to 323 characters on a CPU, the build id, the host and the retry count kept

Real run of ctxprune log.txt --keep 0.5 --protect (ctxprune 0.5.0, this model, CPU): 704 characters in, 323 out; 4821, db-07.internal and 3 survive. One log, not a benchmark; the numbers are below. At 50% of tokens kept, a reader LLM answers 51.5% of SQuAD v2 + HotpotQA questions exactly from this model's output vs 36.5% from headroom's Kompress-v2-base (400 questions, gap CI +10.5 to +19.5; reader Qwen3.8-27B, which also labeled this model's training data), and 68.8% vs 53.4% for LLMLingua-2-large on our agent-text set with an independent reader (DeepSeek V4 Flash). Try it in your browser (runs locally, nothing is uploaded).

Real output on a failing pytest run: struck-through words are deleted

pip install ctxprune
ctxprune build.log --keep 0.5           # or pipe: cmd | ctxprune --keep 0.33 --protect

The same package also ships lossless hooks for coding agents (Claude Code, Codex, Hermes, Pi, OpenCode, dsh) that use no model: uvx ctxprune wrap claude (one line; ctxprune install --all for every agent), see riceharvest/ctxprune. From ctxprune 0.3 this model is used only by the token-pruning API below. In 0.4, 0.2-style calls (prune(text, keep), Compressor, the CLI) still give the same output as in 0.2.1; the new v0.4 engine (query-aware pruning, protect="auto", compress_many) is opt-in on those calls and the default on the new entry points. ctxprune 0.5 adds opt-in integrations and tools (MCP server and wrapper, see the changelog); default output is byte-identical to 0.4.1.

By @imdariotoo · code, Claude Code plugin, LangChain/LlamaIndex integrations: riceharvest/ctxprune

A 140M-parameter token classifier that shortens text before it reaches an LLM by deleting the words that matter least. It is a successor to Microsoft's LLMLingua-2, trained for what agents actually read: tool outputs (JSON, logs, stack traces, diffs, directory listings), code, documents and chat, in many languages.

  • Keeps identifiers intact. Text is rebuilt from whole source spans, so IDs, paths, URLs, IPs and versions are never split or re-spaced (LLMLingua-2 turns ord_8f3a2c91 into ord _ 8f3a2c91 and 0.21 into 0. 21). Optional force_protected=True (protect=True in ctxprune.prune) guarantees no identifier is dropped. Turn it on for tool output and logs: without it the model may delete identifiers. On 30 held-out agent tool outputs at 50% kept, 99.6% of IDs, paths, versions, URLs and numbers survived verbatim with it, 45.8% without it, 72.9% with LLMLingua-2-base and 94.6% with LLMLingua-2-large (all types and rates).
  • Better answers from compressed text. At the same share of LLM tokens kept, QA accuracy from the compressed text is +15 points higher than with LLMLingua-2-large at 50% kept, and +21 points at 33%. The gain comes from agent tool outputs, agent text and code; on multilingual web prose LLMLingua-2-large is still better (see per-source table).
  • Small and fast. ~102 ms per 500-token chunk on CPU (ONNX fp32), ~93 ms int8, vs ~600 ms for LLMLingua-2-large. ONNX files included; no PyTorch needed.
  • Apache-2.0, trained only on permissively licensed data (LLMLingua-2's training labels are CC BY-NC-SA).

Usage

pip install ctxprune             # CPU: onnxruntime + tokenizers, no torch
pip install "ctxprune[torch]"    # PyTorch backend (GPU/CPU)
import ctxprune
ctxprune.prune(tool_output, keep=0.5)                 # int8 ONNX on CPU, model downloads once (143 MB)
ctxprune.prune(tool_output, keep=0.33, protect=True)  # never drop IDs, numbers, paths
ctxprune.prune(tool_output, keep=0.33, protect="auto", query="why did it fail?")  # 0.4: query-aware, keeps technical text intact

from ctxprune import Compressor                       # more control: batching, fp32, torch, thresholds
c = Compressor("darioooooo0o/ctxprune-small", backend="onnx", onnx_file="onnx/model.onnx")
c.compress(tool_output, rate=0.5)["text"]
WhereHow
Coding agentslossless hooks, no model: ctxprune install --all (details)
Shellctxprune FILE --keep 0.5 --stats, reads stdin
Other languagesctxprune serve then POST localhost:8719/compress {"text": ...}
LangChain / LlamaIndexctxprune.integrations.CtxpruneDocumentCompressor / CtxpruneNodePostprocessor
Browser (transformers.js)see the demo source

With LLMLingua (drop-in, needs the tokenizer-detection fix proposed upstream in microsoft/LLMLingua#261):

from llmlingua import PromptCompressor
pc = PromptCompressor(model_name="darioooooo0o/ctxprune-small", use_llmlingua2=True)
pc.compress_prompt(text, rate=0.5, force_tokens=["\n", "?"])

Tokenizer: loading this model's tokenizer with transformers needs transformers>=5.

Raw transformers / ONNX: label 1 = keep (same convention as LLMLingua-2). Score each token with softmax(logits)[..., 1], average per word, and keep the highest-scoring words. onnx/model.onnx is exact fp32. onnx/model_quantized.onnx is int8 (143 MB): its keep decisions match fp32 on ~96% of tokens, and QA accuracy at 50% kept is 68.2 vs 68.8 for fp32 (same eval as below).

Results

Held-out evaluation: 378 questions over 196 chunks from repos, MCP servers and sites never seen in training. Each method compresses the chunk to the same share of the reader's tokens; the reader then answers from the compressed text and is scored by exact match on the gold span.

QA exact match, independent reader (DeepSeek V4 Flash):

Method50% of tokens kept33% of tokens kept
Original (no compression)91.8
ctxprune-small68.853.4
ctxprune-small + force_protected63.552.9
LLMLingua-2 large53.432.5
LLMLingua-2 base41.024.9

Per source, at 50%:

Sourcefineweb2fineweb edugithub codeoasst2swe rebench assistantswe rebench toolswe smith tooltoucan mcp
ctxprune-small @50%5673727570608459
LLMLingua-2 large @50%8373626249482943

Teacher as reader. An earlier checkpoint (conservative labels only, ~2k chunks) was also scored with Qwen3.8-27B, the labeling teacher, as reader: 65.9 / 51.1 vs LLMLingua-2 large 55.0 / 32.5. That is the same ranking as with the independent reader, so the gain is not an artifact of the teacher grading itself.

Identifiers lost (IDs, numbers, paths, versions that no longer appear intact), at 50%:

MethodIDs lostLLM-token ratio
ctxprune-small41%0.49
ctxprune-small + force_protected0%0.54
LLMLingua-2 large34%0.48
LLMLingua-2 base47%0.59

Reasoning on vs off for the reader made no difference on a 40-question check, so readers ran without it.

Training

  • Data: 5,249 training chunks (≤500 tokens) from 7 permissive sources: coding-agent tool outputs (SWE-smith, MIT; SWE-rebench OpenHands, CC BY 4.0), MCP tool outputs (Toucan-1.5M, Apache-2.0), source code (github-code-clean, MIT/Apache/BSD/ISC files only), English and multilingual web text (FineWeb-Edu and FineWeb-2, ODC-BY), assistant chat (oasst2, Apache-2.0). Train/val/test are split per repository, MCP server, website or conversation.
  • Labels: Qwen3.8-27B (Apache-2.0) compresses each chunk by deletion only. Its output is aligned to the source with an LCS over atoms. Two prompts are used: a conservative one, and an aggressive one with an explicit word budget. Training on both gives graded targets: words kept even under the aggressive prompt score highest. This teaches ranking inside the large "keep" set, which is what a 33–50% rate needs.
  • Model: mmBERT-small (MIT) with a 2-class token head, 5 epochs, best epoch by ROC-AUC against teacher labels. Training takes 5 minutes on one Intel Arc Pro B70.
  • What mattered (same eval, DeepSeek reader, 50% / 33% kept): conservative labels only, 65.6 / 45.8; aggressive labels only, 65.6 / 50.8; both together (graded), 68.8 / 53.4. Doubling the labels from ~1k to ~2k added 4 points; mmBERT-base instead of small added ~1 point at 2.3x the latency.

Code, data pipeline and evals: https://github.com/riceharvest/ctxprune.

Limitations

  • On general long documents (LongBench, LLMLingua-2's own benchmark and scorer, 9 English tasks, Gemma-4-31B reader, same per-item token budget as LLMLingua-2-large) the 0.4 query mode is level with LLMLingua-2-large, not better: on 270 held-out items +2.36 [−0.70, +5.51] (9-task macro), +0.15 [−2.76, +3.42] without passage_retrieval_en. The query mode sees the question and LLMLingua-2 does not; 21 of the 270 items share a source document with our dev set. A zero-model BM25 selector at the same budget is level with the query mode (+0.71 [−1.77, +3.40]), so the model's added value over lexical query matching is not shown. Without a question (query-blind) it is level on 9 tasks and worse without passage_retrieval_en (−3.73 [−6.52, −1.14]). On our dev set it also loses triviaqa and lcc. Tables, controls and the dev-set numbers (which the 0.4 code was tuned on): BENCHMARKS §9.
  • Multilingual web prose is the weakest domain: LLMLingua-2-large answers more questions there (small sample: 18 questions). The teacher often rewrote non-English text instead of deleting from it, so fewer of those labels survived filtering.
  • force_protected=True guarantees no identifier is dropped, but at 50% it spends budget on IDs the question did not need and scores a few points lower overall. Use it when exact IDs matter more than everything else (e.g. you will act on them).
  • Compression always loses information. At 50% kept, QA accuracy drops from ~92% (uncompressed) to 69%. Use it where the token savings are worth that.
  • Labels come from one teacher LLM, and the eval questions were written by that same model.
  • Rates are measured in the target LLM's tokens in our evals. With the default character budget, CJK text compresses slightly less than the requested rate.

Attribution

Training data includes content under CC BY 4.0 (nebius/SWE-rebench-openhands-trajectories) and ODC-BY (FineWeb-Edu, FineWeb-2). The deletion-only teacher prompt adapts LLMLingua-2's (MIT, Microsoft). Base model: jhu-clsp/mmBERT-small (MIT).

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

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

GPU в ailist

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

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

Подбираем GPU…

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

0 моделей