/ Модель

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

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

prompt-complexity-router-small

Классификация текстаТекст → label
137скачиваний за 30 дней0лайковвеса обновлены26 ноя 2026

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

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

Мультиязычный классификатор оценивает сложность запросов и направляет их к сильной или более экономичной языковой модели.

Tamarillo разработала prompt-complexity-router-small — мультиязычный классификатор сложности запросов для маршрутизации обращений между сильными и более экономичными языковыми моделями. Модель дообучена на базе jhu-clsp/mmBERT-small и использует архитектуру ModernBERT с головой классификации последовательностей; в ней около 140,5 млн параметров. Она выдаёт один из трёх классов: запрос требует сильной модели, занимает промежуточное положение или подходит для более слабой модели. Модель рассчитана на стандартный интерфейс Transformers AutoModelForSequenceClassification и может использоваться для оптимизации стоимости и нагрузки в системах RouteLLM.

Модель поддерживает 15 языков, включая русский, английский, китайский, испанский, французский, немецкий, японский и другие. Контекст модели имеет нативную длину 8192 токена, однако обучение и длинноконтекстные оценки проводились до 2048 токенов. Репозиторий содержит веса Safetensors и ONNX; лицензия — Apache-2.0. В README приведены результаты сравнительных оценок и варианты развёртывания на CPU, GPU и в браузере.

Ограничения включают снижение надёжности на наборах, состоящих только из сложных исследовательских запросов, и более высокую задержку на коротких запросах GPU по сравнению с некоторыми базовыми моделями. Точность на входах длиннее 2048 токенов не оценивалась; рабочий порог маршрутизации рекомендуется калибровать под конкретную пару моделей и структуру затрат.

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

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

Ограничения

Обучение и длинноконтекстные оценки охватывали запросы до 2048 токенов; точность на более длинном контексте не оценивалась. На наборах только со сложными исследовательскими запросами модель уступает некоторым базовым классификаторам, а порог маршрутизации следует калибровать под выбранную пару моделей.

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

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

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

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

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

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

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

Открыть на Hugging Face

Tamarillo/prompt-complexity-router-small

Balanced Multilingual RouteLLM Drop-In Tier (141M) — an Apache-2.0, 2,048-token-trained (8,192-token native RoPE), zero-trust_remote_code prompt complexity & cost-routing classifier designed as a 1-line drop-in replacement for routellm/bert_gpt4_augmented (BERTRouter in lm-sys/RouteLLM) and a clean, standard AutoModelForSequenceClassification complexity-score alternative to nvidia/prompt-task-and-complexity-classifier.

Key Highlights: 2.0× smaller than routellm/bert_gpt4_augmented (278.1M) and 24% smaller than nvidia/prompt-task-and-complexity-classifier (183.9M), delivering 0.875 Public OOD 2-Suite Mean ROC-AUC (+9.4pp over routellm 0.781, +13.8pp over nvidia 0.737), 0.946 AUC / 0.700 TPR@5%FPR on length-matched Multilingual OOD (+26.8pp AUC over routellm), #1 Macro-F1 (0.847) and 0.718 TPR@5%FPR on Length-Inverted OOD, #1 Arena-55k real human-battle APGR (0.4918 / +4.57pp vs. routellm 0.4912 / +4.51pp) at half the parameter count, and 26.45 ms p50 on x86 CPU @ 64 tok (537.0 MB FP32 ONNX; 268.7 MB FP16 ONNX).

Public OOD 2-Suite Pareto Frontier


Model Family & Recommended Tier

Interactive browser WASM demo (running tiny-en locally): Hugging Face Space Tamarillo/prompt-complexity-router-demo (published alongside this model family).

