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
5 changes: 4 additions & 1 deletion atom/compass/runner/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@
with no driver, so anything reachable from that import cannot be exercised by
a test that runs without one.
- `model_runner` binds those overrides onto `ModelRunner`, and is therefore the
only module here that needs a driver to import.
only module here that needs a driver to import. It is also where the composed
class is checked against `overrides.RPC_SURFACE`, the table of names a worker
dispatches: the worker skips a name the runner lacks without raising, so a
hole in that surface is a caller that waits forever rather than an error.

This package stays empty at import time for the same reason, so naming it costs
nothing.
Expand Down
53 changes: 49 additions & 4 deletions atom/compass/runner/model_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@

from __future__ import annotations

from atom.compass.runner.overrides import NonAllocatingRunner
from atom.compass.runner.overrides import (
RPC_SURFACE,
NonAllocatingRunner,
RunnerRefusal,
unanswered_rpc_names,
)
from atom.model_engine.model_runner import ModelRunner


Expand All @@ -14,9 +19,9 @@ class CompassModelRunner(NonAllocatingRunner, ModelRunner):

Everything the engine does around a step -- the scheduler, admission, the
block manager, the prefix index -- is ATOM's own and runs unchanged. What
this class removes is the weights, the KV tensors and the step itself, by
overriding the five methods that own them; see `overrides`, which holds the
bodies and says why each one does what it does.
this class removes is the weights, the KV tensors, the graph capture and the
step itself, by overriding the six methods that own them; see `overrides`,
which holds the bodies and says why each one does what it does.

Construction is not free of device memory. What remains is the base's
forward-vars ring from `allocate_forward_vars`, whose dominant term is a
Expand All @@ -29,3 +34,43 @@ class CompassModelRunner(NonAllocatingRunner, ModelRunner):
subclass body would get control, so there is no point at which state set
here would be visible to it.
"""


_UNANSWERED = unanswered_rpc_names(CompassModelRunner)
if _UNANSWERED:
# Checked here rather than left to a deployment. The worker resolves each
# RPC with `getattr(runner, name, None)` and skips what comes back None, so
# a name this class stops answering -- because ATOM renamed or dropped it --
# produces no error anywhere: the worker stays healthy and nothing logs.
# Failing the import turns that into a worker that dies at construction,
# with a traceback.
#
# The two halves below fail differently, which is why the message
# partitions them instead of asserting one story for all twelve. A waited
# name parks its caller on an unbounded queue read for the life of the
# process. An unwaited one parks nobody: `busy_loop` skips it and carries
# on -- which for `exit` means the loop never breaks, and for
# `process_kvconnector_output` means a KV load is silently never started.
# Both are real failures; neither is a park.
#
# Two things about this raise itself. No CPU test tier can execute it:
# importing this module imports `ModelRunner`, which runs aiter's
# architecture probe and needs a driver, so a green CPU gate is not
# evidence that the composed class answers the surface -- only an import on
# a machine with a GPU is. And when it does fire inside a worker,
# `AsyncIOProc.__init__` resolves the runner class (`async_proc.py:166`)
# before assigning `self.runners = []` (`:167`), so the atexit finalizer
# then fails on the half-built object and the worker log *ends* with
# `AttributeError: 'AsyncIOProc' object has no attribute 'runners'`. The
# refusal is the traceback above that one.
_WAITED = [name for name in _UNANSWERED if RPC_SURFACE[name]]
_UNREAD = [name for name in _UNANSWERED if not RPC_SURFACE[name]]
raise RunnerRefusal(
"the worker dispatches "
+ ", ".join(_UNANSWERED)
+ " by name and this runner answers none of them. Waited on, so a hole "
"parks its caller for the life of the process: "
+ (", ".join(_WAITED) or "none")
+ ". Dispatched with no reader, so a hole is skipped and the worker "
"carries on without it: " + (", ".join(_UNREAD) or "none") + "."
)
190 changes: 184 additions & 6 deletions atom/compass/runner/overrides.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,72 @@
"""The model-runner methods that keep construction off the device.

These are the memory-owning methods of ATOM's `ModelRunner`: the ones that read
a checkpoint, warm the model, size the KV pool, allocate it, and run a step.
They live here rather than beside the subclass because this module imports
nothing from the engine, and so can be executed on a machine with no driver.
a checkpoint, warm the model, size the KV pool, allocate it, capture graphs, and
run a step. They live here rather than beside the subclass because this module
imports nothing from the engine, and so can be executed on a machine with no
driver.

