Files
headroom/tests/test_kompress_mps_serialization.py
Vaibhav HajareandJerrettDavis bb13384829 fix(kompress): keep words past the tokenizer's truncation point (#4328)
## Description

Kompress chunks input by **words** (`chunk_words=350`) but tokenizes
each chunk with `truncation=True, max_length=512`. When a chunk exceeds
512 tokens, the words past the cut-off never get a `word_id`, so they
are never scored and never reach `kept_ids` — they are **silently
dropped**, regardless of importance. The loss is positional, so whatever
sits at the end of the chunk disappears from the compressed output.

This happens on the default proxy path (`target_ratio=None`, no forced
ratio).

350 words fit in 512 tokens only for prose-like English (~1.2
tokens/word). Logs, IDs, hashes, paths and numbers run at 2.5–3+
tokens/word, and non-Latin scripts at 3–4, so a token-heavy chunk hits
the token limit well before its word budget.

Closes #4309

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- New helper `_add_truncated_words(kept_ids, word_ids, chunk_words,
chunk_start, token_count)`: the covered word count is the highest
`word_id` the tokenizer reported, and every word of the chunk past it is
added to `kept_ids` verbatim.
- The cut can also land **inside** a word. Its visible prefix counts as
covered, so the model scores part of a word and may drop the whole of
it, taking the unseen suffix with it. The last covered word is therefore
kept as well whenever the chunk reached the token limit.
- Applied in the single path and the batch path, which share the same
shape. A chunk that is not truncated is unaffected, so the model's own
keep/drop decision still stands.
- The token limit moved into `_KOMPRESS_MAX_TOKENS` so the helper and
the tokenizer call cannot drift apart.
- **A forced ratio is a hard budget the caller asked for**, so the
unscored tail is only taken back on the model-decides path
(`target_ratio=None`); the ratio path keeps the budget it was given.

## Testing

- [x] Unit tests pass (`pytest`)
- [ ] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ pytest tests/test_kompress_must_keep.py -q
collected 23 items

tests\test_kompress_must_keep.py .......................                 [100%]

======================== 23 passed, 1 warning in 1.81s ========================
```

The wider kompress suites (`test_kompress_compressor.py`,
`test_kompress_deadline.py`, `test_kompress_size_gate.py`,
`test_kompress_line_integrity.py`, `test_kompress_failsafe.py`,
`test_kompress_marker_gate.py`) report `10 failed, 91 passed, 15
skipped`; the same 10 fail on the unmodified tree (`10 failed, 89
passed, 15 skipped`) — they need `torch`/`onnxruntime`/`httpx`, which
are not installed here.

## Real Behavior Proof

- Environment: headroom source checkout on Windows, Python 3.12; no
third-party deps installed
- Exact command / steps: the new tests install a tokenizer that models
the real `truncation=True, max_length=512`: every word costs a number of
tokens, so a 350-word chunk of token-heavy words runs past the limit,
and the cut can fall inside a word
- Observed result: before the fix the tail of the chunk vanished from
the output entirely; after the fix the tail is kept verbatim, the word
the cut landed in is kept too, and a chunk that fits is still left to
the model
- Not tested: the real ONNX model and a real tokenizer (no
`onnxruntime`/`torch`/`transformers` here), and the end-to-end proxy
path

The four new tests fail on the unmodified tree and pass with the fix:

```text
$ pytest tests/test_kompress_must_keep.py -q -k Truncated   # fix reverted
FAILED ...::test_words_past_the_truncation_point_survive
FAILED ...::test_the_word_the_cut_landed_in_is_kept
FAILED ...::test_batch_path_keeps_truncated_words_too
FAILED ...::test_a_forced_ratio_still_gets_its_budget
4 failed, 1 passed, 18 deselected
```

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: only for chunks whose tokenized
length exceeds 512 — the truncated tail is now kept instead of dropped,
so the compressed output is longer and no longer silently lossy
- Kill switch / disable path: n/a (the change only adds words that were
previously discarded)
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this commit

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`

## Additional Notes

- The new tests live in `tests/test_kompress_must_keep.py` next to the
existing must-keep override tests. They model the real 512-token limit
(a word costs several tokens, and the cut can fall inside a word) rather
than pretending the chunk is cut at a word boundary.
- On the live-tokenizer point: this machine has no `transformers` and no
model weights, so a live tokenizer run is not possible here, and the
repository's own kompress tests inject a fake model and tokenizer for
the same reason (`tests/test_kompress_failsafe.py`). The fake above
follows the real tokenizer's contract — `is_split_into_words` word ids,
a cut at `max_length`, and a cut that can land inside a word.
- `opentelemetry` is not installed on this machine, so `import headroom`
fails and the suite cannot be collected as-is. The test run above used a
minimal local stub for the `opentelemetry` API surface that
`headroom/observability` imports; no product code was changed to
accommodate it, and the stub is not part of this PR.
- `ruff` and `mypy` were not run: neither is installed here.