ModelBackboneParamsLangsLength-Inv OOD (AUC / T5)Multilingual OOD (AUC / T5)Public OOD-2 MeanA100 @ 64 tokCPU FP32 @ 64 tokFP16 ONNX
Tamarillo/prompt-complexity-router-tiny-enjhu-clsp/ettin-encoder-32m32.0MEnglish0.791 / 0.6950.498 / 0.0050.64512.2 ms9.91 ms61.3 MB
Tamarillo/prompt-complexity-router-small (this repo)jhu-clsp/mmBERT-small140.6MMultilingual0.805 / 0.7180.946 / 0.7000.87525.2 ms26.45 ms268.7 MB
Tamarillo/prompt-complexity-router-basejhu-clsp/mmBERT-base307.5MMultilingual0.828 / 0.7480.952 / 0.7950.89028.0 ms52.82 ms587.0 MB

30-Second Quickstart (PyTorch / Transformers)

pip install "transformers>=4.48,<5" torch
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer

repo_id = "Tamarillo/prompt-complexity-router-small"
tokenizer = AutoTokenizer.from_pretrained(repo_id)
model = AutoModelForSequenceClassification.from_pretrained(repo_id).eval()

prompts = [
    "What is the capital of Portugal?",
    "Implement a lock-free MPMC ring buffer in Rust with acquire-release orderings and prove ABA safety.",
]

inputs = tokenizer(prompts, padding=True, truncation=True, max_length=2048, return_tensors="pt")
with torch.no_grad():
    probs = torch.softmax(model(**inputs).logits, dim=-1)

for text, p in zip(prompts, probs.tolist()):
    p_strong = p[0]                  # Exact RouteLLM BERTRouter score: 1 - (p[1] + p[2])
    complexity = p[0] + 0.5 * p[1]   # Continuous complexity score in [0, 1]
    tier = "FRONTIER" if p_strong >= 0.30 else "FAST"
    print(f"{tier:8s} | P(STRONG)={p_strong:.3f} | S={complexity:.3f} | {text[:72]}")

Exact 1-Line Drop-In for lm-sys/RouteLLM (BERTRouter)

lm-sys/RouteLLM's BERTRouter expects a 3-class AutoModelForSequenceClassification where label 0 is strong-model-needed, 1 is tie/moderate, and 2 is weak-model-sufficient, computing 1 - (softmax[1] + softmax[2]) == softmax[0] and respecting tokenizer.model_max_length (set to 2048 in this checkpoint — automatically unlocking 4× longer multi-turn routing context inside unmodified BERTRouter).

Dependency note: ModernBERT/mmBERT/Ettin architectures require transformers>=4.48,<5. If your routellm environment pins an older transformers, upgrade transformers (pip install -U "transformers>=4.48,<5"). On PyTorch 2.4.x + CUDA with padded >512-token batches, pass attn_implementation="eager" when loading directly via transformers.

from routellm.routers.routers import BERTRouter

router = BERTRouter(checkpoint_path="Tamarillo/prompt-complexity-router-small")
win_rate = router.calculate_strong_win_rate(
    "Design a Raft consensus state machine with log compaction and joint-consensus membership changes."
)
route_to_strong = win_rate >= 0.30  # Calibrate threshold to your model pair & cost budget

ONNX Runtime (CPU / Edge)

pip install onnxruntime transformers huggingface_hub numpy
import numpy as np
import onnxruntime as ort
from huggingface_hub import hf_hub_download
from transformers import AutoTokenizer

repo_id = "Tamarillo/prompt-complexity-router-small"
tok = AutoTokenizer.from_pretrained(repo_id)
onnx_path = hf_hub_download(repo_id=repo_id, filename="onnx/model.onnx")  # 26.45 ms CPU @ 64 tok (537.0 MB); or "onnx/model_fp16.onnx" (268.7 MB)
sess = ort.InferenceSession(onnx_path, providers=["CPUExecutionProvider"])

enc = tok(["Prove that there are infinitely many primes congruent to 3 mod 4."], padding=True, truncation=True, max_length=2048, return_tensors="np")
logits = sess.run(None, {"input_ids": enc["input_ids"].astype(np.int64), "attention_mask": enc["attention_mask"].astype(np.int64)})[0]
ex = np.exp(logits - logits.max(axis=-1, keepdims=True))
probs = ex / ex.sum(axis=-1, keepdims=True)
print("P(STRONG):", round(float(probs[0, 0]), 4), "| Complexity S:", round(float(probs[0, 0] + 0.5 * probs[0, 1]), 4))