Two of them run during construction (`_build_and_load_model`, `_maybe_warmup`)
and decline to do their work. The rest run afterwards, over the worker's RPC
channel; `allocate_kv_cache` does the arithmetic and none of the allocation,
and the other two refuse by name because their answers are not this module's to
invent -- a wrong duration or a wrong block count would be indistinguishable
from a measured one.
`capture_cudagraph` captures nothing and says so in the shape its caller
unpacks, and the other two refuse by name because their answers are not this
module's to invent -- a wrong duration or a wrong block count would be
indistinguishable from a measured one.

Order matters when mixing this in: `NonAllocatingRunner` must precede
`ModelRunner` in the bases so these definitions win. The class deliberately
defines no `__init__`. The base class runs the whole of its own `__init__`
before a subclass body would get control, so anything these methods read has to
come from `self.config`, which the base sets first.

## The reply contract, and why it is not a matter of taste

A worker runs `AsyncIOProc.busy_loop`, which takes a name off a shared-memory
ring, resolves it with `getattr(runner, name, None)`, calls it, and forwards the
result **only when it is not None** (`async_proc.py:231-252`). The caller's side
is `AsyncIOProcManager.call_func`, whose `wait_out=True` form blocks on
`self.outputs_queue.get()` with no timeout. Three consequences, none of which a
single-process test can show:

* **A name the runner does not have is skipped, not raised.** `getattr` returns
None, the loop moves on, the worker stays healthy, and a caller that asked for
the reply waits for the life of the process. Absence is the quietest failure
on this surface, which is why `RPC_SURFACE` below names every dispatched
method rather than leaving it to whatever the class happens to inherit.
* **A method that is present and answers None parks its caller in exactly the
same way.** This is one line below the skip, not a separate mechanism:
`async_proc.py:243` is `if out is not None:`, and **both** of the loop's
`put_nowait` calls -- the primary output queue at `:248` and the KV queue at
`:250` -- are inside it, while the `getattr` skip is at `:237-239`. So from
the caller's side an answer of None and a method that was never defined are
one event: nothing is queued, nothing logs, and no timeout ends either wait.
Naming only absence is worse than saying nothing, because it sends whoever
is debugging the hang to check whether the method is there, find that it is,
and stop. The shapes here are therefore checked against what the call site
unpacks, not against what reads well -- returning None is the case a
plausible stub falls into by accident, which is why every name on the
surface is either replaced here or left to a base implementation that is
known to end in a value.
* **Raising is the loud option, and it is louder in the worker than in the
parent.** An exception leaves `busy_loop`, kills the worker, and the
manager's process monitor turns that into a `SystemExit` on the output queue,
which `call_func` re-raises in the caller. What crosses the boundary is the
type and nothing else: the parent gets a bare `SystemExit()` with empty args,
no message and no `__cause__`, so a refusal's name and its reason exist only
on the worker's stderr. `SystemExit()` also carries `code=None`, and
`engine_core.py:132` sits in a `try/finally` with no `except`, so letting it
propagate ends the parent process with status 0 -- a clean shutdown to any
supervisor reading exit codes. So a refusal reaches the caller and a silence
never does, but "reaches" means the fact of it and not the reason for it: a
successor that wants its refusal diagnosable in the engine's own log has to
put it there itself, on the worker side, before it raises.

