Repository navigation
[ATOM gRPC] Engine: token-id prompts reuse block-hash chains; an idle EngineCore waits for input - #3672
Conversation
… EngineCore waits for input A prompt sent as token ids takes the complete blocks it shares with the stored prompt sharing the most leading tokens and hashes only the rest (`TokenPrefixChains.block_hashes`). Stored prompts are kept sorted by their tokens' bytes, so that prompt sorts next to the new one and a lookup compares two, from the first token. The store is a `ByteLRU` sized by `ATOM_TOKENIZE_CACHE_MB`; `ATOM_TOKENIZE_CACHE_BLOCK_HASHES=0` turns reuse off, and the first 4 reuses are checked against a full `chained_block_hashes`, any difference turning reuse off. `/debug/cache_stats` serves the counts as `token_prefix_chains`. With nothing to run and no KV work pending, `EngineCore.busy_loop` waits up to `IDLE_WAIT_S` (10 ms) on the event the input thread sets after each item it queues, so a new request no longer waits the GIL switch interval, about 5 ms, before its first forward. Two imports stop loading Triton where nothing needs it: `SpeculativeConfig` imports the rejection sampler only past its no-forced-acceptance return, and `get_dcp_local_seq_lens` moves into `atom/distributed/dcp_layout.py`, which `BlockManager` imports (`dcp_ops` re-exports it). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
🏷️ CI GuideRuns automatically on every eligible PR before approval:
Heavy model tests:
Path scope:
|
There was a problem hiding this comment.
🟡 Changes recommended
An oversized prompt extension evicts the cached base before the replacement is rejected, losing reusable work and causing unnecessary full-chain rehashing.
1 open issue
What changed in this PR
This PR prepares ATOM’s engine for the gRPC stack in #3657 by reducing repeated token-ID prompt hashing and letting idle engines wait for input rather than spin.
Changes:
- Adds byte-budgeted token-prefix hash-chain reuse, initial verification, and cache statistics.
- Adds event-based idle waiting with request-wakeup tests.
- Reduces unnecessary Triton imports in configuration and block allocation.
| File | Description |
|---|---|
tests/test_token_prefix_chains.py |
Tests reuse, eviction, verification fallback, and concurrent prompts. |
tests/test_engine_loop_idle_accounting.py |
Adapts the loop fixture for idle waiting. |
tests/test_engine_core_idle_wait.py |
Tests input wakeups and requests queued before waiting. |
docs/environment_variables.md |
Documents token-ID chain budgets, switches, and statistics. |
atom/model_ops/dcp_ops.py |
Imports the relocated sequence-length helper. |
atom/model_engine/prefix_block_hashes.py |
Implements token-prefix lookup and bounded chain storage. |
atom/model_engine/llm_engine.py |
Integrates chain reuse into preprocessing and cache statistics. |
atom/model_engine/engine_core.py |
Waits for input when idle with no pending KV work. |
atom/model_engine/block_manager.py |
Uses the Triton-independent sequence-length helper. |
atom/distributed/dcp_layout.py |
Houses the relocated DCP sequence-length calculation. |
atom/config.py |
Defers the rejection-sampler import until forced acceptance is configured. |
Review effort: Balanced
…t extends _store dropped the record it replaces before ByteLRU.put rejected an entry over the whole budget, so neither prompt stayed cached. It now checks ByteLRU.fits first and replaces the base only when the new record is kept. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With nothing in flight, nothing scheduled and no KV work pending, the PP head's busy loop waits on the input event like EngineCore.busy_loop instead of spinning on the GIL the input thread needs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Looks good to me; no blocking issues. Two test gaps, found by reverting each change on CPU:
Checked and fine:
|
…rst order The too-large-extension test now checks that the bytes order and the LRU hold the same single record within budget, which fails once the `fits` check in `TokenPrefixChains._store` is removed. A new idle-wait test lands the input thread's put and set between the two queue checks, which fails once `_wait_for_input` clears the event after the checks instead of before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Fixes both test gaps in 035c7e4; each check fails when its fix alone is reverted.
|
valarLip
left a comment
There was a problem hiding this comment.
⚠️ Action required before merge (2)
The engine side checks out. Chain reuse matched a full chained_block_hashes on every call in randomized multi-turn runs: forks, edits, truncations, negative and high-byte ids, block sizes 1–16, eviction-heavy budgets, and 8 threads at once. The idle wait has no lost wakeup: every input-thread put sets the event after it queues, and the event is cleared before the queues are read. The DP loop, DPSyncGate and #3777 are not touched, and both merge cleanly. Two asks:
-
Skip
TokenPrefixChainswhen reuse is off.atom/model_engine/llm_engine.py:980-
Problem:
chains.block_hashes()still runs when the store is disabled (ATOM_TOKENIZE_CACHE_MB=0,ATOM_TOKENIZE_CACHE_BLOCK_HASHES=0, or after_turn_off). It makes an int32 copy and atobytes, a fullextend_block_hashesand two lock round trips, and thenship_prompt_hash_chaincopies again throughas_array. -
Cost: with the switch off, a token-id prompt now costs more than on main, so the off switch does not restore main's cost. Measured on one pinned core, 6 alternating rounds, with main-vs-main and head-vs-head controls within 1%:
Block size 1K tokens 120K tokens 16 25.2 → 32.3 µs 2537 → 2695 µs (+6%) 64 11.1 → 17.0 µs 858 → 911 µs (+6%) -
Fix:
if token_prompt and chains is not None and chains.enabled and envs.ATOM_FRONTEND_PREFIX_HASH:. This restores main's numbers within 1% (2537 vs 2537 µs) andtests/test_token_prefix_chains.pystays green. Readingenabledwithout the lock is safe because it only goes True→False, and a reuse already in flight still takes your late rehash.
-
-
State the cold-miss cost in the PR description. A first-turn token-id prompt that shares no stored prefix now pays for building and storing its record on top of main's hash:
Block size 1K 8K 32K 120K 16 +12 µs +26 µs +81 µs +389 µs (~15%) 64 +11 µs — +35 µs +300 µs (~35%) - Context: this is per request on the preprocess executor, not per engine step. Reused turns get 4–8x faster (720 → 88 µs at 32K), so the trade is fine. Please list the miss row next to the 2.8 ms hit figure in "Why". If you want to cut it, the remaining extra comes from the
np.asarray(...).tobytes()copy and theas_arraycopy inship_prompt_hash_chain; that part is optional.
- Context: this is per request on the preprocess executor, not per engine step. Reused turns get 4–8x faster (720 → 88 µs at 32K), so the trade is fine. Please list the miss row next to the 2.8 ms hit figure in "Why". If you want to cut it, the remaining extra comes from the
Nit (optional): the _wait_for_input docstring says the input thread sets the event. Worker KV outputs set it too (async_proc.py:708), which only ends the wait early, harmlessly.
Reviewed at d0496ea (Deep, 2 hunters + independent pass B + 1 verifier; CPU probes, new tests confirmed run in the pre-checks lane). Already fixed: valar-cop's base-eviction, PP-head wait and dcp_ops-stub asks; Copilot's late-disable race and headers; yitingw1's two test gaps.
With ATOM_TOKENIZE_CACHE_MB=0, ATOM_TOKENIZE_CACHE_BLOCK_HASHES=0 or after a failed first-uses check, preprocess still ran TokenPrefixChains.block_hashes, which copied, rehashed and locked for nothing: 6% over main at 120K tokens. It now checks `chains.enabled` first and costs what main does. The idle wait's docstring also names the worker KV outputs that set its event. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Ready for another look: both asks and the docstring nit are fixed in 59121a7.
I left the copies (about 15 µs at 120K): a miss's extra is mostly first-touching the kept token copy. Details
|
jgong5
left a comment
There was a problem hiding this comment.
No blocking issues from me; three inline notes and one outside the diff.
Same eviction shape in SegmentTokenizer (fix-then-sweep). _store now checks ByteLRU.fits before dropping replaces (6201e41). atom/model_engine/segment_tokenizer.py L388–396 has the same shape: it pops base, then puts entry, and put drops an entry over the budget, so both are lost. It is pre-existing and only reachable with a small ATOM_TOKENIZE_CACHE_MB, but the same guard before the pop (if not self._lru.fits(entry.payload_bytes): return) would close it there too.
… base when a turn cannot fit - `TokenPrefixChains.block_hashes` skips the store when the prompt shares all its tokens with `base` (a truncated retry, a repeat): any later prompt shares at least as many leading tokens with `base`, so the record would only spend budget. `rehash` already implies `verify`. - `SegmentTokenizer._store_prefix` checks `ByteLRU.fits` before dropping `base`, as `TokenPrefixChains._store` does, so a turn too large to keep no longer loses the turn it extends. `put` now always keeps the entry, so the not-kept cleanup after it goes. - `EngineCore._kv_progress_event` is `_wake_event`: every input put, utility put and worker KV output sets it, and both idle waits sleep on it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Ready for another look: all four notes are fixed in f2e39d3.
f2e39d3: the 50 test files importing the changed modules, 3010 passed. ruff, black clean. |
valarLip
left a comment
There was a problem hiding this comment.
✅ LGTM
Both asks and the nit are fixed, and the delta is clean.
- Reuse off costs what main does.
llm_engine.py:980now checkschains.enabledfirst. One pinned core, 6 alternating rounds, with main-vs-main and head-vs-head controls: block 16 is 25.5 vs 25.5 µs at 1K and 2521 vs 2530 µs at 120K. Block 64 is 10.9 vs 11.0 µs and 840 vs 842 µs. Before this change it was +6%. Removing the check fails both "off" cases of the switch test on the newprompts == 0assertion. Readingenabledwithout the lock is safe because it only goes True→False. - The miss cost is in the description, with the full main / miss / reused / off table.
- The
_wait_for_inputdocstring now names worker KV outputs, and_wake_eventsays what it is.
I also checked the rest of the delta:
- The rename changes no logic. The event is still cleared before the queues are read, and every put still sets it.
- The five edited test files only rename the attribute. No assertion is weakened.
- Skipping the store for a prompt that a stored one holds whole is sound, because the stored prompt matches every later prompt at least as far. Removing the skip fails the new test.
SegmentTokenizernow checksfitsbefore it dropsbase.putnow always keeps the entry, so the cleanup that followed it was dead code. Removing the check fails the new test.- The delta has no main merge, and the branch still merges cleanly with main.
Root cause vs patch: root fix. A store that is off is no longer consulted at all, and both stores now check whether the new entry fits before they evict its base.
Reviewed at f2e39d3 (re-review of d0496ea; two independent passes: delta hunter with A/B timing and three mutants, plus orchestrator pass B). CI: "Run non-GPU unit tests" is red with 11 failures that main shows too (main run 45929977885 at 2d7791a has the same 11, e.g. _greedy_ids_only stand-ins, test_an_empty_prompt_gets_a_400), so this PR does not cause them; every other required check is green.
valar-cop
left a comment
There was a problem hiding this comment.
LGTM
ci Run non-GPU unit tests (Pre Checkin) failed — main is already broken the same way (medium): The unit lane is red on main in the same window and the maintainer's comment reports the same 11 failures on main run 45929977885; the job log captured here is empty, so this rests on the summary's main comparison rather than a read log.
same job on main: ['2026-11-27T02:43 failure', '2026-11-27T02:24 failure', '2026-11-27T01:57 failure', '2026-11-27T01:35 failure'], on other recent runs: {'failure': 4}
main run 45929977885 at 2d7791a has the same 11, e.g. _greedy_ids_only stand-ins, test_an_empty_prompt_gets_a_400
next: No change to this PR; re-run the Pre Checkin lane on a rebased head once main's non-GPU unit lane is green. https://github.com/ROCm/ATOM/actions/runs/45930395485/job/140281420533
There was a problem hiding this comment.
🟡 Changes recommended
The decode branch caches a seed--1 hash chain for requests retaining a media-specific cache seed, causing rejected reuse, duplicate prompt hashing, and possible eviction of useful cache records.
1 open issue
Review effort: Balanced
Main now carries #3672 as one squash commit, so the engine files take main's side. api_server.py keeps both: the gRPC server stops before the engine and the encoder close after it, health_problem() answers None under --encoder-only, and --encoder-only refuses --grpc-port. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Part A of the 8 PRs in #3657. No blocking issues.
Why
A token-id prompt rehashed its whole block-hash chain every turn, though most repeats the turn before: 3.2 ms at 120K tokens (block 16, one dev-host core). Reuse cuts a follow-up turn to 0.87 ms; a prompt sharing no stored prefix pays 0.6 ms (18%) more to keep its record, 44 µs at 1K. An idle engine loop spun holding the GIL, so a new request first waited out the 5 ms switch interval.
What changed
TokenPrefixChains: a token-id prompt takes the complete blocks it shares with the stored prompt sharing the most leading tokens, and hashes only the rest.ByteLRUsized byATOM_TOKENIZE_CACHE_MB;ATOM_TOKENIZE_CACHE_BLOCK_HASHES=0turns reuse off, at main's cost. The first 4 reuses are checked against a full rehash;/debug/cache_statsreportstoken_prefix_chains.EngineCore._wait_for_input: with nothing to run and no KV work pending, the busy loop waits up to 10 ms on_wake_event, set by every input put and worker KV output.SpeculativeConfigandBlockManagerstop importing Triton modules they do not need (get_dcp_local_seq_lensmoves todcp_layout.py).SegmentTokenizertoo keeps a stored prompt whose replacement is too large to keep.Review focus
TokenPrefixChains._findand the first-uses check inblock_hashes._wait_for_inputclears the event before reading the queues.Testing
Each turn of a token-id conversation with forks, an edit, a compaction and a retry ships a full recompute's chain, hashing only its unshared blocks. A request the input thread queues wakes an idle loop at once.
7,323 CPU tests pass (Evidence); ruff, black clean.
GPU results
On DeepSeek-V4.1-Flash 6P16D, AgentX at 1,228 concurrent sessions, TTFT over gRPC is at parity with HTTP. No request failed.
GPU numbers
DeepSeek-V4.1-Flash, 6P16D (P TP2 DP2, D TP4 DP4, shared Mooncake Store), AgentX C1228 for 900 s, two runs per configuration, mean of the two. atomesh's prompt encoding came from
ROCm/ATOM#3596(fastokens) and its V4.1 chat render fromROCm/ATOM#3597, neither part of this stack; the stack's code was the integration branch at this stack's part 14.HTTP's two TTFT means were 0.34 s apart, more than either gRPC difference; all three are bound by the prefill queue. GSM8K (lm_eval, 1,319 questions, 1P1D, twice each): gRPC 0.930 and 0.929, HTTP 0.927 and 0.930. Prompt token parity between atomesh's render and ATOM's HTTP chat: 59 of 59 (21 GSM8K, 38 AgentX and tool-call prompts).
Follow-ups
none
Stack
ATOM serves
atom.grpc.v1.AtomEnginebeside its HTTP server (token ids in, token ids out, ATOM's P/D flow unchanged), and atomesh routes to ATOM gRPC workers over a Generate call per request or one Session per instance. One linear stack, merged bottom to top: A, B, C, D, E, F, G, H; each PR's base is the one before it.Evidence
At 8e596e9, CPU only (torch 2.14 CPU, no aiter or Triton):
tests/plugin/test_sglang_qwen4_exp_mtp.py, which needs SGLang.test_worker_relays_engine_routes_to_the_hub_over_its_unix_socketfailed on a 108-byte Unix socket path under the run's basetemp, andtest_server_entrypoints_initialize_native_storage_before_importon its 30 s import timeout (the import alone took 27 to 41 s on main and here). Both passed on a serial rerun with a short basetemp, as on main.The full CPU suite with the whole stack on top against main cccc96a: main 14,936 passed and 10 failed; the top 14,943 passed with the same 9 failures plus 8
test_simulated_tperrors from its fixed port 29591, held by main's run beside it (9 passed alone). The top adds 14 tests, all passing; main's tenth failure is the import timeout above.Per-request cost of a token-id prompt's chain against main, at 59121a7 on one pinned dev-host core, median of 6 alternating rounds on fresh prompts, two runs averaged. "Reused" is a turn adding 512 tokens to a stored one; "reuse off" is any of the three off states.
Building the chain costs about what main's hash does (+51 µs at block 16, 120K); the rest of a miss's extra is keeping the record, mostly fresh memory for its token copy (111 more page faults per 120K prompt).
At 59121a7, the 44 test files importing
llm_engine,engine_coreorprefix_block_hashes: 2,493 passed. The 3 failures intest_structured_admission.pyfail the same at d0496ea: their subprocess imports the installedatom, not the tree.At f2e39d3, the 50 test files importing
llm_engine,engine_core,prefix_block_hashes,segment_tokenizerorbyte_lru, or setting the engine's wake event: 3,010 passed.The idle wait, measured on a CPU instance with a stub model runner: a 1K-token request took 0.61 to 0.74 ms from admission to its first forward, against 5.63 to 5.84 ms before.
🤖 Generated with Claude Code