/* sched_test.cpp -- the scheduler, the chunker, the step batch, the derivations and the draft * controller, against fakes for core/mem and for the device layer. * * The device fakes are WEAK, so wherever core/device/ is linked in its host backend wins at link * time and this file needs no edit; without it they are what lets a scheduler test run at all. The * KV manager and prefix cache are ordinary implementations of the interfaces in * core/sched/mem_iface.h -- see that header for what has to be reconciled with core/mem. */ #include "rad_test.h" #include "sched/scheduler.h" #include "sched/derive.h" #include "server/sink.h" #include #include #include #include #include #include using namespace rad; /* ================================================================== allocation counter */ /* The step path must not allocate. Counting through a replaced global operator new is the only * way to assert that and mean it: a review can miss a vector that grows on the ten-thousandth * request, and that is exactly the one that shows up as a latency spike nobody can reproduce. */ static long g_allocs = 0; static bool g_counting = false; /* malloc/free is a matched pair for a replaced global new/delete, but GCC's * -Wmismatched-new-delete does not model the replacement and reports every inlined delete in this * translation unit as a free() on a pointer that came from new. */ #if defined(__GNUC__) && !defined(__clang__) # pragma GCC diagnostic ignored "-Wmismatched-new-delete" #endif void* operator new(size_t n) { if (g_counting) ++g_allocs; void* p = std::malloc(n ? n : 1); if (!p) throw std::bad_alloc(); return p; } void* operator new[](size_t n) { return operator new(n); } void operator delete(void* p) noexcept { std::free(p); } void operator delete[](void* p) noexcept { std::free(p); } void operator delete(void* p, size_t) noexcept { std::free(p); } void operator delete[](void* p, size_t) noexcept { std::free(p); } /* ================================================================== the device fakes */ /* Weak, so a linked-in real host backend replaces them. Device memory is host memory here, * which is what makes the batch's device arrays readable below -- the assertions on cu_seqlens and * the slot mapping are reading exactly the bytes a kernel would. */ extern "C" { __attribute__((weak)) void* rad_dev_alloc(int64_t bytes, int) { return std::calloc(1, (size_t)(bytes > 0 ? bytes : 1)); } __attribute__((weak)) void rad_dev_free(void* p, int) { std::free(p); } /* The builder binds a card before it allocates that rank's staging slab, because rad_dev_alloc has * no device argument. Stubbed here for the same reason the rest is -- and stubbed at all because a * MISSING one is worse than a wrong one: the linker would pull dispatch.cpp.o in to resolve it, * and that object's STRONG rad_dev_alloc/rad_memcpy_async would replace every weak fake above, * putting this test on the real HIP backend with the null stream it hands the scheduler. */ __attribute__((weak)) int rad_dev_set(int) { return RAD_OK; } __attribute__((weak)) int rad_memcpy_async(void* d, const void* s, int64_t n, RadStream) { if (n > 0) std::memcpy(d, s, (size_t)n); return RAD_OK; } /* The builder zeroes the encoder rows of every rank but the first. */ __attribute__((weak)) int rad_memset_async(void* d, int v, int64_t n, RadStream) { if (n > 0) std::memset(d, v, (size_t)n); return RAD_OK; } __attribute__((weak)) int rad_memcpy_ranges_async(void* d, const void* s, int64_t prefix, const RadCopyRange* r, int n, RadStream) { if (prefix > 0) std::memcpy(d, s, (size_t)prefix); for (int i = 0; i < n; ++i) std::memcpy((char*)d + r[i].dst, (const char*)s + r[i].src, (size_t)r[i].bytes); return RAD_OK; } static int g_fake_event; __attribute__((weak)) int rad_event_create(RadEvent* e) { *e = &g_fake_event; return RAD_OK; } __attribute__((weak)) int rad_event_create_local(RadEvent* e) { *e = &g_fake_event; return RAD_OK; } __attribute__((weak)) int rad_event_create_as(RadEvent* e, unsigned) { *e = &g_fake_event; return RAD_OK; } __attribute__((weak)) void rad_event_destroy(RadEvent) {} __attribute__((weak)) int rad_event_record(RadEvent, RadStream) { return RAD_OK; } __attribute__((weak)) int rad_event_sync(RadEvent) { return RAD_OK; } } /* extern "C" */ /* ================================================================== fake core/mem */ namespace { /* A small but faithful block manager: a free list per group, refcounted blocks so an adopted * prefix-cache block is not returned to the pool while the cache still names it, and per-sequence * state slots for the linear and conv groups. Mirrors core/mem/kv.h's shape (sequence-keyed, the * manager owns the block tables) so the reconciliation is a rename and not a redesign. */ struct FakeKV : IKVManager { std::vector gs; KVGeom geom; int64_t max_ctx = 0; std::vector> freelist; /* per group */ std::vector> refcnt; /* per group, per block */ std::vector total; std::vector> state_free; /* per group */ struct Seq { std::vector> blocks; /* per group */ std::vector state; /* per group, -1 when not stateful */ int64_t n = 0; /* Per group, the lowest table entry changed since take_table_changes last read it, kept * as the real manager keeps it so the builder's partial restage is what these tests run. */ mutable std::vector dirty; }; std::unordered_map seqs; static inline const std::vector kNone{}; void setup(const std::vector& groups, int64_t ctx, int64_t blocks_per_paged_group, int64_t n_states) { gs = groups; geom = KVGeom::of(gs); max_ctx = ctx; freelist.assign(gs.size(), {}); refcnt.assign(gs.size(), {}); total.assign(gs.size(), 0); state_free.assign(gs.size(), {}); for (size_t i = 0; i < gs.size(); ++i) { if (geom.g[i].paged) { total[i] = blocks_per_paged_group; refcnt[i].assign((size_t)blocks_per_paged_group, 0); for (int64_t b = blocks_per_paged_group - 1; b >= 0; --b) freelist[i].push_back((int32_t)b); } else { for (int64_t k = n_states - 1; k >= 0; --k) state_free[i].push_back((int32_t)k); } } } void retain(int32_t g, int32_t b) { ++refcnt[(size_t)g][(size_t)b]; } void release(int32_t g, int32_t b) { if (--refcnt[(size_t)g][(size_t)b] == 0) freelist[(size_t)g].push_back(b); } int32_t grab(int32_t g) { int32_t b = freelist[(size_t)g].back(); freelist[(size_t)g].pop_back(); refcnt[(size_t)g][(size_t)b] = 1; return b; } int64_t rows_for(int gi, int64_t n) const { const KVGeom::G& e = geom.g[(size_t)gi]; return e.paged ? (n + e.block_size - 1) / e.block_size : 1; } int add_sequence(uint64_t id) override { if (seqs.count(id)) return RAD_OK; Seq q; q.blocks.assign(gs.size(), {}); q.state.assign(gs.size(), -1); q.dirty.assign(gs.size(), 0); seqs.emplace(id, std::move(q)); return RAD_OK; } bool has_sequence(uint64_t id) const override { return seqs.count(id) != 0; } void free_sequence(uint64_t id) override { auto it = seqs.find(id); if (it == seqs.end()) return; for (size_t i = 0; i < gs.size(); ++i) { if (geom.g[i].paged) for (int32_t b : it->second.blocks[i]) release((int32_t)i, b); it->second.blocks[i].clear(); if (it->second.state[i] >= 0) { state_free[i].push_back(it->second.state[i]); it->second.state[i] = -1; } } seqs.erase(it); } int ensure(uint64_t id, int64_t n) override { auto it = seqs.find(id); if (it == seqs.end()) return RAD_E_NOTFOUND; Seq& q = it->second; /* All or nothing: a partial grow would leave the sequence holding blocks it cannot use * and the caller unable to tell whether preempting would help. */ for (size_t i = 0; i < gs.size(); ++i) { if (!geom.g[i].paged) continue; int64_t need = rows_for((int)i, n) - (int64_t)q.blocks[i].size(); if (need > 0 && need > (int64_t)freelist[i].size()) return RAD_E_FULL; } for (size_t i = 0; i < gs.size(); ++i) { if (geom.g[i].paged) { int64_t need = rows_for((int)i, n) - (int64_t)q.blocks[i].size(); if (need > 0) q.dirty[i] = std::min(q.dirty[i], (int64_t)q.blocks[i].size()); for (int64_t k = 0; k < need; ++k) q.blocks[i].push_back(grab((int32_t)i)); } else if (q.state[i] < 0) { if (state_free[i].empty()) return RAD_E_FULL; q.state[i] = state_free[i].back(); state_free[i].pop_back(); q.blocks[i].assign(1, q.state[i]); } } if (n > q.n) q.n = n; return RAD_OK; } int adopt(uint64_t id, int32_t g, const std::vector& blocks, int64_t n) override { auto it = seqs.find(id); if (it == seqs.end()) return RAD_E_NOTFOUND; if (n % geom.g[(size_t)g].block_size != 0) return RAD_E_INVAL; Seq& q = it->second; q.blocks[(size_t)g] = blocks; q.dirty[(size_t)g] = 0; for (int32_t b : blocks) retain(g, b); if (n > q.n) q.n = n; return RAD_OK; } int preempt(uint64_t id) override { auto it = seqs.find(id); if (it == seqs.end()) return RAD_E_NOTFOUND; for (size_t i = 0; i < gs.size(); ++i) { if (geom.g[i].paged) for (int32_t b : it->second.blocks[i]) release((int32_t)i, b); it->second.blocks[i].clear(); it->second.dirty[i] = 0; if (it->second.state[i] >= 0) { state_free[i].push_back(it->second.state[i]); it->second.state[i] = -1; } } it->second.n = 0; return RAD_OK; } int rollback(uint64_t id, int64_t n) override { auto it = seqs.find(id); if (it == seqs.end()) return RAD_E_NOTFOUND; for (size_t i = 0; i < gs.size(); ++i) { if (!geom.g[i].paged) continue; /* linear state is NOT rolled back (spec §10) */ int64_t keep = rows_for((int)i, n); std::vector& bl = it->second.blocks[i]; while ((int64_t)bl.size() > keep) { release((int32_t)i, bl.back()); bl.pop_back(); } it->second.dirty[i] = std::min(it->second.dirty[i], (int64_t)bl.size()); } it->second.n = n; return RAD_OK; } bool can_ever_fit(int64_t n) const override { for (size_t i = 0; i < gs.size(); ++i) if (geom.g[i].paged && rows_for((int)i, n) > total[i]) return false; return true; } const std::vector& block_table(uint64_t id, int32_t g) const override { auto it = seqs.find(id); return it == seqs.end() ? kNone : it->second.blocks[(size_t)g]; } int32_t state_slot(uint64_t id, int32_t g) const override { auto it = seqs.find(id); return it == seqs.end() ? -1 : it->second.state[(size_t)g]; } /* One column, the state itself: this fake has no kernel asking for scratch beside it. */ int64_t state_index_width(int32_t) const override { return 1; } int state_index_row(uint64_t id, int32_t g, int32_t* out, int max) const override { if (!out || max <= 0) return 0; out[0] = state_slot(id, g); return 1; } int64_t first_block_pos(uint64_t, int32_t) const override { return 0; } int64_t take_table_changes(uint64_t id, int32_t g) const override { auto it = seqs.find(id); if (it == seqs.end()) return 0; const int64_t d = it->second.dirty[(size_t)g]; it->second.dirty[(size_t)g] = INT64_MAX; return d; } /* Snapshot slots the store has given back; every other slot is held. */ std::vector ck_gone; bool checkpoint_held(int32_t slot) const override { return std::find(ck_gone.begin(), ck_gone.end(), slot) == ck_gone.end(); } /* Blocks an elastic pool has handed back to the card: still carved and free, but not * available to hand out until the pool grows again. free_blocks() is bounded by that and * held_blocks() is not, which is the difference an elastic pool presents. */ int64_t unbacked = 0; int64_t free_blocks(int32_t g) const override { const int64_t n = (int64_t)freelist[(size_t)g].size() - unbacked; return n > 0 ? n : 0; } int64_t total_blocks(int32_t g) const override { return total[(size_t)g]; } int64_t held_blocks(int32_t g) const override { return total[(size_t)g] - (int64_t)freelist[(size_t)g].size(); } /* A BYTE SIZE PER OBJECT SO THE SUM IS CHECKABLE. The real manager reads these off the carved * plan; here they are whatever the test set, and a group left at zero contributes nothing -- * which is what a group the fixture does not care about should do. */ std::vector block_bytes, state_bytes; int64_t pool_bytes(int32_t g) const override { const KVGeom::G& gg = geom.g[(size_t)g]; return gg.paged ? total[(size_t)g] * bb(g) : (int64_t)(state_free[(size_t)g].size() + n_states_out(g)) * sb(g); } int64_t pool_bytes_used(int32_t g) const override { const KVGeom::G& gg = geom.g[(size_t)g]; return gg.paged ? (total[(size_t)g] - free_blocks(g)) * bb(g) : n_states_out(g) * sb(g); } /* This pool is not elastic, so what it was carved to address is what it is holding. */ int64_t pool_bytes_carved(int32_t g) const override { return pool_bytes(g); } int64_t bb(int32_t g) const { return g < (int32_t)block_bytes.size() ? block_bytes[(size_t)g] : 0; } int64_t sb(int32_t g) const { return g < (int32_t)state_bytes.size() ? state_bytes[(size_t)g] : 0; } /* States handed out, which the fake tracks only through the sequences holding them. */ int64_t n_states_out(int32_t g) const { int64_t n = 0; for (const auto& kv : seqs) if (kv.second.state[(size_t)g] >= 0) ++n; return n; } int64_t block_tokens(int32_t g) const override { const KVGeom::G& gg = geom.g[(size_t)g]; return gg.paged ? gg.block_size : 0; } }; struct FakePC : IPrefixCache { FakeKV* kv = nullptr; int32_t attn = 0, lin = 0, src = -1; int32_t next_slot = 0; int32_t reserved = 0; int64_t evicted = 0, ckpt_evicted = 0; int64_t held = 0; /* what the cache would report holding now */ int64_t interval = 256; std::vector groups; /* the paged groups this cache indexes */ std::vector> seeded; /* blocks the cache holds a reference on */ /* Pretend an earlier request filled the cache: take `n_tokens` worth of blocks out of the pool * and hold a reference on them, which is what makes a hit safe -- a block the cache names is * never in the free list. */ void seed(int32_t n_tokens) { attn = n_tokens; seeded.assign(groups.size(), {}); for (size_t i = 0; i < groups.size(); ++i) { int32_t g = groups[i]; int64_t nb = n_tokens / kv->geom.g[(size_t)g].block_size; for (int64_t b = 0; b < nb; ++b) seeded[i].push_back(kv->grab(g)); } } /* The requests whose context is still being read off disk. */ std::vector reading; std::vector restores; Restore restore(const Request& r) override { restores.push_back(r.id); return std::find(reading.begin(), reading.end(), r.id) != reading.end() ? Restore::Wait : Restore::Done; } mutable int64_t lookups = 0; /* A cap (HitCap) as prefix.cpp applies one: attention ends at a block at or below it, the * linear state at the deepest checkpoint under that -- checkpoints at multiples of `interval`, * none below `ckpt_lo` -- and the whole hit stands if that gives back too much. */ int64_t ckpt_lo = 0; CacheHit lookup(const Request&, std::vector>* out, const HitCap* cap) const override { ++lookups; if (out) { out->resize(groups.size()); for (size_t i = 0; i < groups.size() && i < seeded.size(); ++i) (*out)[i] = seeded[i]; } CacheHit h{ attn, lin, src }; const int64_t whole = src >= 0 ? lin : 0; if (cap && attn > cap->tokens / 16 * 16 && whole > cap->tokens) { const int64_t a = cap->tokens / 16 * 16; int64_t l = std::min(lin, a) / interval * interval; if (l < ckpt_lo) l = 0; if (whole - l <= cap->max_give_back) { h.n_attn_tokens = (int32_t)a; h.n_linear_tokens = (int32_t)l; h.checkpoint_slot = l > 0 ? src : -1; h.given_back = (int32_t)(whole - l); if (out) for (auto& b : *out) if ((int64_t)b.size() > a / 16) b.resize((size_t)(a / 16)); } } return h; } const std::vector& cached_groups() const override { return groups; } /* What the scheduler published, and what it asked to be evicted. Recorded rather than acted * on: these tests are about whether the scheduler publishes before it frees and evicts before * it preempts, not about the cache's own indexing, which prefix.cpp's tests cover. */ struct Published { uint64_t seq; int64_t n_tokens; size_t n_groups; }; std::vector published; int64_t evict_calls = 0, evict_grant = 0; int insert(const Request& r, const std::vector>& blocks, int64_t n_tokens) override { published.push_back({ r.id, n_tokens, blocks.size() }); return RAD_OK; } /* Grants only what a test asked it to, so "the cache had nothing to give" is reachable and * the preemption path below it still gets exercised. */ int64_t evict(int64_t n) override { ++evict_calls; if (evict_grant <= 0) return 0; int64_t took = n < evict_grant ? n : evict_grant; if (evict_frees) { /* An entry is one block in every cached group: give that many back to the pool. */ int64_t have = seeded.empty() ? 0 : (int64_t)seeded[0].size(); took = std::min(took, have); for (size_t i = 0; i < groups.size() && i < seeded.size(); ++i) for (int64_t k = 0; k < took; ++k) { kv->release(groups[i], seeded[i].back()); seeded[i].pop_back(); } } evict_grant -= took; evicted += took; return took; } bool evict_frees = false; /* evict() returns the seeded blocks to the pool */ std::vector holds, releases; void hold(const Request& r) override { holds.push_back(r.id); } void release(const Request& r) override { releases.push_back(r.id); } /* What the reserve asked for, call by call. */ std::vector trims; int64_t trim(int64_t n) override { trims.push_back(n); return 0; } /* Cumulative, like the real cache's: the scheduler publishes it as a counter and the * server takes deltas, so a fake that reported per-call would read as a cache that * never evicts. */ int64_t evictions() const override { return evicted; } int64_t ckpt_evictions() const override { return ckpt_evicted; } int64_t held_tokens() const override { return held; } int64_t next_checkpoint_after(int64_t pos) const override { return ((pos / interval) + 1) * interval; } std::vector committed; std::vector resumed; /* the commits marked as resume points */ void commit_checkpoint(const Request&, int64_t pos, bool resume) override { committed.push_back(pos); if (resume) resumed.push_back(pos); } int reserve_checkpoint(const Request&, int64_t, int32_t* slot_out) override { ++reserved; *slot_out = next_slot++; return RAD_OK; } }; /* ------------------------------------------------------------------ a declared program */ /* Two paged groups would be redundant here; what matters is that a paged group and a linear one * coexist, because the whole chunk geometry is the reconciliation between them. * * THE OP CARRIES A SCHEMA because that is where the chunk parameter is identified * (RAD_PROLE_SEQ_CHUNK), rather than by matching a list of spellings. The geometry and the * kernel's constraint must name the SAME key -- a constraint whose key the op's geometry does not * carry does not hold at all (rad_abi.h) -- so declaring "chunk" here and constraining on * "chunk_size" would be a pair the real system cannot produce. */ static const RadParamSpec g_gdn_ps[] = { { "M", RAD_P_INT, RAD_REQUIRED, RAD_PROLE_NONE }, { "chunk", RAD_P_INT, RAD_DERIVED, RAD_PROLE_SEQ_CHUNK }, }; static const RadOpSchema g_gdn_schema = { "gdn_chunk_scan", g_gdn_ps, 2, nullptr, 0, "test" }; static RadConstraint g_gdn_c[] = { RAD_CDIV("chunk", 64) }; static RadKernelInfo g_gdn_ki; static KernelRow g_gdn_row; struct Fixture { Program prog; Config cfg; FakeKV kv; FakePC pc; Scheduler sch; std::vector owned; ~Fixture() { sch.fini(); for (void* p : owned) std::free(p); } void build(int64_t blocks = 4096, int64_t states = 64, int64_t max_tok = 512, int64_t max_ctx = 4096, bool windowed = false) { g_gdn_ki = RadKernelInfo{}; g_gdn_ki.name = "gdn_fake"; g_gdn_ki.op = "gdn_chunked"; g_gdn_ki.constraints = g_gdn_c; g_gdn_ki.n_constraints = 1; g_gdn_row = KernelRow{ &g_gdn_ki, "fake", 0, 0 }; prog.meta.n_ctx_train = 4096; /* index 0 is the sentinel every handle table in Program carries */ prog.ops.emplace_back(); prog.buffers.emplace_back(); KVGroupInfo attn; attn.name = "attn"; attn.decl.kind = RAD_KV_FULL; attn.block_size = 16; prog.kv_groups.push_back(attn); KVGroupInfo lin; lin.name = "gdn"; lin.decl.kind = RAD_KV_LINEAR; lin.decl.state_dim[0] = 128; lin.decl.state_dim[1] = 128; prog.kv_groups.push_back(lin); KVGroupInfo conv; conv.name = "conv"; conv.decl.kind = RAD_KV_CONV; conv.decl.conv_width = 4; prog.kv_groups.push_back(conv); /* A WINDOWED paged group — the second half of the pair a sliding-window model declares * (windowed layers + a full group; qwen35/llama windowed checkpoints declare these). * Paged, block-aligned, and deliberately NOT prefix-cached: prefix.cpp indexes only the * groups whose blocks below the window stay put. Tests that want a prefix cache over a * WINDOW+FULL pair trim pc.groups to the cached ones. */ if (windowed) { KVGroupInfo win; win.name = "swa"; win.decl.kind = RAD_KV_WINDOW; win.decl.window = 64; win.block_size = 16; win.layers = { 2 }; /* bound to a TRUNK layer — the group a trunk attention reads; * a drafter's own group is bound at the trunk's layer count and * above (rad_bind_layer_kv at the drafter declare) */ prog.kv_groups.push_back(win); prog.meta.n_layers = 16; /* trunk layers 0..15; the drafter tests' appended group * stays unbound, and unbound is not trunk-owned */ } OpInfo op; op.op = "gdn_chunk_scan"; op.schema = &g_gdn_schema; Band b; b.hi = 4096; b.dom[RAD_DOMAIN_DEVICE].row = &g_gdn_row; /* The architecture plugin's own declared geometry, in arch/common/rad_block_gdn.h's * spelling, which is the key its schema marks RAD_PROLE_SEQ_CHUNK. Both this and the * kernel's constraint contribute. */ b.dom[RAD_DOMAIN_DEVICE].geom.set_i("chunk", 64); op.bands.push_back(b); prog.ops.push_back(op); add_derived("seq_start", "seq_start_index", 257); add_derived("chunk_bounds", "state_chunk_bounds", 4097); add_derived("conv_idx", "conv_state_index", 256); cfg.max_tok = max_tok; cfg.max_seqs = 32; cfg.max_ctx = max_ctx; cfg.checkpoint_interval = 256; cfg.prefix_cache = true; /* `Config::n_spec` defaults to -1, which is `auto`: a REQUEST that engine_bringup resolves * against rad_arch_probe once the plugin is selected. This fixture builds a Scheduler * directly and so never runs that resolution, and DraftController::configure rightly * refuses a negative depth. The cases that are about speculation set their own depth. */ cfg.n_spec = 0; kv.setup(prog.kv_groups, cfg.max_ctx, blocks, states); pc.kv = &kv; pc.groups.clear(); for (size_t i = 0; i < prog.kv_groups.size(); ++i) if (kv.geom.g[i].paged) pc.groups.push_back((int32_t)i); } void add_derived(const char* name, const char* derive, int64_t n, rad_kvgroup kv = 0) { BufferInfo b; b.name = name; b.decl.dtype = RAD_I32; b.decl.rank = 1; b.decl.shape[0] = n; b.decl.kind = RAD_BUF_DERIVED; b.decl.derive = derive; b.decl.kv = kv; b.bytes = n * 4; void* p = std::calloc(1, (size_t)b.bytes); owned.push_back(p); b.ptr = p; prog.buffers.push_back(b); } int start() { std::vector rio; rio.push_back({ 0, nullptr, &prog }); return sch.init(prog, cfg, &kv, &pc, rio); } const int32_t* derived(const char* name) const { for (const BufferInfo& b : prog.buffers) if (b.name == name) return (const int32_t*)b.ptr; return nullptr; } uint64_t next_id = 1; uint64_t submit(int n_prompt, int max_tokens = 64, int priority = 0, bool ignore_eos = false) { auto r = std::make_unique(); r->id = next_id++; r->priority = priority; r->ignore_eos = ignore_eos; r->max_tokens = max_tokens; r->prompt.resize((size_t)n_prompt); for (int i = 0; i < n_prompt; ++i) r->prompt[(size_t)i] = 1000 + i; uint64_t id = r->id; if (sch.add(std::move(r)) < 0) return 0; return id; } /* The same, with the server's sink attached, for what a request tells its client. */ uint64_t submit_to(server::Sink* sink, int n_prompt, int max_tokens) { auto r = std::make_unique(); r->id = next_id++; r->max_tokens = max_tokens; r->sink = sink; r->prompt.resize((size_t)n_prompt); for (int i = 0; i < n_prompt; ++i) r->prompt[(size_t)i] = 1000 + i; uint64_t id = r->id; if (sch.add(std::move(r)) < 0) return 0; return id; } /* Commit a step in which every sequence produced one token and none ended. */ void commit_plain(int32_t token = 7) { const StepPlan& p = sch.plan(); std::vector acc((size_t)p.e.size(), 0), tok((size_t)p.e.size(), token); std::vector eos((size_t)p.e.size(), 0); Scheduler::StepResult r; r.n_seq = (int)p.e.size(); r.n_accepted = acc.data(); r.token = tok.data(); r.eos = eos.data(); CHECK_OK(sch.commit(r)); } }; } /* namespace */ /* ================================================================== geometry + chunking */ TEST(chunk_geometry_is_computed_not_configured) { Fixture f; f.build(); CHECK_OK(f.start()); const ChunkGeometry& g = f.sch.geometry(); CHECK_EQ(g.attn_block, 16); /* off the paged group */ CHECK_EQ(g.state_chunk, 64); /* off the resolved GDN kernel's DIV constraint */ CHECK_EQ(g.quantum, 64); /* lcm */ CHECK_EQ(g.checkpoint_interval, 256); /* already a multiple of the quantum */ CHECK_EQ(g.min_max_tok, 64); } TEST(chunk_geometry_rounds_the_checkpoint_interval_up_to_a_legal_chunk) { Fixture f; f.build(); f.cfg.checkpoint_interval = 200; /* not a multiple of 64 */ CHECK_OK(f.start()); CHECK_EQ(f.sch.geometry().checkpoint_interval, 256); } TEST(chunk_geometry_refuses_a_budget_it_cannot_serve) { Fixture f; f.build(); f.cfg.max_tok = 32; /* below one quantum */ log_set_level(Log::Error); CHECK_EQ(f.start(), RAD_E_INVAL); } TEST(prefill_chunks_split_at_the_checkpoint_interval) { Fixture f; f.build(); CHECK_OK(f.start()); int64_t ck = -1; /* The budget would allow 512 tokens; the split takes 256 so the chunk ENDS on the interval. */ CHECK_EQ(f.sch.plan_chunk(0, 1000, 512, &ck), 256); CHECK_EQ(ck, 256); CHECK_EQ(f.sch.plan_chunk(256, 1000, 512, &ck), 256); CHECK_EQ(ck, 512); /* The final chunk ends at the prompt's last quantum boundary and writes a checkpoint there: * the next turn of a conversation resumes from it instead of from 768. The remainder, under a * quantum, is the chunk after it and writes none -- that is the accepted cost of owning the * boundaries. */ CHECK_EQ(f.sch.plan_chunk(768, 1000, 512, &ck), 192); CHECK_EQ(ck, 960); CHECK_EQ(f.sch.plan_chunk(960, 1000, 512, &ck), 40); CHECK_EQ(ck, -1); /* A prompt that ends less than a quantum past where the chunk starts has no boundary to * split at, and one inside the first interval is cheap enough to prefill again. */ CHECK_EQ(f.sch.plan_chunk(768, 830, 512, &ck), 62); CHECK_EQ(ck, -1); CHECK_EQ(f.sch.plan_chunk(0, 200, 512, &ck), 200); CHECK_EQ(ck, -1); /* And a prompt ending on a quantum boundary takes its checkpoint at the end, unsplit. */ CHECK_EQ(f.sch.plan_chunk(768, 960, 512, &ck), 192); CHECK_EQ(ck, 960); /* A budget short of the interval still ends on a quantum, never in the middle of a tile. */ CHECK_EQ(f.sch.plan_chunk(0, 1000, 100, &ck), 64); CHECK_EQ(ck, -1); /* A budget that cannot hold one quantum schedules nothing rather than a misaligned chunk. */ CHECK_EQ(f.sch.plan_chunk(0, 1000, 50, &ck), 0); } TEST(a_chunk_ending_on_a_checkpoint_carries_it_into_the_batch) { Fixture f; f.build(); CHECK_OK(f.start()); f.submit(1000, 8); const RadBatch* b = f.sch.step(); CHECK(b != nullptr); CHECK_EQ(b->n_tok, 256); CHECK_EQ(b->n_checkpoints, 1); /* The snapshot is the state after the LAST token of the chunk, and the split put that token * at the interval boundary. */ CHECK_EQ(b->checkpoint_tok[0], 255); CHECK_EQ(b->checkpoint_slot[0], 0); CHECK_EQ(b->phase, RAD_PHASE_PREFILL); } /* ================================================================== admission */ TEST(admission_refuses_when_the_kv_pool_is_short) { Fixture f; f.build(/*blocks=*/20, /*states=*/64); /* 20 x 16 = 320 tokens of paged KV */ CHECK_OK(f.start()); f.submit(160, 8); /* 10 blocks */ f.submit(160, 8); /* 10 blocks -- exactly fills the pool */ f.submit(160, 8); /* must not be admitted */ const RadBatch* b = f.sch.step(); CHECK(b != nullptr); CHECK_EQ(b->n_seq, 2); CHECK_EQ(f.kv.free_blocks(0), 0); SchedMetrics m = f.sch.metrics(); CHECK_EQ(m.running, 2); CHECK_EQ(m.queue_depth, 1); CHECK_EQ(m.admitted, 2); } /* An observer reads the copy the engine thread published, never the live state, so what it sees * moves only at a publication -- and a publication carries exactly what the live readers say. */ TEST(observers_read_what_the_engine_thread_published) { Fixture f; f.build(/*blocks=*/20, /*states=*/64); CHECK_OK(f.start()); f.submit(160, 8); f.submit(160, 8); f.submit(160, 8); CHECK(f.sch.step() != nullptr); std::vector seen(8), live(8); CHECK_EQ(f.sch.observed_metrics().admitted, 0); /* nothing published yet */ CHECK_EQ(f.sch.observed_requests(seen.data(), 8), 0); f.sch.publish(/*idle=*/false); const SchedMetrics o = f.sch.observed_metrics(); const SchedMetrics m = f.sch.metrics(); CHECK_EQ(o.running, m.running); CHECK_EQ(o.queue_depth, m.queue_depth); CHECK_EQ(o.admitted, 2); const int n = f.sch.observed_requests(seen.data(), 8); CHECK_EQ(n, f.sch.requests(live.data(), 8)); CHECK_EQ(n, 3); for (int i = 0; i < n; ++i) { CHECK_EQ(seen[(size_t)i].id, live[(size_t)i].id); CHECK_EQ(seen[(size_t)i].state, live[(size_t)i].state); CHECK_EQ(seen[(size_t)i].prompt_tokens, live[(size_t)i].prompt_tokens); } /* An idle publication inside 20 ms of the last one is skipped; a step's never is. */ f.submit(160, 8); f.sch.publish(/*idle=*/true); CHECK_EQ(f.sch.observed_metrics().queue_depth, 1); f.sch.publish(/*idle=*/false); CHECK_EQ(f.sch.observed_metrics().queue_depth, 2); CHECK_EQ(f.sch.observed_requests(seen.data(), 8), 4); } /* The sequences of one API request go in under one hold of the lock, each accepted or refused on * its own terms: a duplicate id is refused without taking its neighbours with it. */ TEST(add_all_queues_a_set_under_one_lock_and_refuses_members_singly) { Fixture f; f.build(/*blocks=*/20, /*states=*/64); CHECK_OK(f.start()); std::unique_ptr rs[3]; for (int i = 0; i < 3; ++i) { rs[i] = std::make_unique(); rs[i]->id = f.next_id++; rs[i]->max_tokens = 8; rs[i]->prompt.assign(32, 1000 + i); } rs[2]->id = rs[0]->id; int rc[3] = { -1, -1, -1 }; f.sch.add_all(rs, 3, rc); CHECK_EQ(rc[0], RAD_OK); CHECK_EQ(rc[1], RAD_OK); CHECK_EQ(rc[2], RAD_E_DUPLICATE); const RadBatch* b = f.sch.step(); CHECK(b != nullptr); CHECK_EQ(b->n_seq, 2); CHECK_EQ(f.sch.metrics().admitted, 2); } TEST(a_prefix_hit_starts_the_request_at_the_last_usable_checkpoint) { Fixture f; f.build(); CHECK_OK(f.start()); f.pc.seed(304); /* the attention blocks match 304 tokens deep (19 blocks) */ f.pc.lin = 256; /* but the last linear checkpoint is at 256 */ f.pc.src = 3; int64_t free_before = f.kv.free_blocks(0); uint64_t a = f.submit(1000, 8); const RadBatch* b = f.sch.step(); CHECK(b != nullptr); /* Recompute resumes from the checkpoint rather than replaying only the linear layers over * (256, 300], because RadBatch carries ONE query length for every KV group. The chunk still * ends on the next interval, so the next checkpoint is still written. */ CHECK_EQ(f.sch.find(a)->n_computed, 256); CHECK_EQ(b->ctx_lens[0], 256); CHECK_EQ(b->n_tok, 256); CHECK_EQ(b->n_checkpoints, 1); CHECK_EQ(b->checkpoint_tok[0], 255); /* THE RECURRENT HALF OF THE HIT IS CARRIED, and it is carried exactly once. The adopted blocks * describe the attention layers; the linear ones resume from this slot and from nothing * else, so an entry that skipped 256 tokens without naming a snapshot would be a sequence * continuing from whatever the slot last held. */ CHECK_EQ(f.sch.plan().e[0].ckpt_restore, 3); /* The hit is CLAIMED, not merely counted: the sequence adopted the cache's 16 blocks, which * cost the pool nothing because the cache already held them, and then allocated only the 16 * new blocks its 256-token chunk needs. A hit that is not adopted is a sequence attending to * blocks it does not own. */ CHECK_EQ((int)f.kv.block_table(a, 0).size(), 32); CHECK_EQ(f.kv.block_table(a, 0)[0], f.pc.seeded[0][0]); CHECK_EQ(f.kv.free_blocks(0), free_before - 16); SchedMetrics m = f.sch.metrics(); CHECK_EQ(m.prompt_tokens, 1000); CHECK_EQ(m.attn_cached_tokens, 304); /* what the block cache matched */ CHECK_EQ(m.linear_cached_tokens, 256); /* what was actually skipped */ CHECK_EQ(m.checkpoints_written, 1); /* ...and the snapshot this step takes is not offered to anyone until the step has run. The * reservation happened when the chunk was planned; the state exists only afterwards. */ CHECK(f.pc.committed.empty()); f.commit_plain(); CHECK_EQ((int)f.pc.committed.size(), 1); CHECK_EQ(f.pc.committed[0], 512); /* ctx_len 256 + ckpt_tok 255 + 1 */ } /* THE DEEPEST CHECKPOINT A PROMPT GETS IS ITS RESUME POINT, and it alone is committed as one: it is * the state the next turn resumes from, and the tiers copy it off the card at once rather than * with the rest of the conversation at its publish. */ TEST(only_a_prompt_s_deepest_checkpoint_is_its_resume_point) { Fixture f; f.build(); CHECK_OK(f.start()); const uint64_t a = f.submit(1000, 8); for (int i = 0; i < 64 && f.sch.find(a)->n_computed < 1000; ++i) { REQUIRE(f.sch.step() != nullptr); f.commit_plain(); } REQUIRE(f.pc.committed.size() >= 2u); REQUIRE_EQ(f.pc.resumed.size(), 1u); CHECK_EQ(f.pc.resumed[0], f.pc.committed.back()); } /* A hit that skipped tokens with no snapshot to resume from is the corruption this whole mechanism * exists to prevent, so it is refused outright rather than served with a zeroed state. */ TEST(a_hit_with_no_checkpoint_slot_reuses_nothing) { Fixture f; f.build(); CHECK_OK(f.start()); f.pc.seed(304); f.pc.lin = 256; f.pc.src = -1; /* the cache found a prefix but no snapshot covering it */ uint64_t a = f.submit(1000, 8); CHECK(f.sch.step() != nullptr); CHECK_EQ(f.sch.find(a)->n_computed, 0); CHECK_EQ(f.sch.metrics().linear_cached_tokens, 0); } /* A RESTORE FROM A SLOT THE STORE GAVE BACK IS NEVER BUILT. The cache keeps a handed-out snapshot * until the step that restores it has run, so this is a guard: a step that finds one is abandoned, * the request gives its hit back and goes to the queue, and the next step prefills it from a fresh * lookup rather than the engine stopping on the restore. */ TEST(a_restore_from_a_slot_the_store_gave_back_is_prefilled_again) { Fixture f; f.build(); CHECK_OK(f.start()); f.pc.seed(304); f.pc.lin = 256; f.pc.src = 3; f.kv.ck_gone = {3}; const int64_t free_before = f.kv.free_blocks(0); const uint64_t a = f.submit(1000, 8); CHECK(f.sch.step() == nullptr); CHECK_EQ(f.sch.find(a)->n_computed, 0); CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Waiting); CHECK_EQ(f.kv.free_blocks(0), free_before); /* the adopted blocks went back */ /* The next lookup finds no snapshot, and the request runs from zero. */ f.pc.src = -1; f.kv.ck_gone.clear(); const RadBatch* b = f.sch.step(); REQUIRE(b != nullptr); CHECK_EQ(b->ctx_lens[0], 0); CHECK_EQ(f.sch.plan().e[0].ckpt_restore, -1); } TEST(a_hit_that_no_checkpoint_covers_replays_from_zero) { Fixture f; f.build(); CHECK_OK(f.start()); f.pc.seed(192); f.pc.lin = 0; /* nothing checkpointed yet */ uint64_t a = f.submit(1000, 8); CHECK(f.sch.step() != nullptr); CHECK_EQ(f.sch.find(a)->n_computed, 0); CHECK_EQ(f.sch.metrics().linear_cached_tokens, 0); } /* THE PREFIX CACHE CANNOT COVER A MODEL WITH A PAGED GROUP IT DOES NOT INDEX. The fixture's * groups are FULL, LINEAR, CONV, WINDOW — the windowed group is paged, bound to a trunk layer, * and a real cache skips it (prefix.cpp: its blocks below the window are recycled, so no block * list describes them), which is what pc.groups = {0} reproduces: three paged groups, one * cached. The cache below is seeded to a DEEP, checkpoint-covered hit — 304 attention blocks, * the linear state at 256, a slot to restore from — the most legitimate hit there is: every * clamp above the trunk one lets it through untouched. The adopted blocks cover group 0 ONLY, * while used = ctx_len + n_tok makes the windowed trunk layers read the positions below ctx_len * this sequence never wrote — and the pool hands out the most recently freed blocks, i.e. the * previous tenant's. That is reading ANOTHER REQUEST'S KV AS YOUR OWN PREFIX: fluent text * carrying the last request's content. No tail-recompute repairs a trunk hole (a drafter's own * hole is another matter, and the refill tests above keep theirs); the hit is refused. */ TEST(a_hit_on_a_model_with_a_windowed_group_reuses_nothing) { Fixture f; f.build(4096, 64, 512, 4096, /*windowed=*/true); f.pc.groups = {0}; /* a cache that indexes the FULL group only — windowed groups are not * prefix-cacheable; must precede start(), which reads it once */ CHECK_OK(f.start()); f.pc.seed(304); /* a deep, block-aligned attention hit: 19 blocks */ f.pc.lin = 256; /* its linear state checkpoints at 256 — the resume point exists */ f.pc.src = 3; /* and names a snapshot, so no checkpoint clamp applies */ uint64_t a = f.submit(300, 8); const RadBatch* b = f.sch.step(); REQUIRE(b != nullptr); /* The whole hit is refused, not trimmed: the request runs from zero. */ CHECK_EQ(f.sch.find(a)->n_computed, 0); CHECK_EQ(f.sch.find(a)->n_cached, 0); CHECK_EQ(b->ctx_lens[0], 0); CHECK_EQ(f.sch.plan().e[0].ckpt_restore, -1); /* NOTHING IS ADOPTED — the 16 blocks covering the 256-token chunk are all freshly grabbed. */ CHECK_EQ((int)f.kv.block_table(a, 0).size(), 16); CHECK(std::find(f.pc.seeded[0].begin(), f.pc.seeded[0].end(), f.kv.block_table(a, 0)[0]) == f.pc.seeded[0].end()); /* THE CACHE STILL REPORTED THE MATCH, and the metrics say so: this is a real hit the * scheduler refused, not a lookup that found nothing. */ SchedMetrics m = f.sch.metrics(); CHECK_EQ(m.attn_cached_tokens, 304); CHECK_EQ(m.linear_cached_tokens, 0); } /* ================================================================== preemption */ /* A REQUEST WHOSE CONTEXT IS STILL BEING READ OFF DISK WAITS, AND ONLY IT DOES. It is not admitted * short -- the hit length is what its prefill is shaped by -- and it does not hold up the queue: * the request behind it is asked and runs. Once the read is in, it is admitted where it stood. */ TEST(a_request_waiting_on_a_disk_read_lets_the_queue_past_it) { Fixture f; f.build(); CHECK_OK(f.start()); const uint64_t a = f.submit(160, 8); const uint64_t b = f.submit(160, 8); const uint64_t c = f.submit(160, 8); f.pc.reading = {a, c}; const RadBatch* s1 = f.sch.step(); CHECK(s1 != nullptr); CHECK_EQ(s1->n_seq, 1); CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Waiting); CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Running); CHECK_EQ((int)f.sch.find(c)->state, (int)ReqState::Waiting); CHECK_EQ(f.pc.lookups, 1); /* nothing looked up for the ones that wait */ uint64_t q[8]; int n = f.sch.queue_snapshot(q, 8); REQUIRE_EQ(n, 2); CHECK_EQ(q[0], a); /* still in the order they came */ CHECK_EQ(q[1], c); f.commit_plain(); /* Asked again every step, and admitted the step its read is in. */ f.pc.reading = {c}; f.pc.restores.clear(); const RadBatch* s2 = f.sch.step(); CHECK(s2 != nullptr); CHECK_EQ(s2->n_seq, 2); CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Running); CHECK_EQ((int)f.sch.find(c)->state, (int)ReqState::Waiting); CHECK(std::find(f.pc.restores.begin(), f.pc.restores.end(), c) != f.pc.restores.end()); f.commit_plain(); f.pc.reading.clear(); const RadBatch* s3 = f.sch.step(); CHECK(s3 != nullptr); CHECK_EQ(s3->n_seq, 3); CHECK_EQ((int)f.sch.find(c)->state, (int)ReqState::Running); CHECK_EQ(f.sch.queue_snapshot(q, 8), 0); CHECK_EQ(f.sch.metrics().admitted, 3); } TEST(preemption_takes_the_lowest_priority_victim_and_requeues_it_to_the_front) { Fixture f; f.build(/*blocks=*/20, /*states=*/64); CHECK_OK(f.start()); uint64_t a = f.submit(160, 64, /*priority=*/0); /* arrives first, low priority */ uint64_t b = f.submit(160, 64, /*priority=*/5); /* arrives second, high priority */ uint64_t c = f.submit(160, 64, /*priority=*/0); /* stays waiting */ CHECK(a && b && c); const RadBatch* s1 = f.sch.step(); CHECK(s1 != nullptr); CHECK_EQ(s1->n_seq, 2); f.commit_plain(); /* Both are now decoding at position 160, which is a block boundary: the next token needs a * new block and the pool has none. The victim must be A -- lowest priority, and the one that * would be re-admitted last anyway -- not the head-of-line B. */ const RadBatch* s2 = f.sch.step(); CHECK(s2 != nullptr); CHECK_EQ(s2->n_seq, 1); CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Preempted); CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Running); CHECK_EQ(f.sch.find(a)->n_computed, 0); /* preemption is by RECOMPUTE */ CHECK_EQ(f.sch.find(a)->state_slot, -1); /* Re-queued to the FRONT: it keeps its original arrival, so it sits ahead of C, which arrived * later at the same priority. It has already been served once and its blocks were taken from * it; sending it to the back would charge it twice. */ uint64_t q[8]; int n = f.sch.queue_snapshot(q, 8); CHECK_EQ(n, 2); CHECK_EQ(q[0], a); CHECK_EQ(q[1], c); CHECK_EQ(f.sch.metrics().preemptions, 1); CHECK_EQ(f.sch.metrics().preempted_waiting, 1); } /* ================================================================== the step batch */ TEST(a_mixed_step_has_the_right_boundaries_and_slot_mapping) { Fixture f; f.build(); CHECK_OK(f.start()); uint64_t a = f.submit(100, 64); CHECK(a); const RadBatch* s1 = f.sch.step(); CHECK(s1 != nullptr); CHECK_EQ(s1->n_tok, 100); f.commit_plain(4242); /* A is decoding at position 100; B arrives and prefills 64 tokens in the same step. */ uint64_t b = f.submit(64, 64); CHECK(b); const RadBatch* s2 = f.sch.step(); CHECK(s2 != nullptr); CHECK_EQ(s2->phase, RAD_PHASE_MIXED); CHECK_EQ(s2->n_seq, 2); CHECK_EQ(s2->n_tok, 65); CHECK_EQ(s2->cu_seqlens[0], 0); CHECK_EQ(s2->cu_seqlens[1], 1); CHECK_EQ(s2->cu_seqlens[2], 65); CHECK_EQ(s2->q_lens[0], 1); CHECK_EQ(s2->q_lens[1], 64); CHECK_EQ(s2->ctx_lens[0], 100); CHECK_EQ(s2->ctx_lens[1], 0); CHECK_EQ(s2->max_q_len, 64); /* A CEILING ON A COARSE GRID, not the exact longest context: 100 rounds up to the 1024-token * floor, so the step's arguments stay put while the context grows under it. */ CHECK_EQ(s2->max_ctx_len, 1024); /* The decode row feeds the token that was sampled last step, not a prompt token. */ CHECK_EQ(s2->token_ids[0], 4242); CHECK_EQ(s2->positions[0], 100); CHECK_EQ(s2->token_ids[1], 1000); CHECK_EQ(s2->positions[1], 0); /* Slot mapping for the paged group: block id times block size plus the offset in the block. * Position 100 is block 6, offset 4. */ const RadKVGroupBatch& g0 = s2->kv[0]; CHECK_EQ(g0.block_size, 16); const std::vector& bta = f.kv.block_table(a, 0); const std::vector& btb = f.kv.block_table(b, 0); CHECK_EQ(g0.slot_mapping[0], bta[6] * 16 + 4); /* B's first prefill token is the first slot of its first block. */ CHECK_EQ(g0.slot_mapping[1], btb[0] * 16); /* Block tables are one row per sequence, pitched from the step's context bound so the two * move together: the 1024-token bound, plus the longest query (64) and the draft lookahead * (2), is 1090 tokens, 69 blocks of 16, rounded up to the bound's 1024-token grid of 64 * blocks -- 128. The columns past a row's own blocks read -1. */ CHECK_EQ(g0.block_table_pitch, 128); CHECK_EQ(g0.block_table[0], bta[0]); CHECK_EQ(g0.block_table[6], bta[6]); CHECK_EQ(g0.block_table[7], -1); CHECK_EQ(g0.block_table[128], btb[0]); CHECK_EQ(g0.seqused[0], 101); CHECK_EQ(g0.seqused[1], 64); /* The linear group is per sequence, not per token: every token of a sequence maps to its one * state instance, and the block table row is that slot. */ const RadKVGroupBatch& g1 = s2->kv[1]; CHECK_EQ(g1.slot_mapping[0], f.kv.state_slot(a, 1)); CHECK_EQ(g1.slot_mapping[1], f.kv.state_slot(b, 1)); CHECK_EQ(g1.state_index[0], f.kv.state_slot(a, 1)); CHECK(f.kv.state_slot(a, 1) >= 0); } TEST(derived_metadata_is_computed_once_per_step_into_the_arena) { Fixture f; f.build(); CHECK_OK(f.start()); f.submit(100, 64); CHECK(f.sch.step() != nullptr); f.commit_plain(); f.submit(64, 64); const RadBatch* b = f.sch.step(); CHECK(b != nullptr); const int32_t* ss = f.derived("seq_start"); CHECK(ss != nullptr); CHECK_EQ(ss[0], 0); CHECK_EQ(ss[1], 1); CHECK_EQ(ss[2], 65); /* Chunk bounds never cross a sequence, and split on ABSOLUTE multiples of the chunk length. * The decode row spans position 100..100 and the prefill row 0..63, so neither crosses 64 -- * one chunk each, boundaries at 0, 1, 65. */ const int32_t* cb = f.derived("chunk_bounds"); CHECK(cb != nullptr); CHECK_EQ(cb[0], 0); CHECK_EQ(cb[1], 1); CHECK_EQ(cb[2], 65); /* The conv index is the state slot's base in a rolling window of width-1 + num_spec + 1 = 4, * plus the cursor the accepted count moves. */ const int32_t* ci = f.derived("conv_idx"); CHECK(ci != nullptr); const StepPlan& p = f.sch.plan(); int32_t cslot = f.kv.state_slot(p.e[0].seq, 2); /* group 2 is the conv group */ CHECK(cslot >= 0); CHECK_EQ(ci[0], cslot * 4 + (p.e[0].conv_cursor % 4)); } TEST(state_chunk_bounds_split_a_long_prefill_at_absolute_multiples) { DeriveInput in; StepPlan plan; int32_t cu[2] = { 0, 200 }; std::vector pos(200); for (int i = 0; i < 200; ++i) pos[(size_t)i] = 100 + i; /* starts mid-chunk on purpose */ in.plan = &plan; in.cu_seqlens = cu; in.positions = pos.data(); in.n_tok = 200; in.n_seq = 1; in.state_chunk = 64; int idx = derive_index("state_chunk_bounds"); CHECK(idx >= 0); int32_t out[16]; int64_t n = 0; CHECK_OK(derive_row(idx)->fn(in, out, 16, &n)); /* Absolute 128, 192, 256 fall inside [100, 300): local 28, 92, 156, then the tail. */ CHECK_EQ(n, 5); CHECK_EQ(out[0], 0); CHECK_EQ(out[1], 28); CHECK_EQ(out[2], 92); CHECK_EQ(out[3], 156); CHECK_EQ(out[4], 200); CHECK_EQ(derive_index("no_such_derivation"), -1); } /* ================================================================== cancellation */ TEST(cancellation_frees_blocks_immediately) { Fixture f; f.build(/*blocks=*/20, /*states=*/64); CHECK_OK(f.start()); int64_t before = f.kv.free_blocks(0); uint64_t a = f.submit(160, 64); CHECK(f.sch.step() != nullptr); CHECK_EQ(f.kv.free_blocks(0), before - 10); f.commit_plain(); /* Not at completion, and not at the next step: now. A cancelled request that keeps its pool * share until it would have finished is a pool that shrinks under exactly the load that * generates cancellations. */ CHECK_OK(f.sch.cancel(a)); CHECK_EQ(f.kv.free_blocks(0), before); CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Cancelled); CHECK_EQ(f.sch.metrics().running, 0); CHECK_EQ(f.sch.metrics().cancelled, 1); CHECK_OK(f.sch.reap(a)); /* A step that is still on the device is the one exception, and it is a one-step deferral and * not a one-request one: releasing a block a running kernel is writing hands it to a new * sequence mid-step, and that presents as a model quality problem rather than as a crash. */ uint64_t b = f.submit(160, 64); CHECK(f.sch.step() != nullptr); CHECK_EQ(f.kv.free_blocks(0), before - 10); CHECK_OK(f.sch.cancel(b)); CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Cancelled); CHECK_EQ(f.sch.metrics().running, 0); /* out of the running set at once */ CHECK_EQ(f.kv.free_blocks(0), before - 10); /* but the blocks are still the device's */ f.commit_plain(); CHECK_EQ(f.kv.free_blocks(0), before); /* And it is not resurrected: the commit must not append the token the step sampled for a * request that was cancelled while that step was running. */ CHECK_EQ((int)f.sch.find(b)->output.size(), 0); CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Cancelled); } /* A REAP THAT ARRIVES WHILE THE STEP IS STILL ON THE DEVICE, which is not a corner case: the * server reaps a generation as soon as its sink is finished, and cancelling a request finishes the * sink at once, so EVERY client that disconnects mid-decode arrives here. Releasing the Request * there destroys it under commit(), which then reads `r.state` off a null unique_ptr and takes the * process down. Returning the SLOT there is the worse half of the same failure and leaves no * trace: a request admitted before the commit lands is handed the entry, and one client's sampled * token is appended to another client's output. */ TEST(a_reap_during_the_open_step_is_deferred_to_commit) { Fixture f; f.build(/*blocks=*/20, /*states=*/64); CHECK_OK(f.start()); const int64_t before = f.kv.free_blocks(0); uint64_t a = f.submit(160, 64); CHECK(f.sch.step() != nullptr); CHECK_EQ(f.kv.free_blocks(0), before - 10); /* What Server::cancel_all and Server::retire do back to back on a disconnect. */ CHECK_OK(f.sch.cancel(a)); CHECK_OK(f.sch.reap(a)); /* The Request outlives the reap by exactly one commit, and so does its slot: neither the id * nor the blocks are released while a StepEntry still points at them. */ CHECK(f.sch.find(a) != nullptr); CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Cancelled); CHECK_EQ(f.kv.free_blocks(0), before - 10); /* A request admitted in that window must not be given the slot the open step is holding. */ uint64_t b = f.submit(160, 64); CHECK(f.sch.find(b) != nullptr); f.commit_plain(); CHECK(f.sch.find(a) == nullptr); /* released now, and exactly once */ CHECK_EQ(f.kv.free_blocks(0), before); /* And the request admitted in the window is untouched by the commit that reaped the other. */ CHECK(f.sch.find(b) != nullptr); CHECK_EQ((int)f.sch.find(b)->output.size(), 0); CHECK(f.sch.step() != nullptr); CHECK_EQ(f.kv.free_blocks(0), before - 10); f.commit_plain(); CHECK(f.sch.find(b) != nullptr); CHECK_OK(f.sch.cancel(b)); CHECK_OK(f.sch.reap(b)); CHECK_EQ(f.kv.free_blocks(0), before); } /* ============================================ a block drafter's own cache across a prefix hit */ TEST(a_prefix_hit_does_not_stop_a_full_attention_drafter) { Fixture f; f.build(); f.cfg.n_spec = 7; /* copied into the scheduler at init, so it goes first */ CHECK_OK(f.start()); /* A REAL HIT, both halves of it: the attention blocks AND the linear checkpoint have to * reach the same depth or the scheduler recomputes from 0 and ctx_len is 0 -- which is a * test that passes whatever this code does. Seeding only the paged half takes no hit and * makes this case vacuous. */ f.pc.seed(256); f.pc.lin = 256; f.pc.src = 3; uint64_t a = f.submit(272, 64); CHECK(f.sch.step() != nullptr); /* recomputes 0..256 off the checkpoint */ CHECK_EQ(f.sch.find(a)->n_computed, 256); f.commit_plain(); CHECK(f.sch.step() != nullptr); /* 256..272, and this one yields a token */ CHECK_EQ(f.sch.find(a)->n_computed, 272); /* Non-zero is the whole point: this is the floor the guard would take after a hit. */ CHECK(f.sch.plan().e[0].ctx_len > 0); f.commit_plain(11); /* window 0 is a drafter that attends over its whole history, so "wait for the window to * slide past the hit" is a condition that can never come true. Every paged group here IS * prefix-cached, so the hit handed over blocks the previous sequence's own context pass * wrote: there is no hole and the floor is 0. Taking the floor to be the hit position * instead stops a windowless drafter from ever drafting again after a hit. * * THE OTHER SIDE -- a windowed drafter whose group the cache SKIPS, so a hit leaves a hole * -- is the draft-refill cases below. */ Scheduler::BlockRow rows[4]; CHECK_EQ(f.sch.block_begin(/*block=*/8, /*depth=*/7, /*window=*/0, /*mask=*/99, rows, 4), 1); CHECK_EQ((int)rows[0].seq, (int)a); } /* ====================================== a prefix hit and a windowed block drafter (draft refill) * The drafter's own windowed KV group is not prefix-cached, so a hit leaves it without K and V for * the cached tokens, and block_begin declines the sequence until the window has slid past the hole. * The scheduler ends such a hit one drafter window before the end of the prompt, at a checkpoint, * so the recompute covers the window and the drafter drafts from the first decode step. */ namespace { struct RefillRun { int64_t n_after_first = 0; /* n_computed after the admitting step */ int rows = -1; /* drafting rows block_begin offers at the first decode step */ SchedMetrics m; }; RefillRun refill_run(int n_prompt, int32_t seeded, int64_t ckpt_lo = 0) { Fixture f; f.build(/*blocks=*/4096, /*states=*/64, /*max_tok=*/512, /*max_ctx=*/8192); f.cfg.n_spec = 7; f.prog.drafter.kind = RAD_DRAFT_BLOCK; f.prog.drafter.window = 512; KVGroupInfo w; /* the drafter's own group: paged, windowed, not prefix-cached. * UNBOUND, and a drafter group bound at the trunk's layer count * and above is the same — the trunk clamp reads bound TRUNK * layers (scheduler.h, hit_holes_trunk_) and does not fire on a * drafter hole: the refill below is exactly its repair. */ w.name = "draft"; w.decl.kind = RAD_KV_WINDOW; w.decl.window = 512; w.block_size = 16; f.prog.kv_groups.push_back(w); f.kv.setup(f.prog.kv_groups, f.cfg.max_ctx, 4096, 64); f.pc.groups = { 0 }; f.pc.ckpt_lo = ckpt_lo; CHECK_OK(f.start()); if (seeded > 0) { f.pc.seed(seeded); f.pc.lin = seeded; f.pc.src = 3; } RefillRun r; const uint64_t a = f.submit(n_prompt, 64); Scheduler::BlockRow rows[4]; for (int st = 0; st < 40; ++st) { CHECK(f.sch.step() != nullptr); if (st == 0) r.n_after_first = f.sch.find(a)->n_computed; f.commit_plain(11); const int n = f.sch.block_begin(8, 7, 512, 99, rows, 4); f.sch.block_end(); if (!f.sch.find(a)->output.empty()) { r.rows = n; break; } } r.m = f.sch.metrics(); return r; } } /* namespace */ TEST(a_prefix_hit_ends_a_drafter_window_before_the_prompt_and_the_drafter_drafts_at_once) { const RefillRun r = refill_run(/*prompt=*/1100, /*seeded=*/1024); /* The cap is 1100 - 512 = 588: attention 576, and the checkpoint under it 512. */ CHECK_EQ(r.n_after_first, 512); CHECK_EQ(r.rows, 1); CHECK_EQ(r.m.draft_refills, (int64_t)1); CHECK_EQ(r.m.draft_refill_tokens, (int64_t)512); CHECK_EQ(r.m.linear_cached_tokens, (int64_t)512); /* what was actually skipped */ } TEST(a_prefix_hit_already_a_window_back_is_kept_whole) { /* 5000 - 512 is past the 1024-token hit: the drafter's window is recomputed anyway. */ const RefillRun r = refill_run(5000, 1024); CHECK_EQ(r.n_after_first, 1024); CHECK_EQ(r.m.draft_refills, (int64_t)0); CHECK_EQ(r.rows, 1); } TEST(a_prefix_hit_with_no_checkpoint_near_the_cap_is_kept_whole) { /* No checkpoint below 2048: the cap would give back all 2048 tokens, more than two windows, * so the whole hit stands and the drafter waits for its window as it would without a cap. */ const RefillRun r = refill_run(2200, 2048, /*ckpt_lo=*/2048); CHECK_EQ(r.m.draft_refills, (int64_t)0); CHECK_EQ(r.m.linear_cached_tokens, (int64_t)2048); CHECK_EQ(r.rows, 0); } TEST(no_prefix_hit_gives_nothing_back) { const RefillRun r = refill_run(1100, 0); CHECK_EQ(r.m.draft_refills, (int64_t)0); CHECK_EQ(r.rows, 1); } /* ================================================================== speculation */ TEST(rejection_rolls_back_paged_kv_and_moves_the_linear_read_offset) { Fixture f; f.build(/*blocks=*/4096, /*states=*/64); f.cfg.n_spec = 4; CHECK_OK(f.start()); uint64_t a = f.submit(160, 64); CHECK(f.sch.step() != nullptr); f.commit_plain(11); int32_t draft[4] = { 21, 22, 23, 24 }; CHECK_OK(f.sch.set_draft(a, draft, 4)); const RadBatch* b = f.sch.step(); CHECK(b != nullptr); CHECK_EQ(b->n_spec, 4); CHECK_EQ(b->n_tok, 5); CHECK_EQ(b->q_lens[0], 5); CHECK_EQ(b->token_ids[0], 11); CHECK_EQ(b->token_ids[1], 21); CHECK_EQ(b->token_ids[4], 24); int64_t blocks_before = f.kv.free_blocks(0); int32_t cursor_before = f.sch.plan().e[0].conv_cursor; /* Two of the four drafts survive. */ int32_t acc[1] = { 2 }; int32_t tok[1] = { 99 }; uint8_t eos[1] = { 0 }; Scheduler::StepResult r; r.n_seq = 1; r.n_accepted = acc; r.token = tok; r.eos = eos; CHECK_OK(f.sch.commit(r)); const Request* ra = f.sch.find(a); /* Three tokens committed: the two accepted drafts and the bonus. */ CHECK_EQ((int)ra->output.size(), 4); CHECK_EQ(ra->output[1], 21); CHECK_EQ(ra->output[2], 22); CHECK_EQ(ra->output[3], 99); CHECK_EQ(ra->n_computed, 163); CHECK_EQ(ra->n_accepted, 2); /* Paged KV gave blocks back for the rejected tail; the state slot did not move, because a * linear rollback is a read offset and not a free. */ CHECK(f.kv.free_blocks(0) >= blocks_before); CHECK(f.kv.state_slot(a, 1) >= 0); /* The conv cursor advanced by 1 + accepted, modulo the rolling window. */ f.submit(1, 1); /* nothing; just to force a plan rebuild below */ const RadBatch* b2 = f.sch.step(); CHECK(b2 != nullptr); int32_t W = 4 - 1 + 4 + 1; CHECK_EQ(f.sch.plan().e[0].conv_cursor, (cursor_before + 3) % W); } /* A decode measurement needs the request to last as long as the harness asked for; otherwise the * model decides how many steps are measured, one prompt ending after eight tokens and the next * running for hundreds, so the window measures the prompt rather than the change under test. Both * halves are pinned here -- that EOS stops the ordinary request, and that max_tokens still stops * the one ignoring it, because a flag that suppressed BOTH would be an endless generation rather * than a benchmark. */ TEST(ignore_eos_runs_to_max_tokens_and_nothing_else_changes) { Fixture f; f.build(); CHECK_OK(f.start()); uint64_t plain = f.submit(8, /*max_tokens=*/4); uint64_t keep = f.submit(8, /*max_tokens=*/4, /*priority=*/0, /*ignore_eos=*/true); CHECK(f.sch.step() != nullptr); f.commit_plain(7); /* both prefilled, one token each */ /* Every sequence emits end-of-generation on this step. */ const StepPlan& p = f.sch.plan(); CHECK_EQ((int)p.e.size(), 2); std::vector acc((size_t)p.e.size(), 0), tok((size_t)p.e.size(), 9); std::vector eos((size_t)p.e.size(), 1); CHECK(f.sch.step() != nullptr); Scheduler::StepResult r; r.n_seq = (int)p.e.size(); r.n_accepted = acc.data(); r.token = tok.data(); r.eos = eos.data(); CHECK_OK(f.sch.commit(r)); CHECK_EQ((int)f.sch.find(plain)->state, (int)ReqState::Finished); CHECK_EQ(f.sch.find(plain)->finish_reason, std::string("stop")); CHECK_EQ((int)f.sch.find(keep)->state, (int)ReqState::Running); /* It ends on the budget instead, and says so. */ while (f.sch.find(keep)->state == ReqState::Running && f.sch.step() != nullptr) { const StepPlan& q = f.sch.plan(); std::vector a2((size_t)q.e.size(), 0), t2((size_t)q.e.size(), 9); std::vector e2((size_t)q.e.size(), 1); Scheduler::StepResult r2; r2.n_seq = (int)q.e.size(); r2.n_accepted = a2.data(); r2.token = t2.data(); r2.eos = e2.data(); CHECK_OK(f.sch.commit(r2)); } const Request* rk = f.sch.find(keep); CHECK_EQ((int)rk->state, (int)ReqState::Finished); CHECK_EQ(rk->finish_reason, std::string("length")); CHECK_EQ((int)rk->output.size(), 4); } /* A block that wants to treat the two kinds of row differently can only do it if each kind is a * contiguous run of sequences, because cu_seqlens is read as cu[n] and cu[n+1]. The scheduler * walks `running_` in PRIORITY order, so without the sort a high-priority request part way * through its prompt lands ahead of a low-priority one that is decoding -- which is exactly the * arrangement built here. */ TEST(a_mixed_step_puts_its_decode_rows_first) { Fixture f; f.build(/*blocks=*/4096, /*states=*/64); CHECK_OK(f.start()); uint64_t b = f.submit(1000, 64, /*priority=*/1); /* several chunks, sorts first */ uint64_t a = f.submit(160, 64, /*priority=*/0); /* one chunk, then decodes */ const RadBatch* s0 = f.sch.step(); CHECK(s0 != nullptr); CHECK_EQ((int)f.sch.plan().e.size(), 2); CHECK_EQ(f.sch.plan().n_seq_decode, 0); /* both prefill: nothing decodes yet */ f.commit_plain(11); /* a finished its prompt and is decoding; b is on its second chunk and still outranks it. */ const RadBatch* s1 = f.sch.step(); CHECK(s1 != nullptr); CHECK_EQ((int)f.sch.plan().e.size(), 2); CHECK_EQ(f.sch.plan().e[0].seq, a); /* the decode row, despite the priority */ CHECK_EQ(f.sch.plan().e[0].is_prefill, false); CHECK_EQ(f.sch.plan().e[1].seq, b); CHECK_EQ(f.sch.plan().e[1].is_prefill, true); CHECK_EQ(f.sch.plan().n_seq_decode, 1); CHECK_EQ(s1->n_seq_decode, 1); CHECK_EQ(s1->phase, RAD_PHASE_MIXED); /* The per-half bounds: a decodes one row, b's chunk is the interval. */ CHECK_EQ(s1->max_q_len_decode, 1); CHECK_EQ(s1->max_q_len_prefill, 256); CHECK_EQ(s1->max_q_len, 256); /* AND THE ENTRY INDEX FOLLOWED THE ROW. `entry` is how a request finds its own result, so a * sort that leaves it behind hands one request another's token. */ f.commit_plain(12); CHECK_EQ((int)f.sch.find(a)->output.size(), 2); /* 11 from the prefill, 12 from the decode */ CHECK_EQ(f.sch.find(a)->output[1], 12); CHECK_EQ((int)f.sch.find(b)->output.size(), 0); /* still prefilling: no token yet */ } /* A STEP THAT CARRIES A PREFILL CHUNK STILL TAKES A DRAFT. Issuing the chunked path for every * sequence in a mixed step would force the draft to be refused, because that path has no * num_accepted operand to roll a rejection back with; the blocks issue the recurrent path over the * decode half instead. These are the two shapes such a refusal would fire on. */ TEST(a_queued_request_does_not_suppress_the_draft) { Fixture f; f.build(/*blocks=*/4096, /*states=*/64); f.cfg.n_spec = 4; f.cfg.max_seqs = 3; /* a slot is free, so the queue WILL be admitted */ CHECK_OK(f.start()); uint64_t a = f.submit(160, 64); uint64_t b = f.submit(160, 64); CHECK(f.sch.step() != nullptr); f.commit_plain(11); f.submit(160, 64); CHECK_EQ(f.sch.metrics().queue_depth, 1); int32_t draft[4] = { 21, 22, 23, 24 }; CHECK_OK(f.sch.set_draft(a, draft, 4)); CHECK_OK(f.sch.set_draft(b, draft, 4)); const RadBatch* s = f.sch.step(); CHECK(s != nullptr); CHECK_EQ(s->n_spec, 4); /* the draft survives the admission */ CHECK_EQ((int)f.sch.plan().e.size(), 3); /* and the third was admitted into the same step */ CHECK_EQ(f.sch.metrics().queue_depth, 0); CHECK_EQ(s->phase, RAD_PHASE_MIXED); /* The decode rows sorted first and carry the window; the prefill chunk carries none. */ CHECK_EQ(s->n_seq_decode, 2); CHECK_EQ(f.sch.plan().e[0].n_spec, 4); CHECK_EQ(f.sch.plan().e[1].n_spec, 4); CHECK_EQ(f.sch.plan().e[2].n_spec, 0); /* Two decode rows of 1 + 4, so the split the blocks issue over is 10 tokens and then the * chunk. Getting this wrong is how a per-token op reaches into the other half. */ CHECK_EQ(s->n_tok_decode, 10); CHECK_EQ(s->max_q_len_decode, 5); CHECK_EQ(s->max_q_len_prefill, 160); } TEST(a_running_prefill_does_not_suppress_the_draft) { Fixture f; f.build(/*blocks=*/4096, /*states=*/64); f.cfg.n_spec = 4; CHECK_OK(f.start()); uint64_t a = f.submit(160, 64); f.submit(1000, 64); /* several chunks: mixed for the next few steps */ CHECK(f.sch.step() != nullptr); f.commit_plain(11); int32_t draft[4] = { 21, 22, 23, 24 }; CHECK_OK(f.sch.set_draft(a, draft, 4)); const RadBatch* s = f.sch.step(); CHECK(s != nullptr); CHECK_EQ(s->phase, RAD_PHASE_MIXED); CHECK_EQ(s->n_spec, 4); CHECK_EQ(s->n_seq_decode, 1); CHECK_EQ(s->n_tok_decode, 5); CHECK_EQ(f.sch.plan().e[0].seq, a); CHECK_EQ(f.sch.plan().e[0].n_spec, 4); } /* ================================================================== a prefill sharing a step */ /* --busy-prefill-chunk. The shape that starves: the checkpoint interval as large as the step * budget, so a long prefill's chunk can take the whole step every step. Here 512 and 512, the * quantum 64; the sequence is long enough for many full chunks. */ static void share_fixture(Fixture& f, int64_t mode) { f.build(/*blocks=*/4096, /*states=*/64, /*max_tok=*/512, /*max_ctx=*/4096); f.cfg.checkpoint_interval = 512; f.cfg.busy_prefill_chunk = mode; } /* What 1.3.0 did, and `off` still does: once the long prefill owns the step, a request that * arrives is not even admitted until it ends. */ TEST(off_a_long_prefill_keeps_a_new_request_out_of_every_step) { Fixture f; share_fixture(f, /*off=*/0); CHECK_OK(f.start()); uint64_t a = f.submit(3500, 64); CHECK(f.sch.step() != nullptr); CHECK_EQ(f.sch.plan().e[0].n_tokens, 512); f.commit_plain(); uint64_t b = f.submit(100, 64); for (int k = 0; k < 4; ++k) { CHECK(f.sch.step() != nullptr); CHECK_EQ((int)f.sch.plan().e.size(), 1); CHECK_EQ(f.sch.plan().e[0].seq, a); CHECK_EQ(f.sch.plan().e[0].n_tokens, 512); f.commit_plain(); } CHECK_EQ(f.sch.metrics().queue_depth, 1); CHECK(f.sch.find(b) != nullptr); CHECK_EQ(f.sch.metrics().prefill_chunks_capped, 0); } /* auto: the same arrival is admitted in the very next step, and its prompt finishes in two. */ TEST(auto_a_request_arriving_during_a_long_prefill_is_admitted_at_once) { Fixture f; share_fixture(f, /*auto=*/-1); CHECK_OK(f.start()); uint64_t a = f.submit(3500, 64); CHECK(f.sch.step() != nullptr); CHECK_EQ(f.sch.plan().e[0].n_tokens, 512); /* alone: the whole step, as before */ f.commit_plain(); uint64_t b = f.submit(100, 64); CHECK(f.sch.step() != nullptr); CHECK_EQ((int)f.sch.plan().e.size(), 2); CHECK_EQ(f.sch.metrics().queue_depth, 0); int64_t a_tok = 0, b_tok = 0; for (const StepEntry& e : f.sch.plan().e) { if (e.seq == a) a_tok = e.n_tokens; if (e.seq == b) b_tok = e.n_tokens; } CHECK(a_tok >= 64 && a_tok % 64 == 0); CHECK(b_tok > 0); CHECK(a_tok + b_tok <= 512); CHECK_EQ(f.sch.metrics().prefill_chunks_capped, 1); f.commit_plain(11); /* b's 100 tokens are done by the next step and it decodes beside the prefill from then on */ for (int k = 0; k < 4; ++k) { CHECK(f.sch.step() != nullptr); bool saw_b = false; for (const StepEntry& e : f.sch.plan().e) if (e.seq == b) saw_b = true; CHECK(saw_b); f.commit_plain(12); } CHECK((int)f.sch.find(b)->output.size() >= 2); } /* A decode row BEHIND a long prefill in running_ (the prefill outranks it) is planned every step * under auto; under off it is left out of every step that begins on an interval boundary. */ static int decode_rows_seen(int64_t mode) { Fixture f; share_fixture(f, mode); CHECK_OK(f.start()); uint64_t b = f.submit(100, 512, /*priority=*/0); CHECK(f.sch.step() != nullptr); /* b's whole prompt: it decodes from the next step */ f.commit_plain(11); f.submit(3500, 64, /*priority=*/1); /* outranks b: walked first */ int seen = 0; for (int k = 0; k < 8; ++k) { CHECK(f.sch.step() != nullptr); for (const StepEntry& e : f.sch.plan().e) if (e.seq == b && !e.is_prefill) ++seen; f.commit_plain(12); } return seen; } TEST(auto_a_decode_row_behind_a_long_prefill_gets_every_step) { CHECK_EQ(decode_rows_seen(-1), 8); CHECK(decode_rows_seen(0) < 8); } /* Nothing else wants in: the cap does not apply, and a lone prefill is planned chunk for chunk * as before -- which is what keeps every single-request gate unchanged. */ TEST(auto_a_lone_prefill_is_planned_as_before) { std::vector plans[2]; for (int m = 0; m < 2; ++m) { Fixture f; share_fixture(f, m == 0 ? 0 : -1); CHECK_OK(f.start()); f.submit(3000, 4); for (int k = 0; k < 10; ++k) { if (!f.sch.step()) break; plans[m].push_back(f.sch.plan().e[0].n_tokens); f.commit_plain(); } CHECK_EQ(f.sch.metrics().prefill_chunks_capped, 0); } CHECK(plans[0] == plans[1]); } /* An explicit N holds the chunk to N while something waits. */ TEST(an_explicit_busy_prefill_chunk_holds_the_chunk_to_it) { Fixture f; share_fixture(f, 128); CHECK_OK(f.start()); uint64_t a = f.submit(3500, 64); CHECK(f.sch.step() != nullptr); CHECK_EQ(f.sch.plan().e[0].n_tokens, 512); /* alone */ f.commit_plain(); f.submit(100, 64); CHECK(f.sch.step() != nullptr); for (const StepEntry& e : f.sch.plan().e) if (e.seq == a) CHECK_EQ(e.n_tokens, 128); } /* The arithmetic, at the shape of a real deployment: a 2048-token step and interval, the stager * arming at 1025 tokens (so a held-back chunk keeps 1024 and its step-mates make up the rest). */ TEST(busy_cap_keeps_the_stager_floor_and_never_leaves_a_runt) { Fixture f; f.build(/*blocks=*/8192, /*states=*/64, /*max_tok=*/2048, /*max_ctx=*/8192); f.cfg.checkpoint_interval = 2048; CHECK_OK(f.start()); f.sch.set_stage_rows(1025); /* nothing reserved: the budget */ CHECK_EQ(f.sch.busy_cap(0, 100000, 2048, 0), 2048); /* a little reserved at an interval boundary: 2048 - 272 would leave a 272-token runt before * the boundary, so the interval splits in two staged halves instead */ CHECK_EQ(f.sch.busy_cap(0, 100000, 2048, 272), 1024); /* half way to the boundary the rest of the interval already fits under the cap */ CHECK(f.sch.busy_cap(1024, 100000, 2048, 272) >= 1024); CHECK_EQ(f.sch.plan_chunk(1024, 100000, f.sch.busy_cap(1024, 100000, 2048, 272), nullptr), 1024); /* more reserved than the floor allows for: the floor */ CHECK_EQ(f.sch.busy_cap(0, 100000, 2048, 1500), 1024); /* a prompt's last stretch, shorter than the cap: all of it */ CHECK_EQ(f.sch.plan_chunk(0, 1500, f.sch.busy_cap(0, 1500, 2048, 272), nullptr), 1500); /* a budget already under the floor: never more than the budget */ CHECK_EQ(f.sch.busy_cap(0, 100000, 512, 64), 512); /* decode rows alone behind it (2 rows x (1 + 3 drafts)): no split -- the chunk ends a quantum * short of the boundary (1984) and the next step takes the remaining 64, the pair a prefill * already runs with decode rows AHEAD of it */ CHECK_EQ(f.sch.busy_cap(0, 100000, 2048, 8, false, /*rows_only=*/true), 2040); CHECK_EQ(f.sch.plan_chunk(0, 100000, f.sch.busy_cap(0, 100000, 2048, 8, false, true), nullptr), 1984); /* the same reserve with a share in it splits the interval */ CHECK_EQ(f.sch.busy_cap(0, 100000, 2048, 8 + 256, false, false), 1024); } /* The share left for a request that then does not start (here its context is still being read * back from the host tier) goes back to the chunk that made room for it: the step is planned as * if nothing had waited. */ TEST(auto_a_share_nobody_takes_goes_back_to_the_prefill) { Fixture f; share_fixture(f, -1); CHECK_OK(f.start()); uint64_t a = f.submit(3500, 64); CHECK(f.sch.step() != nullptr); f.commit_plain(); uint64_t b = f.submit(100, 64); f.pc.reading.push_back(b); CHECK(f.sch.step() != nullptr); REQUIRE_EQ((int)f.sch.plan().e.size(), 1); CHECK_EQ(f.sch.plan().e[0].seq, a); CHECK_EQ(f.sch.plan().e[0].n_tokens, 512); CHECK_EQ(f.sch.metrics().prefill_chunks_capped, 0); CHECK_EQ(f.sch.metrics().queue_depth, 1); } /* An explicit N also holds a chunk back for rows planned AHEAD of it -- the operator's trade of * prefill speed for every other row's latency; auto leaves those alone. */ TEST(an_explicit_busy_prefill_chunk_applies_to_rows_ahead_auto_does_not) { for (int64_t mode : { (int64_t)-1, (int64_t)128 }) { Fixture f; share_fixture(f, mode); CHECK_OK(f.start()); uint64_t b = f.submit(100, 512, /*priority=*/1); /* outranks the prefill: planned first */ CHECK(f.sch.step() != nullptr); f.commit_plain(11); uint64_t a = f.submit(3500, 64, /*priority=*/0); CHECK(f.sch.step() != nullptr); /* b decodes, a is admitted behind it */ f.commit_plain(12); int64_t most = 0; bool saw_b = true; for (int k = 0; k < 3; ++k) { CHECK(f.sch.step() != nullptr); bool here = false; for (const StepEntry& e : f.sch.plan().e) { if (e.seq == a) most = std::max(most, e.n_tokens); if (e.seq == b) here = true; } saw_b = saw_b && here; f.commit_plain(12); } CHECK(saw_b); if (mode > 0) CHECK_EQ(most, 128); else CHECK(most > 128); } } TEST(busy_cap_is_the_budget_when_off) { Fixture f; f.build(/*blocks=*/8192, /*states=*/64, /*max_tok=*/2048, /*max_ctx=*/8192); f.cfg.checkpoint_interval = 2048; f.cfg.busy_prefill_chunk = 0; CHECK_OK(f.start()); f.sch.set_stage_rows(1025); CHECK_EQ(f.sch.busy_cap(0, 100000, 2048, 272), 2048); CHECK_EQ(f.sch.busy_cap(0, 100000, 2048, 1500), 2048); } TEST(the_draft_depth_is_the_configured_one_whatever_the_acceptance_trace) { DraftController c; DraftController::Params p; p.max_depth = 8; CHECK_OK(c.configure(p)); CHECK_EQ(c.next_depth(), 8); /* A workload that rejects almost everything. A dynamic policy would collapse the depth here; * this one does not move, which is the property being asserted -- the depth is the flag. */ uint64_t rng = 12345; auto coin = [&](double pr) { rng = rng * 6364136223846793005ull + 1442695040888963407ull; return ((double)((rng >> 33) & 0xFFFFFF) / (double)0x1000000) < pr; }; for (int t = 0; t < 4000; ++t) { int d = c.next_depth(); CHECK_EQ(d, 8); int a = 0; while (a < d && coin(0.1)) ++a; c.observe(d, a); } CHECK_EQ(c.next_depth(), 8); CHECK(c.acceptance() > 0.0f && c.acceptance() < 0.3f); /* The accounting is exact and is charged per DRAFTED token, not per step: it is the number a * scraped acceptance rate divides by. */ DraftController d2; DraftController::Params q; q.max_depth = 8; CHECK_OK(d2.configure(q)); for (int i = 0; i < 100; ++i) d2.observe(8, 0); CHECK_EQ(d2.drafted(), 800); CHECK_EQ(d2.accepted(), 0); CHECK_NEAR(d2.acceptance(), 0.0, 1e-9); d2.observe(2, 5); /* accepted past the draft is clamped, not counted */ CHECK_EQ(d2.accepted(), 2); CHECK_EQ(d2.drafted(), 802); /* Depth 0 is speculation off, and it configures. */ DraftController d3; DraftController::Params z; z.max_depth = 0; CHECK_OK(d3.configure(z)); CHECK_EQ(d3.next_depth(), 0); } /* ------------------------------------------------------------------ the adaptive window * --draft-window adaptive (draft.h). The controller cases turn the policy on through Params, which * is what Scheduler::init does with a serial drafter; the scheduler cases start a Fixture whose * program declares one and whose Config asks for the window. */ namespace { /* A small deterministic coin, the one the static case above uses. */ struct Coin { uint64_t s = 12345; bool operator()(double pr) { s = s * 6364136223846793005ull + 1442695040888963407ull; return ((double)((s >> 33) & 0xFFFFFF) / (double)0x1000000) < pr; } }; DraftController adaptive_controller(int max_depth) { DraftController c; DraftController::Params p; p.max_depth = max_depth; p.adapt = true; CHECK_OK(c.configure(p)); return c; } /* An estimate as a test states it: acceptance `a0` at the first position and `rest` after it, * started, with its stop where the controller puts it. */ DraftAdapt estimate(const DraftController& c, double a0, double rest) { DraftAdapt s; s.a[0] = (float)a0; for (int j = 1; j < RAD_SCHED_MAX_SPEC; ++j) s.a[j] = (float)rest; /* The stop draft.h states: the deepest draft emitted at least kDraftMinChance of the time. */ double p = 1.0; int d = 0; while (d < c.next_depth()) { p *= (double)s.a[d]; if (p < DraftController::kDraftMinChance) break; ++d; } s.depth = d < DraftController::kMinDepth ? DraftController::kMinDepth : d; return s; } /* What a scheduler fixture with the adaptive window looks like: a serial head of `depth` * declared by the program, --num-speculative-tokens `depth`, --draft-window adaptive. */ void adaptive_fixture(Fixture& f, int depth) { f.build(/*blocks=*/4096, /*states=*/64); f.cfg.n_spec = depth; f.cfg.draft_window = DraftWindow::Adaptive; f.prog.drafter.kind = RAD_DRAFT_SERIAL; f.prog.drafter.depth = depth; } /* Everything written to stderr while `fn` runs: the log lines a case checks for. */ template std::string stderr_of(F fn) { std::string text; FILE* tmp = std::tmpfile(); if (!tmp) return text; const Log level = log_level(); log_set_level(Log::Info); std::fflush(stderr); const int saved = dup(2); dup2(fileno(tmp), 2); fn(); std::fflush(stderr); dup2(saved, 2); log_set_level(level); close(saved); std::rewind(tmp); char buf[4096]; size_t n; while ((n = std::fread(buf, 1, sizeof buf, tmp)) > 0) text.append(buf, n); std::fclose(tmp); return text; } } /* namespace */ TEST(the_adaptive_window_follows_each_sequences_own_acceptance) { DraftController c = adaptive_controller(6); CHECK(c.adaptive()); CHECK_EQ(c.next_depth(), 6); /* the ceiling is still the flag */ CHECK_EQ(c.step_depth(), 0); /* no step has chosen D: the ceiling stands */ /* Nothing measured yet: both start from the prior, which drafts the whole window. */ DraftAdapt code, summary; CHECK_EQ(c.window_for(code), 6); CHECK_EQ(c.window_for(summary), 6); /* Two texts through one controller. The drafter almost always agrees on one; on the other it * agrees at the first position and rarely after it. Each stop follows its own text. */ Coin coin; for (int t = 0; t < 600; ++t) { int d = c.window_for(code), a = 0; while (a < d && coin(0.95)) ++a; c.observe(d, a); c.adapt_observe(code, d, a); d = c.window_for(summary); a = 0; while (a < d && coin(a == 0 ? 0.6 : 0.2)) ++a; c.observe(d, a); c.adapt_observe(summary, d, a); } CHECK_EQ(c.window_for(code), 6); CHECK(c.window_for(summary) >= 1); CHECK(c.window_for(summary) <= 2); CHECK(code.a[0] > 0.85f); CHECK_NEAR(summary.a[0], 0.6, 0.2); CHECK(c.yield(code, 6) > c.yield(summary, 6)); /* The global hazard is still counted, and the windows the verifies carried. */ CHECK(c.reached(0) == 1200); CHECK(c.verified_at(6) >= 600); CHECK(c.verified_at(1) + c.verified_at(2) > 0); CHECK_EQ(c.verified_at(1) + c.verified_at(2) + c.verified_at(3) + c.verified_at(4) + c.verified_at(5) + c.verified_at(6), (int64_t)1200); /* And a stop that went shallow comes back when the text changes: the positions it stopped * drafting drift toward the deepest it still drafts, so a text the drafter predicts again is * found without anyone drafting deep first. */ for (int t = 0; t < 600; ++t) { const int d = c.window_for(summary); int a = 0; while (a < d && coin(0.95)) ++a; c.adapt_observe(summary, d, a); } CHECK_EQ(c.window_for(summary), 6); } /* A STOP MOVES ONLY PAST THE HOLD: it is the sequence's share of the step's pass shape, and a shape * that followed every flicker of its estimate would re-record its passes for nothing * (runtime/ctx.h). And it never goes below one draft, or the estimate could never recover. */ TEST(the_adaptive_window_moves_only_past_its_hold_and_never_below_one_draft) { DraftController c = adaptive_controller(6); DraftAdapt s; CHECK_EQ(c.window_for(s), 6); for (int t = 0; t < DraftController::kHold - 1; ++t) CHECK_EQ(c.adapt_observe(s, 6, 0), 6); CHECK(c.adapt_observe(s, 6, 0) < 6); /* the kHold-th moves */ for (int t = 0; t < 400; ++t) c.adapt_observe(s, c.window_for(s), 0); CHECK_EQ(c.window_for(s), DraftController::kMinDepth); /* Off, the window is the flag and an observation is not taken. */ DraftController off; DraftController::Params q; q.max_depth = 5; CHECK_OK(off.configure(q)); CHECK(!off.adaptive()); DraftAdapt w; CHECK_EQ(off.window_for(w), 5); CHECK_EQ(off.adapt_observe(w, 5, 0), 5); CHECK_EQ(w.depth, 0); off.observe(5, 2); CHECK_EQ(off.verified_at(5), (int64_t)0); off.step_time(3, 1, 12.0); /* and no step is timed */ CHECK_EQ(off.cost_samples(3, 1), (int64_t)0); /* Adaptive with no speculation is no policy at all. */ DraftController zero = adaptive_controller(0); CHECK(!zero.adaptive()); } /* THE STEP COST IS MEASURED. A key -- the step's deepest window and its class of running * sequences -- with samples is its own mean; one without borrows the nearest measured key's, * scaled by the prior's shape; nothing measured is the prior. The same times give the same * choice, which is what makes the policy a function of what it was shown. */ TEST(the_adaptive_window_prices_a_step_from_measured_step_times) { DraftController c = adaptive_controller(6); CHECK_NEAR(c.step_cost(1, 1), 1.06, 1e-12); /* the prior */ CHECK_NEAR(c.step_cost(6, 1), 1.36, 1e-12); for (int i = 0; i < 10; ++i) c.step_time(3, 1, 12.0); CHECK_EQ(c.cost_samples(3, 1), (int64_t)10); CHECK_NEAR(c.step_cost(3, 1), 12.0, 1e-9); CHECK_NEAR(c.step_cost(5, 1), 12.0 * 1.30 / 1.18, 1e-9); /* borrowed, the prior's shape */ CHECK_NEAR(c.step_cost(3, 9), 12.0, 1e-9); /* the nearest class */ CHECK_EQ(c.cost_samples(3, 9), (int64_t)0); /* The classes: 1, 2-3, 4-7, 8-15, 16 and up. */ c.step_time(3, 2, 20.0); CHECK_NEAR(c.step_cost(3, 3), 20.0, 1e-9); CHECK_NEAR(c.step_cost(3, 4), 20.0, 1e-9); /* 4-7 borrows from 2-3 */ c.step_time(3, 16, 40.0); CHECK_NEAR(c.step_cost(3, 1000), 40.0, 1e-9); CHECK_NEAR(c.step_cost(3, 9), 40.0, 1e-9); /* 8-15: the nearest, 16 and up */ /* A step that waited on something else counts for at most four times the mean. */ const double before = c.step_cost(3, 1); c.step_time(3, 1, 1.0e6); CHECK(c.step_cost(3, 1) <= before * 4.0); CHECK(c.step_cost(3, 1) > before); /* Nonsense is not a sample. */ c.step_time(0, 1, 5.0); c.step_time(7, 1, 5.0); c.step_time(2, 1, -1.0); c.step_time(2, 0, 5.0); CHECK_EQ(c.cost_samples(2, 1), (int64_t)0); /* One sequence that accepts nearly everything: on the prior the whole window pays... */ DraftController p = adaptive_controller(6); DraftAdapt s = estimate(p, 0.9, 0.9); DraftAdapt* one[1] = { &s }; CHECK_EQ(p.plan_step(one, 1, 1), 6); /* ...and where the steps past three were measured dear, three is what pays. */ DraftController m = adaptive_controller(6); const double t[7] = { 0, 10.0, 11.0, 12.0, 30.0, 30.0, 30.0 }; for (int d = 1; d <= 6; ++d) m.step_time(d, 1, t[d]); DraftAdapt u = estimate(m, 0.9, 0.9); DraftAdapt* mu[1] = { &u }; CHECK_EQ(m.plan_step(mu, 1, 1), 3); CHECK_EQ(m.window_for(u), 3); /* Deterministic: the same times and the same estimate give the same depth. */ DraftController m2 = adaptive_controller(6); for (int d = 1; d <= 6; ++d) m2.step_time(d, 1, t[d]); DraftAdapt u2 = estimate(m2, 0.9, 0.9); DraftAdapt* mu2[1] = { &u2 }; CHECK_EQ(m2.plan_step(mu2, 1, 1), 3); } /* THE HEAD DEPTH IS THE STEP'S. A serial head runs as many rounds as the deepest window in the * step, so a sequence that accepts deep is worth deep rounds only while what its neighbours lose * to them -- every round is a pass over every drafting row -- does not outweigh it. */ TEST(the_adaptive_window_chooses_the_head_depth_over_the_whole_batch) { DraftController c = adaptive_controller(6); DraftAdapt deep = estimate(c, 0.95, 0.95); DraftAdapt shallow = estimate(c, 0.5, 0.15); CHECK_EQ(deep.depth, 6); CHECK_EQ(shallow.depth, 1); /* its second draft is emitted 7.5 % of the time */ /* Side by side on the prior: deep rounds pay for the deep sequence, and the shallow one stops * at its own first draft under them. */ DraftAdapt* two[2] = { &deep, &shallow }; CHECK_EQ(c.plan_step(two, 2, 2), 6); CHECK_EQ(c.window_for(deep), 6); CHECK_EQ(c.window_for(shallow), 1); /* The same deep sequence among seven shallow ones, at a class whose steps were measured to * grow by three units a round: what the rounds cost is paid by eight rows, and the one * that gains from them does not repay it. Every window comes down to one. */ DraftController b = adaptive_controller(6); for (int d = 1; d <= 6; ++d) b.step_time(d, 8, 10.0 + 3.0 * d); DraftAdapt bd = estimate(b, 0.95, 0.95); DraftAdapt bs[7]; DraftAdapt* eight[8] = { &bd }; for (int i = 0; i < 7; ++i) { bs[i] = estimate(b, 0.5, 0.15); eight[i + 1] = &bs[i]; } CHECK_EQ(b.plan_step(eight, 8, 8), 1); CHECK_EQ(b.window_for(bd), 1); /* Alone at its own class, unmeasured, the same sequence takes the whole window. */ DraftController a = adaptive_controller(6); for (int d = 1; d <= 6; ++d) a.step_time(d, 8, 10.0 + 3.0 * d); DraftAdapt ad = estimate(a, 0.95, 0.95); DraftAdapt* lone[1] = { &ad }; CHECK(a.plan_step(lone, 1, 1) > 1); /* Rows that do not draft are part of the step: they emit a token whatever D is and pay for * every round. Here three plain rows beside one drafting row at the same measured class. */ DraftController r = adaptive_controller(6); for (int d = 1; d <= 6; ++d) r.step_time(d, 4, 10.0 + 3.0 * d); DraftAdapt rd = estimate(r, 0.95, 0.95); DraftAdapt* rone[1] = { &rd }; const int with_plain = r.plan_step(rone, 1, 4); DraftController r2 = adaptive_controller(6); for (int d = 1; d <= 6; ++d) r2.step_time(d, 4, 10.0 + 3.0 * d); DraftAdapt rd2 = estimate(r2, 0.95, 0.95); DraftAdapt* rone2[1] = { &rd2 }; const int alone = r2.plan_step(rone2, 1, 1); /* class 1 unmeasured: borrows class 4-7 */ CHECK(with_plain <= alone); /* D MOVES PAST A HOLD AND A HYSTERESIS. The first step that drafts takes the best outright; * after that a better depth waits kHold steps. */ DraftController h = adaptive_controller(6); DraftAdapt hs = estimate(h, 0.95, 0.95); DraftAdapt* hone[1] = { &hs }; CHECK_EQ(h.plan_step(hone, 1, 1), 6); for (int d = 1; d <= 6; ++d) h.step_time(d, 1, d <= 2 ? 10.0 : 40.0); for (int t = 0; t < DraftController::kHold - 1; ++t) CHECK_EQ(h.plan_step(hone, 1, 1), 6); CHECK_EQ(h.plan_step(hone, 1, 1), 2); /* No drafting sequence: D stays where it is. */ CHECK_EQ(h.plan_step(hone, 0, 3), 2); } /* THE FLAG, AND ONLY FOR A SERIAL HEAD. --draft-window adaptive with a block drafter, with prompt * lookup alone, or with no speculation keeps the configured depth and says so at startup; the * proposal then reaches the step uncut. The default is the fixed window. */ TEST(the_adaptive_window_is_a_flag_for_a_serial_drafter_and_said_when_it_is_not) { { Fixture f; adaptive_fixture(f, 4); int st = RAD_E_STATE; const std::string log = stderr_of([&] { st = f.start(); }); CHECK_OK(st); CHECK(f.sch.draft().adaptive()); CHECK(log.find("ADAPTIVE") != std::string::npos); } { Fixture f; adaptive_fixture(f, 4); f.cfg.draft_window = DraftWindow::Fixed; CHECK_OK(f.start()); CHECK(!f.sch.draft().adaptive()); Config d; CHECK(d.draft_window == kDraftWindowDefault); /* the default */ } for (int kind : { (int)RAD_DRAFT_BLOCK, (int)RAD_DRAFT_NONE }) { Fixture f; adaptive_fixture(f, 4); f.prog.drafter.kind = (decltype(f.prog.drafter.kind))kind; if (kind == RAD_DRAFT_NONE) f.prog.drafter.depth = 0; int st = RAD_E_STATE; const std::string log = stderr_of([&] { st = f.start(); }); CHECK_OK(st); CHECK(!f.sch.draft().adaptive()); CHECK(log.find("--draft-window adaptive: the window is fixed at 4") != std::string::npos); CHECK(log.find(kind == RAD_DRAFT_BLOCK ? "a block drafter" : "prompt lookup only") != std::string::npos); const uint64_t a = f.submit(160, 64); CHECK(f.sch.step() != nullptr); f.commit_plain(11); int32_t draft[4] = { 21, 22, 23, 24 }; CHECK_OK(f.sch.set_draft(a, draft, 4)); CHECK_EQ(f.sch.find(a)->n_draft, 4); CHECK(!f.sch.metrics().draft_adaptive); } { Fixture f; adaptive_fixture(f, 4); f.cfg.n_spec = 0; const std::string log = stderr_of([&] { CHECK_OK(f.start()); }); CHECK(!f.sch.draft().adaptive()); CHECK(log.find("does not speculate") != std::string::npos); } } /* EACH SEQUENCE ITS OWN STOP, AND THE ROUNDS FOLLOW THE DEEPEST. The step issued ahead of a commit * verifies, for each sequence, the first of those rounds up to its own window -- and the drafter's * longer proposal is taken cut to that count rather than refused as a mismatch. */ TEST(the_adaptive_window_is_per_sequence_and_the_rounds_follow_the_deepest) { Fixture f; adaptive_fixture(f, 4); CHECK_OK(f.start()); REQUIRE(f.sch.draft().adaptive()); const uint64_t a = f.submit(160, 2000); const uint64_t b = f.submit(160, 2000); CHECK(f.sch.step() != nullptr); f.commit_plain(11); /* `a`'s drafts are never taken and `b`'s always are. */ int32_t draft[4] = { 21, 22, 23, 24 }; auto commit_ab = [&]() { const StepPlan& pl = f.sch.plan(); std::vector acc(pl.e.size(), 0), tok(pl.e.size(), 9); std::vector eos(pl.e.size(), 0); for (size_t i = 0; i < pl.e.size(); ++i) acc[i] = pl.e[i].seq == b ? pl.e[i].n_spec : 0; Scheduler::StepResult r; r.n_seq = (int)pl.e.size(); r.n_accepted = acc.data(); r.token = tok.data(); r.eos = eos.data(); CHECK_OK(f.sch.commit(r)); }; for (int t = 0; t < 64; ++t) { CHECK_OK(f.sch.set_draft(a, draft, 4)); CHECK_OK(f.sch.set_draft(b, draft, 4)); REQUIRE(f.sch.step() != nullptr); commit_ab(); } CHECK_OK(f.sch.set_draft(a, draft, 4)); CHECK_OK(f.sch.set_draft(b, draft, 4)); const RadBatch* s = f.sch.step(); REQUIRE(s != nullptr); CHECK_EQ(f.sch.draft().step_depth(), 4); CHECK_EQ(s->n_spec, 4); CHECK_EQ(s->n_tok, 2 + 5); for (const StepEntry& e : f.sch.plan().e) CHECK_EQ(e.n_spec, e.seq == a ? 1 : 4); CHECK_NEAR(f.sch.metrics().draft_depth_adaptive, 2.5, 1e-6); /* The head runs for the deepest. */ int rounds = 4; Scheduler::SerialRow rows[4]; CHECK_EQ(f.sch.serial_begin(&rounds, rows, 4), 2); CHECK_EQ(rounds, 4); REQUIRE(f.sch.serial_batch(0, 1) != nullptr); for (int rd = 2; rd <= rounds; ++rd) REQUIRE(f.sch.serial_batch(rd, 1) != nullptr); /* The step issued ahead: `a` verifies one of the four rounds, `b` all four. */ f.sch.find(a)->speculation_fixed = true; f.sch.find(b)->speculation_fixed = true; f.sch.expect_draft(a, rounds); f.sch.expect_draft(b, rounds); const RadBatch* nb = f.sch.step_next(); REQUIRE(nb != nullptr); CHECK_EQ(nb->n_spec, 4); CHECK_EQ(nb->n_tok, 2 + 5); /* Its commit, the watermark, and the proposals published for the step already on the card: * four rounds' worth to both, and each keeps what its step was planned to verify. */ commit_ab(); f.sch.serial_end(rounds); CHECK_OK(f.sch.set_draft(a, draft, rounds)); CHECK_OK(f.sch.set_draft(b, draft, rounds)); CHECK_EQ(f.sch.find(a)->n_draft, 1); CHECK_EQ(f.sch.find(b)->n_draft, 4); f.sch.promote_next(); for (const StepEntry& e : f.sch.plan().e) CHECK_EQ(e.n_spec, e.seq == a ? 1 : 4); CHECK(f.sch.metrics().draft_verify_depth[1] > 0); CHECK(f.sch.metrics().draft_verify_depth[4] > 0); } /* A NEW SEQUENCE STARTS FROM THE SEQUENCES THAT FINISHED, ONE VOTE EACH. Pooled over verifies, a * deep position is measured almost only on the texts good enough to be given a window that * reaches it; here two texts the head predicts and two it does not, and the deep positions start * a new sequence from all four. Until four have finished, the fixed prior. */ TEST(the_adaptive_window_starts_a_sequence_from_finished_sequences_not_pooled_verifies) { DraftController c = adaptive_controller(6); /* The pooled counts a deep-drafting good text leaves: position 5 accepted 95 % of the times * it was reached. They do not set the prior. */ for (int t = 0; t < 1000; ++t) c.observe(6, 6); CHECK_NEAR(c.prior_at(5), DraftController::kPrior, 1e-9); DraftAdapt fresh; (void)c.window_for(fresh); CHECK_NEAR(fresh.a[5], DraftController::kPrior, 1e-6); auto finished = [&](double a0, double rest) { DraftAdapt s = estimate(c, a0, rest); s.n[0] = 100; return s; }; /* Too few verifies to be more than its own prior: not counted. */ DraftAdapt young = finished(0.1, 0.1); young.n[0] = 3; c.adapt_retire(young); c.adapt_retire(finished(0.95, 0.95)); c.adapt_retire(finished(0.95, 0.95)); c.adapt_retire(finished(0.3, 0.2)); CHECK_NEAR(c.prior_at(5), DraftController::kPrior, 1e-9); /* three: not yet */ c.adapt_retire(finished(0.3, 0.2)); CHECK_NEAR(c.prior_at(0), (0.95 + 0.95 + 0.3 + 0.3) / 4.0, 1e-6); CHECK_NEAR(c.prior_at(5), (0.95 + 0.95 + 0.2 + 0.2) / 4.0, 1e-6); DraftAdapt next; (void)c.window_for(next); CHECK_NEAR(next.a[5], (0.95 + 0.95 + 0.2 + 0.2) / 4.0, 1e-6); /* An unstarted estimate is not a sequence to count. */ c.adapt_retire(DraftAdapt{}); CHECK_NEAR(c.prior_at(5), (0.95 + 0.95 + 0.2 + 0.2) / 4.0, 1e-6); /* And through the scheduler: four requests whose head drafts are all refused finish, and the * fifth starts at one draft where the first four started at the whole window. */ Fixture f; adaptive_fixture(f, 4); CHECK_OK(f.start()); std::vector ids; for (int i = 0; i < 4; ++i) ids.push_back(f.submit(160, 48)); REQUIRE(f.sch.step() != nullptr); f.commit_plain(11); CHECK_NEAR(f.sch.metrics().draft_depth_adaptive, 0.0, 1e-6); /* none drafted yet */ int32_t draft[4] = { 21, 22, 23, 24 }; for (uint64_t id : ids) CHECK_OK(f.sch.set_draft(id, draft, 4)); CHECK_NEAR(f.sch.metrics().draft_depth_adaptive, 4.0, 1e-6); for (int t = 0; t < 200 && f.sch.metrics().finished < 4; ++t) { for (uint64_t id : ids) if (f.sch.find(id)) (void)f.sch.set_draft(id, draft, 4); REQUIRE(f.sch.step() != nullptr); f.commit_plain(11); } CHECK_EQ(f.sch.metrics().finished, (int64_t)4); CHECK(f.sch.draft().prior_at(0) < 0.2); /* The step depth came down with them; a fresh sequence that started at the fixed prior would * take it back to four at its first cycle (the hold has long passed), and this one does not. */ CHECK_EQ(f.sch.draft().step_depth(), 1); const uint64_t e = f.submit(160, 48); REQUIRE(f.sch.step() != nullptr); f.commit_plain(11); CHECK_OK(f.sch.set_draft(e, draft, 4)); REQUIRE(f.sch.step() != nullptr); /* its first cycle chooses D */ f.commit_plain(11); CHECK_EQ(f.sch.draft().step_depth(), 1); CHECK_OK(f.sch.set_draft(e, draft, 4)); CHECK_EQ(f.sch.find(e)->n_draft, 1); } /* PROMPT LOOKUP IS NOT THE HEAD. When the head declines and the n-gram fallback proposes, the * outcome is counted in the reported acceptance like any other draft and kept out of the * sequence's estimate, which prices the head's next window. A run of lookups that are all refused * leaves the head's window where it was; the same run of refusals from the head brings it down. */ TEST(the_adaptive_window_is_not_fed_by_prompt_lookup) { Fixture f; adaptive_fixture(f, 4); CHECK_OK(f.start()); REQUIRE(f.sch.draft().adaptive()); /* A prompt that repeats, so the lookup always has a continuation to propose. */ auto r = std::make_unique(); r->id = f.next_id++; r->max_tokens = 2000; r->prompt.resize(160); for (int i = 0; i < 160; ++i) r->prompt[(size_t)i] = 100 + i % 8; const uint64_t a = r->id; CHECK_OK(f.sch.add(std::move(r))); REQUIRE(f.sch.step() != nullptr); f.commit_plain(100); /* the pattern goes on */ int lookups = 0; for (int t = 0; t < 4 * DraftController::kHold; ++t) { REQUIRE(f.sch.step() != nullptr); /* nothing published: the lookup fills */ const StepEntry& e = f.sch.plan().e[0]; if (e.n_spec > 0) { CHECK(e.ngram); CHECK(e.n_spec <= f.sch.draft().step_window()); ++lookups; } f.commit_plain(100 + (t + 1) % 8); /* every lookup refused */ } CHECK(lookups >= 2 * DraftController::kHold); const SchedMetrics m = f.sch.metrics(); CHECK(m.draft_tokens > 0); /* reported, as ever */ CHECK(m.draft_pos_reached[0] >= lookups); CHECK_EQ(m.draft_accepted, (int64_t)0); CHECK_NEAR(m.draft_depth_adaptive, 4.0, 1e-6); /* the head's window did not move */ /* The head's own refusals are what move it. */ int32_t draft[4] = { 21, 22, 23, 24 }; for (int t = 0; t < 4 * DraftController::kHold; ++t) { CHECK_OK(f.sch.set_draft(a, draft, 4)); REQUIRE(f.sch.step() != nullptr); CHECK(!f.sch.plan().e[0].ngram); f.commit_plain(100 + (t + 1) % 8); } CHECK_NEAR(f.sch.metrics().draft_depth_adaptive, 1.0, 1e-6); } /* THE SCHEDULER'S HALF OF THE COST: a decode step that verified drafts is timed at its deepest * window and its row count when it finishes, and the head depth the next cycle chooses reads it. * Measured dear past one round at two rows, both sequences' windows come down to one, and the * rounds with them. */ TEST(the_adaptive_window_times_its_steps_and_the_next_cycle_reads_them) { Fixture f; adaptive_fixture(f, 4); CHECK_OK(f.start()); REQUIRE(f.sch.draft().adaptive()); const uint64_t a = f.submit(160, 2000); const uint64_t b = f.submit(160, 2000); /* Every draft taken, so both stops stay at the whole window and only the cost moves D. */ auto commit_all = [&]() { const StepPlan& pl = f.sch.plan(); std::vector acc(pl.e.size(), 0), tok(pl.e.size(), 9); std::vector eos(pl.e.size(), 0); for (size_t i = 0; i < pl.e.size(); ++i) acc[i] = pl.e[i].is_prefill ? 0 : pl.e[i].n_spec; Scheduler::StepResult r; r.n_seq = (int)pl.e.size(); r.n_accepted = acc.data(); r.token = tok.data(); r.eos = eos.data(); CHECK_OK(f.sch.commit(r)); }; REQUIRE(f.sch.step() != nullptr); /* both prompts */ commit_all(); f.sch.step_finished(); /* a prefill step: not a sample */ for (int d = 1; d <= 4; ++d) CHECK_EQ(f.sch.draft().cost_samples(d, 2), (int64_t)0); int32_t draft[4] = { 21, 22, 23, 24 }; CHECK_OK(f.sch.set_draft(a, draft, 4)); CHECK_OK(f.sch.set_draft(b, draft, 4)); REQUIRE(f.sch.step() != nullptr); CHECK_EQ(f.sch.plan().n_spec, 4); commit_all(); f.sch.step_finished(); CHECK_EQ(f.sch.draft().cost_samples(4, 2), (int64_t)1); /* The hold, then a cycle that reads steps past one round as four times dearer. */ for (int d = 1; d <= 4; ++d) for (int i = 0; i < 64; ++i) f.sch.draft().step_time(d, 2, d == 1 ? 10.0 : 40.0); for (int t = 0; t < DraftController::kHold + 1; ++t) { CHECK_OK(f.sch.set_draft(a, draft, 4)); CHECK_OK(f.sch.set_draft(b, draft, 4)); REQUIRE(f.sch.step() != nullptr); commit_all(); } CHECK_EQ(f.sch.draft().step_depth(), 1); CHECK_OK(f.sch.set_draft(a, draft, 4)); CHECK_OK(f.sch.set_draft(b, draft, 4)); REQUIRE(f.sch.step() != nullptr); for (const StepEntry& e : f.sch.plan().e) CHECK_EQ(e.n_spec, 1); int rounds = 4; Scheduler::SerialRow rows[4]; CHECK_EQ(f.sch.serial_begin(&rounds, rows, 4), 2); CHECK_EQ(rounds, 1); f.sch.serial_end(0); CHECK_NEAR(f.sch.metrics().draft_depth_adaptive, 1.0, 1e-6); } /* ================================================================== the step path */ TEST(the_step_path_does_not_allocate) { Fixture f; f.build(/*blocks=*/4096, /*states=*/64); CHECK_OK(f.start()); for (int i = 0; i < 6; ++i) f.submit(64, 4096); /* Warm up: the first steps grow the request's block vector and its output, both of which are * sized once and never again. What must be zero is the STEADY-STATE step. */ for (int i = 0; i < 12; ++i) { CHECK(f.sch.step() != nullptr); f.commit_plain(); } g_allocs = 0; g_counting = true; for (int i = 0; i < 40; ++i) { const RadBatch* b = f.sch.step(); if (!b) break; const StepPlan& p = f.sch.plan(); Scheduler::StepResult r; static int32_t acc[64], tok[64]; static uint8_t eos[64]; for (size_t k = 0; k < p.e.size(); ++k) { acc[k] = 0; tok[k] = 5; eos[k] = 0; } r.n_seq = (int)p.e.size(); r.n_accepted = acc; r.token = tok; r.eos = eos; f.sch.commit(r); } g_counting = false; /* Not "few". None: an allocator call here is a declare-phase bug (IMPLEMENTATION.md), and * this is the assertion that finds it the day it is written. */ CHECK_EQ(g_allocs, 0L); } /* THE CARD'S BLOCK TABLES ARE STAGED AS THE ENTRIES THAT CHANGED, so they are checked whole after * every build: every row of a paged group reads the manager's table and then -1 to the pitch, * and a state group's row reads the slot. The run moves the tables every way a real one does -- * appends at block crossings, rejected drafts rolled back, requests ending and their rows taken * by the next, a late arrival's prefill -- and a row staged from a stale picture of the card * reads a block the sequence no longer holds, or a -1 where it holds one. */ TEST(the_cards_block_tables_match_the_manager_after_every_build) { Fixture f; f.build(/*blocks=*/4096, /*states=*/64); f.cfg.n_spec = 4; CHECK_OK(f.start()); std::vector ids; ids.push_back(f.submit(40, 9)); ids.push_back(f.submit(70, 200)); ids.push_back(f.submit(17, 90)); uint32_t rng = 12345; int checked = 0; for (int step = 0; step < 80; ++step) { if (step == 6) ids.push_back(f.submit(33, 120)); if (step == 20) ids.push_back(f.submit(90, 60)); for (uint64_t id : ids) { int32_t draft[4] = { 31, 32, 33, 34 }; (void)f.sch.set_draft(id, draft, 4); } const RadBatch* b = f.sch.step(); if (!b) break; const StepPlan& p = f.sch.plan(); for (int gi = 0; gi < b->n_kv_groups; ++gi) { const RadKVGroupBatch& g = b->kv[gi]; for (int64_t i = 0; i < b->n_seq; ++i) { const uint64_t seq = p.e[(size_t)i].seq; const int32_t* row = g.block_table + i * g.block_table_pitch; if (!f.kv.geom.g[(size_t)gi].paged) { CHECK_EQ(row[0], f.kv.state_slot(seq, gi)); continue; } const std::vector& bt = f.kv.block_table(seq, gi); for (int64_t j = 0; j < g.block_table_pitch; ++j) CHECK_EQ(row[j], j < (int64_t)bt.size() ? bt[(size_t)j] : -1); ++checked; } } Scheduler::StepResult r; static int32_t acc[64], tok[64]; static uint8_t eos[64]; for (size_t k = 0; k < p.e.size(); ++k) { rng = rng * 1664525u + 1013904223u; acc[k] = p.e[k].n_spec > 0 ? (int32_t)((rng >> 16) % (uint32_t)(p.e[k].n_spec + 1)) : 0; tok[k] = 5; eos[k] = 0; } r.n_seq = (int)p.e.size(); r.n_accepted = acc; r.token = tok; r.eos = eos; CHECK_OK(f.sch.commit(r)); } /* The run reached steady decode with rows to compare, not an empty loop. */ CHECK(checked > 100); } /* A SEQUENCE THAT LEAVES A ROW AND COMES BACK TO IT. Its change marks are taken wherever it is * written, so the copy it left behind stops being current the moment it is staged elsewhere: a * builder that still trusted that row would restage only what changed after the marks were taken, * and keep the entries a rollback replaced before them. The scheduler's own passes change the * rows a sequence sits in (a draft round without the sequences that did not draft), so this drives * the builder directly with the row orders written out. */ TEST(a_sequence_back_in_a_row_it_left_is_restaged_whole) { Fixture f; f.build(); ChunkGeometry geo; CHECK_OK(chunk_geometry_resolve(f.prog, f.cfg, &geo)); KVGeom kvg = KVGeom::of(f.prog.kv_groups); for (size_t i = 0; i < kvg.g.size(); ++i) { const int64_t w = f.kv.state_index_width((int32_t)i); if (w > 0) kvg.g[i].sidx_width = w; } BatchBuilder bb; std::vector rio; rio.push_back({ 0, nullptr, &f.prog }); CHECK_OK(bb.init(f.prog, f.cfg, geo, kvg, rio)); for (uint64_t id = 1; id <= 3; ++id) { CHECK_OK(f.kv.add_sequence(id)); CHECK_OK(f.kv.ensure(id, 80)); } StepPlan p; auto build = [&](std::initializer_list rows) { p.reset(); int32_t card = 0; for (uint64_t id : rows) { StepEntry e; e.seq = id; e.card = card++; e.n_tokens = 1; e.ctx_len = (int32_t)f.kv.seqs[id].n - 1; p.e.push_back(e); p.n_tok += 1; } const RadBatch* b = bb.build(p, f.kv, 0); CHECK(b != nullptr); if (!b) return; const RadKVGroupBatch& g = b->kv[0]; for (int64_t i = 0; i < b->n_seq; ++i) { const std::vector& bt = f.kv.block_table(p.e[(size_t)i].seq, 0); const int32_t* row = g.block_table + i * g.block_table_pitch; for (int64_t j = 0; j < g.block_table_pitch; ++j) CHECK_EQ(row[j], j < (int64_t)bt.size() ? bt[(size_t)j] : -1); } }; build({ 1, 2, 3 }); /* Sequence 3's last three blocks are handed to another sequence and replaced: its table keeps * its length and changes below it. */ CHECK_OK(f.kv.rollback(3, 32)); CHECK_OK(f.kv.add_sequence(4)); CHECK_OK(f.kv.ensure(4, 48)); CHECK_OK(f.kv.ensure(3, 80)); build({ 1, 3 }); /* 3 staged in row 1, its marks taken there */ build({ 1, 2, 3 }); /* and back in row 2, which still holds its old blocks */ bb.fini(); } /* TWO CONV GROUPS, AND EACH ONE'S DERIVATION READS ITS OWN WINDOW. * * Held as ONE slot array and ONE window number, both would be filled for whichever RAD_KV_CONV * group was declared LAST, and a second group's row would stay -1. * * WHAT THAT COSTS IS NARROWER THAN IT LOOKS: these two feed `DeriveInput` and nothing else, and * the only derivation that reads them -- `conv_state_index` -- is called by no architecture plugin * at present. A conv kernel takes its slot from RadKVGroupBatch::state_index, which is per group. * So the failure is wrong values in a buffer nobody reads, not a convolution reading no history. * * The two groups here have DIFFERENT WIDTHS on purpose: `conv_state_index` returns * `slot * window + cursor % window`, so a derivation served the wrong group's depth returns a * plausible number and the only way to tell is to make the two depths disagree. */ TEST(each_conv_group_derives_against_its_own_window) { auto two_groups = [](Fixture& f) { KVGroupInfo conv2; conv2.name = "conv_deep"; conv2.decl.kind = RAD_KV_CONV; conv2.decl.conv_width = 10; f.prog.kv_groups.push_back(conv2); f.kv.setup(f.prog.kv_groups, f.cfg.max_ctx, 4096, 64); }; /* ---- an UNNAMED group is refused, not guessed at ----------------------------------------- */ { Fixture f; f.build(); /* declares `conv_idx` with no group -- fine at one */ two_groups(f); /* The refusal logs at Error and that is the point of it; the line is expected here. */ CHECK_EQ(f.start(), RAD_E_INVAL); } /* ---- named, and each reads its own ------------------------------------------------------- */ Fixture f; f.build(); two_groups(f); /* Group 2 is the width-4 conv build() declared; group 3 is the deep one just added. */ for (BufferInfo& b : f.prog.buffers) if (b.name == "conv_idx") b.decl.kv = 2; f.add_derived("conv_idx_deep", "conv_state_index", 256, 3); CHECK_OK(f.start()); CHECK(f.submit(4) != 0); CHECK(f.sch.step() != nullptr); const int32_t* a = f.derived("conv_idx"); const int32_t* c = f.derived("conv_idx_deep"); CHECK(a != nullptr); CHECK(c != nullptr); /* NEITHER IS -1. Under one shared slot array the group that is not the last-declared one gets * -1 for every sequence, which is what this pins -- so that the first architecture to call * this derivation finds it working. */ if (a && c) { CHECK(a[0] >= 0); CHECK(c[0] >= 0); } } /* ================================================================== the derivation registry * * A DERIVATION NAMED IN A SCHEMA AND NOT IN THIS TABLE IS A DECLARE-TIME REFUSAL BY NAME, with * the known list printed beside it -- the same treatment a misspelled op gets (spec §2.3). The * alternative is a buffer the step loop leaves untouched, which a kernel then reads as whatever * the arena last held: on a decode step that is another sequence's index row, and the output is * fluent and wrong. * * So the registry itself has a property worth pinning: every row is reachable by its own name, * every row has a function, and a name that is not in it resolves to nothing rather than to row * zero. */ TEST(every_derivation_is_reachable_by_name_and_an_unknown_one_is_not) { const int n = derive_count(); CHECK(n > 0); for (int i = 0; i < n; ++i) { const DeriveRow* r = derive_row(i); CHECK(r != nullptr); if (!r) continue; CHECK(r->name && *r->name); CHECK(r->fn != nullptr); /* a row with no function is a name that resolves and * then writes nothing, which is the failure above */ CHECK(r->doc && *r->doc); /* it is printed in the refusal's known list */ CHECK_EQ(derive_index(r->name), i); } /* NAMES ARE UNIQUE, or derive_index answers with whichever row came first and the second one can never be selected. */ for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) CHECK(std::strcmp(derive_row(i)->name, derive_row(j)->name) != 0); /* -1 for a name the core does not know, rather than 0 -- which is a valid index. */ CHECK_EQ(derive_index("not_a_derivation"), -1); CHECK_EQ(derive_index(""), -1); CHECK_EQ(derive_index(nullptr), -1); /* A near miss on a real name is still a miss: the point of the table is that a typo is reported rather than approximated. */ CHECK_EQ(derive_index("seq_start_idx"), -1); /* And an index outside the table is null rather than a read past it. */ CHECK(derive_row(-1) == nullptr); CHECK(derive_row(n) == nullptr); CHECK(derive_row(n + 1000) == nullptr); } /* ================================================================== request lifetime */ /* THE SAMPLER SIZES ITS ROWS FROM Request::n_draft, and a drafter can set it for a step that * preemption then takes away. The request comes back as a prefill with one logits row, and a * stale window of four would have the sampler stage five -- every request after it in the step * then samples from its neighbour's row. */ TEST(a_preempted_request_comes_back_with_no_draft_window) { Fixture f; f.build(/*blocks=*/20, /*states=*/64); f.cfg.n_spec = 4; CHECK_OK(f.start()); uint64_t a = f.submit(160, 64, /*priority=*/0); uint64_t b = f.submit(160, 64, /*priority=*/5); CHECK(f.sch.step() != nullptr); f.commit_plain(); int32_t draft[4] = { 21, 22, 23, 24 }; CHECK_OK(f.sch.set_draft(a, draft, 4)); CHECK_EQ(f.sch.find(a)->n_draft, 4); /* Both need a new block at 160 and the pool has none: A, the lower priority, is taken. */ CHECK(f.sch.step() != nullptr); CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Preempted); CHECK_EQ(f.sch.find(a)->n_draft, 0); CHECK(f.sch.find(a)->draft == nullptr); f.commit_plain(); /* And when it is admitted again, the window it carries is the one its entry has. */ CHECK_OK(f.sch.cancel(b)); CHECK_OK(f.sch.reap(b)); REQUIRE(f.sch.step() != nullptr); CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Running); CHECK_EQ(f.sch.plan().e[0].n_spec, 0); CHECK_EQ(f.sch.find(a)->n_draft, 0); } /* EACH TERMINAL ID IS HANDED OVER ONCE. take_completed swaps the list out under the lock. A * reference into scheduler storage that nothing clears would have every finished request walked * again on every step for the life of the process -- and walked without the lock while an HTTP * thread's cancel appends to it. */ TEST(terminal_requests_are_taken_once) { Fixture f; f.build(); CHECK_OK(f.start()); uint64_t a = f.submit(8, /*max_tokens=*/1); uint64_t b = f.submit(8, /*max_tokens=*/64); CHECK(f.sch.step() != nullptr); f.commit_plain(); /* A reaches its one token */ CHECK_OK(f.sch.cancel(b)); std::vector done; f.sch.take_completed(&done); CHECK_EQ((int)done.size(), 2); CHECK(done[0] == a); CHECK(done[1] == b); f.sch.take_completed(&done); CHECK_EQ((int)done.size(), 0); } /* EVERY ROW NAMES ONE OF THE CARD'S STEP SLOTS. A slot is taken on arrival, so requests queued * behind the admission limit are numbered past max_seqs, and so are requests arriving while * finished ones are still held for their reap. The advance indexes max_seqs StepSlots by the * row's card index; a slot number there reads and writes past the end of them. */ TEST(every_row_names_one_of_the_cards_step_slots) { Fixture f; f.build(); f.cfg.max_seqs = 2; CHECK_OK(f.start()); for (int i = 0; i < 6; ++i) CHECK(f.submit(8, /*max_tokens=*/1) != 0); for (int round = 0; round < 3; ++round) { CHECK(f.sch.step() != nullptr); const StepPlan& p = f.sch.plan(); CHECK_EQ((int)p.e.size(), 2); CHECK(p.e[0].card >= 0 && p.e[0].card < 2); CHECK(p.e[1].card >= 0 && p.e[1].card < 2); CHECK(p.e[0].card != p.e[1].card); /* Nothing was reaped, so the later rounds' slots did run past max_seqs. */ if (round > 0) CHECK(p.e[0].slot >= 2 && p.e[1].slot >= 2); f.commit_plain(); /* each reaches its one token */ } CHECK_EQ(f.sch.metrics().queue_depth, 0); } /* THE CONTEXT PASS IS A MIRROR OF THE TRUNK STEP, ROW FOR ROW. The drafter reads the trunk's * hidden states positionally, so a sequence the commit finished still needs its rows -- left out, * every sequence after it drafts from its neighbour's hidden states. It stores nothing: its KV is * gone, so its slots are padding. */ TEST(a_block_drafter_context_pass_keeps_the_rows_of_a_finished_sequence) { Fixture f; f.build(); f.cfg.n_spec = 7; CHECK_OK(f.start()); uint64_t a = f.submit(160, /*max_tokens=*/1); uint64_t b = f.submit(160, 64); CHECK(f.sch.step() != nullptr); CHECK_EQ((int)f.sch.plan().e.size(), 2); f.commit_plain(); CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Finished); Scheduler::BlockRow rows[4]; CHECK_EQ(f.sch.block_begin(/*block=*/8, /*depth=*/7, /*window=*/0, /*mask=*/99, rows, 4), 1); CHECK(rows[0].seq == b); const RadBatch* cb = f.sch.block_context(1); REQUIRE(cb != nullptr); CHECK_EQ(cb->n_seq, 2); CHECK_EQ(cb->n_tok, 320); CHECK_EQ(cb->cu_seqlens[1], 160); CHECK_EQ(cb->kv[0].slot_mapping[0], -1); /* A's rows store nothing */ CHECK(cb->kv[0].slot_mapping[160] >= 0); /* B's rows are B's */ const RadBatch* qb = f.sch.block_query(1); REQUIRE(qb != nullptr); CHECK_EQ(qb->n_seq, 1); f.sch.block_end(); } /* A CANCEL BETWEEN TWO DRAFTER PASSES. The passes are built one at a time with the lock released * between them, so the cancel lands after the context pass was built and before the query pass * is. Freeing then would build the query pass over a sequence with no blocks: a block-table row * of -1 under a non-zero length, which attention reads as block -1. */ TEST(a_cancel_between_drafter_passes_keeps_the_blocks_until_the_passes_are_built) { Fixture f; f.build(/*blocks=*/4096, /*states=*/64); f.cfg.n_spec = 7; CHECK_OK(f.start()); const int64_t before = f.kv.free_blocks(0); uint64_t a = f.submit(160, 64); CHECK(f.sch.step() != nullptr); f.commit_plain(); Scheduler::BlockRow rows[4]; CHECK_EQ(f.sch.block_begin(8, 7, 0, 99, rows, 4), 1); CHECK(f.sch.block_context(1) != nullptr); CHECK_OK(f.sch.cancel(a)); CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Cancelled); CHECK(f.kv.has_sequence(a)); /* not freed under the passes */ const RadBatch* qb = f.sch.block_query(1); REQUIRE(qb != nullptr); CHECK(qb->kv[0].block_table[0] >= 0); /* a real block, not -1 */ f.sch.block_end(); /* The drafter is done with it, so it goes -- at the next commit, or here for an engine that * has gone idle and runs none. */ CHECK(f.sch.has_deferred()); f.sch.release_deferred(); CHECK(!f.kv.has_sequence(a)); CHECK_EQ(f.kv.free_blocks(0), before); CHECK(!f.sch.has_deferred()); CHECK_OK(f.sch.reap(a)); CHECK(f.sch.find(a) == nullptr); } /* A HIT THAT RESUMES FROM A SNAPSHOT IS NOT CARRIED ACROSS A FAILED ADMISSION. The slot is named * by id only; between two attempts it can be retired and handed to another sequence's checkpoint, * and an attempt that trusted the old id would restore that sequence's recurrent state. The next * attempt has to look the prompt up again -- and the accounting counts the admission once. */ TEST(a_failed_admission_gives_back_its_checkpoint_hit) { Fixture f; f.build(/*blocks=*/40, /*states=*/64); CHECK_OK(f.start()); uint64_t r = f.submit(160, 64); /* 10 blocks, and a miss */ CHECK(f.sch.step() != nullptr); f.commit_plain(); CHECK_EQ(f.pc.lookups, 1); f.pc.seed(256); /* 16 blocks the cache holds */ f.pc.lin = 256; f.pc.src = 3; /* A adopts the 16 cached blocks and needs 16 more for its first chunk; 13 are left. */ uint64_t a = f.submit(1000, 8); CHECK(f.sch.step() != nullptr); CHECK_EQ((int)f.sch.plan().e.size(), 1); CHECK_EQ(f.pc.lookups, 2); CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Waiting); CHECK_EQ(f.sch.find(a)->n_computed, 0); /* the hit went back */ CHECK_EQ((int)f.kv.block_table(a, 0).size(), 0); CHECK_EQ(f.sch.metrics().prompt_tokens, 160); /* not counted until it is admitted */ f.commit_plain(); /* Meanwhile the cache's snapshot at 256 moved to another slot. */ f.pc.src = 5; CHECK_OK(f.sch.cancel(r)); CHECK_OK(f.sch.reap(r)); REQUIRE(f.sch.step() != nullptr); CHECK_EQ(f.pc.lookups, 3); CHECK_EQ(f.sch.find(a)->n_computed, 256); CHECK_EQ(f.sch.plan().e[0].ckpt_restore, 5); SchedMetrics m = f.sch.metrics(); CHECK_EQ(m.prompt_tokens, 160 + 1000); CHECK_EQ(m.attn_cached_tokens, 256); CHECK_EQ(m.linear_cached_tokens, 256); } /* A LOOKAHEAD THE POOL REFUSES IS A REASON NOT TO DRAFT, NOT A REASON TO SKIP THE ROW. The history * pass writes the draft head's K and V for positions the sequence already holds blocks for; a row * dropped here leaves them unwritten for good, because the next step's history starts at its own * context. */ TEST(a_refused_lookahead_still_runs_the_history_pass) { Fixture f; f.build(/*blocks=*/10, /*states=*/64); /* exactly the prompt; nothing to look ahead into */ f.cfg.n_spec = 4; CHECK_OK(f.start()); f.submit(160, 64); CHECK(f.sch.step() != nullptr); f.commit_plain(); int rounds = 4; Scheduler::SerialRow rows[4]; CHECK_EQ(f.sch.serial_begin(&rounds, rows, 4), 0); /* nobody drafts */ const RadBatch* hb = f.sch.serial_batch(0, 1); REQUIRE(hb != nullptr); CHECK_EQ(hb->n_tok, 160); /* but the history is written */ f.sch.serial_end(0); } /* DRAFT ROUND 1 RIDES THE HISTORY PASS. A verifying sequence that drafts owes the head's history at * all 1 + n_spec verified positions, and the card repeats the last committed one in the rows past * it, so the run's last row is round 1's whole input: the pass names that row, one a drafting * sequence, and round 1 has no pass of its own. */ TEST(the_history_pass_carries_draft_round_one) { Fixture f; f.build(/*blocks=*/4096, /*states=*/64); f.cfg.n_spec = 4; CHECK_OK(f.start()); const uint64_t a = f.submit(160, 64); CHECK(f.sch.step() != nullptr); f.commit_plain(11); int32_t draft[4] = { 21, 22, 23, 24 }; CHECK_OK(f.sch.set_draft(a, draft, 4)); const RadBatch* b = f.sch.step(); REQUIRE(b != nullptr); CHECK_EQ(b->n_spec, 4); int rounds = 4; Scheduler::SerialRow rows[4]; CHECK_EQ(f.sch.serial_begin(&rounds, rows, 4), 1); CHECK_EQ((int)rows[0].seq, (int)a); const RadBatch* hb = f.sch.serial_batch(0, 1); REQUIRE(hb != nullptr); CHECK(hb->draft_pass < 0); CHECK_EQ(hb->n_tok, 5); /* every verified position, the last included */ CHECK_EQ(hb->n_draft_out, 1); CHECK_EQ(hb->draft_out_ids[0], 4); /* the run's last row */ CHECK(f.sch.serial_batch(1, 1) == nullptr); const RadBatch* r2 = f.sch.serial_batch(2, 1); REQUIRE(r2 != nullptr); CHECK_EQ(r2->draft_pass, 2); CHECK_EQ(r2->n_tok, 1); CHECK_EQ(r2->n_draft_out, 0); f.sch.serial_end(2); } /* A STEP IS ISSUED AHEAD OF A COMMIT ONLY FOR A REQUEST WHOSE SPECULATION THAT COMMIT CANNOT * CHANGE. The ahead step is sized before the commit in front of it, so a request the sampler has * not started yet -- whose grammar, if any, nobody has asked -- is not issued ahead; one whose * grammar rewinds is, grammar or not. */ TEST(a_step_is_issued_ahead_only_once_the_requests_speculation_is_fixed) { Fixture f; f.build(); CHECK_OK(f.start()); const uint64_t id = f.submit(8, 64); CHECK(f.sch.step() != nullptr); /* the prompt */ f.commit_plain(); CHECK(f.sch.step() != nullptr); /* the first decode */ CHECK(f.sch.step_next() == nullptr); /* the sampler has not started it */ Request* r = f.sch.find(id); REQUIRE(r != nullptr); r->sp.grammar = "root ::= \"a\""; r->speculation_fixed = true; /* a grammar whose backend rewinds */ CHECK(f.sch.step_next() != nullptr); } /* THE CONTEXT BOUNDS A SEQUENCE WHATEVER max_tokens SAYS, "no limit" included. Nothing past the * last position the deployment can address has a rotary row or a block-table column; a sequence * allowed to run into it corrupts memory instead of stopping. */ TEST(a_sequence_stops_at_the_context_whatever_max_tokens_says) { Fixture f; f.build(); f.cfg.max_ctx = 170; f.cfg.n_spec = 4; CHECK_OK(f.start()); uint64_t a = f.submit(160, /*max_tokens=*/0); /* unlimited */ CHECK(f.sch.step() != nullptr); f.commit_plain(); int32_t draft[4] = { 21, 22, 23, 24 }; for (int guard = 0; guard < 32 && f.sch.find(a)->state == ReqState::Running; ++guard) { CHECK_OK(f.sch.set_draft(a, draft, 4)); REQUIRE(f.sch.step() != nullptr); const StepEntry& e = f.sch.plan().e[0]; CHECK(e.ctx_len + e.n_tokens <= 170); /* no position at or past the end */ /* Every draft accepted: the most a step can emit, so the bound has to cut it short. */ int32_t acc[1] = { e.n_spec }; int32_t tok[1] = { 9 }; uint8_t eos[1] = { 0 }; Scheduler::StepResult r; r.n_seq = 1; r.n_accepted = acc; r.token = tok; r.eos = eos; CHECK_OK(f.sch.commit(r)); } const Request* ra = f.sch.find(a); CHECK_EQ((int)ra->state, (int)ReqState::Finished); CHECK_EQ(ra->finish_reason, std::string("length")); CHECK_EQ((int)(ra->prompt.size() + ra->output.size()), 170); /* A prompt that fills the context has nothing to generate into and is never run. */ uint64_t full = f.submit(170, 8); CHECK(f.sch.step() == nullptr); CHECK_EQ((int)f.sch.find(full)->state, (int)ReqState::Failed); /* And asking for more than the context holds reserves only what it can hold. */ uint64_t big = f.submit(8, 2147483647); CHECK(f.sch.find(big)->output.capacity() <= (size_t)(170 + RAD_SCHED_MAX_SPEC)); } /* THE CACHE'S RESERVE IS MEASURED AGAINST WHAT IS HELD, NOT AGAINST WHAT IS BACKED. An elastic * pool that has handed its unused top back to the card reads almost no free blocks however little * anything holds, and trimming against that drains the whole cache after every request. */ TEST(the_cache_trim_does_not_mistake_released_vram_for_occupancy) { Fixture f; f.build(/*blocks=*/40, /*states=*/64); CHECK_OK(f.start()); f.pc.evict_grant = 1 << 20; f.kv.unbacked = 30; /* the pool gave 30 blocks back */ f.submit(160, /*max_tokens=*/1); /* holds 10 of 40 */ CHECK(f.sch.step() != nullptr); f.commit_plain(); /* finishes and publishes */ CHECK_EQ((int)f.pc.published.size(), 1); CHECK_EQ(f.pc.evict_calls, 0); CHECK(f.pc.trims.empty()); } /* WHEN LIVE SEQUENCES HOLD MORE THAN THE RESERVE ALLOWS, THE TRIM ASKS FOR THE SHORTFALL ONCE. * Nothing the cache can give closes it entirely, and a loop that kept evicting until it did would * take the conversation this close has just published along with everything else on the list. */ TEST(the_cache_trim_asks_for_the_shortfall_and_not_for_the_whole_cache) { Fixture f; f.build(/*blocks=*/40, /*states=*/64); CHECK_OK(f.start()); f.pc.evict_grant = 1 << 20; f.submit(160, /*max_tokens=*/1); /* 10 blocks, finishes on the first commit */ f.submit(176, /*max_tokens=*/64); /* 11 blocks each, still running after it */ f.submit(176, /*max_tokens=*/64); CHECK(f.sch.step() != nullptr); CHECK_EQ(f.kv.held_blocks(0), 32ll); /* 8 free against a reserve of 10 */ f.commit_plain(); CHECK_EQ((int)f.pc.published.size(), 1); REQUIRE(f.pc.trims.size() == 1u); CHECK_EQ(f.pc.trims[0], 2ll); CHECK_EQ(f.pc.evict_calls, 0); } /* THE CACHE GIVES WAY TO A NEW REQUEST AS IT DOES TO A RUNNING ONE. With nothing running, no * other path takes blocks back from the cache, and a pool full of finished conversations would * keep the request waiting for good. */ TEST(an_admission_short_of_blocks_takes_them_from_the_cache) { Fixture f; f.build(/*blocks=*/20, /*states=*/64); CHECK_OK(f.start()); f.pc.seed(240); /* 15 of 20 held by finished conversations */ f.pc.attn = 0; /* and none of them is this prompt */ f.pc.evict_frees = true; f.pc.evict_grant = 1 << 20; const uint64_t a = f.submit(160, 8); /* 10 blocks, 5 free */ CHECK(f.sch.step() != nullptr); CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Running); CHECK(f.pc.evict_calls >= 1); CHECK(f.pc.holds.empty()); } /* A REFUSED ADMISSION HOLDS WHAT ITS RESTORE BROUGHT BACK, and lets go once the request is gone, * so the next attempt finds the chain on the card instead of copying it again. */ TEST(a_refused_admission_holds_its_chain_until_the_request_goes) { Fixture f; f.build(/*blocks=*/20, /*states=*/64); CHECK_OK(f.start()); f.pc.seed(240); f.pc.attn = 0; const uint64_t a = f.submit(160, 8); /* the cache gives nothing back */ CHECK(f.sch.step() == nullptr); CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Waiting); REQUIRE_EQ(f.pc.holds.size(), 1u); CHECK_EQ(f.pc.holds[0], a); CHECK_OK(f.sch.cancel(a)); CHECK(std::find(f.pc.releases.begin(), f.pc.releases.end(), a) != f.pc.releases.end()); } /* AN ENGINE THAT HAS STOPPED ANSWERS EVERY REQUEST IT HELD AND REFUSES NEW ONES, rather than * leaving their connections waiting on a step that will never come. */ TEST(shutdown_fails_what_is_queued_and_refuses_what_follows) { Fixture f; f.build(/*blocks=*/20, /*states=*/64); CHECK_OK(f.start()); const int64_t before = f.kv.free_blocks(0); uint64_t a = f.submit(160, 64); CHECK(f.sch.step() != nullptr); uint64_t b = f.submit(160, 64); f.sch.shutdown("stopped"); CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Failed); CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Failed); CHECK_EQ(f.kv.free_blocks(0), before); CHECK(f.submit(8, 8) == 0); CHECK(f.sch.step() == nullptr); } /* AND EACH OF THOSE REQUESTS SAYS WHAT STOPPED IT. The sink carries the status and the sentence * the server puts in the 500: without them a client read "the engine failed this request: ok" * after a step failed as unsupported. */ TEST(shutdown_fails_each_sink_with_the_status_that_stopped_the_engine) { server::Sink running, waiting, late; Fixture f; f.build(/*blocks=*/20, /*states=*/64); CHECK_OK(f.start()); CHECK(f.submit_to(&running, 160, 64) != 0); CHECK(f.sch.step() != nullptr); CHECK(f.submit_to(&waiting, 160, 64) != 0); f.sch.shutdown("the engine stopped", RAD_E_UNSUPPORTED); CHECK(f.submit_to(&late, 8, 8) == 0); for (server::Sink* s : { &running, &waiting, &late }) { CHECK(s->done()); CHECK_EQ((int)s->finish_reason(), (int)server::Finish::Error); CHECK_EQ(s->status(), (int)RAD_E_UNSUPPORTED); CHECK_EQ(std::string(s->why() ? s->why() : ""), std::string("the engine stopped")); } } /* A REQUEST'S OWN SPECULATION AND ITS ADMISSION REACH ITS SINK, which is what lets a response say * how many tokens were drafted for it and when its prefill started: the aggregate counters cannot * be split between requests that overlap. The count is the drafts each verify step proposed for * this request and the ones it accepted -- the same numbers /metrics sums. */ TEST(a_sink_carries_its_requests_admission_and_draft_counts) { server::Sink sink; Fixture f; f.build(/*blocks=*/4096, /*states=*/64); f.cfg.n_spec = 4; CHECK_OK(f.start()); const uint64_t id = f.submit_to(&sink, 40, 60); CHECK(id != 0); CHECK(sink.t_admitted_ns() < 0); int64_t drafted = 0, accepted = 0; uint32_t rng = 99; for (int step = 0; step < 40 && !sink.done(); ++step) { int32_t draft[4] = { 31, 32, 33, 34 }; (void)f.sch.set_draft(id, draft, 4); const RadBatch* b = f.sch.step(); if (!b) break; CHECK(sink.t_admitted_ns() >= 0); const StepPlan& p = f.sch.plan(); Scheduler::StepResult r; static int32_t acc[64], tok[64]; static uint8_t eos[64]; for (size_t k = 0; k < p.e.size(); ++k) { rng = rng * 1664525u + 1013904223u; acc[k] = p.e[k].n_spec > 0 ? (int32_t)((rng >> 16) % (uint32_t)(p.e[k].n_spec + 1)) : 0; tok[k] = 5; eos[k] = 0; if (!p.e[k].is_prefill && p.e[k].n_spec > 0) { drafted += p.e[k].n_spec; accepted += acc[k]; } } r.n_seq = (int)p.e.size(); r.n_accepted = acc; r.token = tok; r.eos = eos; CHECK_OK(f.sch.commit(r)); } CHECK(drafted > 0); CHECK_EQ(sink.n_drafted(), drafted); CHECK_EQ(sink.n_draft_accepted(), accepted); } RAD_TEST_MAIN()