fix(scheduler): scope decode permits to disaggregated decode

Keep fused decode and restore on their existing request-capacity path. Add behavior regressions for fused execution and restoration without independent decode permits.

Document the E=B default, resident-state and KV-capacity costs, ready-waiting victim eligibility, and the independent snapshot row and Host-space limits.

Signed-off-by: sunshengqi <69040952+simple-sun@users.noreply.github.com>
This commit is contained in:
sunshengqi
2026-11-16 17:42:02 +08:00
parent 6fec135159
commit f2457e444d
9 changed files with 204 additions and 59 deletions
+68 -25
View File
@@ -531,8 +531,8 @@ Trainer-side contract:
| `--prefill-graph-capture-token-sizes` | Total input-token capacities per forward, summed across the batch. Shorter inputs are padded. |
| `--prefill-graph-capture-batch-sizes` | Request capacities for inline recurrent-layer (KDA, Mamba2, GDN) prefill capture. Replay selects the smallest compatible capacity that fits the batch, padding the missing requests. Unset: `4` (capped by `--max-num-seqs` per data-parallel rank), so a prefill round of up to 4 requests runs its recurrent layers inside the graph; a round of more requests, or one too full for the padding, runs them at eager breaks. Each added count is one more graph per token bucket, with its capture time and memory. |
| `--retraction-snapshot-host-gb` | Explicit size, in gigabytes, of the per-rank pinned Host pool that holds a retraction image's tail (a retracted request's blocks of groups Host L2 never holds, a state group's unpublished input block, and its slot state; the published blocks, the partial last page and the live state block included, go to Host L2 and stay pinned there until the request is restored; with `--disable-kvstore` the pool holds whole images). Wins over `--retraction-snapshot-ratio` when set; `0` (the default) means not set, like `--kvstore-size` against `--kvstore-ratio`. A request a capacity retraction suspends is imaged here and resumes exactly where it stopped once the image is copied back; nothing is recomputed. When no resident's image fits -- the pool or its rows are exhausted -- the scheduler aborts the newest resident instead (finish `err_type` 524, see "Retraction snapshot pool" below), so the pool bounds how much can be suspended at once, never how long an admission waits. Fused and decode roles only; the prefill and encode roles never retract and ignore it with a log. Allowed under `--kv-parallel-size > 1`. |
| `--retraction-snapshot-ratio` | Size of the retraction snapshot pool as a multiple of this rank's Device KV capacity (the base `--kvstore-ratio` scales too), used when `--retraction-snapshot-host-gb` is not set. Unset (the default) derives the pool at device build: 0.1 of the Device KV without the Host KVStore (whole images, kept cheap to pin; `1` makes every resident suspendable), else the image tails of `--retraction-snapshot-max-requests` requests (table below). An explicit `0` is the one way to run **without a pool**: nothing can be imaged, so every capacity block aborts its victim (the newest resident). |
| `--retraction-snapshot-max-requests` | Slot-state image rows of the retraction snapshot pool, that is, the most requests suspended at once, and the request count the derived pool size is multiplied by. `0` (the default) derives to `--max-num-seqs / attention-DP size`, which covers every resident request of the rank; refused with `--retraction-snapshot-ratio 0`, which has no rows to size. When no row is free the scheduler aborts a resident rather than waiting. |
| `--retraction-snapshot-ratio` | Size of the retraction snapshot pool as a multiple of this rank's Device KV capacity (the base `--kvstore-ratio` scales too), used when `--retraction-snapshot-host-gb` is not set. Unset (the default) derives the pool at device build: 0.1 of the Device KV without the Host KVStore (whole images, kept cheap to pin; `1` uses the Device KV pool's usable LCM-block count, with request rows limited separately), else the image tails of `--retraction-snapshot-max-requests` requests (table below). An explicit `0` is the one way to run **without a pool**: nothing can be imaged, so every capacity block aborts its victim (the newest resident). |
| `--retraction-snapshot-max-requests` | Slot-state image rows of the retraction snapshot pool, that is, the most requests suspended at once, and the request count the derived pool size is multiplied by. `0` (the default) derives to `--max-num-seqs / attention-DP size`, the rank-local execution limit B; extra resident slots do not increase this default. Refused with `--retraction-snapshot-ratio 0`, which has no rows to size. When no row is free the scheduler aborts a resident rather than waiting. |
| `--debug-force-retraction-interval` | **Test only.** Every `N` scheduler plans retract the oldest quiescent decoding request (`N > 0`), or with `-N` the one prefilling request between its chunks, without capacity pressure, so a test run exercises the suspend/restore path on every request (the bitwise continuation oracle of [Numerics](../design/numerics.md)). Refused with `--retraction-snapshot-ratio 0` (no pool to image into). `0` (the default) is off; never set it in serving. |
For pure prefill, token capacities count newly computed tokens, not cached
@@ -874,13 +874,16 @@ overflow) proposes a junk token and records the sentinel for that row, so
verify rejects the token and samples from the full target. It never raises a
device error.
Memory: the recorded distributions take
`(max_num_seqs + 2) x num_draft_tokens x vocab_size x 4` bytes
(`--speculative-num-draft-tokens` fp32 rows per request-pool slot), plus a
batch-ordered gather buffer of `max_num_seqs x num_draft_tokens x vocab_size x
4` bytes on the verifier. 80 requests at 4 draft tokens over a 129K
vocabulary cost about 330 MB in total. On CUDA, when the CUDA-graph memory
reserve is on, the runtime charges both to it as startup residue, out of the
Memory: with rank-local execution capacity B and resident capacity C,
dense recorded distributions take (C + 2) x num_draft_tokens x V x 4 bytes,
where V is the full vocabulary size or, for vocabulary-sharded Sonic, this
rank's vocabulary columns. Backends that gather dense q also allocate a
batch-ordered buffer of B_pad x num_draft_tokens x vocab_size x 4 bytes,
where B_pad is B rounded up for the backend's sampling padding; E does not
increase it. With full-vocabulary q, B_pad=B=C=80, 4 draft tokens and a
129K vocabulary, the two buffers total about 330 MB. On CUDA, when the
CUDA-graph memory reserve is on, the runtime charges both to it as startup
residue, out of the
KV-cache budget. Otherwise they come out of the `--gpu-memory-utilization`
headroom.
@@ -903,8 +906,8 @@ probability `min(1, p'(x) / q(x))` and on rejection samples from
request's temperature, top-k and top-p, the one the Triton backend serves.
- Memory: `q` reuses the draft-tree q tables (`RuntimeStates.future_draft_q`),
`(max_num_seqs + 2) x (num_draft_tokens - 1) x K x 8` bytes plus two int32
rows of `num_draft_tokens` per slot. That is under 1 MB at 512 slots, 8
(C + 2) x (num_draft_tokens - 1) x K x 8 bytes, where C is the rank-local
resident capacity, plus two int32 rows of num_draft_tokens per slot. That is under 1 MB at 512 slots, 8
draft tokens and `K = 16`. No dense per-vocab rows, no gather buffer, and
the draft head keeps its shard-local top-K.
- No proposal: a fresh admission, a PD landing and a forced single-token
@@ -1014,17 +1017,47 @@ By default, E=B and C=2B. For example, max-num-seqs=48 with two attention DP
ranks gives B=24, E=24 and C=48 on each rank. Setting E=16 instead gives
C=40. TP replicas use the same rank-local limits.
The extra rows allow KV reception and ready requests to overlap a full
decode batch. They do not enlarge the execution batch, CUDA graph ladder,
or single-forward scratch. Request-indexed persistent state grows with C,
and every admitted request still consumes the ordinary LCM KV capacity.
Receiving all configured requests at their maximum context length is not
guaranteed. More rows can reduce the remaining KV budget.
The E=B default enables the extra capacity even when the flag is omitted.
It targets workloads where a performant execution batch leaves KV headroom,
such as long-input, short-output agent traffic: receiving and ready requests
can overlap that batch. It does not guarantee a full batch when prefill
supplies too little ready work.
Use an explicit extra count when measuring the feature. Restart with zero
to restore the original capacity; shrinking a live request pool is not
supported. A request keeps its original slot when reception completes and
waits for an execution permit before its first decode.
Extra slots increase residency, not KV memory. Receiving, ready and decoding
requests share the same LCM KV pool; E has no separate KV partition. The
execution batch, CUDA graph ladder and single-forward scratch remain sized
by B. Request-indexed persistent state grows with C, which can leave less
GPU memory for the KV arena. The capacity model also charges C residents'
working sets, including state slots, tails and protected windows. Depending
on the model and cache layout, this can reduce the reported token capacity
for the same arena. Receiving all C requests at their maximum context length
is not guaranteed.
For a concrete capacity-model example, fix B=32 and 4,096 usable LCM blocks
on a D rank. Use one full-history group with 64-token pages and one State
group, both with one child block per LCM block; prefix caching and
speculation are disabled, decode width and overlap depth are both 1, and
the context limit is 65,536. The model charges ceil(T/64)+C history pages
and 2C State blocks for a concurrent token budget T:
| Capacity-model example | Explicit E=0 | Default E=B |
|---|---:|---:|
| Resident requests C | 32 | 64 |
| Physical request rows, including null and padding | 34 | 66 |
| Usable LCM blocks | 4,096 | 4,096 |
| Maximum concurrent token budget T | 256,000 | 249,856 |
The token budget decreases by 6,144 (2.4%) in this example, with the same
arena and execution limit. These are sizing-model results, not GPU benchmark
measurements; they exclude the additional persistent tensors' memory cost.
Other cache layouts have different costs.
Use an explicit extra count when measuring the feature. Set E=0 at startup
to retain C=B; shrinking a live request pool is not supported. A request
keeps its original slot when reception completes and waits for an execution
permit before its first decode. Extra slots do not raise the default
snapshot request limit; see [Retraction snapshot pool](#retraction-snapshot-pool)
for the independent request-count and Host-memory limits.
This change requires matching TokenSpeed runtime and native components, even
when E=0. Do not mix runtime or scheduler builds from before this API change
@@ -1427,6 +1460,14 @@ The first rule that applies wins:
| neither, `--disable-kvstore` | 0.1 x this rank's Device LCM blocks (whole images) | same as above |
| neither, Host KVStore on | request cap x one image tail | same as above |
The default snapshot request cap is B, the rank-local execution limit,
even when a decode rank has C=B+E resident rows. Increasing E does not
increase this cap. It limits the number of slot-state images independently
of the KV bytes in the snapshot pool and Host L2. Set
--retraction-snapshot-max-requests explicitly to allow more simultaneous
images, and size the Host pools for those images; raising either limit
alone does not guarantee that every resident can be suspended.
One image tail, per cache group, is one block for a group that publishes
to Host L2 (a state group's unpublished input block; a history group's
margin for a published page L2 could not take) and a request's worst-case
@@ -1438,10 +1479,12 @@ page, so the default is a tenth of the Device KV rather than all of it: an
on-by-default pool must stay cheap to pin (the Device KV once is hundreds of
gigabytes of pinned Host memory for a small model on a large GPU), and it
still suspends a few residents; an image that does not fit aborts its
victim. A deployment that wants every resident suspendable passes
`--retraction-snapshot-ratio 1`, or enables the KVStore, whose tails are
cheap. A size or ratio that holds no whole LCM block is refused,
not rounded down to none. Each engine logs one line at startup with the
victim. Retraction-snapshot-ratio=1 gives the snapshot KV pool the same
usable LCM-block count as Device KV; enabling the KVStore moves published
pages to Host L2. Neither setting raises the snapshot request cap. Suspending a larger set
requires enough slot-state rows and enough space for its complete images
across the snapshot pool and Host L2. A size or ratio that holds no whole
LCM block is refused, not rounded down to none. Each engine logs one line at startup with the
resolved pool (GB and LCM blocks, which rule sized it), the request cap
and arena, and whether Host L2 takes the hash-complete pages; without a
pool the line says that capacity blocks abort. The prefill and encode
+6 -2
View File
@@ -722,12 +722,16 @@ slot; `scheduler.md` §2 and §4 describe the FSM side):
blob — goes to the **retraction snapshot pool**: a small, request-private, pinned pool
sized like the Host L2 tier (an explicit `--retraction-snapshot-host-gb`,
else `--retraction-snapshot-ratio` of the Device KV, else derived: by
default one tail per retractable request, `cache/l2/sizing.py`), never
default one tail per configured snapshot request row, cache/l2/sizing.py), never
evicted, never prefix-indexed, allocated by the scheduler like the Host L2
pool and addressed by scheduler (virtual) block id. Without the L2 tier
(`--disable-kvstore`) the whole image goes there, and the derived default
is a tenth of the Device KV -- an on-by-default pool stays cheap to pin;
`--retraction-snapshot-ratio 1` makes every resident suspendable.
retraction-snapshot-ratio=1 uses Device KV's usable LCM-block count for
snapshot KV. Image rows are limited separately and default to the
rank-local execution limit, excluding extra resident slots; enough Host
space alone does not make
every resident simultaneously suspendable.
The runtime side is **one** `HostCacheExecutor` (`cache/l2/executor.py`)
owning two `HostCacheStorage` buffers over the same field geometry, each with
+24 -12
View File
@@ -11,15 +11,16 @@ prefix granularity, cache groups, LCM blocks).
## Request slots and active decode capacity
The rank-local max_batch_size bounds model forwards and active decode
permits. The separate max_resident_requests bounds the shared request pool.
The rank-local max_batch_size bounds model forwards and, on a D role, active
decode permits. The separate max_resident_requests bounds the shared request pool.
On a D role, disaggregation-decode-extra-slots adds resident rows without
enlarging model batches. RemotePrefilling and a PrefillDone waiting for its
first decode hold a request row and KV pages but no execution permit. All
these requests share one pool; extra rows are not a dedicated transfer pool.
A first local decode acquires a move-only permit and keeps it across rounds.
Newly completed prefills cannot displace an already streaming request.
On a D role, the first local decode acquires a move-only permit and keeps it across rounds.
Permit admission for a newly completed prefill does not displace an
already streaming request; KV-capacity recovery follows the victim policy below.
Restoring a Decoding request reserves a permit before issuing the restore;
the transfer owns it until acknowledgement, including after cancellation.
Finishing requests keep their request row, KV pages and any decode permit
@@ -32,8 +33,10 @@ the request to leave; readmission obtains a new one ahead of fresh work.
A missing request row or decode permit is a scheduling wait, not a cache
capacity failure. Only a failed KV admission enters the existing capacity
recovery policy. The P role hands execution to its peer and does not consume
a local decode permit.
recovery policy. Only the D role allocates decode permits, including during
restore. The P role hands execution to its peer; the fused role already
bounds resident requests by max_batch_size. Both roles report zero active
decode permits and zero requests waiting for a permit.
Forward resources belong to the request's current FSM state. Admission may
reuse a reference to those resources within one attempt; the reference must
@@ -996,7 +999,7 @@ The `CapacityModel` is deliberately **config-only**: it reads every
recipes size a pool from the same model before the arena is allocated
(`recipes/scheduler_bridge.py` builds an unsized config and asks
`ConcurrentGroupPages(max_total_tokens, max_context_len)` for each group's
demand at `max_batch_size` live requests), and then lets the `Scheduler`
demand at max_resident_requests live requests), and then lets the Scheduler
bound requests against the pool they sized. The per-request working set —
`decode_width + overlap_schedule_depth * decode_width` protected tokens, the
next verify window a speculative decode's draft steps write on the roles that
@@ -1589,10 +1592,14 @@ finish (and on the transfer ACK) the D publishes its own frontier like a
fused engine: the KV tail and slot 1 (§1.2), which is how the exact
prompt-end checkpoint of a repeated prompt comes to exist on this node.
**Retraction and restore:** victims are chosen by the shared rule in §2 —
everything resident is decode work (prompts the peer prefilled, in
`PrefillDone` or `Decoding`); `RemotePrefilling` is pinned by the peer's
in-flight prefill and never a victim. The image is taken from this node's own
**Retraction and restore:** victims are chosen by the shared rule in §2.
PrefillDone requests waiting for their first decode permit and Decoding
requests are eligible, subject to the reserve exemption and in-flight guards.
RemotePrefilling is pinned by the peer's in-flight prefill and never a victim.
Ready-waiting requests have no separate victim priority: among eligible
requests whose images fit, the rule favors more newly releasable blocks,
then fewer generated tokens. Restoring PrefillDone does not acquire a
permit; its first decode does. The image is taken from this node's own
pages and nothing crosses the PD wire: the receiver and admission record were
already released at `RemotePrefillDone`, and the bootstrap token lives in the
request's token container, so a `PrefillDone` victim restored to `PrefillDone`
@@ -1933,7 +1940,12 @@ with no request suspended both must read empty and zero.
the newest resident instead of imaging one; §2) and `max_retracted_requests`
(`0` with no pool, `> 0` with one; the runtime's slot-state arena has that
many rows plus the null row) are validated together. The P role refuses a
snapshot pool. L3 addresses page-cyclic sharded groups through replica-stable
snapshot pool. The runtime defaults the snapshot request cap to the
rank-local execution limit B, independently of C=B+E resident rows. Extra
residency does not increase the snapshot row count or guarantee enough Host
space to image every resident. Rows and image storage must both fit; when
no eligible image fits, capacity recovery uses the abort policy in §2.
L3 addresses page-cyclic sharded groups through replica-stable
object keys ([cache concepts](cache-concepts.md)).
`debug_force_retraction_interval` (§2) is the only
knob that chooses victims outside capacity pressure, and it is refused
+7 -5
View File
@@ -48,9 +48,11 @@ from collections.abc import Sequence
from dataclasses import dataclass
#: The derived pool without a Host L2 tier, as a ratio of this rank's Device
#: KV: whole images at a price an on-by-default pool can pin. A deployment
#: that wants every resident suspendable passes ``--retraction-snapshot-ratio
#: 1`` (or enables the KVStore, whose tails are cheap).
#: KV: whole images at a price an on-by-default pool can pin. A ratio of 1
#: gives snapshot KV the same usable LCM-block count as Device KV; enabling
#: the KVStore moves published pages to Host L2. Neither raises the image-row
#: cap, which defaults to execution capacity rather than resident capacity.
#: Both Host space and rows must fit.
DEFAULT_DEVICE_RATIO = 0.1
@@ -66,8 +68,8 @@ class RetractionPoolRequest:
Attributes:
host_gb: ``--retraction-snapshot-host-gb``; 0 is not set.
ratio: ``--retraction-snapshot-ratio``; None is not set, 0 is no pool.
max_retracted_requests: Slot-state rows (explicit, or the rank's
running requests); 0 only with no pool.
max_retracted_requests: Slot-state rows (explicit, or the rank-local
execution limit, excluding extra resident slots); 0 only with no pool.
tail_lcm_blocks_per_request: LCM blocks one image's tail needs beside
Host L2 (``tail_lcm_blocks_per_request``), the derived size's
unit when an L2 tier exists.
+13 -7
View File
@@ -1655,8 +1655,9 @@ class ServerArgs:
a fraction of this rank's Device KV capacity, an explicit 0 disabling
it; neither given means the device builder derives the size
(``cache/l2/sizing.py``). ``--retraction-snapshot-max-requests`` 0
derives to the rank's running requests (``--max-num-seqs`` over the
attention-DP ranks), the most that can ever need an image at once.
derives to the rank-local execution limit B (max-num-seqs over the
attention-DP ranks). Extra resident slots do not increase this cap;
snapshot request rows and Host memory are separate limits.
The prefill and encode roles never retract: their knobs are resolved
to no pool here with a log, as the KVStore's are off on the encode
role.
@@ -3215,7 +3216,9 @@ class ServerArgs:
"concurrency set by --max-num-seqs. If omitted, defaults to "
"--max-num-seqs divided by the attention DP size (integer division) "
"on decode, and zero on other roles. Set to zero to disable the "
"extra capacity.",
"extra capacity. Persistent request state grows with resident "
"capacity and can reduce the KV budget; all requests share one KV "
"pool. The snapshot request limit is configured separately.",
)
parser.add_argument(
"--max-total-tokens",
@@ -3446,7 +3449,8 @@ class ServerArgs:
"aborts its victim -- the only way to get abort-only behaviour. "
"Unset (the default) derives the size: 0.1 of the Device KV without "
"the KVStore (whole images; an on-by-default pool must stay cheap to "
"pin -- pass 1 to make every resident suspendable), else the tails "
"pin; 1 uses Device KV's usable LCM-block count, with image rows "
"limited separately), else the tails "
"of --retraction-snapshot-max-requests images (one page per group "
"that publishes to Host L2, a request's worst case for a group that "
"never does), the slot-state arena coming on top.",
@@ -3457,9 +3461,11 @@ class ServerArgs:
default=ServerArgs.retraction_snapshot_max_requests,
help="Slot-state image rows of the retraction snapshot pool, i.e. the "
"most requests suspended at once. 0 (the default) derives to this "
"rank's running requests, --max-num-seqs / attention-DP size, which "
"covers every resident; a victim that finds no free row is aborted "
"rather than imaged. Refused with --retraction-snapshot-ratio 0.",
"rank's execution limit B, --max-num-seqs / attention-DP size. "
"Extra resident slots do not increase this default. Image rows and "
"Host KV space are separate limits; when no eligible image fits, "
"capacity recovery aborts a resident rather than imaging it. "
"Refused with --retraction-snapshot-ratio 0.",
)
parser.add_argument(
"--debug-force-retraction-interval",
@@ -979,7 +979,7 @@ std::optional<fsm::ScheduleDecodeEvent> Scheduler::scheduleDecode(ExecutionPlan&
Request* request) {
DecodeSlotIndex decode_slot;
fsm::ForwardResources& resources = request->ForwardResourcesRef();
if (config_.role != Role::kP && !resources.decode_slot.valid()) {
if (config_.role == Role::kD && !resources.decode_slot.valid()) {
if (decode_slots_.AvailableSlots() == 0) {
return std::nullopt; // Execution admission, not a KV capacity failure.
}
@@ -1172,7 +1172,8 @@ std::optional<PrefillOperation> Scheduler::schedulePrefillCandidate(ExecutionPla
// once. Then decode work, by most newly releasable blocks and fewest
// generated tokens: the needed pages with the fewest victims disturb the
// fewest clients, and among equal frees the client that has streamed least
// is interrupted. (On the D role everything resident is decoding.)
// is interrupted. On D, this includes PrefillDone requests waiting for
// their first permit and Decoding requests; RemotePrefilling is excluded.
//
// Only candidates whose image fits the host budgets (imageShortfall) are
// ranked. When none does, the host side is out of room and the last resort
@@ -1833,7 +1834,7 @@ bool Scheduler::scheduleRestore(AdmissionFeedback& feedback, PlanBuild& build, R
return false;
}
DecodeSlotIndex decode_slot;
if (std::holds_alternative<fsm::ResumeDecoding>(retracted->shape)) {
if (config_.role == Role::kD && std::holds_alternative<fsm::ResumeDecoding>(retracted->shape)) {
if (decode_slots_.AvailableSlots() == 0) {
return false; // Waiting for execution must not seal KV admission.
}
@@ -89,7 +89,7 @@ CacheKey eventKey(const CacheKey& key) {
Scheduler::Scheduler(SchedulerConfig config)
: config_{validated(std::move(config))},
req_pool_allocator_{config_.max_resident_requests},
decode_slots_{config_.max_batch_size},
decode_slots_{config_.role == Role::kD ? config_.max_batch_size : 0},
snapshot_slots_{config_.max_retracted_requests},
block_pool_{config_.device_allocator.NumUsableBlocks(), slotsPerParentByGroup(config_)},
host_pool_{hostPoolBlocks(config_), config_.host_group_packing},
@@ -472,8 +472,8 @@ std::size_t Scheduler::DecodingSize() const {
}
std::size_t Scheduler::ReadyWaitingSize() const {
if (config_.role == Role::kP) {
return 0; // Completed P requests await a remote handoff, not local execution.
if (config_.role != Role::kD) {
return 0; // Only D requests wait for a separate execution permit.
}
return static_cast<std::size_t>(std::ranges::count_if(requests_, [](const std::unique_ptr<Request>& request) {
return request->Is<fsm::PrefillDone>() && !request->HasDecodeSlot();
@@ -193,10 +193,10 @@ public:
// requests are not running.
std::size_t RunningSize() const;
// Physical resources include in-flight cleanup, even after its request
// leaves the runnable FSM states. Decode permits include restore tickets.
// leaves the runnable FSM states. D-role decode permits include restore tickets.
std::int32_t AllocatedRequestSlots() const { return TotalRequestSlots() - FreeRequestSlots(); }
std::int32_t ActiveDecodeSlots() const { return decode_slots_.Size() - decode_slots_.AvailableSlots(); }
// Prefill is complete but the first local decode has not acquired a permit.
// D-role prefill is complete but the first local decode has not acquired a permit.
std::size_t ReadyWaitingSize() const;
// Device pool parents that are empty or hold only unpinned cache entries.
// Scans the pool and every prefix index: a leak check for tests and
@@ -91,6 +91,83 @@ def _ack(scheduler, op, kind) -> None:
_send(scheduler, event)
def test_fused_decode_uses_request_capacity_without_decode_permits():
cfg = _config(2, 2)
cfg.role = ts.SchedulerConfig.Role.Fused
scheduler = ts.Scheduler(cfg)
scheduler.submit_requests(
[
_spec(rid, [100 * i + 1, 100 * i + 2])
for i, rid in enumerate(("a", "b", "c"))
]
)
assert _forward_ids(scheduler.next_execution_plan()) == ["a", "b"]
for rid in ("a", "b"):
_advance(scheduler, rid, [42])
assert scheduler.allocated_request_slots() == 2
assert scheduler.ready_waiting_size() == 0
for token in (43, 44):
assert _forward_ids(scheduler.next_execution_plan()) == ["a", "b"]
assert scheduler.decoding_size() == 2
assert scheduler.active_decode_slots() == 0
for rid in ("a", "b"):
_advance(scheduler, rid, [token])
_finish(scheduler, "a")
assert _forward_ids(scheduler.next_execution_plan()) == ["c"]
_advance(scheduler, "c", [42])
assert _forward_ids(scheduler.next_execution_plan()) == ["b", "c"]
assert scheduler.allocated_request_slots() == 2
assert scheduler.active_decode_slots() == 0
assert scheduler.ready_waiting_size() == 0
for rid in ("b", "c"):
_advance(scheduler, rid, [45])
_finish(scheduler, rid)
assert _forward_ids(scheduler.next_execution_plan()) == []
assert scheduler.allocated_request_slots() == 0
def test_fused_decode_restores_without_reserving_a_decode_permit():
cfg = _config(1, 1)
cfg.role = ts.SchedulerConfig.Role.Fused
cfg.debug_force_retraction_interval = 4
scheduler = ts.Scheduler(cfg)
scheduler.submit_requests([_spec("running", [1, 2])])
assert _forward_ids(scheduler.next_execution_plan()) == ["running"]
_advance(scheduler, "running", [42])
for token in (43, 44):
assert _forward_ids(scheduler.next_execution_plan()) == ["running"]
_advance(scheduler, "running", [token])
retract = scheduler.next_execution_plan()
[snapshot] = [op for op in retract.cache if isinstance(op, ts.Cache.SnapshotOp)]
assert _forward_ids(retract) == []
assert scheduler.retracted_size() == 1
assert scheduler.active_decode_slots() == 0
_ack(scheduler, snapshot, ts.Cache.SnapshotDoneEvent)
restore = scheduler.next_execution_plan()
[restore_op] = [op for op in restore.cache if isinstance(op, ts.Cache.RestoreOp)]
assert _forward_ids(restore) == []
assert list(restore_op.request_ids) == ["running"]
assert scheduler.allocated_request_slots() == 1
assert scheduler.active_decode_slots() == 0
_ack(scheduler, restore_op, ts.Cache.RestoreDoneEvent)
assert scheduler.retracted_size() == 0
assert scheduler.decoding_size() == 1
assert scheduler.request_token_size("running") == 5
assert _forward_ids(scheduler.next_execution_plan()) == ["running"]
assert scheduler.active_decode_slots() == 0
assert scheduler.ready_waiting_size() == 0
_advance(scheduler, "running", [45])
_finish(scheduler, "running")
assert _forward_ids(scheduler.next_execution_plan()) == []
assert scheduler.allocated_request_slots() == 0
assert scheduler.active_decode_slots() == 0
def test_remote_prefill_uses_resident_capacity_beyond_the_decode_batch():
scheduler = ts.Scheduler(_config(2, 4))
_submit(scheduler, "a", "b", "c", "d", "e")