Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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 @@ -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
Expand All @@ -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:
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 @@ -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
Comment thread
Jasen2201 marked this conversation as resolved.
Resolved

local_len = get_dcp_local_seq_lens(
np.array([seq_len]),
Expand Down
6 changes: 5 additions & 1 deletion atom/model_engine/byte_lru.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 20 additions & 8 deletions atom/model_engine/engine_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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 = (
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Comment thread
Jasen2201 marked this conversation as resolved.
Resolved
yield_gil()
finally:
try:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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}")
Expand Down
30 changes: 25 additions & 5 deletions atom/model_engine/llm_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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]:
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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
Comment thread
Jasen2201 marked this conversation as resolved.
Resolved
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
2 changes: 2 additions & 0 deletions atom/model_engine/pp_engine_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading
Loading