## Model Used

MiniMax M3.1 Flash Free via the opencode agent harness
(`minimax-m3.1-flash-free`)

---------

Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-11-04 22:52:01 -06:00

154 lines
4.6 KiB
Python

"""Device transfers must share Kompress's execution slot with inference."""
import threading
import headroom.transforms.kompress_compressor as kc
def test_validation_device_copy_holds_execution_slot(monkeypatch):
semaphore = threading.BoundedSemaphore(1)
copy_saw_slot: list[bool] = []
class FakeTensor:
def to(self, _device):
acquired = semaphore.acquire(blocking=False)
if acquired:
semaphore.release()
copy_saw_slot.append(not acquired)
return self
class FakeEncoding(dict):
def __init__(self):
super().__init__(input_ids=FakeTensor(), attention_mask=FakeTensor())
class FakeTokenizer:
def __call__(self, *_args, **_kwargs):
return FakeEncoding()
class FakeScore:
def detach(self):
return self
def cpu(self):
return self
class FakeModel:
def get_scores(self, input_ids, attention_mask):
return [FakeScore()]
monkeypatch.setattr(kc, "_execution_semaphore", lambda *_args, **_kwargs: semaphore)
kc._validate_pytorch_device(FakeModel(), FakeTokenizer(), "mps")
assert copy_saw_slot == [True, True]
def test_single_and_batch_device_copies_hold_execution_slot(monkeypatch):
semaphore = threading.BoundedSemaphore(1)
copy_saw_slot: list[bool] = []
class FakeTensor:
def __init__(self, row_lengths):
self.row_lengths = row_lengths
def __getitem__(self, index):
# Real attention masks expose each row for padding-aware counts.
return [1] * self.row_lengths[index]
def to(self, _device):
acquired = semaphore.acquire(blocking=False)
if acquired:
semaphore.release()
copy_saw_slot.append(not acquired)
return self
class FakeEncoding(dict):
def __init__(self, row_lengths):
super().__init__(
input_ids=FakeTensor(row_lengths),
attention_mask=FakeTensor(row_lengths),
)
self.row_lengths = row_lengths
def word_ids(self, batch_index=0):
return list(range(self.row_lengths[batch_index]))
class FakeTokenizer:
def __call__(self, words, **_kwargs):
rows = words if words and isinstance(words[0], list) else [words]
return FakeEncoding([len(row) for row in rows])
class FakeScores:
def __init__(self, row_length):
self.values = [float(index) for index in range(row_length)]
def cpu(self):
return self.values
class FakeParameter:
device = "mps"
class FakeModel:
def parameters(self):
return iter([FakeParameter()])
def get_scores(self, input_ids, _attention_mask):
return [FakeScores(row_length) for row_length in input_ids.row_lengths]
model = FakeModel()
monkeypatch.setattr(kc, "_execution_semaphore", lambda *_args, **_kwargs: semaphore)
monkeypatch.setattr(
kc,
"_load_kompress",
lambda *args, **kwargs: (model, FakeTokenizer(), "pytorch"),
)
compressor = kc.KompressCompressor(kc.KompressConfig(min_input_words=10, enable_ccr=False))
compressor.compress(" ".join(["word"] * 20), target_ratio=0.5)
assert copy_saw_slot == [True, True]
copy_saw_slot.clear()
monkeypatch.setattr(
kc.KompressCompressor,
"_should_use_sequential_fallback",
lambda self: False,
)
compressor.compress_batch(
[" ".join(["word"] * 20), " ".join(["token"] * 20)],
target_ratio=0.5,
)
assert copy_saw_slot == [True, True]
def test_canary_device_copy_holds_execution_slot(monkeypatch):
semaphore = threading.BoundedSemaphore(1)
copy_saw_slot: list[bool] = []
class FakeTensor:
def to(self, _device):
acquired = semaphore.acquire(blocking=False)
if acquired:
semaphore.release()
copy_saw_slot.append(not acquired)
return self
class FakeTokenizer:
def __call__(self, *_args, **_kwargs):
return {"input_ids": FakeTensor(), "attention_mask": FakeTensor()}
class FakeParameter:
device = "mps"
class FakeModel:
def parameters(self):
return iter([FakeParameter()])
def get_keep_mask(self, input_ids, attention_mask):
return []
monkeypatch.setattr(kc, "_execution_semaphore", lambda *_args, **_kwargs: semaphore)
kc.KompressCompressor()._timed_canary(FakeModel(), FakeTokenizer(), "pytorch")
assert copy_saw_slot == [True, True]