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.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(kompress): never drop words the model did not see (#4175)
François Martin421d453c4c1d
diff --git a/headroom/transforms/kompress_compressor.py b/headroom/transforms/kompress_compressor.pyindex cd23c5b5b..3cd98a241 100644--- a/headroom/transforms/kompress_compressor.py+++ b/headroom/transforms/kompress_compressor.py@@ -91,6 +91,44 @@ KOMPRESS_BACKEND_ENV = "HEADROOM_KOMPRESS_BACKEND"KOMPRESS_ONNX_FILENAME_ENV = "HEADROOM_KOMPRESS_ONNX_FILENAME"+# Tokens the model reads per chunk; the tokenizer truncates each chunk here.+_KOMPRESS_MAX_TOKENS = 512+++def _row_token_counts(word_id_rows: list[list[int | None]]) -> list[int]:+ """Real tokens per row of a padded batch, from the word ids alone.++ Padding and special tokens both map to no word, so a row's trailing run+ of ``None`` is its padding plus the special tokens every row ends with.+ The longest row has no padding, so its run is the shortest. Read from+ the word ids rather than ``attention_mask`` so the count does not depend+ on the tensor type (numpy for ONNX, torch for CUDA and MPS).+ """+ trailing = []+ for row in word_id_rows:+ n = 0+ while n < len(row) and row[-1 - n] is None:+ n += 1+ trailing.append(n)+ specials = min(trailing, default=0)+ return [len(row) - (n - specials) for row, n in zip(word_id_rows, trailing)]+++def _words_seen_whole(word_ids: list[int | None], n_tokens: int, n_words: int) -> int:+ """Count the leading words of a chunk the model saw in full.++ ``word_ids`` maps each token to its word. Truncation can stop inside a+ word, so once the chunk was cut (words are missing, or the token cap was+ hit) the last word present may be a prefix and is not counted.+ """+ seen = [wid for wid in word_ids if wid is not None]+ if not seen:+ return 0+ last = max(seen)+ cut = last + 1 < n_words or n_tokens >= _KOMPRESS_MAX_TOKENS+ return last if cut else last + 1++def _add_kompress_must_keep_words(kept_ids: set[int],chunk_words: list[str],@@ -1971,7 +2009,13 @@ class KompressCompressor(Transform):budget = _capped_time_budget(_time_budget_cap_seconds)deadline = time.monotonic() + budget if budget is not None else None- for chunk_start in range(0, n_words, max_chunk_words):+ # The model sees at most 512 tokens per chunk. A 350-word chunk of+ # URLs, code or citation markers tokenizes past that, and a word+ # beyond the cut gets no keep decision at all. Advance by the words+ # the tokenizer kept whole, so the rest start the next chunk and+ # every word is scored or kept.+ chunk_start = 0+ while chunk_start < n_words:remaining: float | None = Noneif deadline is not None:remaining = deadline - time.monotonic()@@ -2007,7 +2051,7 @@ class KompressCompressor(Transform):chunk_words,is_split_into_words=True,truncation=True,- max_length=512,+ max_length=_KOMPRESS_MAX_TOKENS,padding=True,return_tensors=return_tensors,)@@ -2015,6 +2059,14 @@ class KompressCompressor(Transform):input_ids = encoding["input_ids"]attention_mask = encoding["attention_mask"]word_ids = encoding.word_ids(batch_index=0)+ # One row, so no padding: every token in it is real.+ scored = _words_seen_whole(word_ids, len(word_ids), len(chunk_words))+ if scored == 0:+ # One word fills the window by itself (a long URL or a+ # minified line). The model cannot see it whole: keep it.+ kept_ids.add(chunk_start)+ chunk_start += 1+ continueif not is_onnx:device = next(model.parameters()).device@@ -2082,10 +2134,12 @@ class KompressCompressor(Transform):mask_list = keep_mask[0].cpu()inference_ms += (time.perf_counter() - inference_started) * 1000+ # A word past `scored` is a prefix the cut left behind: it is+ # rescored with the next chunk and must not take a slot here.if target_ratio is not None:word_scores: dict[int, float] = {}for idx, wid in enumerate(word_ids):- if wid is None:+ if wid is None or wid >= scored:continues = float(score_list[idx])if wid not in word_scores or s > word_scores[wid]:@@ -2099,7 +2153,7 @@ class KompressCompressor(Transform):kept_ids.add(wid + chunk_start)else:for idx, wid in enumerate(word_ids):- if wid is None:+ if wid is None or wid >= scored:continueif bool(mask_list[idx]):kept_ids.add(wid + chunk_start)@@ -2107,7 +2161,8 @@ class KompressCompressor(Transform):# Hard override: always keep must-keep tokens regardless of model score.# Numbers, error names, paths, and flags carry meaning agents cannot# reconstruct from context. Disable via HEADROOM_KOMPRESS_MUST_KEEP=0.- _add_kompress_must_keep_words(kept_ids, chunk_words, chunk_start)+ _add_kompress_must_keep_words(kept_ids, chunk_words[:scored], chunk_start)+ chunk_start += scoredfor i, line_id in enumerate(line_ids):if line_id in protected_line_ids:@@ -2441,13 +2496,15 @@ class KompressCompressor(Transform):batch_word_lists,is_split_into_words=True,truncation=True,- max_length=512,+ max_length=_KOMPRESS_MAX_TOKENS,padding=True,return_tensors=return_tensors,)input_ids = encoding["input_ids"]attention_mask = encoding["attention_mask"]+ word_id_rows = [encoding.word_ids(batch_index=i) for i in range(len(batch))]+ row_tokens = _row_token_counts(word_id_rows)if not is_onnx:device = next(model.parameters()).device@@ -2495,13 +2552,24 @@ class KompressCompressor(Transform):inference_ms += (time.perf_counter() - inference_started) * 1000for batch_idx, (text_idx, chunk_start, chunk_words, ratio) in enumerate(batch):- word_ids = encoding.word_ids(batch_index=batch_idx)+ word_ids = word_id_rows[batch_idx]score_list = scores[batch_idx] if is_onnx else scores[batch_idx].cpu()- # Token -> word reduction (max score per word).+ # Words past the 512-token cut, and the word the cut may+ # have split, were never scored whole. The batch is built+ # before tokenizing, so instead of re-chunking (the single+ # path does) keep them: an unscored word is not a word the+ # model chose to drop.+ scored = _words_seen_whole(word_ids, row_tokens[batch_idx], len(chunk_words))+ kept_ids_per_text[text_idx].update(+ range(chunk_start + scored, chunk_start + len(chunk_words))+ )++ # Token -> word reduction (max score per word). Words from+ # `scored` on are kept above and must not take a slot here.word_scores: dict[int, float] = {}for idx, wid in enumerate(word_ids):- if wid is None:+ if wid is None or wid >= scored:continues = float(score_list[idx])if wid not in word_scores or s > word_scores[wid]:diff --git a/tests/test_kompress_token_window.py b/tests/test_kompress_token_window.pynew file mode 100644index 000000000..bc01ae61f--- /dev/null+++ b/tests/test_kompress_token_window.py@@ -0,0 +1,159 @@+"""Words the model never saw whole must not be dropped.++A chunk is 350 words, but the tokenizer truncates at 512 tokens. URLs, code and+citation markers take several tokens per word, so the tail of a dense chunk+never reached the model and every word in it was dropped, even when the model+would have kept it. The cut can also land inside a word, leaving the model a+prefix to judge.+"""++from __future__ import annotations++import numpy as np+import pytest++from headroom.transforms import kompress_compressor as kc+from headroom.transforms.kompress_compressor import KompressCompressor, KompressConfig++WINDOW = 7 # stands in for 512 tokens+CONTENT = " ".join(f"w{i}" for i in range(25))+++class _Enc(dict):+ def word_ids(self, batch_index=0):+ return self["_word_ids"][batch_index]+++class _Tok:+ """Gives each word ``tokens_per_word(word)`` tokens and cuts each row at WINDOW."""++ def __init__(self, tokens_per_word):+ self.tokens_per_word = tokens_per_word++ def __call__(self, chunk_words, **kw):+ batch = chunk_words if chunk_words and isinstance(chunk_words[0], list) else [chunk_words]+ rows = [+ [i for i, w in enumerate(words) for _ in range(self.tokens_per_word(w))][:WINDOW]+ for words in batch+ ]+ width = max(len(row) for row in rows)+ return _Enc(+ input_ids=np.zeros((len(rows), width), dtype=np.int64),+ attention_mask=np.array([[1] * len(row) + [0] * (width - len(row)) for row in rows]),+ _word_ids=[row + [None] * (width - len(row)) for row in rows],+ )+++class _KeepAllModel:+ """Keeps every token it is shown."""++ def get_keep_mask(self, input_ids, attention_mask):+ return [[True] * len(row) for row in input_ids]++ def get_scores(self, input_ids, attention_mask):+ return [[1.0] * len(row) for row in input_ids]+++class _RejectsLastTokenModel:+ """Rejects the last token of each row and keeps the rest.++ With two tokens per word a whole word survives on its first token. Only a+ word the cut split, present as a single trailing token, is rejected.+ """++ @staticmethod+ def _keep(mask):+ n = int(mask.sum())+ return [i < n - 1 for i in range(len(mask))]++ def get_keep_mask(self, input_ids, attention_mask):+ return [self._keep(mask) for mask in attention_mask]++ def get_scores(self, input_ids, attention_mask):+ return [[1.0 if k else 0.0 for k in self._keep(mask)] for mask in attention_mask]+++class _PrefixOutscoresModel:+ """Scores a row's last token highest, its first word next, the rest low.++ A split word shows up as that last token. Under a forced ratio its prefix+ score would take the one slot a whole word earned.+ """++ def get_keep_mask(self, input_ids, attention_mask):+ return [[s > 0.5 for s in row] for row in self.get_scores(input_ids, attention_mask)]++ def get_scores(self, input_ids, attention_mask):+ rows = []+ for mask in attention_mask:+ n = int(mask.sum())+ rows.append([1.0 if i == n - 1 else 0.9 if i < 2 else 0.1 for i in range(len(mask))])+ return rows+++def _compress(monkeypatch, path, tokenizer, model, **kwargs):+ """Run CONTENT through one path with the fake model and tokenizer."""+ monkeypatch.setattr(kc, "_load_kompress", lambda *a, **k: (model, tokenizer, "onnx"))+ # The compressor must agree with the fake on where the window ends.+ monkeypatch.setattr(kc, "_KOMPRESS_MAX_TOKENS", WINDOW)+ monkeypatch.setattr(kc, "_model_device_type", lambda *a, **k: "cpu")+ monkeypatch.setenv(kc._KOMPRESS_MUST_KEEP_ENV, "0")+ compressor = KompressCompressor(+ KompressConfig(enable_ccr=False, min_input_words=10, chunk_words=10)+ )+ if path == "compress":+ monkeypatch.setattr(compressor, "_should_batch_single_content", lambda *a, **k: False)+ return compressor.compress(CONTENT, **kwargs)+ monkeypatch.setattr(compressor, "_should_use_sequential_fallback", lambda: False)+ [result] = compressor.compress_batch([CONTENT], batch_size=8, **kwargs)+ return result+++CASES = {+ "cut between words": (_Tok(lambda w: 1), _KeepAllModel()),+ "cut inside a word": (_Tok(lambda w: 2), _RejectsLastTokenModel()),+ "word longer than the window": (+ _Tok(lambda w: WINDOW + 2 if w == "w5" else 2),+ _RejectsLastTokenModel(),+ ),+}++[email protected]("case", CASES)[email protected]("path", ["compress", "compress_batch"])+def test_words_the_model_did_not_see_whole_are_kept(monkeypatch, path, case):+ result = _compress(monkeypatch, path, *CASES[case])++ # The model keeps every word it sees whole, so nothing may go missing.+ assert result.compressed.split() == CONTENT.split()+++# Two tokens per word and a seven-token window, ratio 0.34 keeps one word of+# each scored group. The single path advances three words at a time and keeps+# the first of each group; the batch path keeps the first of each ten-word+# chunk plus the seven it never saw whole.+RATIO_EXPECTED = {+ "compress": ["w0", "w3", "w6", "w9", "w12", "w15", "w18", "w21", "w24"],+ "compress_batch": [+ *["w0", "w3", "w4", "w5", "w6", "w7", "w8", "w9"],+ *["w10", "w13", "w14", "w15", "w16", "w17", "w18", "w19"],+ *["w20", "w23", "w24"],+ ],+}++[email protected]("path", ["compress", "compress_batch"])+def test_a_split_word_takes_no_slot_under_a_forced_ratio(monkeypatch, path):+ result = _compress(+ monkeypatch, path, _Tok(lambda w: 2), _PrefixOutscoresModel(), target_ratio=0.34+ )++ assert result.compressed.split() == RATIO_EXPECTED[path]+++def test_row_token_counts_tell_padding_from_special_tokens():+ # [CLS] w0 w0 w1 [SEP] and [CLS] w0 [SEP] [PAD] [PAD]: the longest row has no+ # padding, so its trailing run of None is the special-token count.+ rows = [[None, 0, 0, 1, None], [None, 0, None, None, None]]++ assert kc._row_token_counts(rows) == [5, 3]