diff --git a/core/config.cpp b/core/config.cpp index d8ce58c5..89d1cd81 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -167,6 +167,11 @@ static const Flag g_flags[] = { " one, for each of --max-num-seqs, within an eighth of host\n" " memory. N fixes the total; 0 keeps none" }, { "--no-prefix-cache", nullptr, "disable prefix caching" }, + { "--prefix-resume", "MODE", "where a prefix hit resumes: exact (default) only where\n" + " an idle server's cold prefill of the prompt starts a\n" + " chunk, so the hit answers bit-identically to a cold run;\n" + " nearest at the deepest snapshot, up to a chunk less to\n" + " re-prefill" }, { "--checkpoint-policy", "NAME", "which snapshots a session retains: geometric-backoff " "(default), tip-only, keep-all" }, @@ -682,6 +687,15 @@ int config_parse(int argc, char** argv, Config* c) { } } else if (S("--no-prefix-cache")) c->prefix_cache = false; + else if (S("--prefix-resume")) { + if (!(v = need(i))) return RAD_E_INVAL; + if (!std::strcmp(v, "exact")) c->prefix_exact = true; + else if (!std::strcmp(v, "nearest")) c->prefix_exact = false; + else { + RAD_ERR("--prefix-resume '%s' is not one of exact, nearest", v); + return RAD_E_INVAL; + } + } else if (S("--checkpoint-policy")) { if (!(v = need(i))) return RAD_E_INVAL; /* Validated, so an unknown name does not silently fall back to the default. */ @@ -1182,6 +1196,8 @@ const ShowRow kShow[] = { return c.checkpoint_slots < 0 ? std::string("auto") : num(c.checkpoint_slots); } }, { "--no-prefix-cache", [](const Config& c) { return std::string(c.prefix_cache ? "not given: prefix caching on" : "prefix caching off"); } }, + { "--prefix-resume", [](const Config& c) { + return std::string(c.prefix_exact ? "exact" : "nearest"); } }, { "--checkpoint-policy", [](const Config& c) { return c.checkpoint_policy; } }, { "--num-speculative-tokens", [](const Config& c) { return c.n_spec < 0 ? std::string("auto") : num(c.n_spec); } }, { "--draft-window", [](const Config& c) { return std::string(draft_window_name(c.draft_window)); } }, diff --git a/core/rad_core.h b/core/rad_core.h index 2ba62765..0b74f5bc 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -898,6 +898,14 @@ struct Config { * store is opened (checkpoint_slots_auto in core/mem/prefix.h). */ int64_t checkpoint_slots = -1; bool prefix_cache = true; + /* --prefix-resume exact|nearest. Exact (the default) resumes a prefix hit only on the grid an + * idle server's cold prefill chunks the same prompt on (ChunkGeometry::grid), and takes a + * prompt's tail snapshot where its last chunk starts: the hit recomputes the cold run's own + * chunks, so its output is the cold run's bit for bit, where a kernel rounds a row differently + * at another chunk length. Nearest resumes at the deepest snapshot or block, a prompt's tail + * snapshot at its last quantum boundary: up to a chunk less re-prefilled a turn, and a hit that + * can differ from a cold run in the last bits (a near-tie in greedy text). */ + bool prefix_exact = true; /* geometric-backoff | tip-only | keep-all. §19.1 records the default as unmeasured; * core/mem/prefix.h ships the two extremes so they can be compared. */ std::string checkpoint_policy = "geometric-backoff"; diff --git a/core/sched/geometry.cpp b/core/sched/geometry.cpp index e5dca1ca..d6af36ed 100644 --- a/core/sched/geometry.cpp +++ b/core/sched/geometry.cpp @@ -143,15 +143,49 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry * checkpoints land wherever a step ends (§7.3). */ g.min_max_tok = g.quantum; - *out = g; - if (cfg.max_tok < g.min_max_tok) { + *out = g; RAD_ERR("--max-num-batched-tokens is %lld but this model's chunk geometry needs at least " "%lld, so a chunk can end on a linear-state boundary: %s", (long long)cfg.max_tok, (long long)g.min_max_tok, g.why.c_str()); return RAD_E_INVAL; } + /* The resume grid (--prefix-resume exact): where an idle server's prefill chunks start. A + * prefill alone in its step takes the budget, rounded down to the quantum, and stops at every + * interval boundary it reaches where chunks split at the interval (linear state, or periodic + * window snapshots); a span carries h intervals from the second one on. An interval past the + * budget must then be a multiple of the budget's chunk, or the chunk after a checkpoint would + * start off the grid every cold run cuts: rounded up, as the quantum rounds it, since a longer + * interval costs only retention. */ + const int64_t I0 = g.checkpoint_interval; + const bool splits = I0 > 0 && (!g.window_ckpt || g.window_periodic); + const int64_t budget_chunk = cfg.max_tok / g.quantum * g.quantum; + g.exact = cfg.prefix_exact && cfg.prefix_cache; + if (g.exact && splits && I0 > budget_chunk && I0 % budget_chunk != 0) { + g.checkpoint_interval = align_up(I0, budget_chunk); + RAD_WARN("--checkpoint-interval %lld resolves to %lld: --prefix-resume exact needs it a " + "multiple of the %lld-token prefill chunk (--max-num-batched-tokens %lld) so " + "every checkpoint is where a cold prefill's chunk ends; give a multiple of %lld, " + "or --prefix-resume nearest to keep %lld", (long long)cfg.checkpoint_interval, + (long long)g.checkpoint_interval, (long long)budget_chunk, (long long)cfg.max_tok, + (long long)budget_chunk, (long long)I0); + } + if (g.exact) { + const int64_t I = g.checkpoint_interval; + if (splits && I <= budget_chunk) { + const int64_t h = g.span > 1 ? std::max(1, std::min(g.span, cfg.max_tok / I)) + : 1; + g.grid = h * I; + g.grid_origin = h > 1 ? I : 0; + } else { + g.grid = budget_chunk; + g.grid_origin = 0; + } + } + + *out = g; + /* Log the effective chunk length. `plan_chunk` splits at the checkpoint interval first, so * when the interval is below --max-num-batched-tokens, raising the budget does not change the * chunk; the log line makes that visible. tip-only window snapshots do not @@ -167,6 +201,13 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry eff >= cfg.max_tok ? "" : g.span > 1 ? " (the checkpoint interval times the span, not the budget)" : " (the checkpoint interval, not the budget)"); + if (g.exact) + RAD_INFO("prefix resume: exact -- a hit resumes only where an idle server's cold prefill " + "of the same prompt starts a chunk (every %lld tokens%s) and a prompt's tail " + "snapshot is taken where its last chunk starts, so the hit recomputes the cold " + "run's own chunks and answers bit-identically; a turn re-prefills up to one chunk " + "more than --prefix-resume nearest", (long long)g.grid, + g.grid_origin > 0 ? fmt(" from %lld", (long long)g.grid_origin).c_str() : ""); if (cfg.prefill_span > 1) { /* What the span does here, said once: the intervals the budget holds can be fewer than * the flag asks for, and a model without an interval grid spans nothing. */ diff --git a/core/sched/geometry.h b/core/sched/geometry.h index 437b0eb5..72583964 100644 --- a/core/sched/geometry.h +++ b/core/sched/geometry.h @@ -60,7 +60,29 @@ struct ChunkGeometry { * tip-only, which keeps the tail alone and so splits no chunk at the interval. */ bool window_periodic = false; + /* --prefix-resume exact (Config::prefix_exact): a prefix hit resumes only where a cold prefill + * of the same prompt starts a chunk, so the tokens a hit recomputes are cut into the chunks a + * cold run cuts them into. A kernel may round a row differently at another chunk length (a + * split-K count chosen from M, a small-M path); computed in the same chunks, the hit's output + * is the cold run's, bit for bit, on an idle server. The grid is where an idle server's prefill + * chunks start: 0, then grid_origin + k * grid. `grid` is the checkpoint interval where chunks + * split at it and it fits the budget, times the span from the second interval on (origin = the + * interval), and otherwise --max-num-batched-tokens rounded down to the quantum (the interval + * is then rounded up to a multiple of it). Zero when not exact. */ + bool exact = false; + int64_t grid = 0; + int64_t grid_origin = 0; + bool checkpoints() const { return checkpoint_interval > 0; } + + /* The deepest grid position at or below `pos`; `pos` itself when not exact. */ + int64_t grid_floor(int64_t pos) const { + if (pos <= 0) return 0; + if (!exact || grid <= 0) return pos; + if (pos < grid_origin) return 0; + return grid_origin + (pos - grid_origin) / grid * grid; + } + bool on_grid(int64_t pos) const { return grid_floor(pos) == pos; } }; /* The budget of a step a span does not take (ChunkGeometry::shared_tok), from the configuration diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index 960826da..4a304cc4 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -871,7 +871,38 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg int64_t want = remaining < budget ? remaining : budget; - if (geo_.checkpoints()) { + if (geo_.checkpoints() && geo_.exact) { + /* --prefix-resume exact: checkpoints only where an idle cold prefill of this prompt starts + * a chunk (ChunkGeometry::grid), so a hit that resumes at one recomputes the cold run's + * own chunks. Splits as below at the interval and a span's end; the tail snapshot is at + * the start of the prompt's last chunk (tail_checkpoint), a boundary an idle chunk already + * ends on, so it costs a copy and no step. A step that shares the budget (another + * request, decode rows) may straddle it, and is split there. */ + const int64_t I = geo_.checkpoint_interval; + const bool periodic = !geo_.window_ckpt || geo_.window_periodic; + const int64_t next = periodic ? ((n_computed / I) + 1) * I : INT64_MAX; + int64_t far = next; + if (geo_.span > 1 && span_now_ && n_computed >= I && n_computed % I == 0) + far = n_computed + geo_.span * I; + if (n_computed + want > far) + want = far - n_computed; + else if (n_computed + want > next && n_computed + want < n_target) + want = (n_computed + want) / I * I - n_computed; + const int64_t tail = tail_checkpoint(n_target); + if (tail > n_computed && n_computed + want >= tail) { + want = tail - n_computed; + if (checkpoint_pos) *checkpoint_pos = tail; + } else if (periodic && (n_computed + want) % I == 0 && geo_.on_grid(n_computed + want)) { + if (checkpoint_pos) *checkpoint_pos = n_computed + want; + } + /* A request's own checkpoint (Request::checkpoint_at) as below, wherever it falls: the + * head the request shares with others resumes there by design. */ + const int64_t keep = keep_at / geo_.quantum * geo_.quantum; + if (keep > n_computed && keep <= n_computed + want && keep <= n_target) { + want = keep - n_computed; + if (checkpoint_pos) *checkpoint_pos = keep; + } + } else if (geo_.checkpoints()) { const int64_t I = geo_.checkpoint_interval; int64_t next = ((n_computed / I) + 1) * I; /* strictly after n_computed */ if (geo_.window_ckpt && !geo_.window_periodic) { @@ -955,6 +986,16 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg int64_t Scheduler::tail_checkpoint(int64_t target) const { const int64_t I = geo_.checkpoint_interval, Q = geo_.quantum; if (I <= 0 || Q <= 0) return -1; + if (geo_.exact) { + /* --prefix-resume exact: where the prompt's last chunk starts on the resume grid, so an + * exact repeat re-prefills that chunk as the cold run did, and an appended turn that chunk + * and what it added. A window snapshot keeps its margin below (next comment): the grid + * point under the end less a block. Past the first interval, as below. */ + const int64_t margin = geo_.window_ckpt ? std::max(Q, 16) : 1; + const int64_t t = geo_.grid_floor(target - margin); + if (geo_.window_ckpt) return t >= I ? t : -1; + return t > I ? t : -1; + } const int64_t tail = target / Q * Q; /* A window snapshot is taken at the tail of any prompt of an interval or more, a block short * of the end: the next turn re-renders the last few tokens (the generation prompt is replaced @@ -1157,6 +1198,20 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { if (reuse > last) reuse = last; if (reuse < 0) reuse = 0; + /* --prefix-resume exact: resume only on the grid an idle cold prefill chunks this prompt + * on (ChunkGeometry::grid), so the tokens recomputed below are cut into the cold run's own + * chunks. A snapshot is already on it (plan_chunk writes none off it, but for a request's + * own Request::checkpoint_at); a hit at a block (no snapshot needed) steps back to it. */ + if (geo_.exact && reuse > 0 && + !(geo_.checkpoints() && h.checkpoint_slot >= 0 && reuse == h.n_linear_tokens)) { + const int32_t g = (int32_t)geo_.grid_floor(reuse); + if (g < reuse) + RAD_DEBUG("admit %llu: prefix hit of %lld tokens resumes at %lld, on the " + "%lld-token chunk grid (--prefix-resume exact)", (unsigned long long)r.id, + (long long)reuse, (long long)g, (long long)geo_.grid); + reuse = g; + } + /* A hit on a hybrid model needs a checkpoint. The adopted blocks cover the paged * attention groups, but nothing covers a recurrent group, whose state lives in a * per-sequence slot; skipping tokens also requires restoring that state (`ckpt_src`, diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 11082e52..58abf901 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1193,6 +1193,31 @@ snapshot lets it skip at least 256 tokens of that head, the request takes one wh ends, at the cost of one chunk split, and the requests after it resume there. A conversation's next turn has only its own earlier turn past that point, so it splits nothing extra. +A prefix hit answers exactly as the same prompt prefilled cold, by default +(`--prefix-resume exact`). A kernel can round a row differently at another chunk +length (the fp8 GEMM's split-K count is chosen from `M`, spec §17), so a hit that +recomputes its tail in other chunks than a cold prefill can flip a near-tie in +greedy text. The hit therefore resumes only where an idle server's cold prefill of +that prompt starts a chunk: every `--max-num-batched-tokens` tokens (rounded down +to the chunk quantum), or every `--checkpoint-interval` when that is smaller. A +prompt's tail snapshot is taken where its last chunk starts, a boundary the chunk +already ends on, so it costs a copy and no step. An exact repeat re-prefills the +cold run's last chunk; an appended turn, that chunk and what the turn added: up to +one chunk more than `--prefix-resume nearest`, which resumes at the deepest +snapshot or block and splits a prompt's last chunk at its last quantum boundary. +The interval must be a multiple of the chunk when it is larger; otherwise it is +rounded up, and startup says so: + + ``` + --checkpoint-interval 6144 resolves to 8192: --prefix-resume exact needs it a multiple of the + 4096-token prefill chunk (--max-num-batched-tokens 4096) ... + ``` + +It is an idle-server property, as greedy batching is: a prefill that shares its +steps with other requests or decode rows (`--busy-prefill-chunk`, +`--prefill-interleave`) is cut differently, and a request's own checkpoint +(`/v1/systemone`'s shared head) resumes where it was asked. + **One prefill sequence in two pieces.** At two ranks, on `qwen35_fp8` (and `qwen35_w8a8`, built from it, where its norms do not write rotated int8 codes) and on `gemma3`'s MXFP4 trunk with the fused fp8 junctions, a step of at least 1024 tokens that carries one prefill sequence and nothing @@ -1947,6 +1972,7 @@ by 0.002-0.003 nats. | `--prefill-span N` | 1 | checkpoint intervals one step may carry of a prefill alone in its step, from the prompt's second interval on; needs `--max-num-batched-tokens` of N intervals. Every other step is planned at the budget less the extra intervals, and the checkpoints inside a span are not written (§4.5) | | `--checkpoint-slots N` | auto | linear-state (hybrid) or sliding-window snapshots the server may hold at once, in total, not per sequence. They live in pinned host memory, allocated at startup: one slot is a snapshot of every rank's shard (113 MB on Flash-Next at `--tp 2`, 144 MiB on Qwen3.8-27B; on Gemma 4 31B the 1024-token window of every sliding layer, 406 MiB at `--tp 2`). `auto` gives each of `--max-num-seqs` what `--checkpoint-policy` keeps for a `--max-model-len` session plus one (10 at 200K tokens under geometric backoff), within an eighth of host memory and what the host can pin; the startup line and the report say what it chose and why (§4.8). A full store retires its least recently used snapshot. A count is taken as given: a store the host memory cannot hold or pin stops the start, and a table placed in host memory leaves room for it; `0` serves with none, every prefix hit then prefilling from the start | | `--checkpoint-policy NAME` | geometric-backoff | also `tip-only`, `keep-all` | +| `--prefix-resume MODE` | exact | `exact`: a prefix hit resumes only where an idle server's cold prefill of the prompt starts a chunk, and a prompt's tail snapshot is taken where its last chunk starts, so a hit answers bit-identically to a cold run; an interval past the chunk is rounded up to a multiple of it. `nearest`: the deepest snapshot or block, up to a chunk less re-prefilled a turn | | `--no-prefix-cache` | prefix cache on | disable prefix caching | **Parallel** diff --git a/spec.md b/spec.md index e01acb59..04f8e7cf 100644 --- a/spec.md +++ b/spec.md @@ -1060,6 +1060,21 @@ token when it sits at `i * block_size`. This engine changes two things: On a model with sliding-window attention and no linear state, a checkpoint snapshots the window behind a prompt's tail instead, and chunks are not split at the interval. +**Exact resume.** A hit recomputes the tokens past where it resumes, and a kernel can round a row +differently at another chunk length (§17), so a hit is bit-identical to a cold run of the same +prompt only if it recomputes the cold run's own chunks. With `--prefix-resume exact` (the default) +a hit resumes only on the grid an idle server's cold prefill chunks on: the budget's chunk +(`--max-num-batched-tokens` rounded down to the quantum), or the interval where chunks split at it +and it is the smaller, times the span from the second interval on. Every snapshot the scheduler +writes is on that grid: interval checkpoints (the interval, when past the chunk, is rounded up to a +multiple of it), and the prompt's tail snapshot, which is taken where its last chunk starts rather +than at its last quantum boundary. That boundary is one the cold chunk already ends on, so the tail +snapshot costs no extra step; an exact repeat re-prefills the last chunk, an appended turn that +chunk and its own tokens, up to one chunk more than `--prefix-resume nearest` (the deepest snapshot +or block). A hit with no snapshot to resume from (full attention) steps back to the grid. The +property holds for a prefill alone in its steps; one sharing its steps with other work is cut +differently, as greedy text under batching already differs (§17). + Snapshots are large (at a 2048-token interval a 128K session on Qwen3.5-27B is 64 checkpoints, about 9 GiB), so retention is budgeted. Retention keeps the session tip, which an appending agent transcript resumes from, and any snapshot a lookup resumed from since the tip was written, which a @@ -1648,7 +1663,8 @@ It does not give bit-exactness. The fp8 GEMM's split-K finisher sums in index or repeats, but the split count is chosen from `M`, so a row computed at `M = 1` and at `M = 8` can differ in the last bits. A speculative decode can therefore diverge from a non-speculative one on a near-tie, and a request at a different batch position can take a different reduction order. Nothing -pins it (§19.7). +pins it (§19.7). A prefix hit is held to the cold run's chunks (§7.3, exact resume), so on an idle +server it repeats the cold run's output. --- diff --git a/tests/config_test.cpp b/tests/config_test.cpp index de575c83..c1f88a8e 100644 --- a/tests/config_test.cpp +++ b/tests/config_test.cpp @@ -437,6 +437,7 @@ const std::map>& legal_values() { { "--placement", { "all_vram" } }, { "--checkpoint-interval", { "256" } }, { "--prefill-span", { "2" } }, { "--checkpoint-slots", { "4" } }, { "--checkpoint-policy", { "tip-only" } }, + { "--prefix-resume", { "nearest" } }, { "--num-speculative-tokens", { "2" } }, { "--draft-window", { "fixed" } }, { "--draft-short-from", { "4" } }, { "--draft-coupling", { "on" } }, { "--host", { "127.0.0.1" } }, { "--port", { "8001" } }, { "--api-key", { "k" } }, @@ -865,6 +866,20 @@ TEST(expert_stats_is_off_until_it_names_a_file) { CHECK(parse_fresh({ "--expert-stats" }) < 0); } +/* A prefix hit resumes on the cold run's chunk grid unless the operator trades that for a shorter + * re-prefill; any other word is refused. */ +TEST(prefix_resume_is_exact_unless_nearest_is_asked_for) { + Config d; + CHECK_EQ(parse({}, &d), RAD_OK); + CHECK(d.prefix_exact); + Config c; + CHECK_EQ(parse({ "--prefix-resume", "nearest" }, &c), RAD_OK); + CHECK(!c.prefix_exact); + CHECK_EQ(parse({ "--prefix-resume", "exact" }, &c), RAD_OK); + CHECK(c.prefix_exact); + CHECK_EQ(parse({ "--prefix-resume", "deepest" }, &c), RAD_E_INVAL); +} + /* --checkpoint-slots is auto by default, resolved by the engine once a snapshot's size is known; * a count is taken as given, 0 included, and the report shows which. */ TEST(the_checkpoint_slots_are_auto_or_a_count) { diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index 78586135..5578f518 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -166,6 +166,10 @@ struct Fixture { cfg.max_ctx = max_ctx; cfg.checkpoint_interval = 256; cfg.prefix_cache = true; + /* The tests below were written for the nearest resume rule (a tail snapshot at the last + * quantum boundary, a hit at any snapshot or block); the exact rule's own tests set + * prefix_exact (--prefix-resume exact, the default). */ + cfg.prefix_exact = false; /* Config::n_spec defaults to -1 (`auto`), which engine_bringup resolves; this fixture * skips that, and DraftController::configure refuses a negative depth. Speculation tests * set their own depth. */ @@ -795,6 +799,248 @@ TEST(a_span_needs_an_interval_grid) { CHECK_EQ((int64_t)f.sch.plan().e.size(), 2ll); } +/* ================================================================== exact resume */ +/* --prefix-resume exact (the default): a hit resumes only where an idle server's cold prefill of + * the same prompt starts a chunk, and a prompt's tail snapshot is where its last chunk starts. A + * kernel may round a row differently at another chunk length (spec §17: the split-K count is + * chosen from M), so a hit is bit-identical to a cold run only when it recomputes the cold run's + * own chunks. */ + +/* The chunk ends and checkpoints an idle server plans for an `L`-token prompt from `from`. */ +struct Cut { std::vector ends, ckpts; }; +static Cut cut_from(const Scheduler& s, int64_t from, int64_t L, int64_t budget) { + Cut c; + for (int64_t pos = from; pos < L;) { + int64_t ck = -1; + const int64_t n = s.plan_chunk(pos, L, budget, &ck); + if (n <= 0) break; + pos += n; + c.ends.push_back(pos); + if (ck > 0) c.ckpts.push_back(ck); + } + return c; +} +static std::vector ends_after(const Cut& c, int64_t from) { + std::vector v; + for (int64_t e : c.ends) if (e > from) v.push_back(e); + return v; +} + +/* Which geometry: 0 the GDN hybrid at interval 256 / budget 512 (chunks split at the interval); + * 1 interval 1024 past a 512 budget; 2 a span of 2; 3 a sliding-window model with periodic + * snapshots; 4 the same, tip-only (no interval split); 5 full attention alone (no snapshots). */ +static void exact_fixture(Fixture& f, int kind) { + const bool window = kind == 3 || kind == 4, attn_only = kind == 5; + f.build(4096, 64, 512, 8192, window, !attn_only); + if (window) { + /* As the window tests above: drop the GDN hybrid's linear and conv groups and its scan. */ + f.prog.kv_groups.erase(f.prog.kv_groups.begin() + 1, f.prog.kv_groups.begin() + 3); + f.prog.ops.resize(1); + f.prog.buffers.resize(1); + f.kv.setup(f.prog.kv_groups, f.cfg.max_ctx, 4096, 64); + f.pc.groups = { 0 }; + if (kind == 4) f.cfg.checkpoint_policy = "tip-only"; + } + if (kind == 1) f.cfg.checkpoint_interval = 1024; + if (kind == 2) f.cfg.prefill_span = 2; + f.cfg.prefix_exact = true; +} + +TEST(exact_resume_grid_is_the_chunk_an_idle_prefill_cuts) { + struct Want { int kind; int64_t interval, grid, origin; }; + for (const Want w : { Want{ 0, 256, 256, 0 }, Want{ 1, 1024, 512, 0 }, Want{ 2, 256, 512, 256 }, + Want{ 3, 256, 256, 0 }, Want{ 4, 256, 512, 0 }, Want{ 5, 0, 512, 0 } }) { + Fixture f; + exact_fixture(f, w.kind); + REQUIRE_EQ(f.start(), RAD_OK); + const ChunkGeometry& g = f.sch.geometry(); + CHECK(g.exact); + CHECK_EQ(g.checkpoint_interval, w.interval); + CHECK_EQ(g.grid, w.grid); + CHECK_EQ(g.grid_origin, w.origin); + } + /* Nearest, or no prefix cache: no grid, every position its own floor. */ + for (int off = 0; off < 2; ++off) { + Fixture f; + exact_fixture(f, 0); + if (off) f.cfg.prefix_cache = false; else f.cfg.prefix_exact = false; + REQUIRE_EQ(f.start(), RAD_OK); + CHECK(!f.sch.geometry().exact); + CHECK_EQ(f.sch.geometry().grid_floor(300), 300); + } + Fixture f; + exact_fixture(f, 2); + REQUIRE_EQ(f.start(), RAD_OK); + const ChunkGeometry& g = f.sch.geometry(); /* 0, 256, 768, 1280, ... */ + CHECK_EQ(g.grid_floor(255), 0); + CHECK_EQ(g.grid_floor(256), 256); + CHECK_EQ(g.grid_floor(767), 256); + CHECK_EQ(g.grid_floor(1000), 768); + CHECK(!g.on_grid(512)); +} + +/* An interval past the budget that is not a multiple of the budget's chunk would put the chunk + * after every checkpoint off the cold run's grid: exact rounds it up, with a warning that names + * both ways out; nearest keeps it. */ +TEST(exact_rounds_an_interval_off_the_chunk_up_to_a_multiple_of_it) { + for (int exact = 0; exact < 2; ++exact) { + Fixture f; + f.build(); /* quantum 64 */ + f.cfg.checkpoint_interval = 768; /* past the 512 budget, not a multiple of it */ + f.cfg.prefix_exact = exact != 0; + log_set_level(Log::Error); + REQUIRE_EQ(f.start(), RAD_OK); + CHECK_EQ(f.sch.geometry().checkpoint_interval, exact ? 1024 : 768); + if (exact) CHECK_EQ(f.sch.geometry().grid, 512); + } + /* A budget off the quantum chunks at the quantum below it: 500 -> 448, and the interval goes + * to the next multiple of 448. */ + Fixture f; + f.build(4096, 64, /*max_tok=*/500); + f.cfg.checkpoint_interval = 1024; + f.cfg.prefix_exact = true; + log_set_level(Log::Error); + REQUIRE_EQ(f.start(), RAD_OK); + CHECK_EQ(f.sch.geometry().checkpoint_interval, 1344); + CHECK_EQ(f.sch.geometry().grid, 448); + int64_t ck = -1; + CHECK_EQ(f.sch.plan_chunk(0, 5000, 500, &ck), 448); + CHECK_EQ(f.sch.plan_chunk(896, 5000, 500, &ck), 448); + CHECK_EQ(ck, 1344); +} + +/* The tail snapshot is where the prompt's last chunk starts, a boundary an idle chunk already + * ends on: no extra step, and an exact repeat re-prefills that last chunk whole. */ +TEST(an_exact_tail_snapshot_is_where_the_last_chunk_starts) { + Fixture f; + exact_fixture(f, 1); /* interval 1024, chunks of 512 */ + REQUIRE_EQ(f.start(), RAD_OK); + Cut c = cut_from(f.sch, 0, 1800, 512); + CHECK((c.ends == std::vector{ 512, 1024, 1536, 1800 })); + CHECK((c.ckpts == std::vector{ 1024, 1536 })); + /* Its last chunk starting on the interval: that checkpoint is the tail's. */ + c = cut_from(f.sch, 0, 1100, 512); + CHECK((c.ends == std::vector{ 512, 1024, 1100 })); + CHECK((c.ckpts == std::vector{ 1024 })); + /* One ending on the grid: the last chunk is [1536, 2048), and its end is an interval. */ + c = cut_from(f.sch, 0, 2048, 512); + CHECK((c.ckpts == std::vector{ 1024, 1536, 2048 })); + /* Inside the first interval nothing (as before, cheap to prefill again). */ + c = cut_from(f.sch, 0, 900, 512); + CHECK(c.ckpts.empty()); + /* A step sharing its budget may straddle the tail: split there, the snapshot written. */ + int64_t ck = -1; + CHECK_EQ(f.sch.plan_chunk(1400, 1800, 512, &ck), 136); + CHECK_EQ(ck, 1536); + /* A budget short of a quantum boundary past it leaves it for the next chunk. */ + CHECK_EQ(f.sch.plan_chunk(1024, 1800, 100, &ck), 64); + CHECK_EQ(ck, -1); + + /* Nearest cuts the same prompt's last chunk at its last quantum boundary instead. */ + Fixture n; + n.build(); + n.cfg.checkpoint_interval = 1024; + REQUIRE_EQ(n.start(), RAD_OK); + c = cut_from(n.sch, 0, 1800, 512); + CHECK((c.ends == std::vector{ 512, 1024, 1536, 1792, 1800 })); + CHECK((c.ckpts == std::vector{ 1024, 1792 })); +} + +/* The property itself, over every geometry and many prompt lengths: every checkpoint is on the + * grid and is a chunk start of the cold run of the prompt that wrote it and of any longer prompt + * it prefixes (an agent's next turn), and from it the hit cuts exactly the cold run's chunks. */ +TEST(an_exact_hit_from_any_checkpoint_recomputes_the_cold_runs_own_chunks) { + for (int kind = 0; kind < 6; ++kind) { + Fixture f; + exact_fixture(f, kind); + REQUIRE_EQ(f.start(), RAD_OK); + const ChunkGeometry& g = f.sch.geometry(); + int checked = 0; + for (int64_t L = 100; L <= 3000; L += 37) { + const Cut cold = cut_from(f.sch, 0, L, 512); + for (int64_t c : cold.ckpts) { + CHECK(g.on_grid(c)); + if (c >= L) continue; + CHECK(std::find(cold.ends.begin(), cold.ends.end(), c) != cold.ends.end()); + CHECK(cut_from(f.sch, c, L, 512).ends == ends_after(cold, c)); + for (int64_t L2 : { L + 1, L + 300, L + 1500 }) { + const Cut cold2 = cut_from(f.sch, 0, L2, 512); + CHECK(std::find(cold2.ends.begin(), cold2.ends.end(), c) != cold2.ends.end()); + CHECK(cut_from(f.sch, c, L2, 512).ends == ends_after(cold2, c)); + } + ++checked; + } + } + CHECK(kind == 5 ? checked == 0 : checked > 20); + } + /* What nearest gives up: its tail snapshot at a 1000-token prompt's last quantum boundary + * (960) is no chunk start of the 1500-token turn after it, which a cold run cuts at 768 and + * 1024, so a hit there recomputes [960, 1024) as a chunk of its own. */ + Fixture n; + n.build(); + REQUIRE_EQ(n.start(), RAD_OK); + const Cut c1000 = cut_from(n.sch, 0, 1000, 512); + CHECK(std::find(c1000.ckpts.begin(), c1000.ckpts.end(), 960) != c1000.ckpts.end()); + const Cut c1500 = cut_from(n.sch, 0, 1500, 512); + CHECK(std::find(c1500.ends.begin(), c1500.ends.end(), 960) == c1500.ends.end()); + CHECK(std::find(c1500.ends.begin(), c1500.ends.end(), 768) != c1500.ends.end()); + CHECK_EQ(cut_from(n.sch, 960, 1500, 512).ends.front(), 1024); +} + +/* At admission: a hit at a snapshot resumes there (plan_chunk put it on the grid); a hit with no + * snapshot to resume from (full attention alone) steps back to the grid, the blocks above it + * left to the cache and recomputed in the cold run's chunk. */ +TEST(an_exact_hit_steps_back_to_the_grid_and_prefills_the_cold_chunks) { + for (int exact = 0; exact < 2; ++exact) { + Fixture f; + exact_fixture(f, 5); /* chunks of 512, no snapshots */ + f.cfg.prefix_exact = exact != 0; + REQUIRE_EQ(f.start(), RAD_OK); + f.pc.seed(784); /* 49 blocks */ + const uint64_t a = f.submit(1300, 8); + const RadBatch* b = f.sch.step(); + REQUIRE(b != nullptr); + CHECK_EQ(f.sch.find(a)->n_computed, exact ? 512 : 784); + CHECK_EQ(b->ctx_lens[0], exact ? 512 : 784); + CHECK_EQ(b->n_tok, 512); /* [512, 1024) as the cold run, or [784, 1296) */ + CHECK_EQ((int)f.kv.block_table(a, 0).size(), exact ? 64 : 81); + CHECK_EQ(f.sch.metrics().hit_cut_tokens, exact ? 272 : 0); + } + /* With snapshots the hit is at one: kept as is, restored from its slot. */ + Fixture f; + exact_fixture(f, 1); + REQUIRE_EQ(f.start(), RAD_OK); + f.pc.seed(1600); + f.pc.lin = 1536; /* a tail snapshot, on the 512 grid */ + f.pc.src = 3; + const uint64_t a = f.submit(1800, 8); + const RadBatch* b = f.sch.step(); + REQUIRE(b != nullptr); + CHECK_EQ(f.sch.find(a)->n_computed, 1536); + CHECK_EQ(b->n_tok, 264); /* the cold run's last chunk, whole */ + CHECK_EQ(f.sch.plan().e[0].ckpt_restore, 3); +} + +/* A cold prompt at the scheduler: the last chunk is not split at the end, and an exact repeat's + * hit at the tail snapshot is that chunk. */ +TEST(an_exact_cold_prefill_keeps_its_last_chunk_whole) { + Fixture f; + exact_fixture(f, 0); /* interval 256, chunks of 256 */ + REQUIRE_EQ(f.start(), RAD_OK); + f.submit(1000, 1); + std::vector toks, ckpts; + for (int i = 0; i < 8; ++i) { + const RadBatch* b = f.sch.step(); + if (!b) break; + toks.push_back(b->n_tok); + for (int k = 0; k < b->n_checkpoints; ++k) + ckpts.push_back(b->ctx_lens[0] + b->checkpoint_tok[k] + 1); + f.commit_plain(); + } + CHECK((toks == std::vector{ 256, 256, 256, 232 })); + CHECK((ckpts == std::vector{ 256, 512, 768 })); +} + TEST(a_chunk_ending_on_a_checkpoint_carries_it_into_the_batch) { Fixture f; f.build();