Skip to content

Commit bf4318f

Browse files
Jasen2201claude
andauthored
[ATOM gRPC] Engine: token-id prompts reuse block-hash chains; an idle EngineCore waits for input (#3672)
* [ATOM gRPC] Engine: token-id prompts reuse block-hash chains; an idle 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> * TokenPrefixChains: an extension too large to store keeps the prompt it 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> * PP head: an idle loop waits for input 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> * tests: drop the dcp_ops stub the BlockManager no longer imports Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * tests: pin the too-large-extension guard and the idle wait's clear-first 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> * TokenPrefixChains: rehash a reuse when reuse turns off before it finishes A reusing prompt past the first-uses check read `enabled` in a lock of its own, so an older check turning reuse off before the prompt's last lock let it ship its reused chain unchecked. The last lock now decides: a reuse it finds with reuse off is hashed again in full. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Give the engine's new test files the full source header CLAUDE.md's header for a new source file is three lines: SPDX, then the AMD and the ATOM Project Contributors copyright notices. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * A token-id prompt skips the prefix chain store when reuse is off 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> * A prefix of a stored prompt is not stored; SegmentTokenizer keeps its 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> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent c910eb2 commit bf4318f

22 files changed

Lines changed: 747 additions & 93 deletions

‎atom/config.py‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1499,11 +1499,6 @@ def _resolve_synthetic_acceptance(self) -> None:
14991499
form is converted to a length and everything downstream reads only
15001500
``synthetic_acceptance_rates``.
15011501
"""
1502-
# Local import: the schedule lives next to the kernel that consumes it,
1503-
# and that module pulls in triton, which has no business loading just
1504-
# because someone imported a config.
1505-
from atom.model_ops.rejection_sampler import acceptance_length_to_rates
1506-
15071502
if (
15081503
self.synthetic_acceptance_length is not None
15091504
and self.synthetic_acceptance_rate is not None
@@ -1515,6 +1510,9 @@ def _resolve_synthetic_acceptance(self) -> None:
15151510
length = self.synthetic_acceptance_length
15161511
if self.synthetic_acceptance_rate is None and length is None:
15171512
return
1513+
# Below the return: the rejection sampler pulls in triton, which a config
1514+
# without forced acceptance has no business loading.
1515+
from atom.model_ops.rejection_sampler import acceptance_length_to_rates
15181516

15191517
n = self.num_speculative_tokens
15201518
if not n:

‎atom/distributed/dcp_layout.py‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,13 @@
33

44
"""DCP token-ownership arithmetic shared by attention and KV transfer.
55
6-
These helpers are pure ``//`` / ``%`` so they stay elementwise over Python
7-
ints, numpy arrays, and torch tensors. They live outside ``dcp_ops`` so P/D
6+
These helpers are ``//``, ``%`` and ``np.clip``, so they stay elementwise over
7+
Python ints, numpy arrays, and torch tensors. They live outside ``dcp_ops`` so P/D
88
relayout can follow the same rule without importing Triton or aiter.
99
"""
1010

11+
import numpy as np
12+
1113

1214
def dcp_owner_rank(pos, dcp_size, cp_kv_cache_interleave_size=1):
1315
"""Which DCP rank owns global token ``pos`` under interleaved KV storage.
@@ -44,3 +46,30 @@ def dcp_global_pos(local_index, dcp_rank, dcp_size, cp_kv_cache_interleave_size=
4446
return (
4547
(local_index // cp_kv_cache_interleave_size) * dcp_size + dcp_rank
4648
) * cp_kv_cache_interleave_size + (local_index % cp_kv_cache_interleave_size)
49+
50+
51+
def get_dcp_local_seq_lens(seq_lens, dcp_size, dcp_rank, cp_kv_cache_interleave_size=1):
52+
"""Compute per-DCP-rank local sequence lengths.
53+
54+
With interleaved storage, token i is stored on rank
55+
(i // cp_kv_cache_interleave_size) % dcp_size.
56+
57+
Args:
58+
seq_lens: numpy array of sequence lengths
59+
dcp_size: DCP world size
60+
dcp_rank: this rank's DCP rank
61+
cp_kv_cache_interleave_size: interleaving granularity (default 1 = token-level)
62+
63+
Returns:
64+
local_seq_lens: numpy array of local sequence lengths
65+
"""
66+
full_chunks = seq_lens // (cp_kv_cache_interleave_size * dcp_size)
67+
base = full_chunks * cp_kv_cache_interleave_size
68+
69+
remainder_total = seq_lens - base * dcp_size
70+
remainder = np.clip(
71+
remainder_total - dcp_rank * cp_kv_cache_interleave_size,
72+
0,
73+
cp_kv_cache_interleave_size,
74+
)
75+
return base + remainder

‎atom/model_engine/block_manager.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -817,7 +817,7 @@ def num_pool_blocks(self, seq_len: int) -> int:
817817
"""
818818
if self.dcp_world_size <= 1:
819819
return (seq_len + self.block_size - 1) // self.block_size
820-
from atom.model_ops.dcp_ops import get_dcp_local_seq_lens
820+
from atom.distributed.dcp_layout import get_dcp_local_seq_lens
821821

822822
local_len = get_dcp_local_seq_lens(
823823
np.array([seq_len]),

‎atom/model_engine/byte_lru.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,16 @@ def get(self, key: Hashable):
4545
self._items.move_to_end(key)
4646
return item[0]
4747

48+
def fits(self, payload_bytes: int) -> bool:
49+
"""Whether `put` would keep an entry of `payload_bytes` at all."""
50+
return payload_bytes + ENTRY_OVERHEAD <= self.budget
51+
4852
def put(self, key: Hashable, value, payload_bytes: int) -> None:
4953
"""Store `value`, charged `payload_bytes` plus `ENTRY_OVERHEAD`, and
5054
evict down to the budget. An entry larger than the budget is not kept."""
5155
cost = payload_bytes + ENTRY_OVERHEAD
5256
self.pop(key)
53-
if cost > self.budget:
57+
if not self.fits(payload_bytes):
5458
return
5559
self._items[key] = (value, cost)
5660
self.bytes += cost

‎atom/model_engine/engine_core.py‎

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@
7070
BLOCKED_IDLE_SLEEP_S = 0.0005
7171
# How long a busy loop that finds its engine held sleeps before it looks again.
7272
HELD_POLL_S = 0.01
73+
# Longest an idle busy loop waits for input before its periodic work runs again.
74+
IDLE_WAIT_S = 0.01
7375

7476

7577
def dp_idle_when_blocked(config: Config) -> bool:
@@ -141,7 +143,8 @@ def __init__(self, config: Config, input_address: str, output_address: str):
141143
self._ingested_seqs = 0
142144
self._last_backlog_report: tuple[int, int] | None = None
143145
self._next_backlog_report = 0.0
144-
self._kv_progress_event = threading.Event()
146+
# Set by every input put and worker KV output: wakes a waiting busy loop.
147+
self._wake_event = threading.Event()
145148
self.input_queue = queue.Queue[Sequence]()
146149
self.output_queue = queue.Queue[list[Sequence]]()
147150
self.stream_output_queue = (
@@ -209,7 +212,7 @@ def __init__(self, config: Config, input_address: str, output_address: str):
209212
config,
210213
local_proc_num=config.tp_size_local if config.is_multinode_tp else None,
211214
on_worker_failure=self._send_engine_dead,
212-
kv_progress_event=self._kv_progress_event,
215+
kv_progress_event=self._wake_event,
213216
)
214217
self._post_model_load_hook()
215218
block_info = self.runner_mgr.call_func("get_num_blocks", wait_out=True)
@@ -620,6 +623,8 @@ def busy_loop(self):
620623
self.scheduler.engine_stats.note_idle(now)
621624
if self.has_pending_kv_work():
622625
self._advance_idle_kv_transfer()
626+
else:
627+
self._wait_for_input()
623628
yield_gil()
624629
finally:
625630
try:
@@ -666,7 +671,7 @@ def _process_engine_step_inner(self):
666671
# Clear before scheduling/polling, never between checking progress and
667672
# waiting. Arrivals during this step remain latched until the next step.
668673
if self.kv_transfer_enabled:
669-
self._kv_progress_event.clear()
674+
self._wake_event.clear()
670675
result = self.scheduler.schedule()
671676

672677
# Surface admit-rejected seqs (those `_unschedulable_reason` flags in
@@ -733,7 +738,14 @@ def _wait_for_kv_progress(self) -> None:
733738
# Work queued before the event was cleared must also prevent sleeping.
734739
if not self.input_queue.empty() or not self.utility_queue.empty():
735740
return
736-
self._kv_progress_event.wait(KV_IDLE_DRAIN_INTERVAL_S)
741+
self._wake_event.wait(KV_IDLE_DRAIN_INTERVAL_S)
742+
743+
def _wait_for_input(self) -> None:
744+
"""Sleep until the input thread queues work, a worker's KV output arrives, or
745+
`IDLE_WAIT_S` passes: a spinning loop holds the GIL the input thread needs."""
746+
self._wake_event.clear() # before the reads: a later put sets it again
747+
if self.input_queue.empty() and self.utility_queue.empty():
748+
self._wake_event.wait(IDLE_WAIT_S)
737749

738750
def _postprocess(self, seqs, fwd_out, batch):
739751
if self._report_backlog:
@@ -1048,21 +1060,21 @@ def process_input_sockets(self, input_address: str, control_address: str):
10481060
f"{self.label}: input get {request_type} {req_ids}"
10491061
)
10501062
self.input_queue.put_nowait(reqs)
1051-
self._kv_progress_event.set()
1063+
self._wake_event.set()
10521064
self._offer_tier_lookups(reqs)
10531065
elif request_type == EngineCoreRequestType.DP_PREFIX_CREDIT:
10541066
self.input_queue.put_nowait((request_type, reqs))
1055-
self._kv_progress_event.set()
1067+
self._wake_event.set()
10561068
elif request_type == EngineCoreRequestType.UTILITY:
10571069
cmd = reqs.get("cmd") if isinstance(reqs, dict) else None
10581070
logger.debug(f"{self.label}: input get UTILITY command: {cmd}")
10591071
self.utility_queue.put_nowait((cmd, reqs))
10601072
self._has_pending_utility = True
1061-
self._kv_progress_event.set()
1073+
self._wake_event.set()
10621074
elif request_type == EngineCoreRequestType.SHUTDOWN:
10631075
logger.debug(f"{self.label}: input get {request_type}")
10641076
self.input_queue.put_nowait([get_exit_sequence()])
1065-
self._kv_progress_event.set()
1077+
self._wake_event.set()
10661078
alive = False
10671079
reason = request_type
10681080
logger.debug(f"{self.label}: input thread exit due to {reason}")

‎atom/model_engine/llm_engine.py‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
from atom.config import Config
1515
from atom.model_engine.engine_core_mgr import CoreManager, DisaggCoreManager
16+
from atom.model_engine.prefix_block_hashes import TokenPrefixChains
1617
from atom.model_engine.prefix_hash import hash_block_size_for, ship_prompt_hash_chain
1718
from atom.model_engine.segment_tokenizer import PrefixEncoding, SegmentTokenizer
1819
from atom.model_engine.sequence import Sequence, leaves_media_on_prefill
@@ -474,9 +475,12 @@ def rate(num: int, den: int = reusable) -> float:
474475
return num / den if den else 0.0
475476

476477
compressed = totals["compressed_tokens"]
478+
chains = self.io_processor.token_prefix_chains
477479
return {
478480
"enabled": bool(rank_stats),
479481
**totals,
482+
# This frontend's chain work for token-id prompts, not summed over ranks.
483+
"token_prefix_chains": None if chains is None else chains.stats(),
480484
"hit": rate(totals["cached_tokens"]),
481485
"compressed_hit": rate(compressed),
482486
"lost_to_checkpoint": rate(
@@ -700,6 +704,7 @@ def serves_greedy_ids(params: SamplingParams) -> bool:
700704
class InputOutputProcessor:
701705
# Class default: a processor built without `__init__` ships nothing.
702706
prefix_hash_block_size = 0
707+
token_prefix_chains: TokenPrefixChains | None = None
703708

704709
def __init__(self, config, tokenizer, block_size):
705710
self.config = config
@@ -741,6 +746,11 @@ def __init__(self, config, tokenizer, block_size):
741746
self.prefix_hash_block_size = hash_block_size_for(
742747
block_size, config.decode_context_parallel_size
743748
)
749+
self.token_prefix_chains = TokenPrefixChains(
750+
envs.ATOM_TOKENIZE_CACHE_MB << 20,
751+
self.prefix_hash_block_size,
752+
self._reuse_block_hashes,
753+
)
744754

745755
@staticmethod
746756
def _per_req_cache_model_types() -> frozenset[str]:
@@ -920,6 +930,9 @@ def preprocess_fanout(
920930
enable_dp_attention=self.config.enable_dp_attention,
921931
)
922932
n = max(1, int(getattr(sampling_params, "n", 1)))
933+
token_prompt = multimodal_data is None and not isinstance(
934+
prompt_or_tokens, (str, PrefixEncoding)
935+
)
923936

924937
if isinstance(prompt_or_tokens, str):
925938
prompt_or_tokens = self.encode_prompt(
@@ -1022,12 +1035,19 @@ def preprocess_fanout(
10221035
# Runs in an executor or submit thread, not the event loop. Siblings
10231036
# share a prompt and seed, so one chain serves them all.
10241037
if self.prefix_hash_block_size:
1038+
block_hashes = (
1039+
None if prefix_encoding is None else prefix_encoding.block_hashes
1040+
)
1041+
chains = self.token_prefix_chains
1042+
if (
1043+
token_prompt
1044+
and chains is not None
1045+
and chains.enabled
1046+
and envs.ATOM_FRONTEND_PREFIX_HASH
1047+
):
1048+
block_hashes = chains.block_hashes(seqs[0].token_ids)
10251049
ship_prompt_hash_chain(
1026-
seqs[0],
1027-
self.prefix_hash_block_size,
1028-
block_hashes=(
1029-
None if prefix_encoding is None else prefix_encoding.block_hashes
1030-
),
1050+
seqs[0], self.prefix_hash_block_size, block_hashes=block_hashes
10311051
)
10321052
for seq in seqs[1:]:
10331053
seq.prompt_hash_chain = seqs[0].prompt_hash_chain

‎atom/model_engine/pp_engine_core.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,8 @@ def _head_busy_loop(self):
111111
else:
112112
if self.has_pending_kv_work():
113113
self._run_then_publish_kv_events(self._advance_idle_kv_transfer)
114+
else:
115+
self._wait_for_input()
114116
yield_gil()
115117
finally:
116118
self._drain_kv_work_at_exit()

0 commit comments

Comments
 (0)