Deployment note: small FP16 ONNX is 268.7 MB — recommended for server-side CPU/GPU routing. For lightweight client-side browser WASM (61.3 MB FP16), use Tamarillo/prompt-complexity-router-tiny-en.


Label Schema & Budget-Control Calibration

Class IDLabelRouting Interpretation
0STRONG_MODEL_NEEDEDComplex reasoning, multi-step math/coding, technical design, or strict multi-constraint tasks where frontier models yield major gains.
1MODERATE_TIEIntermediate complexity or tie zone — route dynamically based on latency/cost budget (τ).
2WEAK_MODEL_SUFFICIENTSimple factual Q&A, casual chat, basic translation, or straightforward summarization/extraction (even on long passages).
  • RouteLLM Score: P(STRONG) = probs[0] = 1 - (probs[1] + probs[2])
  • Continuous Complexity Proxy: S = probs[0] + 0.5 * probs[1] ∈ [0, 1]
  • Validation-Set Reference Thresholds (calibration.json): temperature = 0.9512, validation ECE on P(STRONG) = 0.0523. Reference strong-tier traffic quantiles on our balanced validation set: 25% strong budget τ = 0.669, 50% strong budget τ = 0.299, 75% strong budget τ = 0.111. Because OOD traffic distributions and 2026 model-pair capability gaps differ from our validation mixture, treat outputs as monotonic difficulty proxies and re-calibrate τ on a small sample of your own traffic and model pair.

Benchmarks (Identical NVIDIA A100-SXM4-40GB Evaluation)

All 7 models were evaluated head-to-head on identical frozen splits with strict SHA-256 prompt-hash deduplication guaranteeing zero prompt overlap between any train/validation row and any evaluation suite. Full dataset construction and evaluation scripts are bundled in this repository: scripts/build_data_v2.py and scripts/eval_router_suite.py. Bold values mark the highest score in each column.

1. Public OOD 2-Suite Benchmark (100% Unmodified Public, Dataset-Disjoint — Headline Pareto Metric)

  • ood_length_inverted (n=1,200, 50/50): Short complex prompts (google/frames-benchmark, openai/gsm8k test, bigcode/humanevalpack) vs. simple prompts including long news summarization (basicv8vc/SimpleQA, abisee/cnn_dailymail test 1,200–3,200 chars). Character length is inverted (length-heuristic = 0.301 AUC).
  • ood_multilingual_mgsm_aya (n=400, 50/50, length-matched within ±80 chars): Complex non-English math (juletxara/mgsm test across 10 languages: es, fr, de, ru, zh, ja, th, sw, bn, te) vs. non-English general chat (CohereLabs/aya_evaluation_suite). Length-matched so length-heuristic stays near chance (0.538 AUC). (Note: domain difference between math and general chat still contributes alongside difficulty; see zero-topic-confounding heldout_arena140k_non_en below for same-distribution multilingual complexity.)
ModelParamsContextLicenseLength-Inverted OOD (AUC / F1@0.5 / T5)Multilingual OOD (AUC / F1@0.5 / T5)Public OOD-2 Mean
Tamarillo tiny-en32.0M2,048 (8K RoPE)Apache-2.00.791 / 0.808 / 0.6950.498 / 0.458 / 0.0050.645
Tamarillo small140.6M2,048 (8K RoPE)Apache-2.00.805 / 0.847 / 0.7180.946 / 0.843 / 0.7000.875
Tamarillo base307.5M2,048 (8K RoPE)Apache-2.00.828 / 0.844 / 0.7480.952 / 0.837 / 0.7950.890
routellm/bert_gpt4_augmented278.1M512 input (514 pos)Unknown0.884 / 0.757 / 0.5450.678 / 0.589 / 0.1050.781
nvidia/prompt-task-and-complexity-classifier183.9M512 inputOther0.777 / 0.333 / 0.6230.697 / 0.333 / 0.2850.737
MoritzLaurer/deberta-v3-base-zeroshot-v2.0184.4M512 inputMIT0.588 / 0.492 / 0.1530.235 / 0.316 / 0.0050.411
Character-Length Heuristic0.0MUnlimited—0.301 / 0.180 / 0.0000.538 / 0.513 / 0.0600.420