`RPC_SURFACE` records, for each dispatched name, whether its caller waits for
the reply. The names themselves are not a list anyone typed: they are the ones
`engine_core`, `pp_engine_core` and `engine_utility` broadcast that a
`ModelRunner` answers, and the tests derive that intersection from ATOM's own
source and compare it with this table.
"""

from __future__ import annotations
Expand All @@ -31,6 +81,63 @@

logger = logging.getLogger(__name__)

# Every name broadcast to a worker whose runner is a `ModelRunner`, and whether
# the caller blocks on the reply. True means a None return, or a missing method,
# parks that caller; False means a reply is not read and lands on the output
# queue for whoever asks next. A call site is named beside each one -- but what
# a site fixes varies, and the difference matters: where the comment says the
# caller unpacks, subscripts or reads the reply, the site fixes the shape; where
# it says the reply is forwarded or dropped, the site fixes only that something
# non-None and picklable has to arrive, and any richer shape is a convention
# inherited from the base implementation rather than a requirement.
#
# Scope: a runner reached through `EngineCore`. Nothing else in the tree says
# so, and it is load-bearing. Fourteen dispatched names are absent from this
# table because `ModelRunner` does not define them -- seven belong to
# `RapidServeModelRunner`, seven to the rollout extension. The rollout seven are
# unreachable here. The RapidServe seven are not: `enable_rapidserve` picks
# `PrefillEngineCore` / `DecodeEngineCore` (`llm_engine.py:140`), those classes
# broadcast all seven with `wait_out=True`, and that broadcast never consults
# `runner_qualname`, while the substitution that would install a RapidServe
# runner (`config.py:1729-1736`) fires only while `runner_qualname` is still
# ATOM's default -- which Compass overwrites. `enable_rapidserve=True` with this
# runner is therefore seven silent parks on names this table deliberately
# excludes. Tracked as issue #98; not closed here.
#
# Also outside the table, and outside anything a broadcast-derived enumeration
# can see: three of these twelve are called in-process on the runner itself,
# reached over the `resume_memory` RPC. `rollout/memory_manager.py:176`
# subscripts one key of `get_num_blocks`, `:183` discards `allocate_kv_cache`,
# and `:209` calls `capture_cudagraph` without unpacking it, inside a `try` that
# degrades to `enforce_eager=True`. Different arities, and the one place in the
# tree where a refusal from this module would be caught rather than fatal.
RPC_SURFACE: dict[str, bool] = {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A hole the intersection hides, reachable from in-tree config alone: RapidServe plus a custom runner_qualname.

atom/config.py:1729-1736 substitutes RapidServeModelRunner only when runner_qualname is still the default string. CompassModelRunner sets it to something else. But enable_rapidserve independently selects PrefillEngineCore / DecodeEngineCore, and those broadcast create_prefill_stream_pool, create_decode_stream_pool, prefill_forward and the four IPC import/export names -- all wait_out=True -- at whatever runner the qualname named.

So enable_rapidserve=True with this runner turns seven of the fourteen "out of scope, they belong to another runner" names into seven silent parks: precisely the failure this table exists to prevent, on names the table deliberately excludes. The Group-A exclusion is sound only because the EngineCore class, not the runner class, gates those broadcasts -- and that gate does not consult runner_qualname.

I am not asking for seven more entries. A comment here naming the condition, or a refusal in the composed class when enable_rapidserve is set, closes it. The table is the right place to record that its scope is "a runner reached through EngineCore", because nothing else in the tree says so.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recorded, and opened: #98.

I agree it is not seven more entries — the names are genuinely another runner's, and adding them would make the table claim a scope it does not have. What was missing is the scope itself, so that is what the table now states, in the header comment above RPC_SURFACE:

Scope: a runner reached through EngineCore. Nothing else in the tree says so, and it is load-bearing. Fourteen dispatched names are absent from this table because ModelRunner does not define them — seven belong to RapidServeModelRunner, seven to the rollout extension. The rollout seven are unreachable here. The RapidServe seven are not: enable_rapidserve picks PrefillEngineCore / DecodeEngineCore (llm_engine.py:140), those classes broadcast all seven with wait_out=True, and that broadcast never consults runner_qualname, while the substitution that would install a RapidServe runner (config.py:1729-1736) fires only while runner_qualname is still ATOM's default — which Compass overwrites. enable_rapidserve=True with this runner is therefore seven silent parks on names this table deliberately excludes. Tracked as issue #98; not closed here.

I re-derived the chain before filing rather than taking it: config.py:1731-1736 is the guarded substitution, llm_engine.py:140 is if config.enable_rapidserve: self.core_mgr = DisaggCoreManager(config), and the seven broadcasts are engine_core.py:872, :891, :919, :992, :1097, :1149, :1179 — all wait_out=True, all inside PrefillEngineCore / DecodeEngineCore. The issue names the three ways to close it and recommends the narrow one: validate in Config, so the error lands at configuration time rather than as a park at the first broadcast.

I did not add a refusal in the composed class for enable_rapidserve. The condition is not this runner's to own — it holds for any deployment that sets runner_qualname and enable_rapidserve together, Compass or not — and a refusal here would fix Compass while leaving the general case silent. It belongs in Config, which is what #98 asks for.

Also recorded beside the table, from your finding 4: three of the twelve are called in-process on the runner off the resume_memory RPC (memory_manager.py:176, :183, :209), at different arities, and :209 is inside a try that degrades to enforce_eager=True — the one place in the tree where a refusal from this module is caught rather than fatal. A broadcast-derived enumeration structurally cannot see that, so it is stated rather than derived.

# Replaced here, in this module.
"get_num_blocks": True, # engine_core.py:132-141 reads four keys off a dict
"allocate_kv_cache": True, # engine_core.py:142-145 asserts the reply
"capture_cudagraph": True, # engine_core.py:149 unpacks three values
"forward": True, # scheduler.py:2435-2542 reads nine attributes off it
# Answered by ATOM's own, which needs neither weights nor a device for them.
"dummy_execution": True, # engine_core.py:749 returns it to its own caller
"exit": False, # engine_core.py:260, the last call of the process's life
"freeze_gc_heap": True, # engine_core.py:203-206 catches a raise, not a None
"process_kvconnector_output": False, # engine_core.py:500 does not wait
"async_proc_aggregation": True, # engine_core.py:488, the one bounded wait
"start_profiler": True, # engine_utility.py:252 forwards the reply unread
"stop_profiler": True, # engine_utility.py:264 forwards the reply unread

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The replacement states two of the three legs round 1 named — the JSON one is gone.

Withdrawing {trace_dir, elapsed} is right, and the shape-vs-forwarding distinction in the header is the correct repair. I checked the claim that holds it up: trace_dir really does appear in exactly one file under atom/ — atom/model_engine/model_runner.py, at :1152 (its own docstring), :1156 and :1171. Nothing reads it.

But the header now says a forwarding site fixes only "non-None and picklable", and for these two rows there is one more constraint, imposed by a real in-tree caller. The reply is forwarded opaquely three hops and then serialised:

engine_utility.py:264   result = call_func("stop_profiler", wait_out=True)
engine_utility.py:269   ("UTILITY_RESPONSE", {"cmd": "stop_profile", "result": result})
llm_engine.py:300       return [resp.get("result", {}) for resp in responses]   # the envelope
api_server.py:2441-2443 traces = engine.stop_profile()
                        return {"status": ..., "message": ..., "traces": traces}

atom/entrypoints/openai/api_server.py:2435-2443 is a FastAPI route, so the reply ends up inside a JSON response body. Round 1's own sentence was "non-None, picklable, JSON-serialisable"; two of those three survived the fix. ATOM's own {trace_dir: str, elapsed: float} satisfies it, so nothing is broken today — but this row's whole purpose is to tell a successor what a replacement owes, and a picklable reply that is not JSON-encodable turns /stop_profile into a 500 rather than a park.

One clause in the header, or one more assertion in test_the_profiler_replies_are_forwarded_whole_and_never_unpacked — the route already forms a grep as stable as the envelope string that test pins. Non-blocking.

To be explicit about the loop-stop rule: this is not round 1's finding surviving. Round 1's was "the cited site does not constrain the shape", and that is closed. This is the replacement being one leg short.

"flush_pp_send": True, # pp_engine_core.py:81 waits before the next send
}


def unanswered_rpc_names(runner: Any) -> tuple[str, ...]:
"""The dispatched names `getattr` would answer with None for this runner.

