Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions atom/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -1487,11 +1487,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
Expand All @@ -1503,6 +1498,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:
Expand Down
33 changes: 31 additions & 2 deletions atom/distributed/dcp_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
2 changes: 1 addition & 1 deletion atom/model_engine/block_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -769,7 +769,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
Comment thread
Jasen2201 marked this conversation as resolved.
Resolved

local_len = get_dcp_local_seq_lens(
np.array([seq_len]),
Expand Down
11 changes: 11 additions & 0 deletions atom/model_engine/engine_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@
KV_IDLE_DRAIN_INTERVAL_S = 0.001
# 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

# Upper bound on the drain that runs after the loop exits. A peer that died
# mid-transfer leaves a completion that never arrives; exiting late beats
Expand Down Expand Up @@ -573,6 +575,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()
Comment thread
Jasen2201 marked this conversation as resolved.
Resolved
finally:
try:
# Teardown runs even on exceptions so the sender thread/socket
Expand Down Expand Up @@ -686,6 +690,13 @@ def _wait_for_kv_progress(self) -> None:
return
self._kv_progress_event.wait(KV_IDLE_DRAIN_INTERVAL_S)

def _wait_for_input(self) -> None:
"""Sleep until the input thread queues work or `IDLE_WAIT_S` passes: a loop
that spun instead would hold the GIL that thread needs to queue it."""
self._kv_progress_event.clear() # before the reads: a later put sets it again
Comment thread
valarLip marked this conversation as resolved.
Resolved
if self.input_queue.empty() and self.utility_queue.empty():
self._kv_progress_event.wait(IDLE_WAIT_S)

def _postprocess(self, seqs, fwd_out, batch):
if self._report_backlog:
# Ahead of this step's outputs, which complete or release placements.
Expand Down
25 changes: 20 additions & 5 deletions atom/model_engine/llm_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,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
Expand Down Expand Up @@ -450,9 +451,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(
Expand Down Expand Up @@ -665,6 +669,7 @@ def summed_queues(key: str) -> int:
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
Expand Down Expand Up @@ -706,6 +711,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]:
Expand Down Expand Up @@ -866,6 +876,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(
Expand Down Expand Up @@ -946,12 +959,14 @@ 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 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
Expand Down
167 changes: 161 additions & 6 deletions atom/model_engine/prefix_block_hashes.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,35 @@
# 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
tokenizer's matched cut -- can take those blocks' hashes from the cached record
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)
Expand Down Expand Up @@ -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

Expand All @@ -88,3 +104,142 @@ 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."""

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, rehash = shared // bs, False
if reused: # check the first reuses, and any made while reuse turned off
with self._lock:
rehash = verify or not self.enabled
if rehash:
full = array.array("Q", chained_block_hashes(toks, bs, 0, n, -1)).tobytes()
with self._lock:
if rehash and full != chain.hashes:
self._turn_off()
chain = PrefixBlockHashes(bs, -1, len(toks), full)
elif rehash and verify and self.enabled:
Comment thread
valarLip marked this conversation as resolved.
Resolved
self._verified += 1
if enabled and self.enabled and n:
whole = reused and reused == base.hashes.num_blocks
self._store(raw, chain, base if whole else None)
Comment thread
valarLip marked this conversation as resolved.
Resolved
counts = self._counts
counts["prompts"] += 1
counts["blocks_hashed"] += n - reused
counts["blocks_reused"] += reused
counts["blocks_rehashed"] += n if rehash else 0
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)."""
if replaces is not None and self._lru.pop(replaces.rid) is not None:
Comment thread
Jasen2201 marked this conversation as resolved.
Resolved
self._unlist(replaces.rid, replaces)
record = _TokenRecord(raw, chain, self._next_id)
Comment thread
Copilot marked this conversation as resolved.
Resolved
self._next_id += 1
self._lru.put(record.rid, record, record.payload_bytes)
if record.rid in self._lru: # not larger than the whole budget
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()
Loading
Loading