Token Classification
Transformers
ONNX
Safetensors
Transformers.js
modernbert
prompt-compression
context-compression
llmlingua
rag
agent-observability
tamarillo
Eval Results (legacy)
Run this model with HF Jobs
Run Tamarillo/prompt-compressor-small on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/Tamarillo/prompt-compressor-small. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Tamarillo/prompt-compressor-small on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use Tamarillo/prompt-compressor-small with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Tamarillo/prompt-compressor-small with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="Tamarillo/prompt-compressor-small")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForTokenClassification tokenizer = AutoTokenizer.from_pretrained("Tamarillo/prompt-compressor-small") model = AutoModelForTokenClassification.from_pretrained("Tamarillo/prompt-compressor-small", device_map="auto") - Transformers.js
How to use Tamarillo/prompt-compressor-small with Transformers.js:
// npm i @huggingface/transformers import { pipeline } from '@huggingface/transformers'; // Allocate pipeline const pipe = await pipeline('token-classification', 'Tamarillo/prompt-compressor-small'); - Notebooks
- Google Colab
- Kaggle
Release v2: 3.4x math-hardened corpus, +12.4pp over 560M LLMLingua-2 XLM-R, parity-verified ONNX
ce8152c verified |
Download README.md from Tamarillo/prompt-compressor-small: direct link, hf CLI and curl.
- Browser
- Download file 26.9 kB
-
https://huggingface.co/Tamarillo/prompt-compressor-small/resolve/main/README.md
- Command line
-
hf download hf://Tamarillo/prompt-compressor-small/README.md
-
curl -L -o README.md https://huggingface.co/Tamarillo/prompt-compressor-small/resolve/main/README.md
26.9 kB
| language: | |
| - en | |
| - de | |
| - es | |
| - zh | |
| - ar | |
| - hi | |
| license: apache-2.0 | |
| base_model: jhu-clsp/mmBERT-small | |
| datasets: | |
| - Tamarillo/prompt-compression-corpus-2026 | |
| pipeline_tag: token-classification | |
| library_name: transformers | |
| tags: | |
| - prompt-compression | |
| - context-compression | |
| - llmlingua | |
| - rag | |
| - agent-observability | |
| - token-classification | |
| - modernbert | |
| - onnx | |
| - transformers.js | |
| - tamarillo | |
| model-index: | |
| - name: Tamarillo/prompt-compressor-small | |
| results: | |
| - task: | |
| type: token-classification | |
| name: Extractive Prompt Compression (Public Reader-QA Benchmarks @ rate=0.50 & 0.65) | |
| dataset: | |
| type: multi-suite-ood | |
| name: HotpotQA + SQuAD-v2 + GSM8K (wrapped) + XQuAD (Phi-4-mini-instruct Reader, n=490 public + n=100 Agent JSON) | |
| metrics: | |
| - type: mean_3public_en_50 | |
| value: 0.7090 | |
| name: 3-Public-EN Mean incl. GSM8K (wrapped) @ rate=0.50 | |
| - type: mean_4public_50 | |
| value: 0.6608 | |
| name: 4-Public-Suite Mean incl. GSM8K (wrapped) @ rate=0.50 | |
| - type: mean_5suite_score | |
| value: 0.7287 | |
| name: 5-Suite Mean incl. GSM8K (wrapped) & Agent JSON @ rate=0.50 | |
| - type: mean_4public_65 | |
| value: 0.6922 | |
| name: 4-Public-Suite Mean incl. GSM8K (wrapped) @ rate=0.65 | |
| # Tamarillo/prompt-compressor-small (v2) | |
| **v2 β 140.6M-parameter, Apache-2.0 multilingual extractive prompt compressor** (ModernBERT architecture with `8,192`-token max position embeddings; trained up to `3,584` tokens, ONNX probe parity & CPU latency measured up to `2,048` tokens). Upgraded on our `3.4Γ` larger math-hardened + RAG + multilingual corpus (`Tamarillo/prompt-compression-corpus-2026` v2) with numeric/negation-aware token loss weighting (`1.6Γ`). At **2Γ compression (`rate=0.50`)** evaluated with an independent frozen reader (`microsoft/Phi-4-mini-instruct`), `small` v2 achieves **`0.6608` 4-Public Mean** (**+`13.07` pts vs v1**, **+`12.37` pts vs 4Γ larger `llmlingua-2-XLM-R-Large` `0.5371`** β led by **`#1` on 5-language `XQuAD` (`0.5164` vs `0.4219`)** and boilerplate-wrapped **`GSM8K (wrapped)` (`0.7400` vs `0.3500`, contributing 9.75 pts of the 4-Public gap)**, while `HotpotQA` `0.5926` and `SQuAD-v2` `0.7943` stay near parity with `LLMLingua-2`). At **`rate=0.65`**, `small` v2 reaches **`0.6922` 4-Public Mean** (`#1` on `XQuAD` `0.5836` and `GSM8K (wrapped)` `0.7500`), while running **`1.38Γ` faster than `llmlingua-2-mBERT` (`178M`) on 4-thread FP32 CPU at 512 tokens (`202.8 ms` vs `279.8 ms`)** with **3/3 ONNX exports** (`FP32`, `FP16`, `Gather-INT8`). | |
|  | |
| --- | |
| ## What's New in v2 | |
| - **3.4Γ Larger Commercially-Clean Corpus (`Tamarillo/prompt-compression-corpus-2026` v2):** Scaled from `840` to `2,873` EOS-verified training documents (`345` validation) by adding `2,258` new `Qwen/Qwen2.5-7B-Instruct` (`Apache-2.0`) extractive compressions spanning `631` MIT `microsoft/orca-math-word-problems-200k` problems (filtered for `>=85%` numeric token retention), `614` MIT `PubMedQA`, `423` `CNN/DailyMail`, `299` `oasst2`, and `277` multilingual `Aya` passages (zero SHA256 overlap with any eval suite). | |
| - **Numeric, Unit & Constraint-Aware Token Loss Weighting (`1.6Γ`):** Upweights KEEP errors on tokens containing digits, currency/math symbols, negations, and quantitative comparatives (`twice`, `half`, `more`, `less`, `per`, `each`, `remaining`) so mathematical operands and constraints survive aggressive `0.50Γ` compression. | |
| - **Substantial Reader-QA Gains (Principally on `GSM8K (wrapped)` & Multilingual `XQuAD`):** | |
| - `small` v2 (`141M`): `4-Public Mean` **`0.5301 -> 0.6608`** at `0.50Γ` and **`0.6458 -> 0.6922`** at `0.65Γ` (driven by `GSM8K (wrapped)` `0.24 -> 0.74` / `0.46 -> 0.75` and `#1` `XQuAD` `0.5164` / `0.5836`, while `HotpotQA` & `SQuAD-v2` stay near parity with `LLMLingua-2`). | |
| - `tiny-en` v2 (`32M`): `3-Public-EN Mean` **`0.5695 -> 0.7021`** at `0.50Γ` and **`0.6455 -> 0.7278`** at `0.65Γ` (driven by `GSM8K (wrapped)` `0.33 -> 0.71` / `0.51 -> 0.74`, plus `#1` on `SQuAD-v2` `0.8112` at `0.50Γ`). | |
| --- | |
| ## Model Overview | |
| | Property | Value | | |
| |---|---| | |
| | **Architecture** | `ModernBertForTokenClassification` (`0: DROP`, `1: KEEP`) | | |
| | **Base Backbone** | [`jhu-clsp/mmBERT-small`](https://huggingface.co/jhu-clsp/mmBERT-small) | | |
| | **Parameters** | `140.6M` | | |
| | **Context Window** | `8,192` arch max Β· trained up to `3,584` tok Β· ONNX/CPU measured up to `2,048` tok | | |
| | **Languages** | Multilingual (`jhu-clsp/mmBERT-small` 1,833-language backbone; trained on 20+ languages in `Tamarillo/prompt-compression-corpus-2026` v2 and evaluated on EN + `de/es/zh/ar/hi` XQuAD) | | |
| | **Model License** | `Apache-2.0` | | |
| | **Training Dataset** | [`Tamarillo/prompt-compression-corpus-2026`](https://huggingface.co/datasets/Tamarillo/prompt-compression-corpus-2026) v2 | | |
| | **Sibling Tier** | `Tamarillo/prompt-compressor-tiny-en` | | |
| | **Helper Package** | [`duoi-bt/tamarillo-guardrails`](https://github.com/duoi-bt/tamarillo-guardrails) (`TamarilloPromptCompressor`, installable via GitHub) | | |
| | **Live Browser Demo** | [`Tamarillo/prompt-compressor-demo`](https://huggingface.co/spaces/Tamarillo/prompt-compressor-demo) Β· [`Tamarillo/agent-guardrails-suite`](https://huggingface.co/spaces/Tamarillo/agent-guardrails-suite) | | |
| --- | |
| ## Benchmarks: Downstream Reader QA (`microsoft/Phi-4-mini-instruct`) | |
| All 7 systems are evaluated end-to-end on the **exact same frozen splits** at **matched exact word-retention budgets** (`rate=0.50` for 2Γ compression and `rate=0.65` for 1.54Γ compression) using an **independent frozen non-Qwen 3.8B reader** (`microsoft/Phi-4-mini-instruct`, greedy decoding). We report **Dataset-Disjoint Public External Benchmarks** (`HotpotQA` multi-doc RAG `n=120`, `SQuAD-v2` `n=150`, `GSM8K (wrapped)` numeric word problems wrapped with boilerplate preambles `n=100`, `google/xquad` 5-language `de/es/zh/ar/hi` `n=120` [`24`/lang]) separately from our held-out synthetic **`Agent JSON`** suite (`n=100`, distinct K8s schema, same domain family as `agent_json_log` in training). Metrics are token F1 (QA/JSON) and exact numerical match (`GSM8K (wrapped)`). | |
| ### Table 1: 2Γ Compression (`rate = 0.50`, exact `50.0%` word retention) | |
| | Model | Params | Arch Ctx | `HotpotQA` RAG | `SQuAD-v2` QA | `GSM8K (wrapped)` | `XQuAD` 5-Lang | **3-Public-EN Mean** | **4-Public Mean** | `Agent JSON` *(in-domain family)* | 5-Suite Mean | | |
| |---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| | |
| | `Uncompressed` *(reference)* | β | β | 0.6176 | 0.8775 | 0.6700 | 0.6647 | **0.7217** | **0.7074** | 1.0000 | 0.7660 | | |
| | **`Tamarillo/prompt-compressor-tiny-en` (v2)** | 32.0M | 7,999* | 0.5850 | 0.8112 | 0.7100 | 0.3314 | **0.7021** | **0.6094** | 1.0000 | 0.6875 | | |
| | **`Tamarillo/prompt-compressor-small` (v2)** *(this model)* | 140.6M | 8,192* | 0.5926 | 0.7943 | 0.7400 | 0.5164 | **0.7090** | **0.6608** | 1.0000 | 0.7287 | | |
| | `Tamarillo/prompt-compressor-tiny-en` *(v1)* | 32.0M | 7,999* | 0.5719 | 0.8065 | 0.3300 | 0.3344 | **0.5695** | **0.5107** | 0.9900 | 0.6066 | | |
| | `Tamarillo/prompt-compressor-small` *(v1)* | 140.6M | 8,192* | 0.5731 | 0.7982 | 0.2400 | 0.5092 | **0.5371** | **0.5301** | 0.9900 | 0.6221 | | |
| | `microsoft/llmlingua-2-bert-base-multilingual-cased-meetingbank` | 178.0M | 512 | 0.5954 | 0.7994 | 0.2700 | 0.4072 | **0.5549** | **0.5180** | 0.7267 | 0.5597 | | |
| | `microsoft/llmlingua-2-xlm-roberta-large-meetingbank` | 560.0M | 512 | 0.5830 | 0.7935 | 0.3500 | 0.4219 | **0.5755** | **0.5371** | 0.8700 | 0.6037 | | |
| ### Table 2: 1.54Γ Compression (`rate = 0.65`, exact `65.0%` word retention) | |
| | Model | Params | Arch Ctx | `HotpotQA` RAG | `SQuAD-v2` QA | `GSM8K (wrapped)` | `XQuAD` 5-Lang | **3-Public-EN Mean** | **4-Public Mean** | `Agent JSON` *(in-domain family)* | 5-Suite Mean | | |
| |---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| | |
| | `Uncompressed` *(reference)* | β | β | 0.6176 | 0.8775 | 0.6700 | 0.6647 | **0.7217** | **0.7074** | 1.0000 | 0.7660 | | |
| | **`Tamarillo/prompt-compressor-tiny-en` (v2)** | 32.0M | 7,999* | 0.6142 | 0.8293 | 0.7400 | 0.4314 | **0.7278** | **0.6537** | 1.0000 | 0.7230 | | |
| | **`Tamarillo/prompt-compressor-small` (v2)** *(this model)* | 140.6M | 8,192* | 0.6188 | 0.8165 | 0.7500 | 0.5836 | **0.7284** | **0.6922** | 1.0000 | 0.7538 | | |
| | `Tamarillo/prompt-compressor-tiny-en` *(v1)* | 32.0M | 7,999* | 0.6027 | 0.8237 | 0.5100 | 0.4663 | **0.6455** | **0.6007** | 1.0000 | 0.6805 | | |
| | `Tamarillo/prompt-compressor-small` *(v1)* | 140.6M | 8,192* | 0.6276 | 0.8296 | 0.4600 | 0.5584 | **0.6391** | **0.6189** | 1.0000 | 0.6951 | | |
| | `microsoft/llmlingua-2-bert-base-multilingual-cased-meetingbank` | 178.0M | 512 | 0.6488 | 0.8370 | 0.3600 | 0.5291 | **0.6153** | **0.5937** | 0.9967 | 0.6743 | | |
| | `microsoft/llmlingua-2-xlm-roberta-large-meetingbank` | 560.0M | 512 | 0.6196 | 0.8460 | 0.5400 | 0.5409 | **0.6685** | **0.6366** | 1.0000 | 0.7093 | | |
| *\*Architecture max position embeddings (`7,999` / `8,192`); training docs cap at `3,584` tokens, ONNX parity/latency measured to `2,048` tokens, and Reader-QA above is evaluated on standard benchmark lengths (`<2,048` tokens).* | |
| > **Candid analysis β why `GSM8K (wrapped)` exceeds Uncompressed & where baselines/v1 still win:** | |
| > - **Why compressed `GSM8K (wrapped)` (`0.71β0.75`) beats Uncompressed (`0.67`) β boilerplate-stripping effect & domain nuance:** In `scripts/eval_pc_5suite.py`, each `openai/gsm8k` question is wrapped with verbose tutoring/orchestrator preambles and footers (`~35β45%` boilerplate) to test whether a compressor drops boilerplate instead of math operands. Because v2 trained on **dataset-disjoint** MIT `orca-math` problems wrapped with distinct boilerplate preambles + `1.6Γ` numeric token weighting, v2 cleanly strips the distracting wrapper while retaining the math problem, improving `Phi-4-mini-instruct`'s solver accuracy over the noisier uncompressed input. While `orca-math` is 100% dataset-disjoint from `openai/gsm8k`, it shares the wrapped-math task structure (dataset-disjoint OOD, not domain-unseen), and pure unwrapped math prompts with zero boilerplate cannot exceed uncompressed accuracy under 50% deletion. | |
| > - **Where external baselines & v1 still lead:** | |
| > - `llmlingua-2-mBERT` (`178M`) leads `HotpotQA` RAG at both `0.50Γ` (`0.5954` vs v2 `small` `0.5926`) and `0.65Γ` (`0.6488` vs v2 `small` `0.6188` / v1 `small` `0.6276`). | |
| > - `llmlingua-2-XLM-R-Large` (`560M`) leads `SQuAD-v2` at `0.65Γ` (`0.8460` vs v2 `tiny-en` `0.8293` / v2 `small` `0.8165`), whereas v2 `tiny-en` (`32M`) edges `SQuAD-v2` at `0.50Γ` (`0.8112`). | |
| > - v1 `small` slightly edges v2 `small` on `HotpotQA` (`0.6276` vs `0.6188`) and `SQuAD-v2` (`0.8296` vs `0.8165`) at `0.65Γ`, while v2 `small` improves `XQuAD` (`0.5584 -> 0.5836`, `#1`), `GSM8K (wrapped)` (`0.46 -> 0.75`), and all aggregate means. | |
| > - **Sample size & single reader:** Suites contain `n=100β150` examples (`n=24`/language on `XQuAD`) evaluated with one 3.8B reader (`microsoft/Phi-4-mini-instruct`) without bootstrap CIs; narrow `~0.5β1.5 pt` differences fall within sampling noise. | |
| --- | |
| ## Table 3: ONNX Exports, Probe Parity Gates & 4-Thread CPU Latency | |
| All latencies below were measured on the **same Google Cloud `a2-highgpu-1g` x86-64 host VM** (Intel Xeon Cascade Lake, `onnxruntime` `CPUExecutionProvider`, `intra_op_num_threads=4`, `ORT_ENABLE_ALL`, `bs=1`, `p50` median ms over `12/8/4/4` timed runs after `2` warmups) against an identically exported **FP32 ONNX** of `microsoft/llmlingua-2-bert-base-multilingual-cased-meetingbank` (chunked `2Γ512` at 1,024 tok and `4Γ512` at 2,048 tok). Parity gates were verified on `n=2` probes per artifact (`1` short `<=256`-tok probe + `1` `2,048`-tok multi-paragraph probe) without separate downstream Reader-QA re-evaluation of FP16/INT8 exports. | |
| | Export Artifact | Size | Short Probe Parity (Agree / Top-50 Jaccard / Ξmax) | 2,048-Tok Probe Parity (Agree / Top-50 Jaccard / Ξmax) | CPU @ 256 tok | CPU @ 512 tok | CPU @ 1,024 tok | CPU @ 2,048 tok | | |
| |---|---:|---|---|---:|---:|---:|---:| | |
| | FP32 (`onnx/model.onnx`) | 537.0 MB | 1.0000 / 1.0000 (Ξβ€0.0000) | 1.0000 / 1.0000 (Ξβ€0.0000) | 89.0 ms | 202.8 ms | 571.7 ms | 1810.0 ms | | |
| | FP16 (`onnx/model_fp16.onnx`) | 268.7 MB | 1.0000 / 1.0000 (Ξβ€0.0011) | 1.0000 / 0.9922 (Ξβ€0.0047) | 107.0 ms | 236.0 ms | 702.1 ms | 2313.3 ms | | |
| | Gather-INT8 (`onnx/model_quantized.onnx`) | 255.9 MB | 1.0000 / 1.0000 (Ξβ€0.0036) | 0.9974 / 0.9845 (Ξβ€0.0065) | 90.1 ms | 213.8 ms | 586.1 ms | 1808.5 ms | | |
| | *Baseline:* `llmlingua-2-mBERT` FP32 *(512-tok chunked)* | 676.8 MB | β | β | 125.5 ms | 279.8 ms | 551.9 ms *(2Γ512)* | 1108.6 ms *(4Γ512)* | | |
| **Apples-to-apples latency & size notes:** On apples-to-apples FP32 ONNX against `llmlingua-2-mBERT` (`178M`, `676.8 MB`), `small` v2 (`537.0 MB`) is `1.26Γ` smaller, `1.41Γ` faster at 256 tokens (`89.0 ms` vs `125.5 ms`), `1.38Γ` faster at 512 tokens (`202.8 ms` vs `279.8 ms`), near parity at 1,024 tokens single-pass (`571.7 ms` vs `551.9 ms` 2Γ512 chunked), and slower at 2,048 tokens single-pass (`1810.0 ms` vs `1108.6 ms` 4Γ512 chunked) due to quadratic global-attention layers. | |
| **Withheld precisions (strict parity enforcement):** | |
| - **Full-INT8 (`Gather+MatMul`) dynamic quantization: withheld** β dynamic `MatMul` quantization degrades ModernBERT RoPE/GeGLU token logits below our strict parity gate. | |
| --- | |
| ## Quickstarts | |
| ### 1. Standalone PyTorch (`transformers>=4.48.0`, Zero Extra Packages) | |
| ```bash | |
| pip install "transformers>=4.48.0" torch numpy | |
| ``` | |
| ```python | |
| import re | |
| import numpy as np | |
| import torch | |
| from transformers import AutoModelForTokenClassification, AutoTokenizer | |
| model_id = "Tamarillo/prompt-compressor-small" | |
| tok = AutoTokenizer.from_pretrained(model_id, use_fast=True) | |
| model = AutoModelForTokenClassification.from_pretrained( | |
| model_id, attn_implementation="eager" | |
| ).eval() | |
| # CJK-aware unit splitting & rejoining (avoids inserting spaces between adjacent CJK characters) | |
| UNIT_RE = re.compile(r"[\u4e00-\u9fff\u3040-\u30ff]|[^\s\u4e00-\u9fff\u3040-\u30ff]+") | |
| def compress(text: str, rate: float = 0.50) -> str: | |
| enc = tok( | |
| text, | |
| return_offsets_mapping=True, | |
| truncation=True, | |
| max_length=3584, | |
| return_token_type_ids=False, | |
| return_tensors="pt", | |
| ) | |
| offsets = enc.pop("offset_mapping")[0].tolist() | |
| with torch.no_grad(): | |
| logits = model(**enc).logits[0].float().numpy() | |
| p_keep = 1.0 / (1.0 + np.exp(-np.clip(logits[:, 1] - logits[:, 0], -40, 40))) | |
| words = [(m.start(), m.end(), m.group(0)) for m in UNIT_RE.finditer(text)] | |
| scores, ti = [], 0 | |
| for ws, we, _ in words: | |
| while ti < len(offsets) and offsets[ti][1] <= ws: | |
| ti += 1 | |
| vals, j = [], ti | |
| while j < len(offsets) and offsets[j][0] < we: | |
| if offsets[j][1] > offsets[j][0]: | |
| vals.append(float(p_keep[j])) | |
| j += 1 | |
| scores.append(float(np.mean(vals)) if vals else 0.5) | |
| k = max(1, min(len(words), int(round(len(words) * rate)))) | |
| thr = sorted(scores, reverse=True)[k - 1] | |
| return re.sub(r"(?<=[\u4e00-\u9fff\u3040-\u30ff])\s+(?=[\u4e00-\u9fff\u3040-\u30ff])", "", " ".join([w for (_, _, w), s in zip(words, scores) if s >= thr][:k])) | |
| sample = ( | |
| "During Q3 2025, the billing API in us-east-1 experienced a latency spike to 420ms " | |
| "caused by database connection pool exhaustion; on-call engineers resolved it in 18 minutes " | |
| "by raising the pool limit from 50 to 120." | |
| ) | |
| print(compress(sample, rate=0.50)) | |
| ``` | |
| ### 2. Zero-PyTorch ONNX Runtime (Python CPU Microservice) | |
| ```bash | |
| pip install "transformers>=4.48.0" onnxruntime huggingface_hub numpy | |
| ``` | |
| ```python | |
| import re | |
| import numpy as np | |
| import onnxruntime as ort | |
| from huggingface_hub import hf_hub_download | |
| from transformers import AutoTokenizer | |
| model_id = "Tamarillo/prompt-compressor-small" | |
| tok = AutoTokenizer.from_pretrained(model_id, use_fast=True) | |
| onnx_path = hf_hub_download(model_id, "onnx/model_quantized.onnx") | |
| opts = ort.SessionOptions() | |
| opts.intra_op_num_threads = 4 | |
| sess = ort.InferenceSession(onnx_path, sess_options=opts, providers=["CPUExecutionProvider"]) | |
| # CJK-aware unit splitting & rejoining (avoids inserting spaces between adjacent CJK characters) | |
| UNIT_RE = re.compile(r"[\u4e00-\u9fff\u3040-\u30ff]|[^\s\u4e00-\u9fff\u3040-\u30ff]+") | |
| text = "Routine health check passed. Critical alert: pod checkout-svc failed with OOMKilled at 4096MB (INC-48291)." | |
| enc = tok(text, return_offsets_mapping=True, truncation=True, max_length=2048, return_token_type_ids=False, return_tensors="np") | |
| offsets = enc.pop("offset_mapping")[0].tolist() | |
| logits = sess.run(["logits"], {"input_ids": enc["input_ids"].astype(np.int64), "attention_mask": enc["attention_mask"].astype(np.int64)})[0][0] | |
| p_keep = 1.0 / (1.0 + np.exp(-np.clip(logits[:, 1] - logits[:, 0], -40, 40))) | |
| words = [(m.start(), m.end(), m.group(0)) for m in UNIT_RE.finditer(text)] | |
| word_scores = [] | |
| for ws, we, w in words: | |
| vals = [float(p_keep[i]) for i, (s, e) in enumerate(offsets) if e > s and s < we and e > ws] | |
| word_scores.append((w, float(np.mean(vals)) if vals else 0.5)) | |
| k = max(1, int(round(len(word_scores) * 0.5))) | |
| thr = sorted([s for _, s in word_scores], reverse=True)[k - 1] | |
| print(re.sub(r"(?<=[\u4e00-\u9fff\u3040-\u30ff])\s+(?=[\u4e00-\u9fff\u3040-\u30ff])", "", " ".join([w for w, s in word_scores if s >= thr][:k]))) | |
| ``` | |
| ### 3. Drop-In `LLMLingua`-Schema Helper (`tamarillo-guardrails`, GitHub) | |
| Matches `LLMLingua`'s `compress_prompt()` return schema without hardcoded allowlists or 512-token truncation (installed directly from GitHub, not yet on PyPI): | |
| ```bash | |
| pip install "transformers>=4.48.0" onnxruntime huggingface_hub "git+https://github.com/duoi-bt/tamarillo-guardrails.git" | |
| ``` | |
| ```python | |
| from tamarillo_guardrails import TamarilloPromptCompressor | |
| comp = TamarilloPromptCompressor(model_id="Tamarillo/prompt-compressor-small", onnx_filename="onnx/model_quantized.onnx") | |
| res = comp.compress_prompt( | |
| context=( | |
| "Kubernetes cluster telemetry dump archived by periodic observability cron job for standard compliance retention. " | |
| '{"incident_id": "INC-48291", "pod": "checkout-svc", "reason": "OOMKilled", "memory_mb": 4096} ' | |
| "Routine metrics scraping and TLS certificate checks remained within SLA targets." | |
| ), | |
| rate=0.50, | |
| force_reserve_digit=True, | |
| ) | |
| print(res["compressed_prompt"]) | |
| print(res["ratio"], res["saving"]) | |
| ``` | |
| ### 4. Browser / Node.js (`@huggingface/transformers>=3.5.0`) | |
| Loads `onnx/model_quantized.onnx` (`255.9 MB` Gather-INT8) or `onnx/model_fp16.onnx` (`268.7 MB`) in WebAssembly or WebGPU (`@huggingface/transformers>=3.5.0` required for ModernBERT support) and groups subwords into word-aligned spans to avoid mid-word fragmentation: | |
| ```bash | |
| npm install "@huggingface/transformers>=3.5.0" | |
| ``` | |
| ```javascript | |
| import { AutoTokenizer, AutoModelForTokenClassification } from "@huggingface/transformers"; | |
| const modelId = "Tamarillo/prompt-compressor-small"; | |
| const tokenizer = await AutoTokenizer.from_pretrained(modelId); | |
| const model = await AutoModelForTokenClassification.from_pretrained(modelId, { | |
| dtype: "q8", | |
| }); | |
| const text = "Routine background telemetry passed. Critical incident INC-48291: checkout-svc OOMKilled at 4096MB."; | |
| const rate = 0.50; | |
| const inputs = await tokenizer(text, { truncation: true, max_length: 2048 }); | |
| const { logits } = await model(inputs); | |
| const ids = Array.from(inputs.input_ids.data, (x) => Number(x)); | |
| const specialIds = new Set( | |
| [tokenizer.cls_token_id, tokenizer.sep_token_id, tokenizer.bos_token_id, tokenizer.eos_token_id, tokenizer.pad_token_id] | |
| .filter((v) => v !== undefined && v !== null) | |
| .map(Number) | |
| ); | |
| const wordGroups = []; | |
| for (let i = 0; i < ids.length; i++) { | |
| if (specialIds.has(ids[i])) continue; | |
| const d = logits.data[i * 2 + 1] - logits.data[i * 2]; | |
| const pKeep = 1 / (1 + Math.exp(-Math.max(-40, Math.min(40, d)))); | |
| const piece = tokenizer.decode([ids[i]], { skip_special_tokens: true }); | |
| if (wordGroups.length === 0 || /^\s/.test(piece)) { | |
| wordGroups.push({ ids: [ids[i]], probs: [pKeep] }); | |
| } else { | |
| const cur = wordGroups[wordGroups.length - 1]; | |
| cur.ids.push(ids[i]); | |
| cur.probs.push(pKeep); | |
| } | |
| } | |
| const words = wordGroups | |
| .map((g) => ({ | |
| text: tokenizer.decode(g.ids, { skip_special_tokens: true }).trim(), | |
| prob: g.probs.reduce((a, b) => a + b, 0) / g.probs.length, | |
| })) | |
| .filter((w) => w.text.length > 0); | |
| const k = Math.max(1, Math.min(words.length, Math.round(words.length * rate))); | |
| const thr = [...words.map((w) => w.prob)].sort((a, b) => b - a)[k - 1]; | |
| console.log(words.filter((w) => w.prob >= thr).slice(0, k).map((w) => w.text).join(" ")); | |
| ``` | |
| --- | |
| ## Training Recipe & Data Provenance | |
| Standard `ModernBertForTokenClassification` (`0: DROP`, `1: KEEP`, `attn_implementation="eager"`) fine-tuned from `jhu-clsp/mmBERT-small` (`140.6M` params, `8,192`-token architecture window) on the full multilingual [`Tamarillo/prompt-compression-corpus-2026`](https://huggingface.co/datasets/Tamarillo/prompt-compression-corpus-2026) v2 (`2,873` raw + stitched multi-document long-context examples = `3,623` training docs up to `3,584` tokens; `345` validation docs). Training uses numeric/unit/negation-weighted label-smoothed BCE (`1.6Γ` on KEEP tokens with digits, currency/math symbols, or relational constraints; `Ξ΅=0.02`) + intra-document hardest-pair ranking (`margin=0.6`, weight `0.25`) + cosine LR schedule (`lr=4.0e-5`, 4 epochs, effective `bs=32`, EMA `0.996`). Checkpoint selected strictly on unseen validation token metrics (`step 454`, `ema`, `val_tok_auc=0.8893`, `val_tok_f1=0.8623` β never test scores). | |
| **Corpus provenance (`Tamarillo/prompt-compression-corpus-2026` v2):** | |
| - **Permissive upstream dataset licenses:** Avoids `MeetingBank`'s `CC-BY-NC-SA-4.0` completely, using only upstream repositories carrying permissive license tags (`Apache-2.0`: `oasst2`, `aya`, `cnn_dailymail`, synthetic `agent_json_log`; `MIT`: `orca-math-word-problems-200k`, `PubMedQA`, `UltraChat`; `CC0-1.0`: `BillSum`). Commercial deployers should still note that original publisher copyrights in `CNN/DailyMail` or upstream synthetic generation terms may extend beyond HF metadata tags. | |
| - **No end-truncation drop-off:** New v2 synthetic chunks (`<=120β150` words, generated by Apache-2.0 `Qwen/Qwen2.5-7B-Instruct`) passed strict EOS verification and fuzzy-stem LCS alignment, preserving high retention all the way to document ends (`[0.349, 0.374, 0.402, 0.467, 0.509, 0.519, 0.527, 0.538, 0.496, 0.507]` across deciles 1β10; early deciles are intentionally lower because boilerplate preambles precede wrapped math problems). | |
| - **Validation-selected checkpoints only:** Test benchmarks (`HotpotQA`, `SQuAD-v2`, `GSM8K (wrapped)`, `XQuAD`, `Agent JSON`) were never touched during training or checkpoint selection. | |
| --- | |
| ## Limitations & Responsible Use | |
| - **Long-context CPU scaling (>1,024 tokens) & English-only speed trade-off:** Single-pass global attention over 2,048 tokens on 4-thread CPU takes `1810.0 ms` (`1808.5 ms` INT8), which is slower than 4Γ512 chunked `llmlingua-2-mBERT` (`1108.6 ms`). Chunking inputs at 512 tokens brings 2,048-token CPU latency down to `~811 ms` (`1.37Γ` faster than `mBERT`). For purely English workloads prioritizing speed, prefer `Tamarillo/prompt-compressor-tiny-en` (`32M`, `74.9 ms` @ 512 tok). | |
| - **Unwrapped dense math & dense factual text under aggressive compression:** While v2 excels at pruning boilerplate around quantitative tasks, deleting 50% of an already terse, zero-boilerplate math problem or dense factual paragraph (`HotpotQA`, `SQuAD-v2`) still drops relevant clauses. For zero-boilerplate math, legal, or exact-quote tasks, prefer `rate=0.65β0.75` and/or `force_reserve_digit=True`. | |
| - **Small ONNX parity probe set (`n=2`):** ONNX parity checks (`onnx_benchmark.json`) verified `1` short and `1` 2,048-token probe per artifact rather than re-running the full 590-example Reader-QA benchmark on FP16/INT8 exports; validate FP16/INT8 on your own domain prompts before production rollout. | |
| - **Untested >2Kβ8K long-context QA extrapolation:** Architecture max length is `8,192` tokens, training docs cap at `3,584` tokens, ONNX parity/latency verification stops at `2,048` tokens, and Reader-QA evaluates `<2,048` tokens. Validate `3.5Kβ8K` single-pass compression on your own long-context workloads first. | |
| - **Extractive telegraphic output & non-security scope:** Performs extractive token deletion (`DROP`/`KEEP`) optimized for downstream LLM comprehension rather than prose fluency, and does not filter prompt injections or redact PII (pair with `Tamarillo/injection-span-guard-*` and `Tamarillo/pii-secrets-guard-*`). | |
| --- | |
| ## Repository Files | |
| | File | Description | | |
| |---|---| | |
| | `config.json` | Model architecture configuration (`ModernBertForTokenClassification`, `0: DROP`, `1: KEEP`) | | |
| | `model.safetensors` | PyTorch weights (`140.6M` parameters, FP32 safetensors) | | |
| | `tokenizer.json` | Fast Hugging Face tokenizer | | |
| | `tokenizer_config.json` | Tokenizer configuration | | |
| | `special_tokens_map.json` | Special tokens mapping | | |
| | `onnx/model.onnx` | FP32 ONNX export (`537.0 MB`, opset 17) | | |
| | `onnx/model_fp16.onnx` | FP16 ONNX export (`268.7 MB`, browser/WASM & edge ready) | | |
| | `onnx/model_quantized.onnx` | Gather-INT8 ONNX export (`255.9 MB`) | | |
| | `eval_5suite_v2.json` | Full 7-system 5-suite frozen `Phi-4-mini-instruct` Reader-QA & baseline CPU ONNX benchmark results | | |
| | `onnx_benchmark.json` | Short & 2,048-token ONNX probe parity and 4-length x86-64 CPU latency benchmarks | | |
| | `training_summary.json` | Validation trajectory and checkpoint selection record | | |
| | `assets/pareto.svg` | 2-panel v2 public-benchmarks Reader-QA Pareto frontier chart (size & FP32 CPU latency) | | |
| | `scripts/synth_v2_math_rag.py` | v2 Math-hardened + RAG + multilingual corpus synthesizer (`Qwen/Qwen2.5-7B-Instruct`) | | |
| | `scripts/train_pc_v2.py` | v2 Numeric-aware trainer, soft-logit distiller & ONNX parity exporter | | |
| | `scripts/eval_pc_5suite_v2.py` | 7-system 5-suite frozen Reader-QA evaluation harness | | |
| | `scripts/eval_pc_5suite.py` | Core 5-suite benchmark builder & `Phi-4-mini-instruct` evaluator | | |
| | `scripts/train_and_eval_pc.py` | Shared EMA, multi-doc stitching, soft-logit alignment & ONNX export utilities | | |
| --- | |
| ## Citation | |
| ```bibtex | |
| @misc{tamarillo_prompt_compressor_v2_2026, | |
| title = {Tamarillo/prompt-compressor-small (v2): Apache-2.0 Math-Hardened Extractive Prompt Compression}, | |
| author = {Tamarillo Open-Model Lab}, | |
| year = {2026}, | |
| publisher = {Hugging Face}, | |
| howpublished = {\url{https://huggingface.co/Tamarillo/prompt-compressor-small}} | |
| } | |
| ``` | |