greendesk1631's picture
Release Tamarillo/prompt-compressor-small (Apache-2.0, ModernBERT extractive prompt compressor, parity-verified ONNX)
4875150 verified
|
Raw History Blame Contribute Delete
26.3 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)
dataset:
type: multi-suite-ood
name: HotpotQA + SQuAD-v2 + GSM8K + XQuAD (Phi-4-mini-instruct Reader, n=490 public + n=100 Agent JSON)
metrics:
- type: mean_3public_en_50
value: 0.5371
name: 3-Public-EN Mean (rate=0.50)
- type: mean_4public_50
value: 0.5301
name: 4-Public-Suite Mean (rate=0.50)
- type: mean_5suite_score
value: 0.6221
name: 5-Suite Mean incl. Agent JSON (rate=0.50)
- type: mean_4public_65
value: 0.6189
name: 4-Public-Suite Mean (rate=0.65)
---
# Tamarillo/prompt-compressor-small
**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 parity & CPU latency verified up to `2,048` tokens). At 2× compression (`rate=0.50`) evaluated with an independent frozen reader (`microsoft/Phi-4-mini-instruct`), `prompt-compressor-small` outperforms `llmlingua-2-mBERT` (`178M`) on the **4 public external benchmarks** (`0.5301` vs `0.5180`, driven by **#1 on 5-language `XQuAD` `0.5092` vs `0.4219` / `0.4072`**; within `0.0070` of 4.0× larger `llmlingua-2-XLM-R-Large` `0.5371`), and ranks **#1 on the full 5-suite mean including held-out Agent JSON (`0.6221` vs `XLM-R-Large` `0.6037` / `mBERT` `0.5597`)**. Note that on the 3 public English-only suites (`HotpotQA`, `SQuAD-v2`, `GSM8K`) at `0.50×`, `small` (`0.5371`) trails `llmlingua-2-mBERT` (`0.5549`) and our English-only `Tamarillo/prompt-compressor-tiny-en` (`0.5695`). On apples-to-apples **FP32 ONNX**, `small` is **`1.26×` smaller (`537.0 MB` vs `676.8 MB`)** and runs **`1.43×` faster on 4-thread CPU at 256 tokens (`85.9 ms` vs `123.2 ms`)** and **`1.41×` faster at 512 tokens (`195.7 ms` vs `276.7 ms`)**; a parity-verified `255.9 MB` Gather-INT8 ONNX export (`87.4 ms` @ 256 tok) is also included.
![Tamarillo/prompt-compressor Public Benchmarks Pareto Frontier](assets/pareto.svg)
---
## Why This Model Exists
Production RAG and AI-agent pipelines rely heavily on extractive prompt compressors (`microsoft/llmlingua-2-*`), but the incumbent encoders carry three practical limitations:
1. **Non-commercial training dataset (`MeetingBank`):** LLMLingua-2 encoders were trained on `MeetingBank` (`CC-BY-NC-SA-4.0`), complicating enterprise commercial compliance.
2. **Hard 512-token context cap:** BERT/XLM-R encoders force blind 512-token chunking across multi-document RAG prompts and JSON tool traces.
3. **Heavy CPU/browser footprints:** `llmlingua-2-mBERT` (`178M`) is `676.8 MB` in FP32 ONNX (`276.7 ms` CPU @ 512 tok), and `llmlingua-2-XLM-R-Large` is `560M`.
**`Tamarillo/prompt-compressor-small`** addresses these with:
- **Apache-2.0 weights** trained on [`Tamarillo/prompt-compression-corpus-2026`](https://huggingface.co/datasets/Tamarillo/prompt-compression-corpus-2026) v3 (avoiding `CC-BY-NC-SA` `MeetingBank`; see *Training Recipe & Data Provenance* below for source-level licensing notes).
- **ModernBERT long-context architecture** (`8,192` max position embeddings; trained on stitched multi-document examples up to `3,584` tokens; ONNX parity & CPU latency verified up to `2,048` tokens) with zero `trust_remote_code`.
- **Parity-verified ONNX exports** ready for zero-PyTorch Python (`onnxruntime`) and browser/Node.js (`@huggingface/transformers`), plus a standalone Python helper in [`duoi-bt/tamarillo-guardrails`](https://github.com/duoi-bt/tamarillo-guardrails).
| 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 verified 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` v3 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) v3 |
| **Sibling Tier** | `Tamarillo/prompt-compressor-tiny-en` |
| **Helper Package** | [`duoi-bt/tamarillo-guardrails`](https://github.com/duoi-bt/tamarillo-guardrails) (`TamarilloPromptCompressor`) |
| **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 compressors are evaluated end-to-end at **matched exact word-retention budgets** (`rate=0.50` for 2× compression and `rate=0.65` for 1.5× compression) using an **independent frozen non-Qwen 3.8B reader** (`microsoft/Phi-4-mini-instruct`, greedy decoding) to avoid teacher-family bias. To separate strictly external generalization from in-domain-family performance, we report **Public External Benchmarks** (`HotpotQA` multi-doc RAG `n=120`, `SQuAD-v2` `n=150`, `GSM8K` numeric word problems `n=100`, `google/xquad` 5-language `de/es/zh/ar/hi` `n=120` [`24` examples/lang]) separately from our held-out synthetic **`Agent JSON`** suite (`n=100`, distinct Kubernetes/e-commerce schema, same domain family as `agent_json_log` in training). Metrics are token F1 (QA/JSON) and exact numerical match (`GSM8K`).
### Table 1: 2× Compression (`rate = 0.50`, exact `50.0%` word retention)
| Model | Params | Arch Ctx | `HotpotQA` RAG | `SQuAD-v2` QA | `GSM8K` Math | `XQuAD` 5-Lang | **3-Public-EN Mean** | **4-Public Mean** | `Agent JSON` *(in-domain family)* | 5-Suite Mean |
|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
| `Uncompressed` *(upper bound)* | — | — | 0.6176 | 0.8775 | 0.6700 | 0.6647 | **0.7217** | **0.7074** | 1.0000 | 0.7660 |
| **`Tamarillo/prompt-compressor-tiny-en`** | 32.0M | 7,999* | 0.5719 | 0.8065 | 0.3300 | 0.3344 | **0.5695** | **0.5107** | 0.9900 | 0.6066 |
| **`Tamarillo/prompt-compressor-small`** *(this model)* | 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.5× Compression (`rate = 0.65`, exact `65.0%` word retention)
| Model | Params | Arch Ctx | `HotpotQA` RAG | `SQuAD-v2` QA | `GSM8K` Math | `XQuAD` 5-Lang | **3-Public-EN Mean** | **4-Public Mean** | `Agent JSON` *(in-domain family)* | 5-Suite Mean |
|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
| `Uncompressed` *(upper bound)* | — | — | 0.6176 | 0.8775 | 0.6700 | 0.6647 | **0.7217** | **0.7074** | 1.0000 | 0.7660 |
| **`Tamarillo/prompt-compressor-tiny-en`** | 32.0M | 7,999* | 0.6027 | 0.8237 | 0.5100 | 0.4663 | **0.6455** | **0.6007** | 1.0000 | 0.6805 |
| **`Tamarillo/prompt-compressor-small`** *(this model)* | 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 verified to `2,048` tokens, and Reader-QA above is evaluated on standard benchmark lengths (`<2,048` tokens).*
> **Honest reading of where baselines win & statistical caveats:**
> - **Public external benchmarks vs. custom `Agent JSON`:** At `rate=0.50`, `Tamarillo/prompt-compressor-tiny-en` (`32M`) beats `llmlingua-2-mBERT` (`178M`) on the **3-Public-EN Mean** (`0.5695` vs `0.5549`), while 17.5× larger `llmlingua-2-XLM-R-Large` (`560M`) still leads (`0.5755`). Similarly, `Tamarillo/prompt-compressor-small` (`141M`) beats `mBERT` on the **4-Public Mean** (`0.5301` vs `0.5180`, led by #1 on `XQuAD` `0.5092`) and trails 4× larger `XLM-R-Large` (`0.5371`) by `0.0070`, while trailing `mBERT` across the 3 public English-only suites (`0.5371` vs `0.5549`). The `#1` 5-suite mean (`small` `0.6221` vs `XLM-R-Large` `0.6037` / `mBERT` `0.5597`) and 4-EN mean (`tiny-en` `0.6746`, `small` `0.6503` vs `XLM-R-Large` `0.6491` / `mBERT` `0.5979`, in `eval_5suite_reader_qa.json`) are substantially lifted by `Agent JSON` (`0.9900` vs `0.7267` / `0.8700`), which shares the JSON tool-log domain family seen in training.
> - **At `rate=0.65` (1.5× compression):** 4×–17.5× larger **`llmlingua-2-XLM-R-Large` (`560M`) leads overall** (`0.6366` 4-Public / `0.6685` 3-Public-EN), driven by `GSM8K` (`0.5400`) and `SQuAD-v2` (`0.8460`), while `llmlingua-2-mBERT` leads `HotpotQA` (`0.6488`). `Tamarillo/prompt-compressor-small` remains #1 on `XQuAD` (`0.5584`), and `tiny-en` remains competitive on `GSM8K` (`0.5100` vs `mBERT` `0.3600`).
> - **Sample size & single reader:** Each suite contains `n=100–150` examples (`n=24` per language on `XQuAD`, where per-language breakdowns were not logged separately) evaluated with a single 3.8B reader (`microsoft/Phi-4-mini-instruct`) without bootstrap confidence intervals. Narrow `~0.5–1.5 pt` gaps (e.g., `SQuAD-v2` `tiny-en` `0.8065` vs `mBERT` `0.7994` vs `small` `0.7982`) fall within sampling noise.
---
## Table 3: ONNX Exports, Parity Gates & Same-Machine 4-Thread CPU Latency
All latencies measured on the **same x86-64 CPU host VM** (`onnxruntime` `CPUExecutionProvider`, `intra_op_num_threads=4`, `ORT_ENABLE_ALL`, `bs=1`, `p50` median ms) on a Google Cloud `a2-highgpu-1g` VM against an identically exported **FP32 ONNX** of `microsoft/llmlingua-2-bert-base-multilingual-cased-meetingbank` (which must chunk inputs `>512` tokens into `2×512` at 1,024 tok and `4×512` at 2,048 tok).
| Export Artifact | Size | Short Parity (Agree / Top-50 Jaccard / Δmax) | 2,048-Tok 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) | 85.9 ms | 195.7 ms | 556.8 ms | 1764.6 ms |
| FP16 (`onnx/model_fp16.onnx`) | 268.7 MB | 1.0000 / 1.0000 (Δ≤0.0009) | 1.0000 / 1.0000 (Δ≤0.0009) | 103.3 ms | 226.0 ms | 666.5 ms | 2219.1 ms |
| Gather-INT8 (`onnx/model_quantized.onnx`) | 255.9 MB | 1.0000 / 1.0000 (Δ≤0.0030) | 1.0000 / 0.9922 (Δ≤0.0039) | 87.4 ms | 201.8 ms | 572.3 ms | 1752.4 ms |
| *Baseline:* `llmlingua-2-mBERT` FP32 *(512-tok chunked)* | 676.8 MB | — | — | 123.2 ms | 276.7 ms | 547.5 ms *(2×512)* | 1092.5 ms *(4×512)* |
**Apples-to-apples latency & size notes:** On apples-to-apples FP32 ONNX, `small` (`537.0 MB`) is `1.26×` smaller than `llmlingua-2-mBERT` (`676.8 MB`), `1.43×` faster at 256 tokens (`85.9 ms` vs `123.2 ms`), `1.41×` faster at 512 tokens (`195.7 ms` vs `276.7 ms`), near parity at 1,024 tokens single-pass (`556.8 ms` vs `547.5 ms` 2×512 chunked), and slower at 2,048 tokens single-pass (`1764.6 ms` vs `1092.5 ms` 4×512 chunked) due to quadratic global-attention layers; chunking `small` into 512-token windows brings 2,048-token CPU latency down to `~783 ms` (`1.40×` faster than `mBERT`).
**Withheld precisions (strict parity enforcement):**
- **Full-INT8 (`Gather+MatMul`) dynamic quantization: withheld** — dynamic `MatMul` quantization degrades ModernBERT RoPE/GeGLU attention logits below our strict parity gate.
---
## Quickstarts
### 1. Drop-In Python Helper (`tamarillo-guardrails`, PyTorch or Zero-PyTorch ONNX)
Matches `LLMLingua`'s `compress_prompt()` return schema without `microsoft/LLMLingua`'s hardcoded 6-model allowlist or 512-token truncation (`transformers>=4.48.0` required for `ModernBertForTokenClassification`):
```bash
# PyTorch backend:
pip install "transformers>=4.48.0" torch "git+https://github.com/duoi-bt/tamarillo-guardrails.git"
# Or zero-PyTorch ONNX Runtime backend:
pip install "transformers>=4.48.0" onnxruntime huggingface_hub "git+https://github.com/duoi-bt/tamarillo-guardrails.git"
```
```python
from tamarillo_guardrails import TamarilloPromptCompressor
# Use PyTorch (default) or pass onnx_filename="onnx/model_quantized.onnx" for zero-PyTorch ONNX CPU:
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"])
```
### 2. Standalone PyTorch (`transformers>=4.48.0`)
```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 so unspaced scripts (e.g., zh) compress character-by-character while spaced scripts stay word-aligned
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 " ".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))
```
### 3. 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 so unspaced scripts (e.g., zh) compress character-by-character while spaced scripts stay word-aligned
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(" ".join([w for w, s in word_scores if s >= thr][:k]))
```
### 4. Browser / Node.js (`@huggingface/transformers` / Transformers.js)
Loads `onnx/model_quantized.onnx` (`255.9 MB` Gather-INT8, 100.0% token parity) or `onnx/model_fp16.onnx` (`268.7 MB`) directly in WebAssembly or WebGPU using **rate-based top-k subword-token retention** (note: filters subword tokens directly rather than word units, so outputs may differ slightly from Python word-aligned snippets):
```bash
npm install @huggingface/transformers
```
```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 contentTokens = [];
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))));
contentTokens.push({ id: ids[i], pKeep });
}
const k = Math.max(1, Math.min(contentTokens.length, Math.round(contentTokens.length * rate)));
const thr = [...contentTokens.map((t) => t.pKeep)].sort((a, b) => b - a)[k - 1];
const keptIds = contentTokens.filter((t) => t.pKeep >= thr).slice(0, k).map((t) => t.id);
console.log(tokenizer.decode(keptIds, { skip_special_tokens: true }));
```
---
## 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, 1,833-language Gemma-2 tokenizer) on the full multilingual [`Tamarillo/prompt-compression-corpus-2026`](https://huggingface.co/datasets/Tamarillo/prompt-compression-corpus-2026) v3 (`840` raw + stitched multi-document long-context examples = `1124` training docs up to `3,584` tokens; `120` validation docs). Training uses label-smoothed BCE (`ε=0.02`) + intra-document hard-negative pairwise ranking (`margin=0.6`, weight `0.25`) + cosine LR schedule (`lr=4.5e-5`, 6 epochs) so token keep probabilities rank cleanly across arbitrary compression ratios. Checkpoint selected strictly on validation token metrics (`step 150`, `val_tok_auc=0.8829`, `val_tok_f1=0.8711` — never test scores).
**Corpus quality & provenance notes (`Tamarillo/prompt-compression-corpus-2026` v3):**
- **Upstream dataset license tags & provenance nuance:** All upstream Hugging Face dataset repositories used in v3 carry permissive HF license tags (`Apache-2.0`: `oasst2`, `aya`, synthetic `agent_json_log`; `MIT`: `PubMedQA`, `UltraChat`, `CNN/DailyMail`; `CC0-1.0`: `BillSum`), avoiding `MeetingBank`'s explicit `CC-BY-NC-SA-4.0`. However, commercial deployers should note that underlying upstream source rights (e.g., original publisher news copyrights in `CNN/DailyMail` and upstream synthetic LLM generation terms in `UltraChat`) may extend beyond Hugging Face repo metadata tags.
- **Zero positional truncation bias:** Every synthetic chunk (`<=120` words, `max_new_tokens=240`, generated by Apache-2.0 `Qwen/Qwen3-8B` / `Qwen/Qwen3-14B`) passed strict EOS verification and fuzzy-stem LCS alignment, yielding a flat 10-decile keep-rate across document positions (`[0.5265, 0.5116, 0.5418, 0.5529, 0.5588, 0.5620, 0.5580, 0.5508, 0.5309, 0.5322]`, spread `<=0.05`).
- **Validation-selected checkpoints only:** Test benchmarks (`HotpotQA`, `SQuAD-v2`, `GSM8K`, `XQuAD`, `Agent JSON`) were never touched during training or checkpoint selection.
---
## Limitations & Responsible Use
- **Long-context CPU scaling (>1,024 tokens) & English-only trade-off:** Single-pass global attention over 2,048 tokens on 4-thread CPU takes `1764.6 ms` (`1752.4 ms` INT8), which is slower than 4×512 chunked `llmlingua-2-mBERT` (`1092.5 ms`). If sub-second CPU latency matters on 2K+ token documents without needing cross-document attention, chunk inputs at 512–1,024 tokens (`~783 ms` for 4×512). For purely English prompts, prefer `Tamarillo/prompt-compressor-tiny-en` (`32M`, `3-Public-EN=0.5695` vs `small` `0.5371` @ `0.50×`, `735.5 ms` @ 2K single-pass).
- **Compact training corpus size:** Fine-tuned on `840` raw (`1124` stitched) EOS-verified documents from `Tamarillo/prompt-compression-corpus-2026` v3 across 7 domains; specialized out-of-domain formats (e.g., dense source code diffs, medical tables, legal contracts) should be validated before production use.
- **Untested >2K–8K long-context QA extrapolation:** While the ModernBERT architecture supports up to `8,192` tokens, training examples cap at `3,584` tokens, ONNX parity/latency verification stops at `2,048` tokens, and our Reader-QA suites evaluate standard lengths (`<2,048` tokens). Users relying on `3.5K–8K` single-pass compression should benchmark on their own long-context inputs first.
- **Aggressive compression (`rate <= 0.50`) on arithmetic & dense multi-hop reasoning:** Deleting 50% of tokens removes some numeric constraints or multi-hop bridge clauses (`GSM8K` drops from `0.6700` uncompressed to `0.2400` at `0.50×`, recovering to `0.4600` at `0.65×`). For math, legal, or exact-quote tasks, prefer `rate=0.65–0.75` and/or `force_reserve_digit=True`.
- **Extractive telegraphic output:** Like LLMLingua-2, this model performs extractive token/word deletion (`DROP`/`KEEP`) rather than abstractive rewriting. Compressed prompts are optimized for downstream LLM comprehension and token-cost reduction, not human prose readability.
- **Not a security filter:** Prompt compression reduces context length and cost; it does not defend against prompt injection or redact PII. Pair with dedicated runtime guardrails (`Tamarillo/injection-span-guard-*`, `Tamarillo/pii-secrets-guard-*`, `Tamarillo/groundedness-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` | Parity-verified FP32 ONNX export (`537.0 MB`, opset 17) |
| `onnx/model_fp16.onnx` | Parity-verified FP16 ONNX export (`268.7 MB`, browser/WASM & edge ready) |
| `onnx/model_quantized.onnx` | Parity-verified Gather-INT8 ONNX export (`255.9 MB`) |
| `eval_5suite_reader_qa.json` | Full 5-suite frozen `Phi-4-mini-instruct` Reader-QA & baseline CPU ONNX benchmark results |
| `onnx_benchmark.json` | Short & 2,048-token ONNX parity verification and 4-length x86-64 CPU latency benchmarks |
| `training_summary.json` | Validation trajectory and checkpoint selection record |
| `assets/pareto.svg` | 2-panel public-benchmarks Reader-QA Pareto frontier chart (size & FP32 CPU latency) |
| `scripts/train_and_eval_pc.py` | End-to-end training, soft-logit distillation & ONNX parity export script |
| `scripts/eval_pc_5suite.py` | 5-suite zero-touch Reader-QA & same-machine CPU ONNX evaluation harness |
| `scripts/synth_v3_selfgated.py` | Self-gating EOS-verified flat-decile corpus synthesis script (`Qwen/Qwen3-8B`) |
| `scripts/synth_corpus_v3_clean.py` | Fresh multi-domain source collector & decile-balance helper |
| `scripts/synth_corpus_v2.py` | Held-out evaluation hash deduplication helper |
| `scripts/synth_corpus_2026.py` | LCS extractive alignment, chunking & token-F1 utility module |
---
## Citation
```bibtex
@misc{tamarillo_prompt_compressor_2026,
title = {Tamarillo/prompt-compressor-small: Apache-2.0 Extractive Prompt Compression},
author = {Tamarillo Open-Model Lab},
year = {2026},
publisher = {Hugging Face},
howpublished = {\url{https://huggingface.co/Tamarillo/prompt-compressor-small}}
}
```