diff --git a/atom/config.py b/atom/config.py index b0ae13f2944..66830e79ffe 100644 --- a/atom/config.py +++ b/atom/config.py @@ -1499,11 +1499,6 @@ def _resolve_synthetic_acceptance(self) -> None: form is converted to a length and everything downstream reads only ``synthetic_acceptance_rates``. """ - # Local import: the schedule lives next to the kernel that consumes it, - # and that module pulls in triton, which has no business loading just - # because someone imported a config. - from atom.model_ops.rejection_sampler import acceptance_length_to_rates - if ( self.synthetic_acceptance_length is not None and self.synthetic_acceptance_rate is not None @@ -1515,6 +1510,9 @@ def _resolve_synthetic_acceptance(self) -> None: length = self.synthetic_acceptance_length if self.synthetic_acceptance_rate is None and length is None: return + # Below the return: the rejection sampler pulls in triton, which a config + # without forced acceptance has no business loading. + from atom.model_ops.rejection_sampler import acceptance_length_to_rates n = self.num_speculative_tokens if not n: diff --git a/atom/distributed/dcp_layout.py b/atom/distributed/dcp_layout.py index 012ab8dca61..6c2c86c1896 100644 --- a/atom/distributed/dcp_layout.py +++ b/atom/distributed/dcp_layout.py @@ -3,11 +3,13 @@ """DCP token-ownership arithmetic shared by attention and KV transfer. -These helpers are pure ``//`` / ``%`` so they stay elementwise over Python -ints, numpy arrays, and torch tensors. They live outside ``dcp_ops`` so P/D +These helpers are ``//``, ``%`` and ``np.clip``, so they stay elementwise over +Python ints, numpy arrays, and torch tensors. They live outside ``dcp_ops`` so P/D relayout can follow the same rule without importing Triton or aiter. """ +import numpy as np + def dcp_owner_rank(pos, dcp_size, cp_kv_cache_interleave_size=1): """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= return ( (local_index // cp_kv_cache_interleave_size) * dcp_size + dcp_rank ) * cp_kv_cache_interleave_size + (local_index % cp_kv_cache_interleave_size) + + +def get_dcp_local_seq_lens(seq_lens, dcp_size, dcp_rank, cp_kv_cache_interleave_size=1): + """Compute per-DCP-rank local sequence lengths. + + With interleaved storage, token i is stored on rank + (i // cp_kv_cache_interleave_size) % dcp_size. + + Args: + seq_lens: numpy array of sequence lengths + dcp_size: DCP world size + dcp_rank: this rank's DCP rank + cp_kv_cache_interleave_size: interleaving granularity (default 1 = token-level) + + Returns: + local_seq_lens: numpy array of local sequence lengths + """ + full_chunks = seq_lens // (cp_kv_cache_interleave_size * dcp_size) + base = full_chunks * cp_kv_cache_interleave_size + + remainder_total = seq_lens - base * dcp_size + remainder = np.clip( + remainder_total - dcp_rank * cp_kv_cache_interleave_size, + 0, + cp_kv_cache_interleave_size, + ) + return base + remainder diff --git a/atom/model_engine/block_manager.py b/atom/model_engine/block_manager.py index 18c1bec9aaf..6dee4e6424d 100644 --- a/atom/model_engine/block_manager.py +++ b/atom/model_engine/block_manager.py @@ -817,7 +817,7 @@ def num_pool_blocks(self, seq_len: int) -> int: """ if self.dcp_world_size <= 1: return (seq_len + self.block_size - 1) // self.block_size - from atom.model_ops.dcp_ops import get_dcp_local_seq_lens + from atom.distributed.dcp_layout import get_dcp_local_seq_lens local_len = get_dcp_local_seq_lens( np.array([seq_len]), diff --git a/atom/model_engine/byte_lru.py b/atom/model_engine/byte_lru.py index 0f4645304da..01ba5aaafd5 100644 --- a/atom/model_engine/byte_lru.py +++ b/atom/model_engine/byte_lru.py @@ -45,12 +45,16 @@ def get(self, key: Hashable): self._items.move_to_end(key) return item[0] + def fits(self, payload_bytes: int) -> bool: + """Whether `put` would keep an entry of `payload_bytes` at all.""" + return payload_bytes + ENTRY_OVERHEAD <= self.budget + def put(self, key: Hashable, value, payload_bytes: int) -> None: """Store `value`, charged `payload_bytes` plus `ENTRY_OVERHEAD`, and evict down to the budget. An entry larger than the budget is not kept.""" cost = payload_bytes + ENTRY_OVERHEAD self.pop(key) - if cost > self.budget: + if not self.fits(payload_bytes): return self._items[key] = (value, cost) self.bytes += cost diff --git a/atom/model_engine/engine_core.py b/atom/model_engine/engine_core.py index 1220c890620..73536e33a23 100644 --- a/atom/model_engine/engine_core.py +++ b/atom/model_engine/engine_core.py @@ -70,6 +70,8 @@ BLOCKED_IDLE_SLEEP_S = 0.0005 # How long a busy loop that finds its engine held sleeps before it looks again. HELD_POLL_S = 0.01 +# Longest an idle busy loop waits for input before its periodic work runs again. +IDLE_WAIT_S = 0.01 def dp_idle_when_blocked(config: Config) -> bool: @@ -141,7 +143,8 @@ def __init__(self, config: Config, input_address: str, output_address: str): self._ingested_seqs = 0 self._last_backlog_report: tuple[int, int] | None = None self._next_backlog_report = 0.0 - self._kv_progress_event = threading.Event() + # Set by every input put and worker KV output: wakes a waiting busy loop. + self._wake_event = threading.Event() self.input_queue = queue.Queue[Sequence]() self.output_queue = queue.Queue[list[Sequence]]() self.stream_output_queue = ( @@ -209,7 +212,7 @@ def __init__(self, config: Config, input_address: str, output_address: str): config, local_proc_num=config.tp_size_local if config.is_multinode_tp else None, on_worker_failure=self._send_engine_dead, - kv_progress_event=self._kv_progress_event, + kv_progress_event=self._wake_event, ) self._post_model_load_hook() block_info = self.runner_mgr.call_func("get_num_blocks", wait_out=True) @@ -620,6 +623,8 @@ def busy_loop(self): self.scheduler.engine_stats.note_idle(now) if self.has_pending_kv_work(): self._advance_idle_kv_transfer() + else: + self._wait_for_input() yield_gil() finally: try: @@ -666,7 +671,7 @@ def _process_engine_step_inner(self): # Clear before scheduling/polling, never between checking progress and # waiting. Arrivals during this step remain latched until the next step. if self.kv_transfer_enabled: - self._kv_progress_event.clear() + self._wake_event.clear() result = self.scheduler.schedule() # Surface admit-rejected seqs (those `_unschedulable_reason` flags in @@ -733,7 +738,14 @@ def _wait_for_kv_progress(self) -> None: # Work queued before the event was cleared must also prevent sleeping. if not self.input_queue.empty() or not self.utility_queue.empty(): return - self._kv_progress_event.wait(KV_IDLE_DRAIN_INTERVAL_S) + self._wake_event.wait(KV_IDLE_DRAIN_INTERVAL_S) + + def _wait_for_input(self) -> None: + """Sleep until the input thread queues work, a worker's KV output arrives, or + `IDLE_WAIT_S` passes: a spinning loop holds the GIL the input thread needs.""" + self._wake_event.clear() # before the reads: a later put sets it again + if self.input_queue.empty() and self.utility_queue.empty(): + self._wake_event.wait(IDLE_WAIT_S) def _postprocess(self, seqs, fwd_out, batch): if self._report_backlog: @@ -1048,21 +1060,21 @@ def process_input_sockets(self, input_address: str, control_address: str): f"{self.label}: input get {request_type} {req_ids}" ) self.input_queue.put_nowait(reqs) - self._kv_progress_event.set() + self._wake_event.set() self._offer_tier_lookups(reqs) elif request_type == EngineCoreRequestType.DP_PREFIX_CREDIT: self.input_queue.put_nowait((request_type, reqs)) - self._kv_progress_event.set() + self._wake_event.set() elif request_type == EngineCoreRequestType.UTILITY: cmd = reqs.get("cmd") if isinstance(reqs, dict) else None logger.debug(f"{self.label}: input get UTILITY command: {cmd}") self.utility_queue.put_nowait((cmd, reqs)) self._has_pending_utility = True - self._kv_progress_event.set() + self._wake_event.set() elif request_type == EngineCoreRequestType.SHUTDOWN: logger.debug(f"{self.label}: input get {request_type}") self.input_queue.put_nowait([get_exit_sequence()]) - self._kv_progress_event.set() + self._wake_event.set() alive = False reason = request_type logger.debug(f"{self.label}: input thread exit due to {reason}") diff --git a/atom/model_engine/llm_engine.py b/atom/model_engine/llm_engine.py index 2436027e1e0..7a53050457a 100644 --- a/atom/model_engine/llm_engine.py +++ b/atom/model_engine/llm_engine.py @@ -13,6 +13,7 @@ from atom.config import Config from atom.model_engine.engine_core_mgr import CoreManager, DisaggCoreManager +from atom.model_engine.prefix_block_hashes import TokenPrefixChains from atom.model_engine.prefix_hash import hash_block_size_for, ship_prompt_hash_chain from atom.model_engine.segment_tokenizer import PrefixEncoding, SegmentTokenizer from atom.model_engine.sequence import Sequence, leaves_media_on_prefill @@ -474,9 +475,12 @@ def rate(num: int, den: int = reusable) -> float: return num / den if den else 0.0 compressed = totals["compressed_tokens"] + chains = self.io_processor.token_prefix_chains return { "enabled": bool(rank_stats), **totals, + # This frontend's chain work for token-id prompts, not summed over ranks. + "token_prefix_chains": None if chains is None else chains.stats(), "hit": rate(totals["cached_tokens"]), "compressed_hit": rate(compressed), "lost_to_checkpoint": rate( @@ -700,6 +704,7 @@ def serves_greedy_ids(params: SamplingParams) -> bool: class InputOutputProcessor: # Class default: a processor built without `__init__` ships nothing. prefix_hash_block_size = 0 + token_prefix_chains: TokenPrefixChains | None = None def __init__(self, config, tokenizer, block_size): self.config = config @@ -741,6 +746,11 @@ def __init__(self, config, tokenizer, block_size): self.prefix_hash_block_size = hash_block_size_for( block_size, config.decode_context_parallel_size ) + self.token_prefix_chains = TokenPrefixChains( + envs.ATOM_TOKENIZE_CACHE_MB << 20, + self.prefix_hash_block_size, + self._reuse_block_hashes, + ) @staticmethod def _per_req_cache_model_types() -> frozenset[str]: @@ -920,6 +930,9 @@ def preprocess_fanout( enable_dp_attention=self.config.enable_dp_attention, ) n = max(1, int(getattr(sampling_params, "n", 1))) + token_prompt = multimodal_data is None and not isinstance( + prompt_or_tokens, (str, PrefixEncoding) + ) if isinstance(prompt_or_tokens, str): prompt_or_tokens = self.encode_prompt( @@ -1022,12 +1035,19 @@ def preprocess_fanout( # Runs in an executor or submit thread, not the event loop. Siblings # share a prompt and seed, so one chain serves them all. if self.prefix_hash_block_size: + block_hashes = ( + None if prefix_encoding is None else prefix_encoding.block_hashes + ) + chains = self.token_prefix_chains + if ( + token_prompt + and chains is not None + and chains.enabled + and envs.ATOM_FRONTEND_PREFIX_HASH + ): + block_hashes = chains.block_hashes(seqs[0].token_ids) ship_prompt_hash_chain( - seqs[0], - self.prefix_hash_block_size, - block_hashes=( - None if prefix_encoding is None else prefix_encoding.block_hashes - ), + seqs[0], self.prefix_hash_block_size, block_hashes=block_hashes ) for seq in seqs[1:]: seq.prompt_hash_chain = seqs[0].prompt_hash_chain diff --git a/atom/model_engine/pp_engine_core.py b/atom/model_engine/pp_engine_core.py index 1dafc6b30a4..c201201537b 100644 --- a/atom/model_engine/pp_engine_core.py +++ b/atom/model_engine/pp_engine_core.py @@ -111,6 +111,8 @@ def _head_busy_loop(self): else: if self.has_pending_kv_work(): self._run_then_publish_kv_events(self._advance_idle_kv_transfer) + else: + self._wait_for_input() yield_gil() finally: self._drain_kv_work_at_exit() diff --git a/atom/model_engine/prefix_block_hashes.py b/atom/model_engine/prefix_block_hashes.py index 66624e8b53d..6362b1b41b9 100644 --- a/atom/model_engine/prefix_block_hashes.py +++ b/atom/model_engine/prefix_block_hashes.py @@ -1,5 +1,6 @@ # SPDX-License-Identifier: MIT -"""The prompt block-hash chain, kept with a tokenizer-cached prefix. +"""The prompt block-hash chain, kept with a tokenizer-cached prefix or, for a +prompt sent as token ids, with its tokens (`TokenPrefixChains`). `prefix_hash.chained_block_hashes` of a prompt depends only on its tokens, so a conversation's next turn -- which shares the cached prefix's tokens up to the @@ -7,13 +8,28 @@ and hash only the blocks after them. These are content hashes: they say nothing about whether a block's KV is still resident (BlockManager decides that). -A record lives inside the tokenizer cache's stored prefix, under its byte -budget, and refers to no earlier record, so evicting an old turn frees it. +A text prompt's record lives in the tokenizer cache's stored prefix, a token-id +prompt's in `TokenPrefixChains`' own ByteLRU; each counts toward its store's +byte budget and refers to no earlier record, so evicting an old turn frees it. """ import array +import logging import sys +import threading +from bisect import bisect_left, insort from dataclasses import dataclass +from operator import attrgetter +from typing import NamedTuple + +import numpy as np + +from atom.model_engine.byte_lru import ByteLRU + +logger = logging.getLogger("atom") + +# Reuses checked against a full `chained_block_hashes` before reuse is trusted. +_VERIFY_FIRST = 4 @dataclass(frozen=True, slots=True) @@ -63,9 +79,9 @@ def extend_block_hashes(tokens, block_size, seed=-1, *, base=None, shared_tokens """`tokens`' block hashes, taking the first blocks from `base`. `shared_tokens` is how many leading tokens `tokens` shares with `base`'s, - and must come from SegmentTokenizer's matched added-token cut -- an - internal fact, never a client-supplied cached-token count. Only complete - blocks inside it are reused; the rest is hashed here. + and must come from SegmentTokenizer's matched added-token cut or + TokenPrefixChains' token compare -- never a client-supplied count. Only + complete blocks inside it are reused; the rest is hashed here. """ from atom.model_engine.prefix_hash import chained_block_hashes @@ -88,3 +104,148 @@ def extend_block_hashes(tokens, block_size, seed=-1, *, base=None, shared_tokens ) ) return PrefixBlockHashes(block_size, seed, len(tokens), packed.tobytes()) + + +class _TokenRecord(NamedTuple): + """A stored token-id prompt: its int32 tokens as bytes, its chain, its LRU key.""" + + tokens: bytes + hashes: PrefixBlockHashes + rid: int + + @property + def payload_bytes(self) -> int: + return ( + sys.getsizeof(self) + + sys.getsizeof(self.tokens) + + self.hashes.payload_bytes + + sys.getsizeof(self.rid) + ) + + +_TOKENS = attrgetter("tokens") + + +def _shared_tokens(a: np.ndarray, b: np.ndarray) -> int: + """Length of the common prefix of `a` and `b`.""" + n, start, step = min(len(a), len(b)), 0, 4096 + while start < n: + end = min(start + step, n) + diff = np.flatnonzero(a[start:end] != b[start:end]) + if len(diff): + return start + int(diff[0]) + start, step = end, step * 2 + return n + + +class TokenPrefixChains: + """Token-id prompts' chains: each reuses the complete blocks it shares with + the stored prompt sharing the most leading tokens, then is stored itself + unless that prompt holds all of its tokens.""" + + def __init__(self, budget_bytes: int, block_size: int, enabled: bool = True): + self.block_size = block_size + self.enabled = enabled and budget_bytes > 0 + self._lock = threading.Lock() + self._lru = ByteLRU(budget_bytes, on_evict=self._unlist) + # Stored records in their tokens' bytes order, which is lexicographic: the + # one sharing the most leading tokens with a prompt sorts beside the prompt. + self._order: list[_TokenRecord] = [] + self._next_id = 0 + self._verified = 0 + self._counts = dict.fromkeys( + ("prompts", "blocks_hashed", "blocks_reused", "blocks_rehashed"), 0 + ) + + def stats(self) -> dict: + """Prompts seen and their chains' complete blocks: hashed, reused from a + stored prompt, and hashed again to check a reuse.""" + with self._lock: + return {"enabled": self.enabled, **self._counts} + + def block_hashes(self, tokens) -> PrefixBlockHashes: + """`chained_block_hashes` of `tokens`' complete blocks (seed -1), hashing + only those past what it shares with a stored prompt.""" + from atom.model_engine.prefix_hash import chained_block_hashes + + bs, raw = self.block_size, np.asarray(tokens, dtype=np.int32).tobytes() + toks = np.frombuffer(raw, dtype=np.int32) + n = len(toks) // bs + with self._lock: + enabled, verify = self.enabled, self._verified < _VERIFY_FIRST + base, shared = self._find(raw, toks) if enabled and n else (None, 0) + chain = extend_block_hashes( + toks, bs, base=None if base is None else base.hashes, shared_tokens=shared + ) + reused = shared // bs + rehash = bool(reused) and verify # check the first reuses + if rehash: + full = array.array("Q", chained_block_hashes(toks, bs, 0, n, -1)).tobytes() + with self._lock: + # a reuse still in flight when reuse turned off is hashed again below + late = bool(reused) and not rehash and not self.enabled + if rehash and full != chain.hashes: + self._turn_off() + chain = PrefixBlockHashes(bs, -1, len(toks), full) + elif rehash and self.enabled: + self._verified += 1 + # a prefix of `base` would serve no later prompt better than `base` + if enabled and self.enabled and n and shared < len(toks): + whole = reused and reused == base.hashes.num_blocks + self._store(raw, chain, base if whole else None) + counts = self._counts + counts["prompts"] += 1 + counts["blocks_hashed"] += n - reused + counts["blocks_reused"] += reused + counts["blocks_rehashed"] += n if rehash or late else 0 + if late: + full = array.array("Q", chained_block_hashes(toks, bs, 0, n, -1)).tobytes() + chain = PrefixBlockHashes(bs, -1, len(toks), full) + return chain + + def _find(self, raw: bytes, toks: np.ndarray): + """`(record, shared tokens)` of the stored prompt sharing the most leading + tokens with `toks`, one of the two `raw` sorts between; `(None, 0)` if none.""" + with self._lock: + i = bisect_left(self._order, raw, key=_TOKENS) + near = self._order[max(i - 1, 0) : i + 1] + best, shared = None, 0 + for record in near: + count = _shared_tokens(toks, np.frombuffer(record.tokens, dtype=np.int32)) + if count > shared: + best, shared = record, count + if best is not None: + with self._lock: + self._lru.get(best.rid) + return best, shared + + def _store(self, raw: bytes, chain, replaces) -> None: + """Keep `raw` and its chain, in place of `replaces`, a record whose every + block it reused (lock held).""" + record = _TokenRecord(raw, chain, self._next_id) + if not self._lru.fits(record.payload_bytes): + return # it would not be kept, so `replaces` stays + if replaces is not None and self._lru.pop(replaces.rid) is not None: + self._unlist(replaces.rid, replaces) + self._next_id += 1 + self._lru.put(record.rid, record, record.payload_bytes) + insort(self._order, record, key=_TOKENS) + + def _unlist(self, _rid, record) -> None: + """Drop `record` from the bytes order (lock held; also ByteLRU's eviction + callback).""" + i = bisect_left(self._order, record.tokens, key=_TOKENS) + while self._order[i] is not record: + i += 1 + del self._order[i] + + def _turn_off(self) -> None: + """A reused chain differed from a full rehash: stop reusing (lock held).""" + if self.enabled: + logger.warning( + "token prefix chains: a reused chain differs from a full rehash; " + "reuse is off" + ) + self.enabled = False + self._lru.clear() + self._order.clear() diff --git a/atom/model_engine/segment_tokenizer.py b/atom/model_engine/segment_tokenizer.py index d9df96cc0a7..52ede415d13 100644 --- a/atom/model_engine/segment_tokenizer.py +++ b/atom/model_engine/segment_tokenizer.py @@ -381,6 +381,8 @@ def _store_prefix( with self._lock: if not self.enabled: # as for segments above return + if not self._lru.fits(entry.payload_bytes): + return # it would not be kept, so `base` stays pids = self._buckets.get(bucket, []) if replaces: for pid in list(pids): @@ -394,10 +396,6 @@ def _store_prefix( if len(pids) > _PREFIX_BUCKET: self._lru.pop(("p", pids.pop(0))) self._lru.put(("p", pid), entry, entry.payload_bytes) - if ("p", pid) not in self._lru: # larger than the whole budget - pids.remove(pid) - if not pids: - self._buckets.pop(bucket, None) def _evicted(self, key, value) -> None: """LRU eviction callback (lock held): unindex a stored prompt.""" diff --git a/atom/model_ops/dcp_ops.py b/atom/model_ops/dcp_ops.py index 8010d6c9f7f..d307b3c6b96 100644 --- a/atom/model_ops/dcp_ops.py +++ b/atom/model_ops/dcp_ops.py @@ -34,6 +34,7 @@ dcp_global_pos, dcp_local_index, dcp_owner_rank, + get_dcp_local_seq_lens, ) from atom.distributed.dcp_utils import get_dcp_group, get_dcp_world_size from atom.model_ops.indexer.layout import MFMA, PRESHUFFLE @@ -1322,33 +1323,6 @@ def reorg_kvcache( return reorganized_kv_c_normed, reorganized_k_pe -def get_dcp_local_seq_lens(seq_lens, dcp_size, dcp_rank, cp_kv_cache_interleave_size=1): - """Compute per-DCP-rank local sequence lengths. - - With interleaved storage, token i is stored on rank - (i // cp_kv_cache_interleave_size) % dcp_size. - - Args: - seq_lens: numpy array of sequence lengths - dcp_size: DCP world size - dcp_rank: this rank's DCP rank - cp_kv_cache_interleave_size: interleaving granularity (default 1 = token-level) - - Returns: - local_seq_lens: numpy array of local sequence lengths - """ - full_chunks = seq_lens // (cp_kv_cache_interleave_size * dcp_size) - base = full_chunks * cp_kv_cache_interleave_size - - remainder_total = seq_lens - base * dcp_size - remainder = np.clip( - remainder_total - dcp_rank * cp_kv_cache_interleave_size, - 0, - cp_kv_cache_interleave_size, - ) - return base + remainder - - def get_dcp_local_window_lens( positions, dcp_size, dcp_rank, cp_kv_cache_interleave_size=1 ): diff --git a/docs/environment_variables.md b/docs/environment_variables.md index 4dd2333ffa4..3dedd0e8f4f 100644 --- a/docs/environment_variables.md +++ b/docs/environment_variables.md @@ -134,7 +134,7 @@ cannot affect a server that does not use the feature. |----------|------|---------|-------------| | **ATOM_DISABLE_MMAP** | bool | false | If set to `true`, disable memory-mapped file loading for model weights. Useful in containerized environments where mmap may cause issues. | | **ATOM_LOADER_NUM_THREADS** | int | 16 | Worker threads for weight loading. `>1` (default `16`) enables the batched parallel loader (routed expert weights staged in a CPU buffer, flushed with a single H2D copy when every routed expert of that parameter has arrived) with that many threads; set to `1` to fall back to the original sequential per-expert path. Raise on high-core hosts if loading is CPU-bound. | -| **ATOM_TOKENIZE_CACHE_MB** | int | 512 | Host memory, in MB, the API server keeps for reusing prompt tokenization across requests. A chat template separates messages with added (special) tokens, and the text between two of them tokenizes the same on its own. Each prompt is kept with its ids up to its last added token, so the next turn of the conversation reuses them up to the last added token both share; the rest is split at added tokens and each segment's ids are cached by content, the missing ones encoded in one parallel batch. Both are exact: they are used only when the tokenizer's added tokens, normalizer and pre-tokenizer allow it, and the first prompts are checked against the plain encoder (any difference turns the cache off). Prompts under 100K characters are encoded whole. One budget covers segment ids and stored prompts, counted by the bytes they retain (ids, text, per-entry overhead). The result still covers the whole prompt, so a request costs time linear in its length; what is saved is re-encoding text already encoded. Lowers TTFT on long multi-turn conversations; ITL and throughput are unaffected. `0` turns it off. | +| **ATOM_TOKENIZE_CACHE_MB** | int | 512 | Host memory, in MB, the API server keeps for reusing prompt tokenization across requests. A chat template separates messages with added (special) tokens, and the text between two of them tokenizes the same on its own. Each prompt is kept with its ids up to its last added token, so the next turn of the conversation reuses them up to the last added token both share; the rest is split at added tokens and each segment's ids are cached by content, the missing ones encoded in one parallel batch. Both are exact: they are used only when the tokenizer's added tokens, normalizer and pre-tokenizer allow it, and the first prompts are checked against the plain encoder (any difference turns the cache off). Prompts under 100K characters are encoded whole. One budget covers segment ids and stored prompts, counted by the bytes they retain (ids, text, per-entry overhead). The result still covers the whole prompt, so a request costs time linear in its length; what is saved is re-encoding text already encoded. Lowers TTFT on long multi-turn conversations; ITL and throughput are unaffected. Prompts sent as token IDs keep their block-hash chains in a store of their own with a budget of the same size (`ATOM_TOKENIZE_CACHE_BLOCK_HASHES`). `0` turns both off. | | **ATOM_LOADER_STRICT_COVERAGE** | bool | `true` | Fail loading when a fused MoE parameter does not receive every routed expert from the checkpoint. Set to `false` to downgrade to a warning and load anyway, leaving those expert slots at their init values — useful when bringing up a checkpoint known to be partial, misleading otherwise (the symptom is an accuracy drop much later). | | **ATOM_LOADER_PREFETCH** | bool | `true` | Warm the page cache by reading this rank's share of the checkpoint sequentially on a background thread, instead of leaving it to demand faults through the mmap. The fault pattern sustains ~3.2 GB/s on a local NVMe that a single sequential reader drives at 6.06 GB/s, so this is an access-pattern fix, not a queue-depth one. Measured on DeepSeek-R1 MXFP4 (350 GiB, TP=4): cold load 154s → 69s. Set to `false` to restore demand faulting. Also applies with `ATOM_DISABLE_MMAP=true`, whose whole-file reads go through the same page cache (DeepSeek-V4.1-Flash, TP=4, cold: 282–315s without it, 169–207s with it). | | **ATOM_LOADER_PREFETCH_THREADS** | int | 4 | Concurrent sequential readers per rank used by the prefetcher. The device saturates at ~2 streams, so raising this mostly adds contention with the loader; `0` is clamped to `1` (use `ATOM_LOADER_PREFETCH=false` to switch prefetching off). | @@ -458,7 +458,7 @@ and catches it; set it when chasing a corruption that does not reproduce. | Variable | Type | Default | Description | |----------|------|---------|-------------| -| **ATOM_TOKENIZE_CACHE_BLOCK_HASHES** | bool | true | Keep the prompt block-hash chain that frontend prefix hashing ships to the engine (`ATOM_FRONTEND_PREFIX_HASH`) with each prompt the tokenizer cache stores, and on the next turn hash only the blocks after the tokenizer's matched prefix instead of the whole prompt. Content hashes only: whether a block's KV is still resident is decided by BlockManager, so this cannot turn into a KV prefix hit. The hashes count toward `ATOM_TOKENIZE_CACHE_MB`. Needs prefix caching, `ATOM_FRONTEND_PREFIX_HASH=1` and an active tokenizer cache; multimodal and token-ID requests hash as before. `0` hashes every prompt in full. | +| **ATOM_TOKENIZE_CACHE_BLOCK_HASHES** | bool | true | Keep the prompt block-hash chain that frontend prefix hashing ships to the engine (`ATOM_FRONTEND_PREFIX_HASH`) with each prompt the tokenizer cache stores, and on the next turn hash only the blocks after the tokenizer's matched prefix instead of the whole prompt. Content hashes only: whether a block's KV is still resident is decided by BlockManager, so this cannot turn into a KV prefix hit. The hashes count toward `ATOM_TOKENIZE_CACHE_MB`. Needs prefix caching, `ATOM_FRONTEND_PREFIX_HASH=1` and an active tokenizer cache. A prompt sent as token IDs (`prompt_token_ids`, gRPC) is stored with its chain instead, in a store of its own sized by `ATOM_TOKENIZE_CACHE_MB`; the next one takes the complete blocks it shares with the stored prompt sharing the most leading tokens, found by token comparison. The first reuses are checked against a full rehash, and any difference turns reuse off. `/debug/cache_stats` reports the blocks hashed and reused under `token_prefix_chains`. Multimodal requests hash as before. `0` hashes every prompt in full. | | **ATOM_FRONTEND_PREFIX_HASH** | bool | true | Hash the prompt's block chain while the request is built (API server preprocessing executor) and ship it to the engine with a fingerprint of the prompt tokens, beside the request in the ADD message (never inside a pickled `Sequence`; with `DisaggCoreManager` only the decode engine, which allocates, gets it). The engine adopts it if block size, seed, length and fingerprint match and its first, middle and last links rehash equal, then uses it for the prefix walk, `allocate` and publishing the prompt blocks after prefill, so prefill hashes no prompt block on the scheduler thread (it hashes the prompt bytes once for the fingerprint, about 26 us at 186k tokens; the LMCache/offload and PD-transfer publish paths still hash their blocks). Any mismatch falls back to engine-side hashing. Read in the API server process. | | **ATOM_PROMPT_IDS_B64** | bool | true | Read a chat request's `prompt_token_ids_b64` (the prompt ids packed as little-endian uint32 and base64-encoded into one JSON string, e.g. `base64.b64encode(array.array("I", ids).tobytes())` on a little-endian host) into the `array("i")` a `Sequence` stores, instead of parsing and validating a JSON list of ids. A P/D client sends this field in place of `prompt_token_ids`. A P/D prefill leg (`kv_transfer_params.do_remote_decode`) that got its ids this way does not echo them (`return_token_ids`), so the PD router carries no second JSON copy into decode's `kv_transfer_params`: decode reads the same field from the client body the router forwards. Any other request with `return_token_ids` (for example on a single server) still gets its ids, and a multimodal prefill still echoes (its ids have the image placeholders expanded). A multimodal decode leg runs on its prefill's expanded ids from `kv_transfer_params` and does not compare them with the b64 ids. Enable on P and D together; a mixed setup is not supported. Upgrade P and D before a client sends the field. A P or D that runs an ATOM without this change, or sets it to 0, makes the pair mixed. Malformed base64, an empty or ragged buffer, ids above int32, or ids that disagree with `prompt_token_ids` are a 422. Chat completions only. A request without `prompt_token_ids_b64` is served exactly as before. `0`: the field is ignored (one warning). Read in the API server process. | | **ATOM_PREFIX_FAST_WALK** | bool | true | Look the prompt's chain up with C-speed `map` rounds (the first block alone, then 16, 64, ... blocks, so a cold prompt costs one lookup), compare tokens on the last hit block only (all blocks if that one differs), and let `allocate` claim the blocks `can_allocate` found instead of walking the prompt again; any block that changed in between sends it back to the block-by-block walk. `0` walks block by block with a token compare per block. | diff --git a/tests/test_admission_host_overhead.py b/tests/test_admission_host_overhead.py index 329448e209b..c40eee16c9d 100644 --- a/tests/test_admission_host_overhead.py +++ b/tests/test_admission_host_overhead.py @@ -545,7 +545,7 @@ def test_the_chain_rides_beside_the_seqs(monkeypatch, manager): poller = SimpleNamespace(register=lambda *a: None, poll=lambda: [(sock, 1)]) monkeypatch.setattr(core.zmq, "Poller", lambda: poller) engine = object.__new__(core.EngineCore) - engine._kv_progress_event = threading.Event() + engine._wake_event = threading.Event() engine.label, engine.input_queue = "test", queue.Queue() engine.process_input_sockets("input", "control") want = reference_chain(tokens, BLOCK, -1, 10) diff --git a/tests/test_dense_offload_connector.py b/tests/test_dense_offload_connector.py index 58babb6137d..1f15d9bdeec 100644 --- a/tests/test_dense_offload_connector.py +++ b/tests/test_dense_offload_connector.py @@ -1,12 +1,10 @@ # SPDX-License-Identifier: MIT # Copyright (C) 2024-2026, Advanced Micro Devices, Inc. All rights reserved. -import sys import threading from contextlib import nullcontext -from types import ModuleType, SimpleNamespace +from types import SimpleNamespace -import numpy as np import pytest import torch from conftest import with_min_load @@ -100,32 +98,10 @@ def _engine_scheduler(connector): return scheduler -def _stub_dcp_ops_without_triton(monkeypatch): - """BlockManager pulls get_dcp_local_seq_lens from dcp_ops, which imports Triton.""" - - def get_dcp_local_seq_lens( - seq_lens, dcp_size, dcp_rank, cp_kv_cache_interleave_size=1 - ): - full_chunks = seq_lens // (cp_kv_cache_interleave_size * dcp_size) - base = full_chunks * cp_kv_cache_interleave_size - remainder_total = seq_lens - base * dcp_size - remainder = np.clip( - remainder_total - dcp_rank * cp_kv_cache_interleave_size, - 0, - cp_kv_cache_interleave_size, - ) - return base + remainder - - fake_dcp_ops = ModuleType("atom.model_ops.dcp_ops") - fake_dcp_ops.get_dcp_local_seq_lens = get_dcp_local_seq_lens - monkeypatch.setitem(sys.modules, "atom.model_ops.dcp_ops", fake_dcp_ops) - - @pytest.mark.parametrize("hbm", [0, 8]) def test_loaded_prefix_can_publish_suffix_and_be_reused( monkeypatch, mock_config, seq_factory, hbm ): - _stub_dcp_ops_without_triton(monkeypatch) mock_config.enable_prefix_caching = True mock_config.decode_context_parallel_size = 2 mock_config.num_kvcache_blocks = 16 diff --git a/tests/test_engine_core_idle_wait.py b/tests/test_engine_core_idle_wait.py new file mode 100644 index 00000000000..05b850462c6 --- /dev/null +++ b/tests/test_engine_core_idle_wait.py @@ -0,0 +1,134 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors +"""An idle `EngineCore.busy_loop` sleeps on the event its input thread sets after each +put, rather than spinning on the GIL that thread needs; a request queued wakes it.""" + +import pickle +import queue +import threading +from collections import deque +from contextlib import nullcontext +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +LONG_WAIT_S = 3600.0 # the idle loop's timeout here: only a wake ends its wait + + +@pytest.fixture +def idle(monkeypatch, request): + """An `EngineCore` or PP head with nothing to run, whose scheduler steps what it + is given; `waits` gets each wait's timeout and whether it could return at once.""" + from aiter_stub import stubbed_aiter + + with stubbed_aiter(): + from atom.model_engine import engine_core as core + from atom.model_engine.pp_engine_core import PPEngineCoreProc + monkeypatch.setattr(core, "IDLE_WAIT_S", LONG_WAIT_S) + pp_head = getattr(request, "param", "EngineCore") == "PP head" + cls = PPEngineCoreProc if pp_head else core.EngineCore + engine = cls.__new__(cls) + waits, pending, stepped = queue.Queue(), [], [] + + class Event(threading.Event): + def wait(self, timeout=None): + queued = not engine.input_queue.empty() or not engine.utility_queue.empty() + waits.put((timeout, self.is_set() or queued)) + return super().wait(timeout) + + def step(): + stepped.append([seq.id for seq in pending]) + pending.clear() + return True + + engine.scheduler = Mock(extend=pending.extend, is_finished=lambda: not pending) + engine.utility_handler = Mock() + engine.label = "test" + engine.kv_transfer_enabled = False + engine._ingested_seqs = 0 + engine._is_rl_weights_offloaded = False + engine._weight_sync_fenced = False + engine._generation_paused = False + engine.input_queue = queue.Queue() + engine.utility_queue = queue.Queue() + engine._wake_event = Event() + engine._process_engine_step = step + if pp_head: + engine.is_head, engine._in_flight = True, deque() + engine._pp_kv_aggregator, engine.runner_mgr = None, Mock() + engine._run_then_publish_kv_events = lambda run: run() + engine._pp_head_step = step + return core, engine, waits, stepped + + +@pytest.mark.parametrize("idle", ["EngineCore", "PP head"], indirect=True) +def test_a_request_from_the_input_thread_wakes_an_idle_loop(idle, monkeypatch): + core, engine, waits, stepped = idle + frames = queue.Queue() # what the input thread's sockets receive + sock = SimpleNamespace(send=lambda frame: None, recv=lambda **_: frames.get()) + poller = SimpleNamespace( + register=lambda *args: None, poll=lambda: [(sock, core.zmq.POLLIN)] + ) + monkeypatch.setattr(core, "make_zmq_socket", lambda *a, **k: nullcontext(sock)) + monkeypatch.setattr(core.zmq, "Poller", lambda: poller) + seq = core.Sequence([1, 2, 3], block_size=4) + inputs = threading.Thread( + target=engine.process_input_sockets, args=("input", "control"), daemon=True + ) + loop = threading.Thread(target=engine.busy_loop, daemon=True) + inputs.start() + loop.start() + try: + assert waits.get(timeout=5) == (LONG_WAIT_S, False) # idle: asleep + frames.put(pickle.dumps((core.EngineCoreRequestType.ADD, [seq]))) + assert waits.get(timeout=5) == (LONG_WAIT_S, False) # stepped, asleep again + assert stepped == [[seq.id]] + finally: + frames.put(pickle.dumps((core.EngineCoreRequestType.SHUTDOWN, None))) + inputs.join(5) + loop.join(5) + assert not inputs.is_alive() and not loop.is_alive() + + +def test_a_request_queued_before_the_wait_is_not_slept_on(idle): + core, engine, waits, stepped = idle + seq = core.Sequence([1, 2, 3], block_size=4) + stats = engine.scheduler.engine_stats + + def arrive(now): # the input thread's put and set, after the pull, before the wait + stats.note_idle = lambda now: None + engine.input_queue.put_nowait([seq]) + engine._wake_event.set() + + stats.note_idle = arrive + loop = threading.Thread(target=engine.busy_loop, daemon=True) + loop.start() + try: + assert waits.get(timeout=5) == (LONG_WAIT_S, False) # only after its step + assert stepped == [[seq.id]] + finally: + engine.input_queue.put_nowait([core.get_exit_sequence()]) + engine._wake_event.set() + loop.join(5) + assert not loop.is_alive() + + +def test_a_put_while_the_queues_are_checked_is_not_slept_on(idle): + _, engine, _, _ = idle + arrived = [] + + class Arriving(queue.Queue): # the input thread's put and set land in the check + def empty(self): + if not arrived: + arrived.append(True) + engine.input_queue.put_nowait("request") + engine._wake_event.set() + return super().empty() + + engine.utility_queue = Arriving() + waiter = threading.Thread(target=engine._wait_for_input, daemon=True) + waiter.start() + waiter.join(5) + assert not waiter.is_alive() # woken at once, not after IDLE_WAIT_S diff --git a/tests/test_engine_core_kv_wait.py b/tests/test_engine_core_kv_wait.py index b2675a27a86..2a42222509e 100644 --- a/tests/test_engine_core_kv_wait.py +++ b/tests/test_engine_core_kv_wait.py @@ -36,7 +36,7 @@ def engine_step(monkeypatch): kv_transfer_enabled=True, runner_mgr=SimpleNamespace(call_func=Mock(return_value="forward-result")), _poll_kv_transfer_progress=Mock(return_value=False), - _kv_progress_event=event, + _wake_event=event, input_queue=queue.Queue(), utility_queue=queue.Queue(), _postprocess=Mock(), @@ -125,7 +125,7 @@ def test_already_queued_work_does_not_wait(engine_step, queue_name): def test_arrival_during_poll_is_latched_until_wait(engine_step): module, engine, _, _ = engine_step event = threading.Event() - engine._kv_progress_event = event + engine._wake_event = event def poll(): event.set() @@ -139,7 +139,7 @@ def poll(): def test_arrival_between_queue_check_and_wait_is_not_lost(engine_step): module, engine, _, _ = engine_step event = threading.Event() - engine._kv_progress_event = event + engine._wake_event = event class ArrivalQueue: def empty(self): @@ -165,7 +165,7 @@ def wait(self, timeout): # within the production 1 ms interval. assert event.wait(5) - engine._kv_progress_event = ObservedEvent() + engine._wake_event = ObservedEvent() def run(): module.EngineCore._wait_for_kv_progress(engine) diff --git a/tests/test_engine_idle_gil.py b/tests/test_engine_idle_gil.py index d599d2a419c..d6d2e92b916 100644 --- a/tests/test_engine_idle_gil.py +++ b/tests/test_engine_idle_gil.py @@ -28,6 +28,7 @@ def _idle_engine(passes): pull_and_process_input_queue=lambda: next(passes), _is_engine_held=lambda: False, has_pending_kv_work=lambda: False, + _wait_for_input=lambda: None, _drain_kv_work_at_exit=lambda: None, scheduler=SimpleNamespace( heartbeat_throughput=lambda _: None, diff --git a/tests/test_engine_loop_idle_accounting.py b/tests/test_engine_loop_idle_accounting.py index 1014a6a8429..7bd381ce649 100644 --- a/tests/test_engine_loop_idle_accounting.py +++ b/tests/test_engine_loop_idle_accounting.py @@ -162,6 +162,9 @@ def has_pending_kv_work(self): def _advance_idle_kv_transfer(self): raise AssertionError("no KV work was scripted") + def _wait_for_input(self): + pass + def _drain_kv_work_at_exit(self): return None diff --git a/tests/test_kv_events.py b/tests/test_kv_events.py index 2969dda5770..2a9121496f0 100644 --- a/tests/test_kv_events.py +++ b/tests/test_kv_events.py @@ -729,6 +729,7 @@ def run_then_publish(step): _run_then_publish_kv_events=run_then_publish, has_pending_kv_work=lambda: work == "kv", _advance_idle_kv_transfer=do_work, + _wait_for_input=lambda: None, _drain_kv_work_at_exit=lambda: None, kv_transfer_enabled=False, pp_transport=SimpleNamespace(recv_metadata=recv_metadata), diff --git a/tests/test_pd_chunked_transfer.py b/tests/test_pd_chunked_transfer.py index 44bf466781d..15d2339f3c2 100644 --- a/tests/test_pd_chunked_transfer.py +++ b/tests/test_pd_chunked_transfer.py @@ -1930,7 +1930,7 @@ def test_last_unadmitted_cancel_reaches_worker_despite_idle_throttle( dispatch(worker, request) assert p.abort_request(seq.id) core = EngineCore.__new__(EngineCore) - core._kv_progress_event = threading.Event() + core._wake_event = threading.Event() core.input_queue = queue.Queue() core.utility_queue = queue.Queue() core.scheduler = p diff --git a/tests/test_scheduler_metrics.py b/tests/test_scheduler_metrics.py index 858247b7492..9257cd0b397 100644 --- a/tests/test_scheduler_metrics.py +++ b/tests/test_scheduler_metrics.py @@ -175,7 +175,7 @@ def test_engine_receipt_includes_time_buffered_before_scheduler_admission( ), ) engine = core.EngineCore.__new__(core.EngineCore) - engine._kv_progress_event = core.threading.Event() + engine._wake_event = core.threading.Event() engine.label = "metrics-test" engine.input_queue = Queue() engine.process_input_sockets("input", "control") diff --git a/tests/test_segment_tokenizer.py b/tests/test_segment_tokenizer.py index b7ef8ccbfac..2af3116b2bf 100644 --- a/tests/test_segment_tokenizer.py +++ b/tests/test_segment_tokenizer.py @@ -484,6 +484,31 @@ def test_a_rewritten_generation_prompt_replaces_the_stored_turn(tok): assert len(_stored(seg)) == 1 +def test_a_turn_too_large_to_store_keeps_the_turn_it_extends(tok): + from atom.model_engine.byte_lru import ENTRY_OVERHEAD + + rng = random.Random(24) + first = _long_conversation(rng, 2) + "<|Assistant|>" + second = first + _text(rng, 3000) + "<|User|>" + _text(rng, 20) + "<|Assistant|>" + third = first + _text(rng, 20) + "<|User|>" + _text(rng, 20) + "<|Assistant|>" + + def run(budget, prompts): + seg = SegmentTokenizer.maybe_create(tok, budget) + seg._verified = seg_mod._VERIFY_FIRST + for p in prompts: + assert seg._encode_cached(p) == tok.encode(p) + assert seg._lru.bytes <= budget + return seg + + # One byte short of keeping `second`, which would replace `first`. + [entry] = _stored(run(10**7, [first, second])) + seg = run(entry.payload_bytes + ENTRY_OVERHEAD - 1, [first, second]) + assert [e.text for e in _stored(seg)] == [first] + hits = seg._stats[4] + assert seg._encode_cached(third) == tok.encode(third) + assert seg._stats[4] == hits + 1 + + def test_a_fork_keeps_the_stored_prompt_it_left(tok): seg = SegmentTokenizer.maybe_create(tok, 10**7) seg._verified = seg_mod._VERIFY_FIRST diff --git a/tests/test_token_prefix_chains.py b/tests/test_token_prefix_chains.py new file mode 100644 index 00000000000..4a9fc5b78b1 --- /dev/null +++ b/tests/test_token_prefix_chains.py @@ -0,0 +1,316 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors +"""Token-id prompts reuse the block-hash chain of the stored prompt they share +the most leading tokens with (`TokenPrefixChains`).""" + +from concurrent.futures import ThreadPoolExecutor +from itertools import pairwise +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import numpy as np +import pytest +from aiter_stub import stubbed_aiter +from conftest import MockConfig +from test_admission_host_overhead import over_ipc + +from atom.model_engine import prefix_block_hashes as pb +from atom.model_engine import prefix_hash as ph +from atom.model_engine.block_manager import BlockManager +from atom.sampling_params import SamplingParams + +with stubbed_aiter(): + from atom.model_engine.llm_engine import InputOutputProcessor, LLMEngine + +COUNTS = ("prompts", "blocks_hashed", "blocks_reused", "blocks_rehashed") +GEN = [3, 4] # a turn's generation prompt, rewritten once the turn is answered + + +@pytest.fixture(autouse=True) +def env(monkeypatch): + monkeypatch.delenv("ATOM_TOKENIZE_CACHE_MB", raising=False) + monkeypatch.delenv("ATOM_TOKENIZE_CACHE_BLOCK_HASHES", raising=False) + monkeypatch.setenv("ATOM_FRONTEND_PREFIX_HASH", "1") + + +def processor(block_size): + config = SimpleNamespace( + hf_config=SimpleNamespace(model_type="llama"), + speculative_config=None, + enable_prefix_caching=True, + decode_context_parallel_size=1, + ) + return InputOutputProcessor(config, MagicMock(), block_size) + + +def served(proc): + """The token-id chain counts `/debug/cache_stats` serves for `proc`.""" + engine = LLMEngine.__new__(LLMEngine) + engine.io_processor = proc + engine.core_mgr = SimpleNamespace(broadcast_utility_command_sync=lambda *a, **k: []) + return engine.get_cache_statistics()["token_prefix_chains"] + + +def full_chain(prompt, block): + return ph.chained_block_hashes(prompt, block, 0, len(prompt) // block, -1) + + +def tokens(rng, n): + return rng.integers(10, 150_000, int(n)).tolist() + + +def conversation(rng, system, turns): + """A token-id conversation's prompts: each turn rewrites the generation + prompt, then adds an answer, a user message and the generation prompt.""" + prompt = system + tokens(rng, rng.integers(50, 3000)) + GEN + for _ in range(turns): + yield prompt + prompt = prompt[: -len(GEN)] + [5] + tokens(rng, rng.integers(50, 3000)) + GEN + + +def scenario(): + rng = np.random.default_rng(0) + system = tokens(rng, 6000) + a, b = conversation(rng, system, 7), conversation(rng, system, 7) + prompts = [p for pair in zip(a, b) for p in pair] + fork = prompts[6] + # a fork, an edit inside a turn, a compaction, no complete block, a retry + prompts += [fork + tokens(rng, 900), fork[:-500] + tokens(rng, 700)] + return prompts + [system + tokens(rng, 400), tokens(rng, 7), list(prompts[3])] + + +def shared_blocks(earlier, prompt, block): + """Complete blocks `prompt` shares with the earlier prompt sharing the most.""" + best, p = 0, np.array(prompt) + for other in earlier: + q = np.array(other) + m = min(len(p), len(q)) + diff = np.flatnonzero(p[:m] != q[:m]) + best = max(best, int(diff[0] if len(diff) else m) // block) + return best + + +@pytest.mark.parametrize("block", [16, 48, 256]) +def test_each_turn_ships_a_full_recompute_hashing_only_unshared_blocks(block): + proc, prompts = processor(block), scenario() + bm = BlockManager(MockConfig(kv_cache_block_size=block, enable_prefix_caching=True)) + before, reuses = served(proc), 0 + for i, prompt in enumerate(prompts): + with patch.object(ph, "_link", wraps=ph._link) as link: + [seq] = proc.preprocess_fanout(prompt, SamplingParams()) + n, reused = len(prompt) // block, shared_blocks(prompts[:i], prompt, block) + assert list(seq.prompt_hash_chain.hashes) == full_chain(prompt, block) + after = served(proc) + checked = reused > 0 and reuses < pb._VERIFY_FIRST + assert {k: after[k] - before[k] for k in COUNTS} == { + "prompts": 1, + "blocks_hashed": n - reused, + "blocks_reused": reused, + "blocks_rehashed": n if checked else 0, + } + assert link.call_count == n - reused + (n if checked else 0) + [seq] = over_ipc([seq]) + assert bm._prompt_hashes(seq) == full_chain(prompt, block) + before, reuses = after, reuses + (reused > 0) + assert after["enabled"] and reuses == len(prompts) - 2 + assert (bm.shipped_chains_adopted, bm.shipped_chains_rejected) == (len(prompts), 0) + assert proc.tokenizer.encode.call_count == 0 + proc.tokenizer.encode.side_effect = lambda text, **_: list(range(1, 99)) + proc.preprocess_fanout("a prompt sent as text", SamplingParams()) + assert served(proc)["prompts"] == len(prompts) + + +def test_each_conversation_finds_its_own_turn_among_many_sharing_a_start(): + # 40 conversations share a 6,000-token system prompt; each one's next turn, + # oldest first, reuses every block it shares with its own stored turn. + proc, rng = processor(16), np.random.default_rng(3) + system = tokens(rng, 6000) + firsts = [system + tokens(rng, rng.integers(500, 1500)) + GEN for _ in range(40)] + for prompt in firsts: + proc.preprocess_fanout(prompt, SamplingParams()) + for first in firsts: + prompt = first[: -len(GEN)] + [5] + tokens(rng, 300) + GEN + before = served(proc)["blocks_reused"] + [seq] = proc.preprocess_fanout(prompt, SamplingParams()) + assert list(seq.prompt_hash_chain.hashes) == full_chain(prompt, 16) + assert served(proc)["blocks_reused"] - before == (len(first) - len(GEN)) // 16 + + +def test_reuse_is_sized_by_a_token_compare_from_the_first(): + # Past the first-uses check, stored prompts that sort next to a new one and + # differ from it only at its first token, or inside a block, size its reuse. + proc, rng = processor(16), np.random.default_rng(4) + prompt = tokens(rng, 2000) + for _ in range(1 + pb._VERIFY_FIRST): + proc.preprocess_fanout(prompt, SamplingParams()) + prompt = prompt + tokens(rng, 100) + stored, cut = prompt[:-100], 37 * 16 + 5 + for edit, reused in ((0, 0), (cut, cut // 16)): + new = list(stored) + new[edit] += 1 + new += tokens(rng, 50) + before = served(proc) + [seq] = proc.preprocess_fanout(new, SamplingParams()) + assert list(seq.prompt_hash_chain.hashes) == full_chain(new, 16) + after = served(proc) + assert after["blocks_reused"] - before["blocks_reused"] == reused + assert after["blocks_rehashed"] == before["blocks_rehashed"] + + +@pytest.mark.parametrize( + "env, kept", + [ + ({}, "a1"), + # One 124K-token prompt fits in 1 MB, two do not. + ({"ATOM_TOKENIZE_CACHE_MB": "1"}, "b1"), + ({"ATOM_TOKENIZE_CACHE_MB": "0"}, None), + ({"ATOM_TOKENIZE_CACHE_BLOCK_HASHES": "0"}, None), + ], +) +def test_reuse_follows_the_cache_budget_and_its_switch(monkeypatch, env, kept): + for var, value in env.items(): + monkeypatch.setenv(var, value) + rng = np.random.default_rng(1) + system = tokens(rng, 4096) + a1, b1 = system + tokens(rng, 120_000), system + tokens(rng, 120_000) + proc, reused = processor(16), [] + for prompt in (a1, b1, a1 + tokens(rng, 3000)): + before = served(proc)["blocks_reused"] + [seq] = proc.preprocess_fanout(prompt, SamplingParams()) + assert list(seq.prompt_hash_chain.hashes) == full_chain(prompt, 16) + reused.append(served(proc)["blocks_reused"] - before) + assert served(proc)["enabled"] == (kept is not None) + if kept is None: # a store that is off is not consulted + assert reused == [0, 0, 0] and served(proc)["prompts"] == 0 + else: # b1 shares the system prompt with a1; a1's next turn finds a1 or b1 + assert reused == [0, 256, len(a1) // 16 if kept == "a1" else 256] + + +def test_an_extension_too_large_to_store_keeps_the_prompt_it_extends(monkeypatch): + # One 124K-token prompt fits in 1 MB; its 300K-token extension does not. + monkeypatch.setenv("ATOM_TOKENIZE_CACHE_MB", "1") + rng = np.random.default_rng(3) + a1 = tokens(rng, 124_000) + proc, reused = processor(16), [] + for prompt in (a1, a1 + tokens(rng, 176_000), a1): + before = served(proc)["blocks_reused"] + [seq] = proc.preprocess_fanout(prompt, SamplingParams()) + assert list(seq.prompt_hash_chain.hashes) == full_chain(prompt, 16) + reused.append(served(proc)["blocks_reused"] - before) + chains = proc.token_prefix_chains # only a1: the extension is in neither + assert len(chains._order) == len(chains._lru) == 1 + assert chains._lru.bytes <= chains._lru.budget + assert reused == [0, len(a1) // 16, len(a1) // 16] + + +def test_a_prompt_a_stored_one_holds_whole_is_not_stored(): + # A truncated retry or a repeat: the stored prompt serves every later one + # at least as well, so only a fork from the retry is stored beside it. + rng = np.random.default_rng(6) + long = tokens(rng, 3000) + chains = pb.TokenPrefixChains(1 << 20, 16) + for prompt, reused, stored in ( + (long, 0, 1), + (long[:1000], 1000 // 16, 1), + (long, 3000 // 16, 1), + (long[:1000] + tokens(rng, 500), 1000 // 16, 2), + ): + before = chains.stats()["blocks_reused"] + assert list(chains.block_hashes(prompt).as_array()) == full_chain(prompt, 16) + assert chains.stats()["blocks_reused"] - before == reused + assert len(chains._order) == len(chains._lru) == stored + assert np.asarray(long, np.int32).tobytes() in [r.tokens for r in chains._order] + + +_extend = pb.extend_block_hashes + + +def wrong_when_reused(tokens, block_size, seed=-1, *, base=None, shared_tokens=0): + out = _extend(tokens, block_size, seed, base=base, shared_tokens=shared_tokens) + if base is None: + return out + bad = bytes([out.hashes[0] ^ 1]) + out.hashes[1:] + return pb.PrefixBlockHashes(block_size, seed, out.num_tokens, bad) + + +def test_a_mismatch_in_the_first_uses_check_turns_reuse_off(monkeypatch, caplog): + monkeypatch.setattr(pb, "extend_block_hashes", wrong_when_reused) + proc, reused = processor(16), [] + with caplog.at_level("WARNING", logger="atom"): + for prompt in scenario()[:6]: + before = served(proc)["blocks_reused"] + [seq] = proc.preprocess_fanout(prompt, SamplingParams()) + assert list(seq.prompt_hash_chain.hashes) == full_chain(prompt, 16) + reused.append(served(proc)["blocks_reused"] - before) + # The second prompt reuses the first's system prompt; nothing reuses after it. + assert reused == [0, 6000 // 16, 0, 0, 0, 0] + assert not served(proc)["enabled"] and "reuse is off" in caplog.text + + +class CountingLock: + """`lock`, running `before` ahead of its acquire number `at`.""" + + def __init__(self, lock, at=0, before=None): + self.lock, self.at, self.before, self.count = lock, at, before, 0 + + def __enter__(self): + self.count += 1 + if self.count == self.at: + self.before() + return self.lock.__enter__() + + def __exit__(self, *exc): + return self.lock.__exit__(*exc) + + +def test_reuse_turned_off_before_a_reusing_prompt_finishes_rehashes_it(monkeypatch): + # Past the first-uses check, an older check turns reuse off just before a + # reusing prompt takes its last lock: the prompt ships a full rehash. + monkeypatch.setattr(pb, "extend_block_hashes", wrong_when_reused) + rng = np.random.default_rng(5) + first = tokens(rng, 2000) + prompt = first + tokens(rng, 100) + + def checked_chains(): + chains = pb.TokenPrefixChains(1 << 20, 16) + chains.block_hashes(first) + chains._verified = pb._VERIFY_FIRST + return chains + + chains = checked_chains() + chains._lock = counted = CountingLock(chains._lock) + chains.block_hashes(prompt) + chains = checked_chains() + lock = chains._lock + + def turn_off(): + with lock: + chains._turn_off() + + chains._lock = CountingLock(lock, counted.count, turn_off) + assert list(chains.block_hashes(prompt).as_array()) == full_chain(prompt, 16) + assert chains.stats()["blocks_rehashed"] == len(prompt) // 16 + + +def test_concurrent_forks_each_ship_a_full_recompute(): + proc, rng = processor(16), np.random.default_rng(2) + base = tokens(rng, 9000) + proc.preprocess_fanout(base, SamplingParams()) + forks = [ + base[: rng.integers(1, 9000)] + tokens(rng, rng.integers(1, 3000)) + for _ in range(48) + ] + + def ships_full_chain(prompt): + [seq] = proc.preprocess_fanout(prompt, SamplingParams()) + return list(seq.prompt_hash_chain.hashes) == full_chain(prompt, 16) + + with ThreadPoolExecutor(8) as pool: + assert all(pool.map(ships_full_chain, forks)) + stats, chains = served(proc), proc.token_prefix_chains + assert stats["enabled"] and stats["prompts"] == 49 and stats["blocks_reused"] + assert chains._lru.bytes <= chains._lru.budget + order = chains._order + assert len(order) == len(chains._lru) and all(r.rid in chains._lru for r in order) + assert all(a.tokens <= b.tokens for a, b in pairwise(order))