2. Synthetic 2K Long-Context Diagnostic, Held-Out 2025 Arena-140K, Real Battle APGR (Arena-55k), & AutoBench-2026

  • ood_long_multiturn_2k (n=300, 50/50 — Synthetic Long-Context Stress Diagnostic, NOT in Public OOD-2 headline): Constructed from disjoint slices (indices 200..250/200..350) of google/frames-benchmark, openai/gsm8k test, bigcode/humanevalpack vs. basicv8vc/SimpleQA, prefixed with 4,800–6,200 chars of neutral multi-turn context (scripts/build_data_v2.py). Directly tests truncation past 512 tokens; note that this synthetic prefix structure mirrors training augmentation #4 and mechanically forces 512-token baselines near chance.
  • heldout_arena140k_en (n=2,400) & heldout_arena140k_non_en (n=1,800, 15+ languages): Prompt-hash-disjoint held-out splits from lmarena-ai/arena-human-preference-140k (2025 Chatbot Arena user prompts scored on LMSYS's 7-criteria Arena-Hard complexity rubric 0..7, zero topic confounding). Important caveat: Tamarillo was trained on disjoint prompts using this exact criteria_v0.1 rubric, whereas baseline models were not.
  • heldout_arena55k_battles (n=2,500): Held-out strong-vs-weak real human battles from lmarena-ai/arena-human-preference-55k, scored with exact RouteLLM BERTRouter formula (P(STRONG)) using Cost-Quality APGR (Average Performance Gain Ratio vs. oracle, plus percentage-point gain over random routing across budgets 10%–90%).
  • ood_autobench_2026 (n=252, AutoBench/router-benchmark-2026-10, October 2026): 252 long, open-ended research questions evaluated across 2026 frontier models (Claude-sonnet-5, Gpt-5.6-sol, Qwen3.8-max, Grok-4.6, GLM-5.3, Grok-4.3) vs. fast/cheap models (Qwen3.5-9b, Deepseek-v4-flash-0731, Nemotron-3.5-lightning, Gpt-oss-120b, Gemma-4-31b-it).
ModelParams2K Multi-Turn Diagnostic (AUC / T5)Held-Out Arena-140K EN (AUC / ρ)Held-Out Arena-140K Non-EN (AUC / ρ)Arena-55k Human APGR (vs. Rand)AutoBench-2026 All-Hard Tail (AUC / ρ / APGR)
Tamarillo tiny-en32.0M0.881 / 0.7200.938 / 0.7210.837 / 0.5290.4801 (+3.27pp)0.502 / -0.002 (+2.77pp)
Tamarillo small140.6M0.901 / 0.7000.942 / 0.7360.942 / 0.7230.4918 (+4.57pp)0.508 / +0.010 (+2.93pp)
Tamarillo base307.5M0.896 / 0.7270.948 / 0.7440.949 / 0.7320.4858 (+3.91pp)0.527 / +0.044 (+3.41pp)
routellm/bert_gpt4_augmented278.1M0.489 / 0.0530.686 / 0.2370.671 / 0.2130.4912 (+4.51pp)0.502 / +0.002 (+2.05pp)
nvidia/prompt-task-and-complexity-classifier183.9M0.521 / 0.0530.760 / 0.4050.780 / 0.4380.4553 (+0.53pp)0.624 / +0.158 (+2.75pp)
MoritzLaurer/deberta-v3-base-zeroshot-v2.0184.4M0.525 / 0.0670.523 / 0.0330.571 / 0.1210.4321 (-2.05pp)0.620 / +0.215 (+6.30pp)
Character-Length Heuristic0.0M0.657 / 0.2070.804 / 0.4670.760 / 0.4160.4455 (-0.56pp)0.607 / +0.163 (+4.52pp)

Evaluation protocol notes:

  • routellm/bert_gpt4_augmented scored using exact BERTRouter formula 1 - (softmax[1] + softmax[2]) == softmax[0] at its 512-token input cap (max_position_embeddings=514).
  • nvidia/prompt-task-and-complexity-classifier scored using its official README.md CustomModel ("Prompt: " prefix, exact 6-head weighted prompt_complexity_score, number_of_few_shots >= 0.05 clamp, 512-token input cap). Because NVIDIA's continuous complexity score is not calibrated around a 0.50 binary cutoff (giving 0.333 F1@0.50), always evaluate its threshold-free ROC-AUC and TPR@5%FPR alongside F1.
  • MoritzLaurer/deberta-v3-base-zeroshot-v2.0 scored via entailment probability for the hypothesis: "This user prompt is complex and requires an advanced frontier reasoning model rather than a small fast model."

ONNX Parity & Latency Benchmarks

Hardware: GPU = NVIDIA A100-SXM4-40GB (bs=1, median over 20 runs); CPU = GCP a2-highgpu-1g (Intel Xeon Cascade Lake @ 2.20 GHz, AVX-512, 4 ORT threads) (bs=1, ORT_SEQUENTIAL, median p50 ms).

ArtifactFile SizeShort Parity (Agree / Max Δp)2,048-Tok Parity (Agree / Max Δp)CPU p50 @ 64 tokCPU p50 @ 256 tokCPU p50 @ 512 tokCPU p50 @ 1024 tok
onnx/model.onnx (FP32)537.0 MB100.0% / 0.00000100.0% / 0.0000026.45 ms86.24 ms193.50 ms547.62 ms
onnx/model_fp16.onnx (FP16)268.7 MB100.0% / 0.00040100.0% / 0.0000631.08 ms102.80 ms220.33 ms653.21 ms
  • GPU Latency (Tamarillo/prompt-complexity-router-small on A100-40GB, bs=1 p50): 64 tok = 25.17 ms | 512 tok = 25.69 ms | 2,048 tok = 46.42 ms.
  • Dynamic INT8 intentionally omitted: Selective dynamic INT8 was tested and automatically discarded because max_abs_prob_diff (0.103) exceeded our strict <= 0.08 probability parity gate.

Training Recipe & Commercially Permissive Data Provenance

Trained for 2 epochs at max_length=2048 on 64,109 prompt-deduplicated examples (val=3,000; validation-only checkpoint selection with EMA 0.996) using sample-weighted soft cross-entropy + 1D ordinal Wasserstein/EMD loss (penalizing STRONG <-> WEAK inversions 2× more than adjacent MODERATE shifts). Every training source carries a commercially permissive license:

  1. lmarena-ai/arena-human-preference-140k (CC-BY-4.0, 2025): Real multilingual Chatbot Arena prompts mapped via LMSYS's 7-criteria Arena-Hard complexity rubric (criteria_v0.1: >=6/7 or 5/7 with complexity + problem_solving -> 0, 3–4/7 -> 1, <=2/7 -> 2).
  2. lmarena-ai/arena-human-preference-55k (Apache-2.0) & routellm/gpt4_judge_battles (Apache-2.0): Real strong-vs-weak human battles and GPT-4-judged battles strictly class-balanced 1:1:1 per source to eliminate source-to-label confounding.
  3. 100% Disjoint Anti-Length Anchors (4,000 rows, balanced 50/50): Short complex (qwedsacf/competition_math MIT + google-research-datasets/mbpp CC-BY-4.0) vs. long simple summarization/extraction (FiscalNote/billsum CC0-1.0, sentence-sliced to 1,400–3,000 chars).
  4. Symmetric 2K Multi-Turn Augmentation (4,000 rows, balanced 50/50): Balanced Class 0 and Class 2 prompts prefixed with 3,600–5,800-char varied neutral multi-turn agent transcripts so the router attends to the true task past token 1,000.

Honest Limitations & Where Baselines Win

  1. Length-Inverted Raw AUC, Short-Prompt GPU Latency, & Real Battle APGR (routellm/bert_gpt4_augmented wins): On ood_length_inverted (n=1,200), routellm/bert_gpt4_augmented achieves higher raw ROC-AUC (0.884 vs. Tamarillo 0.791–0.828), although Tamarillo leads substantially on default-threshold Macro-F1 (0.808–0.847 vs. 0.757) and high-precision TPR@5%FPR (0.695–0.748 vs. 0.545). On heldout_arena55k_battles real human-battle APGR, Tamarillo small (0.4918) edges out routellm (0.4912), while both Tamarillo tiny-en (0.4801) and Tamarillo base (0.4858) slightly trail routellm. On short <=512-token prompts on A100 GPU, routellm (8.1–8.7 ms) is also faster than small/base (25.2–28.0 ms) because XLM-RoBERTa has 12 layers vs. ModernBERT/mmBERT's 22 layers (while truncating everything past 512 input tokens).
  2. All-Hard Research Tail Ceiling (ood_autobench_2026, n=252): When every incoming query is already a long, difficult research question (AutoBench/router-benchmark-2026-10), nvidia/prompt-task-and-complexity-classifier (0.624 AUC) and DeBERTa-v3 zero-shot (0.620 AUC) discriminate subtle frontier-vs-fast gaps better than both routellm (0.502) and Tamarillo (0.502–0.527), because full-spectrum routers saturate near the high-complexity ceiling.
  3. Held-Out Rubric Alignment (heldout_arena140k): Both heldout_arena140k_en and heldout_arena140k_non_en are prompt-hash-disjoint held-out splits using the same LMSYS criteria_v0.1 rubric that Tamarillo trained on (whereas baselines were not trained on that rubric). Rely on Table 1's dataset-disjoint Public OOD-2 suites and Arena-55k human-battle APGR for rubric-neutral comparisons.
  4. Not a Multi-Head Task-Type Drop-In for NVIDIA: Unlike nvidia/prompt-task-and-complexity-classifier (which uses a custom PyTorchModelHubMixin with 11 task-type classes + 6 complexity sub-dimension heads under a non-standard license), Tamarillo ships a standard 3-class AutoModelForSequenceClassification router. If you specifically need task-type classification (Brainstorming, Closed QA, Extraction, etc.), use NVIDIA's classifier or a task-specific classifier.
  5. Context Window Scope (2,048 Trained / 8,192 Native RoPE): All training and long-context evaluations were performed up to 2,048 tokens. Although the underlying ModernBERT/mmBERT/Ettin backbone supports 8,192-token RoPE, routing accuracy between 2,049 and 8,192 tokens has not been empirically evaluated.
  6. Language Scope & Pair-Specific Calibration: tiny-en is English-only (0.498 AUC on ood_multilingual_mgsm_aya); use small (0.946) or base (0.952) for multilingual workloads. Always calibrate your operating threshold τ on your specific strong/weak model pair and cost ratio rather than relying on default validation quantiles.

License & Citation

Released under the Apache-2.0 License by Tamarillo. All base models (jhu-clsp/ettin-encoder-32m MIT, jhu-clsp/mmBERT-{small,base} Apache-2.0) and training corpora carry commercially permissive licenses (CC-BY-4.0, Apache-2.0, MIT, CC0-1.0).

@misc{tamarillo_prompt_complexity_router_2026,
  title        = {Tamarillo Prompt Complexity Router: Apache-2.0 2K-Context Multilingual LLM Cost-Routing Classifiers},
  author       = {Tamarillo Open-Model Lab},
  year         = {2026},
  howpublished = {\url{https://huggingface.co/Tamarillo/prompt-complexity-router-small}},
  license      = {Apache-2.0}
}

Gather-INT8 Quantized ONNX (onnx/model_quantized.onnx — 255.91 MB, 2.1x smaller)

  • Verified Parity (onnx/quantization_check.json): 100.0% prediction agreement vs. FP32 ONNX (mean abs probability diff 0.0012, max 0.00349; 76.02 ms 4-thread CPU p50 @ 256 tokens).
  • Browser WASM / Node.js (@huggingface/transformers v3): pass { dtype: "q8" } to load onnx/model_quantized.onnx automatically.

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

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

GPU в ailist

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

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

Подбираем GPU…

Класс архитектуры
ModernBertForSequenceClassification
Ревизия весов
1b561e2

0 моделей