Each one is a caller that parks forever rather than an error anyone sees,
so this is checked where the class is composed instead of being discovered
by a deployment.
"""
return tuple(name for name in RPC_SURFACE if getattr(runner, name, None) is None)


class RunnerRefusal(RuntimeError):
"""Raised where this runner has no answer and will not invent one."""
Expand Down Expand Up @@ -94,6 +201,21 @@ def get_num_blocks(self) -> dict[str, object]:
are resident. Neither figure exists here, and the substitute belongs to
the memory model rather than to the runner, so answering would mean
inventing a block count that the scheduler would then treat as measured.

Whoever supplies that count answers a dict, and `engine_core.py:132-141`
fixes its four keys: `num_kvcache_blocks` (`:133`) and `state_runtime`
(`:141`) are subscripted, `pool_entries` (`:139`) and
`pool_entries_per_req` (`:140`) are taken with a `{}` default. The block
count goes on to `BlockManager`, which asserts it is greater than zero
(`block_manager.py:78`).

`state_runtime` is not an opaque value. `:141` hands it to
`StateRuntime.from_wire` (`state_runtime.py:159-166`), which raises
`TypeError` unless it is a `Mapping` and `ValueError` unless its key set
is exactly `{"transfer", "checkpoint_spec"}`. The fourth value is a
two-key nested wire dict, and a successor who builds a four-key dict
with anything else under that key gets a `ValueError` in the parent on
the first RPC of the engine's life.
"""
raise RunnerRefusal(
"a non-allocating runner cannot size the KV pool from a device it "
Expand All @@ -115,12 +237,68 @@ def allocate_kv_cache(self, num_kvcache_blocks: int) -> bool:
)
return True

