This repository has been archived on 2026-11-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
radiance-sycl/core/sched/scheduler.h
T
Deadcode 2a2b756371 radiance 2.1.0
New models. Recursive Flint (39.8B, about 2.5B active) by everplays (#422): `arch/flint`, as an
IQ8R container with rotated int8 experts or a four-bit one, with a sink-aware WMMA prefill
attention and the fused attention prologue at `rotary_dim` 0. Meta Muse Glimmer 30B by
launch80_assets (#423): bf16, an int4 trunk or IQ8R, its windowed vision tower, its DFlash
drafter, the ATEM tool dialect and context extension. Ling-3.0-tiny by RikshaDriver (#441):
served from its GGUF releases or as IQ8R on `bailing_hybrid`, with six more libr3d kernels. Block
FP8, MXFP4 and NVFP4 conversions of the three are not served. IQ8R containers of all three
(round to nearest, no calibration) are on Hugging Face under StillDeadcode: flint-iq8r,
muse-glimmer-30b-iq8r-dflash and ling-3.0-tiny-iq8r. They were checked for sane answers on two
R9700; nothing was benchmarked, and Muse Glimmer's pictures, video and tool calls were not tried.

Speech. Breeze-TTS-2 clones a voice from a reference recording and its transcript, with an
optional delivery direction, by farcryjohn (#436). The published Breeze container needs
converting again with the updated recipe before it can.

Tools. A model entry with `diagnose: DIR` runs a fixed workload on the engine instead of serving
and writes a report: step times, tokens a step, draft acceptance, TTFT and prefill rates by
category, concurrency and prompt length, and with `diagnose-baseline` a token-for-token comparison
against an earlier report (docs/DIAGNOSE.md), by Code000 (#418).

Scheduler. `mixed-step-target-ms` holds a mixed prefill and decode step to a service time, off by
default, by tnhnyzc (#413). `scheduler.stuck-exit` (60s by default, 0 never) ends the process when
the device has advanced nothing for that long, so a restart policy brings a hung server back
(#409, #415, #428).

Fixed. Draft trees with the int8 KV cache, which stopped Gemma 4 31B with DFlash2 on its first
request (#454, diagnosed by aelfwyne). The expert loan held at zero by a few leftover cache blocks
after long sessions (#455, diagnosed by thekk1). The mapped tier's pages kept in the page cache
across a load and a restore, by C_Tamas (#421). Replayed tool calls with blank arguments, and
arguments that are not JSON refused naming the call, by dschmitz (#444). The dashboard's card
temperature reads the junction sensor, by dschmitz (#453). The VRAM shortfall report says what the
KL mode needs, by baKon (#448). The out-of-tree plugin test builds its plugins in parallel and
takes its toolchain from the tree.

Plugin ABI 40: out-of-tree plugins need to be rebuilt.

Thanks to @everplays, @launch80_assets, @RikshaDriver, @farcryjohn, @Code000, @tnhnyzc, @C_Tamas, @dschmitz, @baKon, @aelfwyne and @thekk1.
2026-11-15 16:00:05 +01:00

928 lines
54 KiB
C++

/* scheduler.h -- continuous batching, chunked prefill, a priority queue and preemption by
* recompute. One scheduler decision per step, producing one RadBatch (spec §7.1).
*
* Host time spent here is GPU idle time. The step path allocates nothing: its storage is sized at
* max_tok / max_seqs, and allocation happens only on arrival and completion (HTTP threads).
*
* Unlike vLLM's scheduler it also owns:
* - Chunk boundaries. A prefill chunk splits at a linear-state checkpoint interval, so a
* checkpoint is always written instead of only when a step happens to end on a boundary.
* The cost is an occasional short chunk; the hit rate then depends on the workload, not on
* scheduling luck (§7.3).
* - Draft depth, controlled against measured acceptance (draft.h, §10).
*/
#pragma once
#include "batch.h"
#include "draft.h"
#include "lookup.h"
#include "metrics.h"
#include "ngram.h"
#include "diag/diagnose.h"
#include <chrono>
#include <condition_variable>
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
#include <functional>
#endif
#include <memory>
#include <mutex>
#include <unordered_map>
namespace rad {
/* The scheduler's own per-request state. Request (rad_core.h) is shared across components and
* frozen; state only the scheduler needs lives here. */
struct SchedReq {
std::unique_ptr<Request> req;
uint64_t arrival = 0; /* monotonic; the tiebreak below priority. A preempted request
* keeps it, so it re-enters ahead of later arrivals */
int32_t slot = -1;
/* The card's index for this sequence: the StepSlot the advance reads and writes (advance.h),
* and the sequence identity a batch carries. Not `slot`, which is taken on arrival and can
* exceed the card's max_seqs StepSlots. Taken on admission from a pool of max_seqs and
* returned with the sequence's KV (free_kv, preempt_back). */
int32_t card = -1;
bool running = false;
/* Wall clock, for the live request table; `arrival` is a counter and cannot measure time. */
int64_t arrived_us = 0;
int64_t first_tok_us = 0; /* 0 until the first output token: this request's TTFT */
int64_t admitted_us = 0; /* 0 until the first admission: where the queue ends, so a
* prefill rate can divide by the prefill alone. ttft covers
* the wait for admission (GUIDE); this excludes it. */
int64_t preempted_us = 0; /* when this state became Preempted; 0 otherwise. Bounds the
* whole-recompute admission wait (--preempt-wait-ms). */
/* The drafter's proposal for the next step, and the conv-window read cursor a rejection
* moves rather than rolls back (§10). */
int32_t draft[RAD_SCHED_MAX_SPEC] = {};
int32_t n_draft = 0;
int32_t conv_cursor = 0;
/* A tree drafter's parents for `draft` (StepEntry::draft_parent), valid while `draft_tree`;
* a chain proposal (prompt lookup, or a chain drafter) clears it. */
int32_t draft_par[RAD_SCHED_MAX_SPEC] = {};
bool draft_tree = false;
/* A serial drafter's valid history: positions [0, draft_filled) of the head's own layer hold
* K and V for the sequence's real tokens. Only the head writes that layer, so before drafting
* it runs a history pass over what the last step added. */
int64_t draft_filled = 0;
/* The range [draft_lo, draft_hi) of a block drafter's own KV cache that holds real K and V.
* The low end is non-zero when a prefix hit left the drafter's group uncached
* (hit_holes_draft_); drafting then waits until the window has slid past it. */
int64_t draft_lo = 0;
int64_t draft_hi = 0;
/* Clears all drafter state for the sequence in this slot, on admission and on preemption.
* Slots are recycled, so anything not reset here leaks into an unrelated sequence: a stale
* `draft_filled`, for one, empties the next prefill's history pass (hs = max(draft_filled,
* ctx_len)), and the MTP head drafts against stale pool contents, making greedy output vary
* per request with speculation on. */
void drafter_reset() {
n_draft = 0;
draft_next = 0;
conv_cursor = 0;
draft_filled = 0;
draft_lo = 0;
draft_hi = 0;
}
/* The adaptive draft window's estimate (--draft-window adaptive, draft.h). Not reset by
* drafter_reset(): it describes the text, which preemption does not change. */
DraftAdapt adapt;
/* The proposal the step being planned carries came from prompt lookup (StepEntry::ngram). */
bool draft_ngram = false;
/* Prompt lookup's index over prompt ++ output (ngram.h), built at the sequence's first lookup
* and extended by each later one. It depends on the tokens alone, so preemption keeps it; it
* is keyed by request id, so a recycled slot starts over, and a closed request frees it. */
NgramIndex ngram_ix;
/* Prompt lookup's record on this text for the verify gate (lookup.h): it describes the text,
* so preemption keeps it; a new request starts it over. */
LookupSeq look;
int32_t sched_tokens = 0; /* tokens given to this request in the current step */
int32_t entry = -1; /* its index in the current StepPlan, or -1 */
/* Its index in the next step, already issued while this one runs (step_next), or -1; and the
* drafts the drafter issued for it, which that step verifies. */
int32_t entry_next = -1;
int32_t draft_next = 0;
/* Cancelled while a step in flight or a drafter snapshot still names it; its blocks are
* released once nothing does. Freed earlier, a kernel still writing a block would put one
* sequence's KV in another's attention, and a drafter pass built after the free would carry
* an all -1 block-table row with a non-zero length, reading block -1 below the pool. */
bool pending_free = false;
/* Reaped in the same window. A disconnect finishes the sink and the server reaps at once;
* destroying the Request then would leave commit() reading a null `req`, or committing one
* client's tokens into a re-admitted slot. */
bool reap_pending = false;
int64_t pending_ckpt = -1; /* absolute position this step's chunk checkpoints at */
/* The checkpoint the linear state is seeded from on admission, handed to the sequence's first
* entry as StepEntry::ckpt_restore. Never held across a step: nothing pins a checkpoint slot,
* so a failed admission gives the hit back (admit_one) and the next attempt looks it up
* again. */
int32_t ckpt_src = -1;
/* The prefix hit this admission attempt found, in tokens, and whether its accounting is still
* owed. Counted once, when admission succeeds; counting each retry of a request that does not
* fit would inflate the prompt and hit totals. */
int32_t hit_attn = 0;
bool hit_owed = false;
/* Why that hit was cut, for the counters (SchedMetrics::hit_cut_*): to nothing, or to a
* snapshot more than an interval below it. */
enum class HitCut : uint8_t { None, NoSnapshot, Window, Adopt, ResumedBelow };
HitCut hit_cut = HitCut::None;
/* Admission waited a step for a sequence's deferred release before cutting its restore
* (Scheduler::admit_one); it waits once. */
bool restore_waited = false;
/* That attempt's restore came back cut (SchedMetrics::prefix_restore_cuts, counted once the
* admission happens). */
bool restore_cut = false;
/* The whole sequence is prompt ++ output; n_computed indexes into it. */
int64_t seq_len() const {
return (int64_t)req->prompt.size() + (int64_t)req->output.size();
}
};
class Scheduler {
public:
/* What the sampler hands back after a step: per sequence, how many drafts survived, the token
* sampled at the accepted position, and whether the sequence ended. No logits. commit() fills
* in the two counts. */
struct StepResult {
int n_seq = 0;
const int32_t* n_accepted = nullptr; /* [n_seq] drafted tokens accepted, 0..n_spec */
const int32_t* token = nullptr; /* [n_seq] token sampled at the accepted position */
const uint8_t* eos = nullptr; /* [n_seq] 1 when the sequence ended */
int n_prefill_done = 0; /* prompts this step fully placed */
int n_finished = 0; /* requests that ended during this step */
/* Logprobs, null on a step where no request asked: entry i's j-th emitted token (its
* accepted drafts first, then the sampled token) is lp[first_row[i] + j]. */
const TokenLogprobs* lp = nullptr;
const int32_t* first_row = nullptr; /* [n_seq] */
/* A tree step's accepted nodes, [n_seq][RAD_SCHED_MAX_SPEC]: entry i's t-th accepted
* draft is draft[path[i][t] - 1]. Null on a chain step, where it is draft[t]. */
const int32_t* path = nullptr;
};
/* What commit left a sequence at: its committed length and whether it is still Running.
* Copied under the lock in commit because reap() may free the Request before the serial bind
* reads it. */
struct CommittedSeq {
uint64_t seq = 0;
uint64_t n_out = 0;
bool live = false;
};
/* `geo` is the already-resolved chunk geometry. The engine resolves it once because
* PrefixCache::configure runs first and needs its checkpoint interval; pass nullptr to
* resolve one here. */
int init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCache* pc,
const std::vector<BatchBuilder::RankIO>& ranks,
const ChunkGeometry* geo = nullptr);
/* The batch the last build produced for one rank; see BatchBuilder::batch_for. */
const RadBatch* batch_for(int rank) const { return builder_.batch_for(rank); }
/* See BatchBuilder::step_seqs. */
const std::vector<uint64_t>* step_seqs(const RadBatch* b) const { return builder_.step_seqs(b); }
/* The advance's view of that build on one rank; see BatchBuilder::advance_args. Also carries
* the serial head's shape, which only the draft passes' modes read. */
AdvanceArgs advance_args(int rank) const {
AdvanceArgs a = builder_.advance_args(rank);
a.shared_kv = serial_shared_ ? 1 : 0;
a.rot_shift = serial_rot_shift_;
return a;
}
void fini();
/* ---------------------------------------------------------- off the step path */
int add(std::unique_ptr<Request> r);
/* `n` requests under one hold of the queue lock, each accepted or refused as add() would, with
* its result in rc[i]. For the sequences of one API request, which must reach the same step. */
void add_all(std::unique_ptr<Request>* rs, size_t n, int* rc);
/* The step loop's idle wait. wake_seq() before a step() that finds nothing, then
* wait_idle(seen, max): it returns at once if anything woke the loop since `seen` (a request
* added or cancelled, or wake()), else after `max` at the latest. */
uint64_t wake_seq();
void wait_idle(uint64_t seen, std::chrono::microseconds max);
void wake();
/* Frees blocks immediately rather than at completion (spec §14); otherwise the pool shrinks
* under exactly the load that cancels. */
int cancel(uint64_t id);
Request* find(uint64_t id);
/* Fail every request prefilling in the step just committed, with `why` for the client: a streamed
* group's resolve latched overflow, so their selection tables no longer address the pool
* (docs/KV-STREAMING.md §3.4). */
int fail_prefilling(const char* why);
/* Whether the request is still admitted and Running, read under the lock. */
bool running(uint64_t id) const;
/* What the step just committed left for `seq`, copied by commit under the lock. False when
* that step carried no such sequence. */
bool committed_seq(uint64_t seq, uint64_t* n_out, bool* live) const;
/* Requests that reached a terminal state since the last call, oldest first, swapped into
* `out` under the lock (old contents discarded). Only the engine consumes it, to drop
* per-request sampler state; the server learns through the sink and calls reap(). A swap
* because cancel() appends from HTTP threads; swapping the same vectors keeps both
* capacities, so steady state allocates nothing. */
void take_completed(std::vector<uint64_t>* out);
int reap(uint64_t id);
/* ---------------------------------------------------------- the step record (--diagnose)
*
* One diag::StepRecord per committed step, in a ring sized at init and only with --diagnose: a
* serving process keeps no ring and records nothing. A reader takes every step a phase ran --
* its shape and its time -- without a second clock. Both calls take the lock; `step_records`
* appends what came after `from` and returns how many of those the ring overwrote before they
* were read (diag/diagnose.h). */
uint64_t step_record_count() const;
size_t step_record_capacity() const; /* 0 without --diagnose */
uint64_t step_records(uint64_t from, std::vector<diag::StepRecord>* out) const;
/* ---------------------------------------------------------- the lock, for the engine
*
* Every mutation of the KV manager and the prefix cache happens under this lock; neither has
* its own, and both are reached from the step path, from HTTP threads (cancel(), reap(),
* reset_prefix_cache()) and from the engine's passes between steps (idle tiers, elastic
* rebalance, checkpoint copies). Taken once per pass that has work, never per sequence.
*
* Nothing run under it may call back into the scheduler: the mutex is not recursive and every
* public method takes it. */
template <class Fn> auto locked(Fn&& fn) {
std::lock_guard<std::mutex> lk(mu_);
return fn();
}
/* The same lock, held for the rest of the caller's scope. */
[[nodiscard]] std::unique_lock<std::mutex> hold() { return std::unique_lock<std::mutex>(mu_); }
/* ---------------------------------------------------------- work the device still owes
*
* A request cancelled while a drafter pass was being built keeps its blocks until the passes
* that name them are done (SchedReq::pending_free). commit() releases them; an idle engine
* runs no commit, so it drains its streams and calls release_deferred() instead.
* has_deferred() is the cheap test for whether that is needed. */
bool has_deferred() const;
void release_deferred();
/* The engine has stopped and will run no more steps. Every queued or running request is
* failed with `reason` so its connection gets an answer, and later submissions are refused the
* same way. `status` is the cause, and what each of those requests reports. */
void shutdown(const char* reason, int status = RAD_E_STATE);
/* The waiting queue's request ids in service order, for the live view and for tests (a
* preempted request re-enters at the front). Returns how many were written. */
int queue_snapshot(uint64_t* out, int max) const;
/* ---------------------------------------------------------- who is in flight
*
* Per-request state for the dashboard and for debugging a stall. Copied out under the step
* lock, since a pointer into scheduler storage could outlive a reaped request. */
struct ReqStat {
uint64_t id = 0;
int state = 0; /* ReqState, as an int -- the caller has the enum */
bool running = false;
int64_t prompt_tokens = 0;
int64_t computed_tokens = 0; /* of the prompt, how much is in the KV: prefill progress */
int64_t cached_tokens = 0; /* of those, how many came from the prefix cache */
int64_t output_tokens = 0;
int64_t max_tokens = 0;
int64_t ctx_tokens = 0; /* prompt ++ output */
/* This request's share of the paged pools: the blocks it holds and the tokens they cover.
* It differs from `ctx_tokens` (what it uses) by a partial block and by whatever a
* rejected draft left. */
int64_t kv_blocks = 0;
int64_t kv_tokens = 0;
int32_t n_draft = 0; /* the proposal standing for the next step */
int32_t slot = -1;
double age_s = 0;
double ttft_s = -1; /* negative until the first token */
double prefill_s = -1; /* first token minus admission; negative until both */
double decode_tps = 0; /* this request's own, since its first token */
};
/* Oldest first, since the oldest is the one most likely stuck. Returns how many were
* written. */
int requests(ReqStat* out, int max) const;
/* The drafter's proposal for a request's next step. n is clamped to the sequence's window
* (draft_cap): the controller's depth, or what the adaptive policy gives the sequence. */
/* `parents`: a tree drafter's (rad_drafter_tree), node j + 1's parent node, null for a chain. */
int set_draft(uint64_t id, const int32_t* tokens, int n, const int32_t* parents = nullptr);
/* ---------------------------------------------------------- media the encoder owes
* A request carrying media is admitted only once every item is encoded; until then it keeps
* its queue position and later requests are admitted around it. The engine takes the items
* (take_encodes) and encodes them between steps, which keeps the encoder off the step path. */
bool encodes_pending() const;
void take_encodes(std::vector<std::shared_ptr<mm::Item>>* out);
/* An encoder pass over whole segments; see BatchBuilder::build_encoder. */
const RadBatch* build_encoder(const std::vector<BatchBuilder::EncoderPart>& parts, int step,
const RadEncoderDecl& enc) {
std::lock_guard<std::mutex> lk(mu_);
return builder_.build_encoder(parts, step, enc);
}
/* Drop every prefix-cache entry; returns how many, or RAD_E_UNSUPPORTED without a prefix
* cache. Takes the step lock because the step path inserts into the map (live sequences hold
* their own block references). See IScheduler::reset_prefix_cache. */
int64_t reset_prefix_cache();
/* Least recently used entries leave VRAM until `enough()` (called under the step lock) holds
* or the whole cache has gone; an entry with a host copy stays restorable as long as that
* gives enough room. Returns how many went.
* The step lock, with nothing in flight reading the blocks. */
int64_t evict_prefix_until(const std::function<bool()>& enough);
/* Running requests go back to the queue by recompute, youngest first, their blocks freed,
* until `enough()` (called under the step lock) holds or none runs: the fleet takes a
* lower-priority model's cache while it is busy (docs/MULTIMODEL.md §6.4). Between steps
* only, with nothing in flight. Returns how many went back. */
int preempt_until(const std::function<bool()>& enough);
/* The end-of-generation ids the card's acceptance reads, for ends_every_request. Set once at
* start; without them only max_tokens ends are predicted. */
void set_eog(std::vector<int32_t> ids);
/* Forget one stored conversation, by label or engine id, keeping its first `keep_tokens`
* (IPrefixCache::release_session). Refused with RAD_E_STATE while a request of that
* conversation is queued or running: its blocks would be skipped as live and its close
* would publish the chain again, so the release would be half done and undone at once.
* Takes the step lock like reset_prefix_cache. */
int release_session(const std::string& label, uint64_t id, int64_t keep_tokens,
SessionRelease* out);
/* ---------------------------------------------------------- the step path */
/* One decision, one batch. Null when there is nothing to run, which is not an error. */
const RadBatch* step();
/* ---------------------------------------------------- the next step, before this one commits
*
* A decode step's successor needs nothing the host learns from it: every row continues where
* the card's acceptance leaves it (sched/advance.h), with drafts proposed on the card, and the
* host can bound how far that is. So the next forward pass is issued while this one runs.
*
* expect_draft after the drafter is issued: how many drafts the next step verifies for a
* sequence, capped at its window (under the adaptive policy possibly fewer
* than the rounds that ran).
* step_next plans and builds that step: every row of this one, as a device row, at
* the furthest context it can reach. Null (step() runs after the commit
* instead) when only committed state can decide: a request awaiting admission,
* a prefill chunk to continue, a grammar, the context's end, or a pool that
* cannot grow.
* promote_next once this step has committed: the next step becomes the open one.
*
* While the next step is open, commit() leaves continuing requests' blocks in place, and a
* finished request keeps them until that step has run. */
void expect_draft(uint64_t id, int n);
const RadBatch* step_next();
const RadBatch* step_next_locked();
/* Whether the step just issued likely ends every request it carries; step_next_locked then
* issues nothing behind it. */
bool ends_every_request() const;
void promote_next();
/* Fold the step's outcome back in: append tokens, roll back rejected speculation, retire
* finished requests, feed the draft controller, and fill `r`'s report counts
* (n_prefill_done, n_finished). */
int commit(StepResult& r);
/* Ends the step for timing; call once per loop iteration that ran a step, after the drafter,
* so the draft rounds are charged to the step (see the definition). Without it the counters
* stay correct but there is no timing. */
void step_finished();
/* Feed the open mixed step a completed service time, as step_finished does. Visible for
* deterministic scheduler tests and timed host simulations. */
void note_mixed_step_cost(int64_t ns);
/* ---------------------------------------------------- the serial drafter (spec §10)
*
* A serial draft head (RAD_DRAFT_SERIAL) runs as extra steps after the trunk step that fed it,
* because round 1 needs the sampled token and its position, which depends on how many drafts
* the verify accepted. The engine drives it through:
*
* serial_begin before commit(), right after the step is issued, while plan() describes it.
* Says which sequences may draft, reserves lookahead KV up to the furthest
* position acceptance could reach, and clamps `rounds` to the current depth.
* serial_batch one batch per pass: 0 is the history, which also carries round 1 for the
* drafting rows (RadBatch::draft_out_ids), then rounds from 2. Rows continuing
* a sampled verify are device rows (advance.h): the card fills their positions
* and tokens, so no pass waits on the host.
* serial_end after commit(), with the rounds that ran: moves the history watermark.
* set_draft publishes each row's tokens like any other draft. A row the head declined
* keeps n_draft 0 and the n-gram drafter fills in.
*/
struct SerialRow {
uint64_t seq = 0;
int32_t slot = -1;
int32_t card = -1;
};
int serial_begin(int* rounds, SerialRow* out, int max);
const RadBatch* serial_batch(int round, int step);
/* Round 0 is the history pass (null when no row needs one); round 1 is always null, because
* round 0 carries it. Call serial_end() once the step has committed. */
void serial_end(int rounds_done);
/* ----------------------------------------------------- the block drafter (spec §10)
*
* A block-diffusion drafter (RAD_DRAFT_BLOCK) proposes a whole block of `block` positions in
* one pass, so there are no rounds; instead it runs two passes of different shapes.
*
* block_begin right after the step is issued, before commit(), while plan() still
* describes it. Reserves the draft KV block the query pass writes, and
* returns which sequences may draft.
* block_context the context pass, draft_pass -1. Its entries mirror the trunk step's
* row for row (BlockSeq).
* block_query the query pass, draft_pass +1. One entry per drafting sequence: the
* anchor at its next position, then `block - 1` masks; `out_ids` names the
* last `depth` rows.
* block_end after commit(): moves the filled range over what actually ran.
*
* The drafter writes its proposal to its declared proposal buffer, not through the sampler,
* and the engine publishes it through set_draft().
*
* Both passes queue behind the step with no readback in between. The context pass mirrors the
* trunk step, whose positions the host knows. The query pass's anchor depends on acceptance,
* so its rows are device rows (advance.h, ADV_BLOCK) staged at the furthest position
* acceptance could leave, and the reservation covers that far.
*
* With `on_card` false, block_begin runs after commit() instead and stages the query pass
* from the committed sequence. The engine does not use it; it is the reference the
* scheduler's tests hold the card's staging to.
*/
struct BlockRow {
uint64_t seq = 0;
int32_t slot = -1;
int32_t card = -1;
};
/* `block` is the drafter's trained block in rows, `depth` how many tokens it proposes (the
* last `depth` rows), `window` its attention window (0 for none) and `mask` the token id its
* masked query slots embed. Returns how many sequences may draft and fills `out` with them,
* in the order block_query() emits them. */
int block_begin(int block, int depth, int window, int32_t mask, BlockRow* out, int max,
bool on_card = false);
/* How many running sequences the step just run decoded (produced a token for), the load a
* block drafter's block length is chosen by. Read before block_begin(). */
int decoded_seqs() const;
/* Whether a block drafter runs its short block (--draft-short-from `from`), given whether it
* ran it last step and this step's decoded_seqs(): on from `from`, and off again two below or
* at one sequence below `from`, where the long block pays. Two below keeps a load wavering at
* a threshold of 3 or more from switching the pass shape every step. From 2 there is no such
* margin: a load between one and two sequences switches every step (block_shape reads it per
* step), and the one sequence left after an overlap runs the long block again. */
static bool short_block_on(bool was_on, int64_t decoded, int64_t from) {
if (decoded >= from) return true;
if (decoded <= 1 || decoded + 2 <= from) return false;
return was_on;
}
const RadBatch* block_context(int step);
const RadBatch* block_query(int step);
void block_end();
const StepPlan& plan() const { return plan_; }
const ChunkGeometry& geometry() const { return geo_; }
DraftController& draft() { return draft_; }
LookupGate& lookup_gate() { return lookup_; }
SchedMetrics metrics() const;
/* The observers' copy. Dashboards, scrapers and admin calls read what the engine thread last
* published, never the scheduler's state behind the step lock, so an observer cannot slow
* the step. publish() runs on the engine thread once a step (at most every 20 ms while idle),
* builds the copy under mu_ and swaps it in only if no reader holds the copy's lock; a
* skipped swap happens at the next call. */
void publish(bool idle);
SchedMetrics observed_metrics() const;
int observed_requests(ReqStat* out, int max) const;
/* plan_chunk's tail-checkpoint rule for each --prefix-resume mode (see the definition). */
int64_t tail_checkpoint(int64_t target) const;
/* The least recompute a snapshot at a shared head (CacheHit::branch_at) must save each later
* request for the chunk split that takes it. */
static constexpr int64_t kSharedHeadMin = 256;
/* The lowest position tail_checkpoint takes a window snapshot at (ChunkGeometry::window_ckpt),
* or the interval where that is lower. A prompt reaches it at kWindowSnapshotMin +
* max(quantum, 16) tokens: 528 at a quantum of 16. */
static constexpr int64_t kWindowSnapshotMin = 512;
/* Visible for tests: the chunk the scheduler would give a request at `n_computed` under a
* token budget, and the checkpoint position it will land on (-1 for none). `keep_at` is the
* request's own checkpoint (Request::checkpoint_at), 0 for none. */
int64_t plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget,
int64_t* checkpoint_pos, int64_t keep_at = 0,
const Request* r = nullptr) const;
/* Visible for tests: `want` tokens of `r` from `n_computed` cut so the chunk ends inside no run
* the language model reads both ways (RadEncoderDecl::bidirectional): before the run on a
* quantum, or at its end when the chunk starts in it and `budget` holds that, else 0. A run
* longer than any step keeps the cut where it falls. `want` unchanged for a program with no
* such runs. */
int64_t bidi_fit(const Request& r, int64_t n_computed, int64_t n_target, int64_t want,
int64_t budget) const;
/* The smallest step the prefill stager overlaps, in tokens (0 = no stager), set once by the
* engine after init. --busy-prefill-chunk keeps a held-back chunk at or above it (busy_cap).
* Also logs the resolved policy at startup. */
void set_stage_rows(int64_t rows);
/* The shortest prefill that spans, in tokens (0: every one alone in its step), set once by
* the engine after init. Where routed experts are read from host memory, the arena a spanned
* step takes is room the experts lose for it, which on a short prompt costs more than the span
* saves (Engine::serve). */
void set_span_min(int64_t tokens);
/* Whether the step just planned leaves a prompt with at least the stager's smallest pass still
* to prefill, so the next step most likely carries a chunk the stager arms for. */
bool prefill_continues() const;
/* Visible for tests: the most a prefill chunk at `n_computed` of a `n_target`-token sequence
* may take of `budget` when `reserve` tokens of other work are still to be planned in the step
* and `shared` says rows are already planned ahead of it. Returns `budget` when
* --busy-prefill-chunk is off, or when auto has nothing to reserve. */
int64_t busy_cap(int64_t n_computed, int64_t n_target, int64_t budget, int64_t reserve,
bool shared = false, bool rows_only = false,
int64_t mixed_target_shares = 0, int64_t mixed_target_decode_reserve = 0) const;
/* Where a prefill chunk of a `n_target`-token sequence may end. For a sequence with a runtime
* window (IKVManager::set_window) a chunk ends at the prompt, and past it the output a
* recompute replays runs one token a step: the ring rewrites its slots in place, so a
* multi-token chunk past the floor would overwrite keys its own earlier rows still read, while
* one token a step attends as its decode step did. Otherwise `n_target`. */
int64_t chunk_end(const Request& r, int64_t n_target) const;
/* --prefill-interleave: the decode-only steps that follow a chunk run beside decoding
* sequences. N as configured; under auto, from the measured step costs (see the definition).
* Visible for tests, as is note_step_cost, which feeds auto a step's wall time as
* step_finished does: `chunk` for a step that carried a prefill chunk, else a decode step. */
int64_t interleave_steps() const;
void note_step_cost(bool chunk, double seconds);
private:
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
friend class Engine;
/* Test-build-only observer at the concrete rollback operation. */
void set_kv_rollback_test_hook(std::function<void(uint64_t, int, int, int64_t, bool)> hook) {
kv_rollback_test_hook_ = std::move(hook);
}
#endif
Program* prog_ = nullptr;
Config cfg_{};
ChunkGeometry geo_{};
KVGeom kvgeom_{};
/* Does this model carry recurrent state a prefix hit would have to restore? See admit_one. */
bool has_linear_state_ = false;
/* set_stage_rows: the prefill stager's smallest pass, 0 when it is not armed. */
int64_t stage_rows_ = 0;
/* set_span_min: the shortest prefill a span is taken for, 0 for any. */
int64_t span_min_ = 0;
/* Set by admit_one when it held the admitted chunk back: what it would have taken. */
int64_t admit_full_ = 0;
bool admit_next_step_ = false; /* admit_one's refusal is a wait for the next step */
/* Whether this step's prefill may span (ChunkGeometry::span): set by step() for the step it
* plans, true only for a prefill alone in its step, and read by plan_chunk. True outside a
* step, so plan_chunk called directly answers for a span. */
bool span_now_ = true;
IKVManager* kv_ = nullptr;
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
std::function<void(uint64_t, int, int, int64_t, bool)> kv_rollback_test_hook_;
#endif
IPrefixCache* pc_ = nullptr;
/* Does a prefix-cache hit leave a hole in a block drafter's own KV? Only if some paged group
* is neither prefix-cached nor restored from the window snapshot. prefix.cpp skips windowed
* groups, so a windowed drafter the snapshot does not carry has K and V only from the hit
* position and must wait for its window to slide past it. A full-attention drafter's group is
* cached like the trunk's and its floor is 0; treating it as windowed would stop drafting for
* good, since it has no window to slide. Read off IPrefixCache::cached_groups() and
* IKVManager::window_snapshot() so prefix.cpp's and the KV manager's rules live in one
* place. */
bool hit_holes_draft_ = true;
/* Does a hit leave a hole in the trunk: a paged group with a trunk layer (bound below
* meta.n_layers; drafter layers bind from `base_layer` up) that the cache does not index and
* no checkpoint slot carries? Unlike a drafter hole, recomputing the tail cannot repair it;
* every hit is refused (admit_one). */
bool hit_holes_trunk_ = false;
/* The end-of-generation ids, sorted and unique (set_eog), and a lookup in them. */
std::vector<int32_t> eog_;
bool is_eog(int32_t id) const;
/* A windowed trunk group, which the cache does not index: a hit stands only where it resumes
* at a window snapshot (IKVManager::has_window_snapshot), which restores the window. */
bool hit_needs_window_ = false;
/* R-SWA: the groups whose KV manager carries per-sequence runtime windows, with the W a
* sequence is armed with (IKVManager::runtime_window_tokens). Empty for every model that does
* not declare one, in which case admission and commit are exactly as before. A sequence with
* one keeps its prompt as a reference and decodes into a ring after it; it is excluded from
* prefix publish, checkpoints and speculation (the window is runtime data). */
struct RswaWindow { int32_t group = -1; int64_t tokens = 0; };
std::vector<RswaWindow> rswa_windows_;
/* Draft refill: the drafter's window where a hit can leave a hole in a windowed block
* drafter's cache, else 0. The drafter would be declined until its window slid past the hole,
* which on a chat's follow-up turn is most of the reply, so the hit ends one window before the
* prompt's end (HitCap) and the recompute fills the drafter's window too. Output is unchanged.
* A hit whose nearest checkpoint below that point gives back more than two windows is kept
* whole. */
int64_t draft_refill_ = 0;
/* A serial head with no cache of its own (rad_drafter_shared_kv). It owes no history, so
* serial_begin gives it one row per drafting sequence and none otherwise, and its rounds stay
* at the committed position (advance.h). False and 0 for every other drafter. */
bool serial_shared_ = false;
int32_t serial_rot_shift_ = 0;
/* A tree drafter (rad_drafter_tree): every trunk plan is StepPlan::spec_is_tree. */
bool tree_ = false;
BatchBuilder builder_;
DraftController draft_;
/* Where this sequence's block-drafter cache begins; block_begin's guard reads it and
* block_end records it. */
int64_t draft_floor(const SchedReq& s, int64_t ctx_len) const {
if (s.draft_hi != 0 || s.draft_lo != 0) return s.draft_lo;
return hit_holes_draft_ ? ctx_len : 0;
}
/* The window a sequence may draft into: the configured depth, or under the adaptive window
* min(D, its stop) (DraftController::window_for, which starts the estimate on first use).
* Every site that caps a proposal applies it: step(), set_draft(), expect_draft() and the
* rounds in serial_begin(). With the policy off it is next_depth(). */
int draft_cap(SchedReq& s) const {
return draft_.adaptive() ? draft_.window_for(s.adapt) : draft_.next_depth();
}
/* The step's head depth D is chosen once per cycle by draft_cycle(), the first thing step()
* and promote_next() do. A proposal passes four sites that must agree on it: the verifying
* plan, the drafting rounds, expect_draft() and set_draft(). A commit or a disconnect changes
* the running set mid-cycle, so a D read live could move between them; held, a proposal
* drafted under one D and planned under the next is only ever cut shorter.
*
* `draft_est_` is the list plan_step reads, reserved at init so the step path does not
* allocate. */
std::vector<DraftAdapt*> draft_est_;
void draft_cycle();
/* The built-in prompt-lookup drafter (scheduler.cpp, ngram.h). Fills s.draft and returns how
* many tokens it proposed; 0 when the sequence has no repeated pattern to extend. It tries
* --spec-ngram-max down to --spec-ngram-min tokens, longest first. `match`, if given, gets how
* far the match behind the proposal runs back (NgramIndex::propose), -1 when the proposal did
* not come from the index (--debug-draft-oracle). */
int draft_ngram(SchedReq& s, int depth, int* match = nullptr) const;
/* Prompt lookup is the deployment's only drafter and --draft-window adaptive is on: its
* proposals feed each sequence's estimate and are capped by its window, as a head's are. */
bool lookup_adapt_ = false;
/* Prompt lookup is the deployment's only drafter: each proposal is verified only when its
* sequence's record says it pays for its verify rows at the measured step cost (lookup.h).
* Beside a draft head the lookup only fills in for a sequence the head declines, and is
* left to the head's window. */
bool lookup_gate_on_ = false;
LookupGate lookup_;
/* Decode rows and expected tokens of the step being planned, for the gate: a decode row
* counts once up front, and each verified proposal adds its drafts and expected yield. */
int64_t gate_rows_ = 0;
double gate_tokens_ = 0.0;
/* --debug-draft-oracle (draft_ngram): a fixed continuation the lookup proposes from instead,
* with kDebugMiss of the drafts corrupted, so a verify accepts and rejects at every depth on
* any model. A test harness; empty when not given. */
std::vector<int32_t> debug_oracle_;
static constexpr double kDebugMiss = 0.3;
mutable std::mutex mu_;
/* wake_seq/wait_idle/wake. */
std::mutex wake_mu_;
std::condition_variable wake_cv_;
uint64_t wake_n_ = 0;
SchedMetrics metrics_locked() const;
int requests_locked(ReqStat* out, int max) const;
/* The published copy and its lock (publish()). The scratch pair is the engine thread's, filled
* under mu_ and then swapped with the published pair, so a publication allocates nothing once
* the vectors have grown to the request count. */
mutable std::mutex pub_mu_;
SchedMetrics pub_m_;
std::vector<ReqStat> pub_reqs_;
SchedMetrics scratch_m_;
std::vector<ReqStat> scratch_reqs_;
int64_t pub_at_us_ = 0;
std::vector<std::unique_ptr<SchedReq>> reqs_; /* by slot */
std::vector<int32_t> free_slots_;
std::vector<int32_t> free_cards_; /* card indices not held by any sequence; see SchedReq::card */
std::unordered_map<uint64_t, int32_t> by_id_;
/* Both kept sorted by (priority desc, arrival asc). running_ is sorted so the preemption
* victim is the back; waiting_ so admission takes the front. */
std::vector<int32_t> running_;
std::vector<int32_t> waiting_;
std::vector<uint64_t> completed_;
/* StepResult's counts for the step being committed: the ids whose prompt it completed, and the
* requests it ended. Reset at every commit. */
std::vector<uint64_t> last_prefill_ids_;
int step_finished_ = 0;
/* Requests whose release waits on something that still refers to them (a deferred reap or a
* deferred free). A count, so the sweeps cost nothing on the steps where there are none. */
int n_deferred_ = 0;
/* Items a waiting request needs encoded, in the order its requests reached the queue's head;
* each at most once (Item::queued). mu_ held. */
std::vector<std::shared_ptr<mm::Item>> enc_want_;
/* Are all of this request's items encoded? The ones that are not are queued for the encoder. */
bool media_ready(SchedReq& s);
/* Set by shutdown(); add() refuses from then on. */
bool closed_ = false;
const char* closed_reason_ = "";
int closed_status_ = RAD_E_STATE;
/* The longest sequence (prompt plus output) this deployment can address. The batch builder's
* block tables and the rotary tables are sized for it, so no position at or past it may be
* scheduled, whatever max_tokens a request carries. */
int64_t ctx_limit_ = 0;
/* The longest sequence the KV pool can ever hold alone, when that is less than ctx_limit_,
* else -1; and the refusal a longer prompt gets, naming it (a sink keeps the pointer, so it
* lives here). See add_locked. */
int64_t pool_tokens_ = -1;
std::string pool_refusal_;
/* fail_prefilling()'s message; a sink keeps the pointer until the HTTP thread writes it. */
std::string stream_why_;
/* Scratch for a prefix-cache hit's block ids, one row per cached group. Reserved at init so
* an admission does not reach the allocator. */
std::vector<std::vector<int32_t>> hit_blocks_;
/* Scratch for publishing a finished sequence into the prefix cache. Reused so close_request
* does not allocate per completion. */
std::vector<std::vector<int32_t>> pub_blocks_;
StepPlan plan_;
StepPlan plan_next_;
bool next_open_ = false;
/* Is a step the card may still be running holding this request? */
bool in_step(const SchedReq& s) const {
return (step_open_ && s.entry >= 0) || (next_open_ && s.entry_next >= 0);
}
/* The serial drafter's rows, valid between serial_begin() and serial_end(). */
struct SerialSeq {
uint64_t seq = 0;
int32_t slot = -1;
int32_t card = -1;
int32_t hist_row = -1; /* the trunk row the history pass starts at */
int32_t hist_n = 0; /* how many positions it has to fill, 0 for none */
int64_t hist_pos = 0; /* the head index that first row is */
/* The verify step this row continues from, as the card's advance reads it (advance.h):
* whether it sampled, the token row of its first verified position, its first sampled
* row, and how many history positions come before the verified ones. */
bool dev = false;
int32_t dev_tok = 0;
int32_t dev_out = -1;
int32_t lead = 0;
/* Its index among the drafting rows, or -1 for a row that only owes history (e.g. a
* sequence mid-prompt, with hidden states but no token to draft from). */
int32_t draft_idx = -1;
/* No Request* here, as for BlockSeq: serial_batch reads serial_ after the lock was
* released and retaken. */
/* The furthest position round 1 can write at: the verify step's last position, reached
* when every draft is accepted. The card knows the real one; this bounds it. */
int64_t base_pos = 0;
};
std::vector<SerialSeq> serial_;
StepPlan serial_plan_;
/* The block drafter's rows, valid between block_begin() and block_end(): one per entry of the
* trunk step just run, in order, with `ctx_len`/`n_tokens` mirroring it. The drafter reads
* the trunk's tapped hidden states positionally from its own buffer, so row i must be the
* trunk's row i. `can_draft` says whether the row also gets a query pass. */
struct BlockSeq {
uint64_t seq = 0;
int32_t slot = -1;
int32_t card = -1;
int32_t ctx_len = 0;
int32_t n_tokens = 0;
int32_t n_spec = 0; /* the trunk entry's drafts: a tree verify when > 0 */
int64_t base_pos = 0; /* the anchor's position: the sequence's next one */
bool can_draft = false;
/* On the card: the anchor's position is the card's, and `base_pos` the furthest it can
* be (Scheduler::block_begin). */
bool dev = false;
/* A placeholder: the trunk step finished this sequence, so it has no KV and drafts
* nothing, but keeps its row so later rows stay aligned with the trunk's. The pass stores
* nothing for it (a negative slot is padding). */
bool mirror = false;
/* No Request* here: block_ is read by later passes with the lock released in between,
* and a disconnect could free the Request. Rows hold `slot` plus `seq`, resolved through
* block_req(). */
};
std::vector<BlockSeq> block_;
StepPlan block_plan_;
int32_t block_len_ = 0;
int32_t block_depth_ = 0; /* tokens proposed; the head takes the last this many */
/* `block` - 1 copies of the drafter's mask token, which a query entry's `draft` points at:
* token_at() walks prompt ++ output ++ draft, so the mask positions come from the accessor
* every other pass uses. */
std::vector<int32_t> block_mask_;
int step_ = 0;
uint64_t arrival_ = 0;
SchedMetrics m_{};
std::chrono::steady_clock::time_point step_start_{};
/* When the last step ended. An idle engine runs no steps, so nothing adds time to the
* throughput window; metrics() decays what it reports by this. */
std::chrono::steady_clock::time_point last_step_at_ = std::chrono::steady_clock::now();
int64_t step_prefill_tok_ = 0, step_decode_tok_ = 0;
/* The step record, picked once at init: with --diagnose the ring is sized and record_step is
* written into it, without it step_finished calls a no-op. One indirect call a step, no test
* of the mode and no ring on the serving path. Callers of step_finished hold mu_. */
void record_step(int64_t ns, int64_t end_ns);
void record_no_step(int64_t, int64_t) {}
void (Scheduler::*record_step_)(int64_t, int64_t) = &Scheduler::record_no_step;
diag::StepRing step_ring_;
/* --prefill-interleave: decode-only steps still owed before the next chunk, and how many
* prefilling requests the last step() held back. step_next_locked stops issuing ahead once
* the hold is spent, or the chunk would wait as long as the decoders keep stepping ahead. */
int64_t interleave_left_ = 0;
int64_t held_prefill_ = 0;
/* --prefill-interleave auto: the decode-only steps after a chunk (interleave_steps), sized by
* the running means of a step that carried a chunk and of a decode step, in seconds, fed by
* step_finished. */
static constexpr double kInterleaveEma = 0.25;
static constexpr int64_t kInterleaveAutoMax = 64;
double ema_chunk_s_ = 0.0, ema_decode_s_ = 0.0;
void step_cost_locked(bool chunk, double seconds);
/* --mixed-step-target-ms: learned mixed-step cap and whether this planning pass has a decoder
* whose output latency the cap protects. */
MixedStepTarget mixed_target_;
bool mixed_target_active_ = false;
/* Aggregate prefill rows already admitted to this mixed step. The learned cap is a budget
* for the step, not a per-request allowance. */
int64_t mixed_target_prefill_planned_ = 0;
/* At least one prefill in the issued mixed step has work beyond this chunk. Unlike a true
* prompt tail, a policy or checkpoint-limited chunk is representative feedback. */
bool mixed_target_prefill_continues_ = false;
void mixed_target_observe_locked(int64_t ns);
/* The throughput window (step_finished): each kind's tokens and the wall time the steps
* covered, both decayed with the same time constant, so their ratio is tokens over time. */
double tps_win_prefill_ = 0.0, tps_win_decode_ = 0.0, tps_win_time_ = 0.0;
bool step_open_ = false;
/* The step just committed: its sequences' committed length and liveness, in plan order. */
std::vector<CommittedSeq> committed_;
/* The single-sequence decode floor (rad::DecodeFloor), fed by step_finished. */
DecodeFloor decode_floor_;
/* arrival; mu_ held */
int add_locked(std::unique_ptr<Request> r);
/* ordering */
bool ahead_of(int32_t a, int32_t b) const;
void queue_insert(std::vector<int32_t>& q, int32_t slot);
static void queue_erase(std::vector<int32_t>& q, int32_t slot);
/* lifecycle */
/* Ends a request: counts it by `st` and queues its id for take_completed. `publish` is
* false only at shutdown, where a possibly half-computed sequence is not worth indexing. A
* failed request's sink is failed with `status` and `why`, which reach the client's error;
* RAD_OK leaves an already-failed sink (an overflow) as it is. */
void close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free = false,
bool publish = true, int status = RAD_OK, const char* why = nullptr);
void reserve_ckpt(StepEntry& e, const Request& r, int64_t pos, int32_t tok);
/* What reap() does once nothing points at the slot: give the blocks back, forget the id,
* destroy the Request and return the slot. Called by reap() directly, or by the sweep in
* commit() for a request whose reap arrived while something still pointed at it. */
void release_locked(SchedReq& s);
/* The sequence's KV back to the manager and its card index back to the pool, together: a step
* in flight still addresses both, so both wait for the same moment. */
void free_kv(SchedReq& s);
void drop_card(SchedReq& s);
/* Is this request still named by a drafter snapshot? block_ and serial_ outlive the lock. */
bool block_holds(uint64_t id) const;
/* Release every deferred reap and free whose request nothing refers to any more. At most one
* step late: what blocked it is either the step just committed or a drafter snapshot that
* block_end() / serial_end() has since cleared. */
void sweep_deferred();
/* Give back a prefix hit an admission attempt took and then could not use: the adopted
* blocks, the checkpoint it would have restored, and the position it would have resumed at.
* The next attempt looks the prompt up again. */
void undo_hit(SchedReq& s);
/* The live Request behind a snapshot row, or null if it went away. */
const Request* block_req(const BlockSeq& d) const;
const Request* serial_req(const SerialSeq& m) const;
/* Both snapshots resolve the same way; the two wrappers exist because the row types differ. */
const Request* live_req(int32_t slot, uint64_t id) const;
bool preempt_back(); /* true: the victim published its prefix */
bool publish_prefix(SchedReq& s);
/* A preempted request waits until the pool can hold its WHOLE remaining recompute, the rest
* of every running prefill, and one block of headroom per runner. Admitting it against only
* the next token steals the blocks a running prefill still needs and preempt_back() resets
* that prefill to zero — the loop. `preempt_wait_overdue` bounds the wait for every overdue
* preempted request: after --preempt-wait-ms the scheduler reclaims cache blocks and preempts
* a decoding runner until one of them can prefill. A runner still prefilling is not a victim. */
bool preempted_can_prefill(const SchedReq& s) const;
bool preempt_wait_overdue(const SchedReq& s) const;
/* Give blocks back from the prefix cache until the pool has headroom again. */
void trim_prefix_cache();
/* RAD_OK, or a negative status when the request cannot be admitted now, nor anything behind
* it. `reserve`: tokens of the step to leave for the requests queued behind this one
* (--busy-prefill-chunk; busy_cap); 0 plans the chunk on the whole budget. */
int admit_one(SchedReq& s, int64_t budget, int64_t reserve = 0,
int64_t mixed_target_shares = 0);
/* Positive sentinel from admit_one: the request waits (its context is still being read off
* disk, or a preempted prefill has no room yet) and the walk may ask the one behind it. */
static constexpr int kAdmitWait = 1;
/* The queue positions one step's admission took, kept to reuse the allocation. */
std::vector<size_t> took_;
/* A step's prefill entries while step() moves its decode entries first; reserved at init,
* since std::stable_partition would take a temporary buffer from the allocator every step. */
std::vector<StepEntry> part_;
/* The conv rolling window, width-1 + num_spec + 1 entries (spec §10). */
int32_t conv_window() const;
};
} /* namespace rad */