Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(tokenizers): resolve HF tokenizer names by most-specific prefix (#2096)

Abhay Singhe0232df9b42b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 177c60446..5f13d5018 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -102,6 +102,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug Fixes
+* **tokenizers:** resolve HuggingFace tokenizer names by the most-specific prefix. `get_tokenizer_name` scanned `MODEL_TO_TOKENIZER` in dict-insertion order and returned the first key the model merely starts with, so a short family key shadowed a more-specific one — `qwen2-7b-instruct` matched `qwen` before `qwen2`/`qwen2-7b` and resolved to the Qwen1 tokenizer (a different vocabulary, hence wrong token counts); `qwen2.5-*` and `deepseek-v2.x` were mis-resolved the same way. It now picks the longest matching prefix, mirroring the order-dependent-prefix guard the sibling tiktoken `get_encoding_for_model` already documents.
* **pricing:** map retired `claude-3-sonnet-20240229` to a Sonnet-tier price instead of Haiku. When LiteLLM's cost DB lacks the retired model, resolution falls through to `MODEL_ALIASES`, which pointed Claude 3 Sonnet (a $3/$15-per-1M model) at `claude-3-haiku-20240307` ($0.25/$1.25) — a different tier that underpriced every cost/savings figure for that model ~12x on both input and output. It now aliases to `claude-sonnet-4-20250514`, the same-price target the other retired-Sonnet aliases already use.
* **cache/semantic:** don't evict an unrelated entry when re-storing a key that is already cached. `SemanticCache.put` ran its at-capacity eviction loop before computing the entry's key, so overwriting a key that was already present (a duplicate or retried store) still evicted the LRU-oldest distinct entry even though an in-place update grows nothing. That silently dropped a live entry and turned a later lookup for it into a false cache miss. The key is now computed first and the eviction loop only runs when the key is genuinely new (mirroring `CompressionCache.store_compressed`, which deletes-then-inserts).
* **tokenizers:** stop `TiktokenCounter.count_messages` from exploding on non-text content blocks. Its multi-part branch handled only `text` and OpenAI `image_url`; every other shape (Anthropic `image`/`tool_result`/`tool_use`, Strands blocks) fell through to `count_text(str(part))`, which json-stringified the base64 payload and tokenized it as text — a 1MB image counted as ~330K phantom tokens (~218x overcount in a standalone repro), corrupting every downstream budgeting/compression decision for multimodal OpenAI-model requests. Unknown block shapes now delegate to the base `_count_content_parts`, which prices images/documents by a bounded estimate (the overcount that helper already exists to prevent).
diff --git a/headroom/tokenizers/huggingface.py b/headroom/tokenizers/huggingface.py
index 718ee940a..c48c16474 100644
--- a/headroom/tokenizers/huggingface.py
+++ b/headroom/tokenizers/huggingface.py
@@ -204,10 +204,15 @@ def get_tokenizer_name(model: str) -> str:
if model_lower in MODEL_TO_TOKENIZER:
return MODEL_TO_TOKENIZER[model_lower]
- # Try prefix matching
- for key, value in MODEL_TO_TOKENIZER.items():
+ # Try prefix matching, longest (most specific) key first. Scanning in
+ # dict-insertion order is wrong: a short family key like "qwen" precedes
+ # "qwen2"/"qwen2.5", so "qwen2-7b-instruct" would match "qwen" first and
+ # resolve to the Qwen1 tokenizer (a different vocabulary -> wrong counts).
+ # The sibling tiktoken resolver (get_encoding_for_model) documents and
+ # guards this exact order-dependent pitfall.
+ for key in sorted(MODEL_TO_TOKENIZER, key=len, reverse=True):
if model_lower.startswith(key):
- return value
+ return MODEL_TO_TOKENIZER[key]
# Assume model name is the tokenizer name
return model
diff --git a/tests/test_huggingface_tokenizer_timeout.py b/tests/test_huggingface_tokenizer_timeout.py
index 8e9243ea7..8d7e8b888 100644
--- a/tests/test_huggingface_tokenizer_timeout.py
+++ b/tests/test_huggingface_tokenizer_timeout.py
@@ -16,7 +16,11 @@ from typing import Any
import pytest
from headroom.tokenizers import huggingface as hf_mod
-from headroom.tokenizers.huggingface import HuggingFaceTokenizer, _load_tokenizer
+from headroom.tokenizers.huggingface import (
+ HuggingFaceTokenizer,
+ _load_tokenizer,
+ get_tokenizer_name,
+)
@pytest.fixture(autouse=True)
@@ -112,3 +116,20 @@ def test_count_messages_fails_open_to_estimation(monkeypatch: pytest.MonkeyPatch
def test_invalid_timeout_env_falls_back_to_default(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("HEADROOM_HF_TOKENIZER_LOAD_TIMEOUT_SECS", "not-a-number")
assert hf_mod._load_timeout_secs() == hf_mod._LOAD_TIMEOUT_DEFAULT
+
+
+def test_get_tokenizer_name_prefers_most_specific_prefix() -> None:
+ """A more-specific family key must win over a shorter one.
+
+ Prefix matching used to scan MODEL_TO_TOKENIZER in dict-insertion order, so
+ the short "qwen" key preceded "qwen2"/"qwen2.5" and shadowed them —
+ "qwen2-7b-instruct" resolved to the Qwen1 tokenizer (a different vocabulary,
+ hence wrong counts). The resolver now picks the longest matching prefix.
+ """
+ # Versioned models not present as literal keys must hit the right family.
+ assert get_tokenizer_name("qwen2-7b-instruct") == "Qwen/Qwen2-7B"
+ assert get_tokenizer_name("qwen2.5-turbo") == "Qwen/Qwen2.5-7B"
+ assert get_tokenizer_name("deepseek-v2.5") == "deepseek-ai/DeepSeek-V2"
+ # Direct hits and the shorter family fallback still resolve as before.
+ assert get_tokenizer_name("qwen-14b") == "Qwen/Qwen-14B"
+ assert get_tokenizer_name("deepseek-chat") == "deepseek-ai/deepseek-llm-7b-base"