def capture_cudagraph(self) -> tuple[float, list[int], int]:
"""Capture nothing, and say so in the three values the caller unpacks.

The base reaches the model only after it has zeroed device buffers,
opened a graph memory pool and entered a capture context, so inheriting
it would put bytes on a device before it discovered there are no
weights to trace. Nothing is captured here, and the reply says exactly
that: no seconds spent, no batch sizes captured, no pool bytes held.

The shape is fixed by `engine_core.py:149-151` and `1109-1111`, which
both write `cap_cost, bs, pool_bytes = ...` and then format the first
and third as numbers. Returning two values, or None, is not a test
failure over there: the worker dies on the unpack, or never replies, and
the caller waits for the rest of its life either way.

`capture_sizes` and `capture_sizes_np` are deliberately left at the
eager-fallback values the base set during construction, because the
attention metadata builder reads them on every step. The reply
deliberately disagrees with the attribute it preserves: the base sends
`self.capture_sizes` -- the same `[0]` -- as the second element
(`model_runner.py:4085`), and this sends `[]`. Both are only ever
formatted into a log line, and `[]` is the truthful one.

`engine_core.py:148` reaches this method only when `not enforce_eager
and not disagg_is_decode`, so on an eager deployment the override never
runs at all. Replacing it anyway is the point: a runner must not depend
on a caller-side flag to stay off the device.
"""
logger.info("no cudagraph captured: there are no weights to trace.")
return 0.0, [], 0

def forward(self, batch: Any) -> Any:
"""Refuse to run a step.

This class is the attachment point and not the replacement for a step. A
step's output has to reproduce what the scheduler reads back from a real
one, and a plausible-looking stub that does not is worse than no answer.

What a replacement owes its callers. Four sites broadcast this name --
`engine_core.py:386` and `:1264`, and `pp_engine_core.py:118` (which
waits and discards the reply) and `:379`. None of them unpacks it; the
reply is one object, read for its attributes, and the reads are these:

* `.req_ids`, an iterable of request ids in the batch's own order --
`pp_engine_core.py:144`. That read is on the head's side of the
transport, on what `recv_tokens()` returns at `:139`, not at the
`:379` call site, which only passes the object on.
* `.token_ids`, `.draft_token_ids`, `.is_deferred_out`, `.logprobs`
(None or a `dict[int, float]`) -- `scheduler.py:2435-2438`.
* `.get_idx(req_id)`, returning a row index or None --
`scheduler.py:2454`.
* `.num_rejected[idx]` and `.num_bonus[idx]`, indexable by that row and
castable to `int` -- `scheduler.py:2521-2522`.
* `.dspark_ell`, either None or a mapping answering `.get(seq.id)` --
`scheduler.py:2541-2542`.

Nine attributes, and picklable on top: under pipeline parallelism the
last stage sends the object whole (`pp_engine_core.py:385`) and the head
reads it back (`:139`), each hop through `pickle` in
`atom/distributed/pp_transport.py:141` and `:114`. ATOM's own answer is
a `ScheduledBatchOutput`; the contract a replacement has to meet is the
nine reads and the pickle, not that class.
"""
raise RunnerRefusal(
"this runner has no cost model and no step semantics yet, so it "
Expand Down
11 changes: 9 additions & 2 deletions tests/compass/test_runner_non_allocating.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"_maybe_warmup",
"get_num_blocks",
"allocate_kv_cache",
"capture_cudagraph",
"forward",
}

Expand Down Expand Up @@ -108,7 +109,7 @@ def test_every_replaced_method_exists_on_the_class_being_replaced():
assert OVERRIDDEN <= _methods(_classes(ATOM_RUNNER)["ModelRunner"])


def test_the_difference_from_the_in_tree_non_allocating_runner_is_two_methods():
def test_the_difference_from_the_in_tree_non_allocating_runner_is_three_methods():
"""`RapidServeModelRunner` is the working non-allocating runner in the tree.

It overrides two things this one does not. `__init__`: it has to bind a
Expand All @@ -117,13 +118,19 @@ def test_the_difference_from_the_in_tree_non_allocating_runner_is_two_methods():
it holds bytes back because a second process shares its GPU, and a runner
that allocates nothing has no tenant to hold anything back from.

This one overrides one thing it does not: `capture_cudagraph`. RapidServe
allocates no weights of its own but imports real ones over CUDA IPC, so it
has a model to trace and keeps ATOM's capture. This runner has none, and
ATOM's capture zeroes device buffers and opens a graph pool before it finds
that out.

Its `_init_weight_params_on_meta` is not in the difference because it is not
an override -- it is a helper the base does not have.
"""
base = _methods(_classes(ATOM_RUNNER)["ModelRunner"])
template = _methods(_classes(ATOM_RUNNER)["RapidServeModelRunner"]) & base
assert template - OVERRIDDEN == {"__init__", "_kv_budget_extra_reserve"}
assert OVERRIDDEN - template == set()
assert OVERRIDDEN - template == {"capture_cudagraph"}


# --- construction allocates nothing -----------------------------------------
Expand Down
Loading