From b8bca7885a5a118bfa65a62dde74e0a6e2d4e42e Mon Sep 17 00:00:00 2001 From: Code000 Date: Tue, 17 Nov 2026 12:52:23 +0100 Subject: [PATCH] sched: --draft-suffix on, SuffixDecoding as a step selector on the MTP chain After each commit the scheduler looks in the sequence's own prompt and output for the latest earlier occurrence of its last --draft-suffix-min-match tokens; the next step then verifies what followed it (up to --draft-suffix-max rows, cut where the product of the follower frequencies falls under --draft-suffix-min-score) in place of the head's draft. The verify window becomes the larger of the two while the head keeps its own rounds. A sequence whose history ended in a recurring pattern is not issued ahead, since the step is built after the commit where the lookup can read the committed end. It works with the fixed MTP chain, with --draft-depth adaptive and with --draft-verify traversal. A suffix chain carries no coupled row (Request::draft_suffix): the sampler binds none of the head's staged states to its rows, so each row is the target's plain draw and the rows are leaves of the traversal walk; mtp_rrs_test checks the law with a negative control that fails. --draft-verify block is refused. The window is at most 7 rows on Flash-Next (the delta-net fold's register window). On Flash-Next IQR-V4 (TP2) on our branch, window 7 on chain 3 with coupling: +1.4% overall, +2.9% on repetitive tasks, +11% on quoting, free chat unchanged; beside adaptive depth +0.2% [-1.0, +1.5] overall, code +1.0%. Off by default. Co-Authored-By: Claude Opus 5.5 --- core/config.cpp | 37 +++++ core/engine_bringup.cpp | 38 +++++ core/engine_draft.cpp | 5 +- core/rad_core.h | 19 +++ core/sample/sampler.cpp | 6 +- core/sched/batch.h | 4 + core/sched/draft.cpp | 4 +- core/sched/draft.h | 7 +- core/sched/metrics.h | 7 + core/sched/scheduler.cpp | 66 +++++++- core/sched/scheduler.h | 13 ++ core/sched/suffix.h | 172 ++++++++++++++++++++ core/server/adapters.h | 2 + core/server/iface.h | 6 + core/server/metrics.cpp | 14 ++ core/server/metrics.h | 1 + docs/GUIDE.md | 56 +++++++ tests/advance_test.cpp | 62 ++++++++ tests/arch_test.cpp | 51 ++++++ tests/config_test.cpp | 41 +++++ tests/mtp_rrs_test.cpp | 181 +++++++++++++++++++++ tests/sched_test.cpp | 329 +++++++++++++++++++++++++++++++++++++++ 22 files changed, 1112 insertions(+), 9 deletions(-) create mode 100644 core/sched/suffix.h diff --git a/core/config.cpp b/core/config.cpp index d5413011..f31902ba 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -238,6 +238,18 @@ static const Flag g_flags[] = { "0 or 1 (default 1: the host decides while the next round runs)" }, { "--draft-depth-stat", "S", "--draft-depth adaptive: top (default, each round's largest\n" "probability) | path (the probability of the token it drew)" }, + { "--draft-suffix", "MODE", "off (default) | on -- SuffixDecoding as a step selector on a serial head's chain: when the\n" + "sequence's last --draft-suffix-min-match tokens occurred earlier in\n" + "its own prompt ++ output, a host-built step verifies the earlier\n" + "continuation (a chain, up to --draft-suffix-max rows) instead of the\n" + "head's draft. Lossless; works beside the fixed chain, --draft-verify\n" + "traversal and --draft-depth adaptive, not --draft-verify block" }, + { "--draft-suffix-min-match", "L", "shortest suffix match that selects a suffix step (default 6)" }, + { "--draft-suffix-max", "N", "most rows of a suffix step (default 7; the verify window becomes\n" + "max(--num-speculative-tokens, N), the head still drafts its own)" }, + { "--draft-suffix-min-score", "D", "cut the suffix chain where its path score (the product of the\n" + "follower frequencies along it, SuffixDecoding's D) falls under D\n" + "(default 0.3)" }, { "--draft-model", "PATH", "NOT IMPLEMENTED -- merge the drafter at convert time" }, { "--host", "ADDR", "listen address" }, @@ -970,6 +982,27 @@ int config_parse(int argc, char** argv, Config* c) { return RAD_E_INVAL; } } + else if (S("--draft-suffix")) { + if (!(v = need(i))) return RAD_E_INVAL; + if (!std::strcmp(v, "off")) c->draft_suffix = false; + else if (!std::strcmp(v, "on")) c->draft_suffix = true; + else { + RAD_ERR("--draft-suffix takes off or on, not '%s'", v); + return RAD_E_INVAL; + } + } + else if (S("--draft-suffix-min-match")) { if (!num(1, 12, &c->draft_suffix_min_match)) return RAD_E_INVAL; } + else if (S("--draft-suffix-max")) { if (!num(1, 32, &c->draft_suffix_max)) return RAD_E_INVAL; } + else if (S("--draft-suffix-min-score")) { + if (!(v = need(i))) return RAD_E_INVAL; + char* end = nullptr; + const double d = std::strtod(v, &end); + if (end == v || *end || !(d >= 0.0 && d <= 1.0)) { + RAD_ERR("--draft-suffix-min-score takes a number in [0, 1], not '%s'", v); + return RAD_E_INVAL; + } + c->draft_suffix_min_score = (float)d; + } else if (S("--draft-model")) { /* Refused, not ignored: separate draft models are not supported (spec §10), and the * drafter comes from the container (rad-convert --draft-model merges one in; an MTP @@ -1649,6 +1682,10 @@ const ShowRow kShow[] = { { "--draft-depth-stop", [](const Config& c) { return fnum(c.draft_depth_stop); } }, { "--draft-depth-lag", [](const Config& c) { return num(c.draft_depth_lag); } }, { "--draft-depth-stat", [](const Config& c) { return std::string(c.draft_depth_stat == 1 ? "path" : "top"); } }, + { "--draft-suffix", [](const Config& c) { return onoff(c.draft_suffix); } }, + { "--draft-suffix-min-match", [](const Config& c) { return num(c.draft_suffix_min_match); } }, + { "--draft-suffix-max", [](const Config& c) { return num(c.draft_suffix_max); } }, + { "--draft-suffix-min-score", [](const Config& c) { return fnum(c.draft_suffix_min_score); } }, { "--draft-model", [](const Config&) { return std::string("not implemented (the container's own drafter)"); } }, { "--host", [](const Config& c) { return c.host; } }, { "--port", [](const Config& c) { return num(c.port); } }, diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 2c15fa46..cf4e76c7 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -1306,6 +1306,44 @@ int Engine::declare() { decide("draft trees", "asked", why); } } + /* --draft-suffix: SuffixDecoding's selector (core/sched/suffix.h). A suffix step verifies up to + * `draft_suffix_max` rows of the sequence's own history while the head still drafts its own + * `n_spec` rounds, so the verify window every consumer of `n_spec` sees (buffers, rings, the + * scheduler's window) becomes the larger of the two and the head's rounds are kept apart in + * `n_spec_head`. A serial head's chain only: a block drafter's block is fixed. It works with + * the fixed chain, with --draft-depth adaptive (whose depth stays within the head's rounds) + * and with the traversal verify (a suffix row binds no coupled state, so it is a leaf of the + * walk); the block verify decides a head chain as a whole and is refused. */ + cfg_.n_spec_head = 0; + if (cfg_.draft_suffix) { + RadArchProbe pb{}; + (void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs); + const char* bad = nullptr; + if (cfg_.n_spec <= 0) bad = "speculation is off (this container carries no draft head)"; + else if (draft_tree_) bad = "it needs the head's chain, not a block drafter's tree"; + else if (pb.draft_depth_fixed) bad = "this drafter is a block drafter, not a serial head"; + else if (cfg_.draft_window == DraftWindow::Adaptive) + bad = "it needs the fixed window (--draft-window fixed)"; + else if (cfg_.draft_verify_block) bad = "it cannot be combined with --draft-verify block " + "(a suffix chain is no block; --draft-verify token | traversal)"; + if (bad) { + RAD_ERR("--draft-suffix on: %s", bad); + return RAD_E_UNSUPPORTED; + } + const int window = std::max(cfg_.n_spec, cfg_.draft_suffix_max); + if (window > (int)RAD_SCHED_MAX_SPEC) { + RAD_ERR("--draft-suffix-max %d is past the largest verify window (%d)", cfg_.draft_suffix_max, + (int)RAD_SCHED_MAX_SPEC); + return RAD_E_INVAL; + } + cfg_.n_spec_head = cfg_.n_spec; + cfg_.n_spec = window; + RAD_INFO("draft suffix: on -- a host-built step verifies up to %d row(s) of the sequence's own " + "history when its last %d token(s) recur (path score >= %.2f); the head drafts %d " + "round(s), the verify window is %d", cfg_.draft_suffix_max, cfg_.draft_suffix_min_match, + (double)cfg_.draft_suffix_min_score, cfg_.n_spec_head, window); + decide("draft suffix", "on", "--draft-suffix on"); + } /* The audio encoder's pass: the plugin's longest clip, when the model file carries an audio * encoder (`radiance.encoder` names one) and the deployment is not text-only. */ if (cfg_.mm_audio_frames < 0) { diff --git a/core/engine_draft.cpp b/core/engine_draft.cpp index 963f0013..c000feb8 100644 --- a/core/engine_draft.cpp +++ b/core/engine_draft.cpp @@ -138,6 +138,9 @@ int Engine::step_state_init() { } depth_cfg_.on = true; depth_cfg_.max = (int)std::min(drafter_.depth, couple_planes_); + /* --draft-suffix widens the verify window (and the depth the plugin declares) past the head's + * own rounds: the chain never goes deeper than the head's num-speculative-tokens. */ + if (cfg_.n_spec_head > 0) depth_cfg_.max = std::min(depth_cfg_.max, cfg_.n_spec_head); if (cfg_.draft_depth_max > 0) depth_cfg_.max = std::min(depth_cfg_.max, cfg_.draft_depth_max); depth_cfg_.max = std::min(depth_cfg_.max, (int)RAD_MTP_COUPLE_MAX_ROUNDS); depth_cfg_.min = std::min(std::max(cfg_.draft_depth_min, 1), depth_cfg_.max); @@ -613,7 +616,7 @@ int Engine::finish_serial_drafter(const StepOut& so) { for (size_t i = 0; i < plan.e.size(); ++i) { const StepEntry& e = plan.e[i]; if (so.first_row[i] < 0 || e.n_spec <= 0 || e.n_spec > (int)RAD_MTP_COUPLE_MAX_ROUNDS || - e.card < 0 || (size_t)e.card >= couple_by_card_.size()) + e.suffix || e.card < 0 || (size_t)e.card >= couple_by_card_.size()) continue; const RadMtpCoupleDraw& d = couple_by_card_[(size_t)e.card]; if (d.seq != e.seq || d.mode != 1) continue; diff --git a/core/rad_core.h b/core/rad_core.h index 15e27373..f3d9c037 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -743,6 +743,10 @@ struct Request { /* A tree drafter's parents for `draft` (StepEntry::draft_parent): draft[j]'s parent node, * 0 the bonus token. Null for a chain. The sampler reads each row's ancestors from it. */ const int32_t* draft_parent = nullptr; + /* The draft is a SuffixDecoding chain (--draft-suffix, sched/suffix.h): copied from the + * sequence's own history, not drawn from the head's law. The coupled sampler binds no state to + * its rows, whatever stale states the head's own draft for the same positions left. */ + bool draft_suffix = false; int32_t n_accepted = 0; /* from the previous verify */ /* Whether this request may be speculated on. Written by the engine after every step, read by @@ -1062,6 +1066,21 @@ struct Config { int draft_depth_lag = 1; int draft_depth_stat = 0; double draft_depth_stop = 0.85; + /* --draft-suffix on (core/sched/suffix.h): SuffixDecoding as a step SELECTOR on a serial head's + * chain. On a host-built step, when the sequence's own history (prompt ++ output) ends in a + * pattern of at least `draft_suffix_min_match` tokens that occurred before, the step verifies + * that earlier occurrence's continuation (a chain of at most `draft_suffix_max` rows (7: the + * delta-net fold's register window serves 8 query rows, so a Flash-Next verify window past 7 + * drafts leaves its kernels unsupported), cut where the path score falls under + * `draft_suffix_min_score`) in place of the head's draft. Lossless: the proposal's rows are never + * coupled. Off (default) is the engine as it was, bit for bit. */ + bool draft_suffix = false; + int draft_suffix_min_match = 6; + int draft_suffix_max = 7; + float draft_suffix_min_score = 0.3f; + /* The head's own rounds when --draft-suffix raised `n_spec` (the verify window) past them; 0 = + * `n_spec` (set by the engine, not a flag). */ + int n_spec_head = 0; /* ---------------- KL DIVERGENCE AGAINST A REFERENCE (core/kld.h) ---------------- * diff --git a/core/sample/sampler.cpp b/core/sample/sampler.cpp index 54baac2d..a0e7ca4e 100644 --- a/core/sample/sampler.cpp +++ b/core/sample/sampler.cpp @@ -859,8 +859,10 @@ int Sampler::build_step(const std::vector& reqs, int64_t step) { if (couple_) { couple_stage_[row] = RadMtpCoupleState{}; const auto sit = seqs_.find(r->id); - if (sit != seqs_.end() && !sp.greedy() && r->draft && k + 1 < n_pos && - k < sit->second.couple_n) { + /* A suffix chain (Request::draft_suffix) was not drawn from the head's law: no row of + * it binds a state, so each is the target's plain draw. */ + if (sit != seqs_.end() && !sp.greedy() && r->draft && !r->draft_suffix && + k + 1 < n_pos && k < sit->second.couple_n) { const RadMtpCoupleState& c = sit->second.couple[k]; /* Same request and seed, this row's round, position and proposed token * (rad_mtp_couple_binds); anything else is a stale state from another step. */ diff --git a/core/sched/batch.h b/core/sched/batch.h index e3278de1..2005e1b7 100644 --- a/core/sched/batch.h +++ b/core/sched/batch.h @@ -62,6 +62,10 @@ struct StepEntry { * acceptance but not the adaptive window's estimate of the draft head (DraftController, * draft.h). */ bool ngram = false; + /* The drafts are a SuffixDecoding proposal (--draft-suffix, suffix.h): a chain of the + * sequence's own history, verified with no coupled row (Request::draft_suffix). Implies + * `ngram`. */ + bool suffix = false; /* Device row: the card overwrites its tokens, positions, rollback count and slots from the * StepSlot before the pass runs (advance.h); `ctx_len` is then only an upper bound for the * host-side ceilings. dev_tok/dev_out/dev_aux are advance.h's row descriptor: the verify diff --git a/core/sched/draft.cpp b/core/sched/draft.cpp index 85340830..f4d323be 100644 --- a/core/sched/draft.cpp +++ b/core/sched/draft.cpp @@ -128,14 +128,14 @@ double DraftController::yield(const DraftAdapt& s, int d) const { } int DraftController::window_of(const DraftAdapt& s) const { - if (!adapt_) return p_.max_depth; + if (!adapt_) return next_depth(); if (s.depth <= 0) return 0; const int D = step_d_ > 0 ? step_d_ : p_.max_depth; return s.depth < D ? s.depth : D; } int DraftController::window_for(DraftAdapt& s) const { - if (!adapt_) return p_.max_depth; + if (!adapt_) return next_depth(); if (s.depth <= 0) start(s); return window_of(s); } diff --git a/core/sched/draft.h b/core/sched/draft.h index 96437fae..28a8936d 100644 --- a/core/sched/draft.h +++ b/core/sched/draft.h @@ -60,6 +60,9 @@ class DraftController { public: struct Params { int max_depth = 0; /* the deployment's window; 0 disables speculation entirely */ + /* The head's own rounds when the window is wider than they are (--draft-suffix: a suffix + * step verifies more rows than the head drafts); 0 = max_depth. */ + int head_depth = 0; /* The adaptive policy: `--draft-window adaptive` with a serial drafter, decided by * Scheduler::init. Off, the depth is max_depth. */ bool adapt = false; @@ -114,7 +117,7 @@ public: /* The draft depth for the next step; 0 means do not speculate. Constant: under the adaptive * policy it is the ceiling, and window_for() is the window. */ - int next_depth() const { return p_.max_depth; } + int next_depth() const { return p_.head_depth > 0 ? p_.head_depth : p_.max_depth; } /* ---------------------------------------------------------- the adaptive policy */ bool adaptive() const { return adapt_; } @@ -146,7 +149,7 @@ public: /* The deepest window a step at depth D carries: D capped at the deepest stop it was chosen * over; the ceiling before the first choice or with the policy off. Proposals from outside * the head (prompt lookup) are held to it, so they add no deeper pass shape. */ - int step_window() const { return adapt_ && step_w_ > 0 ? step_w_ : p_.max_depth; } + int step_window() const { return adapt_ && step_w_ > 0 ? step_w_ : next_depth(); } /* T(R): a drafting decode step of `q_rows` query rows (every sequence's verified token and * its drafts) took `ms` since the end of the previous step, the head's rounds included. Fed diff --git a/core/sched/metrics.h b/core/sched/metrics.h index f0316709..e2e14cc6 100644 --- a/core/sched/metrics.h +++ b/core/sched/metrics.h @@ -164,6 +164,13 @@ struct SchedMetrics { int64_t lookup_held = 0; int64_t lookup_held_drafts = 0; int64_t lookup_held_hits = 0; + /* --draft-suffix (suffix.h): verifies that carried a suffix chain, the rows they carried and the + * drafts accepted; decode steps not issued ahead because the sequence was in a recurring + * pattern (where the lookup could run after the commit instead). */ + int64_t suffix_steps = 0; + int64_t suffix_rows = 0; + int64_t suffix_accepted = 0; + int64_t suffix_held_ahead = 0; }; diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index d5e9a0b7..5eecc73d 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -215,6 +215,7 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac DraftController::Params dp; dp.max_depth = cfg.n_spec; + dp.head_depth = cfg.n_spec_head > 0 && cfg.n_spec_head < cfg.n_spec ? cfg.n_spec_head : 0; /* The adaptive window (draft.h) prices a draft by the measured cost of the step it adds to. * A block drafter proposes its block in one pass, but each verified draft is still a verify * row, which is not free on a MoE that reads each row's routed experts. So it takes the same @@ -749,6 +750,7 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool if (cfg_.prefix_cache && pc_) pc_->release(*s.req); /* Prompt lookup's index is this text's alone. */ s.ngram_ix.reset(); + s.suffix_ix.reset(); if (lookup_gate_on_ && s.look.started && s.look.proposed > 0) RAD_DEBUG("prompt lookup: request %llu made %lld proposals, held back %lld (%lld drafts, " "%lld of those scored came true); a %d-draft verify costs %.2f plain steps", @@ -1088,6 +1090,24 @@ int Scheduler::draft_ngram(SchedReq& s, int depth, int* match) const { LookupGate::kLongMatch); } +/* --draft-suffix: SuffixDecoding's chain for the sequence's committed history (suffix.h). */ +int Scheduler::suffix_propose(SchedReq& s, int32_t* out, int* match) { + if (match) *match = -1; + if (!s.req) return 0; + const Request& r = *s.req; + TokenSeq seq; + seq.a = r.prompt.data(); + seq.na = (int64_t)r.prompt.size(); + seq.b = r.output.data(); + seq.nb = (int64_t)r.output.size(); + const SuffixIndex::Out o = + s.suffix_ix.propose(seq, r.id, cfg_.draft_suffix_min_match, + std::min(cfg_.draft_suffix_max, (int)RAD_SCHED_MAX_SPEC), + cfg_.draft_suffix_min_score, out); + if (match && o.n > 0) *match = o.match; + return o.n; +} + /* ------------------------------------------------------------------ chunking */ int64_t Scheduler::chunk_end(const Request& r, int64_t n_target) const { if (rswa_windows_.empty() || !kv_->has_runtime_window(r.id)) return n_target; @@ -2031,7 +2051,8 @@ const RadBatch* Scheduler::step() { const int64_t Q = std::max(geo_.quantum, 1); /* An eighth of this step's budget, which under a span is shared_tok for a shared step. */ const int64_t share_tok = std::max(Q, budget / 8 / Q * Q); - const int64_t dec_row_tok = 1 + std::max(depth, draft_.step_window()); + const int64_t dec_row_tok = 1 + std::max({ (int64_t)depth, (int64_t)draft_.step_window(), + cfg_.draft_suffix ? (int64_t)cfg_.draft_suffix_max : 0 }); int64_t behind_dec = 0, behind_pf = 0; if (share_step) { for (int32_t slot : running_) { @@ -2120,7 +2141,24 @@ const RadBatch* Scheduler::step() { * drafts this step and no deeper. */ const int cap = draft_.adaptive() ? draft_cap(s) : depth; bool ngram = false; - if (!r.may_speculate) s.n_draft = 0; + bool suffix = false; + /* --draft-suffix: a sequence whose own history ends in a recurring pattern verifies that + * pattern's earlier continuation in place of the head's draft (the head still drafted + * behind the step before, so a miss costs nothing but that draft). A function of the + * committed text alone, so the choice never reads a draw; the rows it verifies carry no + * coupled state (Request::draft_suffix below), so each is the target's plain draw. */ + if (cfg_.draft_suffix && r.may_speculate) { + int32_t buf[RAD_SCHED_MAX_SPEC]; + const int np = suffix_propose(s, buf); + if (np > 0) { + std::copy(buf, buf + np, s.draft); + s.n_draft = np; + s.draft_tree = false; + suffix = true; + } + } + if (suffix) ngram = true; + else if (!r.may_speculate) s.n_draft = 0; else if (s.n_draft == 0) { /* As the only drafter under the adaptive window, the lookup is the head: its * proposal is cut to the sequence's own window. */ @@ -2148,6 +2186,7 @@ const RadBatch* Scheduler::step() { } if (!ngram && s.n_draft > cap) s.n_draft = cap; s.draft_ngram = ngram; + s.draft_suffix = suffix; /* No verified position at or past the context end: nothing past ctx_limit_ - 1 has a * rotary row or block-table column. commit() finishes a sequence before it reaches * the limit, so the one token itself always fits. */ @@ -2227,6 +2266,11 @@ const RadBatch* Scheduler::step() { e.n_draft = s.n_draft; e.is_prefill = prefill; e.ngram = !prefill && s.draft_ngram && s.n_draft > 0; + e.suffix = e.ngram && s.draft_suffix; + /* A suffix chain has no model node: the coupled sampler binds no state to any row of it + * (core/sample/sampler.cpp), whatever stale state the head's own draft for these positions + * left. */ + r.draft_suffix = e.suffix; /* A tree drafter's parents, unless prompt lookup replaced its proposal with a chain. */ e.draft_parent = (!prefill && s.draft_tree && !e.ngram) ? s.draft_par : nullptr; r.draft_parent = e.n_spec ? e.draft_parent : nullptr; @@ -2676,6 +2720,10 @@ const RadBatch* Scheduler::step_next_locked() { * that cannot rewind decides at commit whether the next step may speculate; one that can, * or no grammar, keeps its answer. */ if (!e.produces_token || !r.speculation_fixed) return nullptr; + /* --draft-suffix: a sequence whose history ended in a recurring pattern at the last commit + * is likely to continue it; its next step is built after the commit, where the lookup can + * read the committed end (a step issued ahead is made on the card from the head's drafts). */ + if (cfg_.draft_suffix && s.suffix_hot) { ++m_.suffix_held_ahead; return nullptr; } /* A SCORED row (Request::token_scores, a /v1/systemone question) that the step in flight * brings to max_tokens gets no step issued ahead: it would run a whole forward pass for a * request that finishes at the commit, and max_tokens=1 pays a decode step after its @@ -2966,6 +3014,11 @@ int Scheduler::commit(StepResult& res) { draft_.yield(s.adapt, now), est); } } + if (e.suffix) { + ++m_.suffix_steps; + m_.suffix_rows += e.n_spec; + m_.suffix_accepted += a; + } m_.draft_tokens += e.n_spec; m_.draft_accepted += a; server::sink_drafts(r.sink, e.n_spec, a); @@ -2973,7 +3026,16 @@ int Scheduler::commit(StepResult& res) { } s.n_draft = 0; r.n_draft = 0; + s.draft_suffix = false; + r.draft_suffix = false; s.entry = -1; + /* --draft-suffix: does the history now end in a pattern that recurred? (step_next_locked) */ + if (cfg_.draft_suffix && e.produces_token && r.state == ReqState::Running) { + int32_t buf[RAD_SCHED_MAX_SPEC]; + s.suffix_hot = r.may_speculate && suffix_propose(s, buf) > 0; + } else { + s.suffix_hot = false; + } /* A request the next step carries finishes now but keeps its blocks, which that step * writes; its commit finds the request not running and returns them. */ diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index e8f3b4e6..8831875e 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -17,6 +17,7 @@ #include "lookup.h" #include "metrics.h" #include "ngram.h" +#include "suffix.h" #include "diag/diagnose.h" #include @@ -82,6 +83,8 @@ struct SchedReq { void drafter_reset() { n_draft = 0; draft_next = 0; + draft_suffix = false; + suffix_hot = false; conv_cursor = 0; draft_filled = 0; draft_lo = 0; @@ -93,6 +96,13 @@ struct SchedReq { DraftAdapt adapt; /* The proposal the step being planned carries came from prompt lookup (StepEntry::ngram). */ bool draft_ngram = false; + /* --draft-suffix (suffix.h): the proposal the step being planned carries is a suffix chain + * (StepEntry::suffix); and whether the last commit left the sequence's history ending in a + * recurring pattern, which keeps the next step from being issued ahead (it is built after the + * commit, where the lookup can run). */ + bool draft_suffix = false; + bool suffix_hot = false; + SuffixIndex suffix_ix; /* Prompt lookup's index over prompt ++ output (ngram.h), built at the sequence's first lookup * and extended by each later one. It depends on the tokens alone, so preemption keeps it; it * is keyed by request id, so a recycled slot starts over, and a closed request frees it. */ @@ -651,6 +661,9 @@ private: * far the match behind the proposal runs back (NgramIndex::propose), -1 when the proposal did * not come from the index (--debug-draft-oracle). */ int draft_ngram(SchedReq& s, int depth, int* match = nullptr) const; + /* --draft-suffix: the suffix proposal for `s`'s next step, over its committed history, into + * `out` (RAD_SCHED_MAX_SPEC entries). Returns its length, 0 for none. */ + int suffix_propose(SchedReq& s, int32_t* out, int* match = nullptr); /* Prompt lookup is the deployment's only drafter and --draft-window adaptive is on: its * proposals feed each sequence's estimate and are capped by its window, as a head's are. */ bool lookup_adapt_ = false; diff --git a/core/sched/suffix.h b/core/sched/suffix.h new file mode 100644 index 00000000..90faefdb --- /dev/null +++ b/core/sched/suffix.h @@ -0,0 +1,172 @@ +/* suffix.h -- SuffixDecoding's proposal for a hybrid step selector (--draft-suffix, DESIGN-suffix.md). + * + * SuffixDecoding (Oliaro et al., arXiv 2411.04975) drafts from a suffix tree of earlier text: for + * the longest suffix of the current context that occurred before, it expands the tokens that + * followed, each node scored by the product of its followers' frequencies (D, the expected number of + * accepted tokens along its path). Here the tree is the per-request one (prompt ++ output of THIS + * request; an offline study found a cross-request tree adds nothing on this workload), reduced to what + * a chain needs: + * + * - the earlier occurrence comes from the existing NgramIndex (the --spec-ngram matcher): the + * latest earlier occurrence of the longest recurring suffix of `min_match..min_match+3` tokens; + * - the frequency rule comes from two count tables over `min_match`-token contexts: how often a + * context was followed by anything, and by each token. A proposal token at depth j has + * C_j = count(context_j + token_j) / count(context_j) with context_j the last `min_match` + * tokens of the sequence extended by the proposal so far, and the chain is cut where its path + * score D_j = prod C_i falls under `min_score`. + * + * It is a heuristic and only that: every proposed token is verified (the sampler's own draw must + * equal it), so a collision in the tables, a stale count or a wrong match changes how many tokens a + * step lands, never which tokens come out. The tables key on 64-bit hashes and store 32 bits of the + * key; a clash merges two contexts' counts. + * + * The index is incremental: each call indexes the tokens committed since the last one, prompt + * included at the first, so a sequence is indexed once over its lifetime. Memory is about 8 bytes a + * token per table and per NgramIndex pattern length (4 lengths). + */ +#pragma once +#include "ngram.h" + +#include +#include + +namespace rad { + +class SuffixIndex { +public: + /* NgramIndex tries pattern lengths min_match .. min_match + kExtra, longest first: the proposal + * follows the latest occurrence of the longest recurring suffix in that range. */ + enum { kExtra = 3, kMaxK = 12 }; + + /* Forget the sequence; `owner` is the request id the next lookups are for. */ + void reset(uint64_t owner = 0) { + ix_.reset(owner); + followed_.clear(); + follow_.clear(); + filled_ = 0; + k_ = 0; + } + uint64_t owner() const { return ix_.owner(); } + + struct Out { + int n = 0; /* tokens proposed */ + int match = 0; /* how far the match behind the proposal runs back (>= min_match) */ + float score = 0.0f; /* D of the last proposed node: the chance the whole chain is taken */ + float expect = 0.0f; /* sum of D along the chain: expected accepted tokens */ + }; + + /* The proposal for `seq`: at most `max_rows` tokens into `out` (the index is brought up to the + * sequence first). n == 0 when the last `min_match` tokens did not occur before, or the first + * token's own score is under `min_score`. 1 <= min_match <= kMaxK. */ + Out propose(const TokenSeq& seq, uint64_t owner, int min_match, int max_rows, float min_score, + int32_t* out) { + Out r; + if (min_match < 1 || min_match > kMaxK || max_rows < 1 || seq.size() <= min_match) return r; + if (ix_.owner() != owner || k_ != min_match) { reset(owner); k_ = min_match; } + const int64_t L = seq.size(); + if (L < filled_) { reset(owner); k_ = min_match; } + index_to(seq, L); + int match = 0; + const int n = ix_.propose(seq, min_match, min_match + kExtra, max_rows, out, &match, 64); + if (n <= 0) return r; + /* Score the chain: the context moves forward over the proposal's own tokens. */ + int32_t win[kMaxK]; + for (int i = 0; i < k_; ++i) win[i] = seq[L - k_ + i]; + float d = 1.0f, sum = 0.0f; + int m = 0; + for (; m < n; ++m) { + const uint64_t h = hash_ctx(win, k_); + const uint32_t a = followed_.get(h); + const uint32_t b = follow_.get(mix(h, (uint64_t)(uint32_t)out[m])); + if (a == 0 || b == 0) break; /* a path the history never took */ + const float c = (float)b / (float)a; + if (d * c < min_score) break; + d *= c; + sum += d; + for (int i = 0; i + 1 < k_; ++i) win[i] = win[i + 1]; + win[k_ - 1] = out[m]; + } + r.n = m; + r.match = match; + r.score = m > 0 ? d : 0.0f; + r.expect = sum; + return r; + } + + int64_t indexed() const { return filled_; } + size_t bytes() const { return ix_.bytes() + (followed_.t.capacity() + follow_.t.capacity()) * 8; } + +private: + /* Open addressing; an entry is key (the high 32 bits of a 64-bit hash, never 0) << 32 | count. + * The probe starts from the stored key, so a rehash needs nothing else. */ + struct Table { + std::vector t; + uint64_t mask = 0; + int64_t n = 0; + void clear() { t.clear(); t.shrink_to_fit(); mask = 0; n = 0; } + static uint32_t key_of(uint64_t h) { return (uint32_t)(h >> 32) | 1u; } + static uint64_t start(uint32_t key) { return ((uint64_t)key * 0x9e3779b97f4a7c15ull) >> 29; } + uint32_t get(uint64_t h) const { + if (t.empty()) return 0; + const uint32_t key = key_of(h); + for (uint64_t i = start(key) & mask;; i = (i + 1) & mask) { + const uint64_t e = t[i]; + if (e == 0) return 0; + if ((uint32_t)(e >> 32) == key) return (uint32_t)e; + } + } + void bump(uint64_t h) { + if (t.empty() || (uint64_t)(n + 1) * 2 > mask + 1) grow(); + const uint32_t key = key_of(h); + for (uint64_t i = start(key) & mask;; i = (i + 1) & mask) { + uint64_t& e = t[i]; + if (e == 0) { e = (uint64_t)key << 32 | 1u; ++n; return; } + if ((uint32_t)(e >> 32) == key) { if ((uint32_t)e != 0xffffffffu) ++e; return; } + } + } + void grow() { + std::vector old; + old.swap(t); + const uint64_t cap = old.empty() ? 1024 : (mask + 1) * 2; + t.assign(cap, 0); + mask = cap - 1; + for (uint64_t e : old) { + if (!e) continue; + for (uint64_t i = start((uint32_t)(e >> 32)) & mask;; i = (i + 1) & mask) + if (t[i] == 0) { t[i] = e; break; } + } + } + }; + + NgramIndex ix_; + Table followed_; /* a k-token context -> how many times anything followed it */ + Table follow_; /* a k-token context and a token -> how many times that token did */ + int64_t filled_ = 0; /* positions < filled_ are counted */ + int k_ = 0; + + static uint64_t mix(uint64_t h, uint64_t v) { + h ^= v + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2); + h *= 0xff51afd7ed558ccdull; + h ^= h >> 32; + return h; + } + static uint64_t hash_ctx(const int32_t* t, int k) { + uint64_t h = 0x84222325cbf29ce4ull; + for (int i = 0; i < k; ++i) h = mix(h, (uint64_t)(uint32_t)t[i]); + return h; + } + /* Count, for every position e in [filled_, upto) with k tokens before it, the context + * seq[e-k..e-1] followed by seq[e]. */ + void index_to(const TokenSeq& seq, int64_t upto) { + int32_t win[kMaxK]; + for (int64_t e = filled_ < k_ ? k_ : filled_; e < upto; ++e) { + for (int i = 0; i < k_; ++i) win[i] = seq[e - k_ + i]; + const uint64_t h = hash_ctx(win, k_); + followed_.bump(h); + follow_.bump(mix(h, (uint64_t)(uint32_t)seq[e])); + } + filled_ = upto; + } +}; + +} /* namespace rad */ diff --git a/core/server/adapters.h b/core/server/adapters.h index 9a4991b2..a3068b5f 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -127,6 +127,8 @@ inline SchedMetrics bridge_metrics(const rad::SchedMetrics& m) { o.draft_refills = m.draft_refills; o.draft_refill_tokens = m.draft_refill_tokens; o.lookup_proposals = m.lookup_proposals; o.lookup_held = m.lookup_held; o.lookup_held_drafts = m.lookup_held_drafts; o.lookup_held_hits = m.lookup_held_hits; + o.suffix_steps = m.suffix_steps; o.suffix_rows = m.suffix_rows; + o.suffix_accepted = m.suffix_accepted; o.suffix_held_ahead = m.suffix_held_ahead; o.linear_hit_rate = m.linear_hit_rate; o.attn_cached_tokens = m.attn_cached_tokens; o.linear_cached_tokens = m.linear_cached_tokens; diff --git a/core/server/iface.h b/core/server/iface.h index f1b58851..637284bc 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -116,6 +116,12 @@ struct SchedMetrics { int64_t lookup_held = 0; int64_t lookup_held_drafts = 0; int64_t lookup_held_hits = 0; + /* --draft-suffix: verifies that carried a suffix chain, their rows and accepted drafts, and the + * decode steps kept from being issued ahead by a recurring pattern. */ + int64_t suffix_steps = 0; + int64_t suffix_rows = 0; + int64_t suffix_accepted = 0; + int64_t suffix_held_ahead = 0; /* Per-position draft acceptance. The pooled `draft_acceptance` cannot tell a drafter that * decays with depth from one whose later rounds are broken. Per position j: verifies that * reached j (every earlier position accepted) and how many of those took j. */ diff --git a/core/server/metrics.cpp b/core/server/metrics.cpp index 5db56040..900fe1c4 100644 --- a/core/server/metrics.cpp +++ b/core/server/metrics.cpp @@ -200,6 +200,10 @@ void Metrics::sample(const SchedMetrics& m) { c_lookup_held_.advance_to(m.lookup_held); c_lookup_held_drafts_.advance_to(m.lookup_held_drafts); c_lookup_held_hits_.advance_to(m.lookup_held_hits); + c_suffix_steps_.advance_to(m.suffix_steps); + c_suffix_rows_.advance_to(m.suffix_rows); + c_suffix_accepted_.advance_to(m.suffix_accepted); + c_suffix_held_ahead_.advance_to(m.suffix_held_ahead); c_attn_cached_.advance_to(m.attn_cached_tokens); c_linear_cached_.advance_to(m.linear_cached_tokens); c_prefix_queries_.advance_to(m.prefix_queries); @@ -474,6 +478,16 @@ std::string Metrics::render() const { "Of the held-back proposals scored against the text that followed, the drafts " "that came true: what verifying them would have accepted.", L, c_lookup_held_hits_.get()); + w.counter("radiance:suffix_steps_total", + "Verify steps that carried a --draft-suffix chain of the sequence's own history.", + L, c_suffix_steps_.get()); + w.counter("radiance:suffix_rows_total", + "Draft rows those suffix steps verified.", L, c_suffix_rows_.get()); + w.counter("radiance:suffix_accepted_total", + "Of those rows, the drafts accepted.", L, c_suffix_accepted_.get()); + w.counter("radiance:suffix_held_ahead_total", + "Decode steps not issued ahead of the previous commit because the sequence's " + "history ended in a recurring pattern (--draft-suffix).", L, c_suffix_held_ahead_.get()); /* Decoupled prefix caching (spec §7.3). vllm:gpu_prefix_cache_hit_rate is the attention hit * rate, as in vLLM. The linear side hits at a different granularity (whole checkpoints, not diff --git a/core/server/metrics.h b/core/server/metrics.h index ab5734ab..0ddf7066 100644 --- a/core/server/metrics.h +++ b/core/server/metrics.h @@ -158,6 +158,7 @@ private: Counter c_prefill_tokens_, c_decode_tokens_, c_draft_tokens_, c_draft_accepted_; Counter c_draft_refills_, c_draft_refill_tokens_; Counter c_lookup_proposals_, c_lookup_held_, c_lookup_held_drafts_, c_lookup_held_hits_; + Counter c_suffix_steps_, c_suffix_rows_, c_suffix_accepted_, c_suffix_held_ahead_; Counter c_attn_cached_, c_linear_cached_, c_checkpoints_; Counter c_prefix_queries_; Counter c_prefix_evict_, c_prefix_ckpt_evict_; diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 5d5302d2..236b75bb 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1666,6 +1666,60 @@ sensitive between 0.80 and 0.90. The engine keeps 48 recorded passes instead of chain makes more pass shapes than 24 hold: 3352 recordings per benchmark became 1472, +1.7% tokens a second for this mode); the other modes touch no more than they did. +**SuffixDecoding as a step selector: `draft-suffix`.** `draft-suffix: on` (default off, which is the +engine as it was, bit for bit) lets a serial head's chain give a step to the sequence's own history. +After each commit the engine looks, in the sequence's prompt and output, for an earlier occurrence of +its last `draft-suffix-min-match` tokens (default 6; the longest of that length and three more wins, +the latest occurrence of it). If there is one, the next step is a pure verify of what followed it (a +chain of at most `draft-suffix-max` rows, default 7) in place of the head's draft, cut where the path +score falls under `draft-suffix-min-score` (default 0.3): SuffixDecoding's frequency rule (Oliaro et +al., arXiv 2411.04975), the product along the chain of how often that token followed that context in +the history. Otherwise the step is the head's, as before. It pays where the reply copies its context +(code edits, quoting, agent and tool loops, pasted text, structured output) and does nothing on free +chat. A cross-request suffix tree adds nothing on such loads and is not built. + +It works with the normal fixed MTP chain, with `draft-depth: adaptive` (the adaptive chain stays within +the head's `num-speculative-tokens` rounds; the suffix window only widens the verify) and with +`draft-verify: traversal` (a suffix row carries no coupled state, so it is a leaf of the walk). It is +refused with `draft-verify: block` (the block verify decides a head chain as a whole), with +`draft-window: adaptive`, and on a block drafter. + +How it is built: the verify window (`num-speculative-tokens` for every buffer, ring and kernel band) +becomes `max(num-speculative-tokens, draft-suffix-max)` while the head keeps drafting its own +`num-speculative-tokens` rounds, so the head's passes (and `draft-coupling`'s draws) do not change. A +suffix step is built after the commit, where the lookup can read the committed end, so a sequence whose +history ended in a recurring pattern at the last commit is **not issued ahead** (the step ahead is made +on the card from the head's drafts, before the commit; deciding on the last readback costs one step of +lag when a copy starts and one built-after-commit step when it ends, where the card-side alternative +would need a per-sequence token history and a hash table in the advance kernels). The head still drafts +behind every step, a suffix step included: its history pass covers all 1 + rows positions the step +verified, so the head's cache has no hole behind it and its next draft is as good as after a head step; +the draft pass behind a suffix step is the price of that. + +Exactness: the choice reads the committed text and nothing else, never a draw. A suffix step carries no +coupled row (`Request::draft_suffix`): the sampler binds none of the head's staged states to its rows (a +proposal that equals the head's unused draw `x` would otherwise select the coupling by the value of that +draw). Each row is the target's plain draw from `(seed, position)` and the walk follows the proposal iff +the draw equals it: greedy text is the head-only run's (up to the last-bit differences a different row +count makes to the logits, as between any two window sizes) and the sampled law is the target's. +`tests/mtp_rrs_test.cpp` checks the law (chi-square over the first three tokens, alone and mixed with +adaptive-depth steps, under the row-wise and the traversal verify, with a negative control that exposes +the variant in which the coupled rows see the suffix chain), `tests/sched_test.cpp` the selection, the +issue-ahead rule and the head's catch-up, `tests/arch_test.cpp` the issue pattern of a nine-row verify. +The window is bounded by the model's kernels: Flash-Next's fused conv + recurrent update serves at most 8 +query rows (a register window), so `draft-suffix-max` is at most 7 there; a larger window makes the first +step fail with `unsupported`. `/metrics` has `radiance:suffix_steps_total`, `suffix_rows_total`, +`suffix_accepted_total` and `suffix_held_ahead_total`. + +```yaml + num-speculative-tokens: 3 + draft-coupling: on + draft-suffix: on + draft-suffix-min-match: 6 + draft-suffix-max: 7 + draft-suffix-min-score: 0.3 +``` + **Chained launches.** Where the model's plugin measured its step faster with them, the AQL backend lets a kernel that depends on the one before it on its queue wait in its own prologue instead of behind the packet processor's barrier bit, which saves most of the launch gap between dependent @@ -2468,6 +2522,8 @@ switch is set with `true`. The fleet's own keys (a model's `aliases`, `priority` | `draft-depth-stop: P` | 0.85 | `draft-depth: adaptive`: the chain goes on while its confidence is at least P | | `draft-depth-lag: K` | 1 | `draft-depth: adaptive`: rounds the decision trails the chain (0 or 1); 1 hides the host's decision behind a running round | | `draft-depth-stat: S` | top | `draft-depth: adaptive`: `top` multiplies each round's largest probability, `path` the probability of the token it drew | +| `draft-suffix: MODE` | off | SuffixDecoding as a step selector on a serial head's chain: a step whose sequence's own history recurs (the last `draft-suffix-min-match` tokens occurred before) verifies the earlier continuation instead of the head's draft; lossless; with the fixed chain, `draft-verify: traversal` and `draft-depth: adaptive`, not `draft-verify: block` (§4.6) | +| `draft-suffix-min-match: L`, `draft-suffix-max: N`, `draft-suffix-min-score: D` | 6, 7, 0.3 | the shortest match (1..12), the most rows of a suffix step (1..32; widens the verify window to max(`num-speculative-tokens`, N); at most 7 on Flash-Next), and the path score under which the chain is cut | | `draft-short-from: N` | auto | a block drafter that declares a shorter block runs it from N decoding sequences on, its own block again two below or at one sequence; 0 never; auto never for a chain and 2 for a tree drafter, which then verifies the short block's nodes (§4.6) | | `draft-coupling: MODE` | off | `on`: a linear MTP drafter with a 2-bit candidate head (Qwen3.8-Flash-Next) samples each proposal from its reranked top-8 and the sampler maximally couples the target's draw to it. The output distribution is unchanged and a fixed seed yields other tokens than `off`. The head's law is taken at temperature 1, so it pays at high request temperatures and costs at low ones: on Flash-Next TP2 at 2x R9700, tokens per decode step +18% at temperature 1.0 and c1, +11% at 0.7 and c4, -4% at 0.3. Greedy rows are unchanged. A DFlash2 drafter (Qwen3.5/3.8) couples its candidate walk instead: each position is sampled from the softmax of the walk's own scores over its best eight candidates, at temperature 0.6 (fixed in `qwen35_fp8`, where acceptance peaked); on Qwen3.8-27B MXFP4 TP2 at 2x R9700 and request temperature 1, tokens per verify step +8% on held-out prompts at c4 (3.53 to 3.82) and decode +2..8% per stream at c1/c4. Any other drafter is refused at startup | | `draft-verify: MODE` | token | how a coupled draft chain is verified: `token` decides each row on its own (maximal coupling); `block` decides the whole chain at once (Block Verification, arXiv 2403.10444) and switches `draft-coupling` on; `traversal` walks the chain bottom-up (Traversal Verification, arXiv 2505.12398) and needs `draft-coupling: on`. The output distribution is the same in all three, every draft a step accepts is one the target's own law would have produced, and `block` and `traversal` accept at least as many drafts a step as `token`. Sampled rows only: a greedy row is verified as before. The verify runs as one workgroup a request, with no scratch (§6) | diff --git a/tests/advance_test.cpp b/tests/advance_test.cpp index a5c29c1a..691c9b87 100644 --- a/tests/advance_test.cpp +++ b/tests/advance_test.cpp @@ -779,4 +779,66 @@ TEST(a_block_drafter_step_on_the_card_continues_where_the_verify_left_off) { } } +/* ================================================================== a suffix step (--draft-suffix) */ + +/* A suffix step is a host-built verify of up to 8 proposals behind the bonus token while the head + * drafts 3 rounds. The card's side of it: the acceptance walks all 8 drafts (a prefix of them, up to + * the end-of-generation cut), the head's history pass covers all 9 positions with round 1 on the + * last committed one and the rejected rows repeating it, and the 3 rounds publish the next verify's + * 3 proposals into tok[1..3] without touching what lies past them. */ +TEST(a_host_built_nine_row_verify_is_accepted_caught_up_and_followed_by_three_rounds) { + for (int acc_want = 0; acc_want <= 8; ++acc_want) { + const int ctx = 200, n = 9; + /* the verify: the bonus token and 8 proposals, a host row (no device row) */ + Slab a(ADV_ACCEPT); + a.row(0, false, 0, n, ctx, /*card=*/3, /*rtok=*/0, /*rout=*/0, /*aux=*/8); + for (int j = 0; j < n; ++j) a.w[Slab::TOK + j] = 500 + j; + for (int j = 0; j <= 8; ++j) a.src[j] = j < acc_want ? 500 + j + 1 : 9000 + j; + a.run(); + const StepSlot& S = a.st[3]; + CHECK_EQ(S.acc, acc_want); + CHECK_EQ(S.tok[0], 9000 + acc_want); + CHECK_EQ(S.head, ctx + acc_want); + CHECK_EQ(S.ctx, ctx + acc_want + 1); + CHECK_EQ(S.n_acc, acc_want + 1); + CHECK_EQ(S.npath, 0); + + /* the head's history pass over all nine rows: positions up to the last committed one, the + * rest repeating it, so no rejected proposal's hidden state reaches the head's cache */ + Slab h(ADV_HIST); + h.st[3] = S; + h.row(0, true, 0, n, ctx, 3, 0, 0, /*aux=*/0); + for (int j = 0; j < n; ++j) h.src[j] = a.src[j]; + h.run(); + for (int j = 0; j < n; ++j) { + const int up = std::min(j, acc_want); + CHECK_EQ(h.w[Slab::POS + j], ctx + up); + CHECK_EQ(h.slot(0, j), ctx + up); + CHECK_EQ(h.w[Slab::OUT + j], up); + } + CHECK_EQ(h.used(0, 0), ctx + acc_want + 1); + + /* the head's own rounds: 3 of the 8 the verify window allows */ + for (int round = 2; round <= 3; ++round) { + Slab r(ADV_ROUND); + r.a.round = round; + r.st[3] = h.st[3]; + r.row(0, true, 0, 1, 0, 3, 0, 0, 0); + r.src[0] = 7100 + round; + r.run(); + h.st[3] = r.st[3]; + } + Slab t(ADV_TAKE); + t.a.round = 3; + t.st[3] = h.st[3]; + t.row(0, true, 0, 1, 0, 3, 0, 0, 0); + t.src[0] = 7200; + t.run(); + const StepSlot& N = t.st[3]; + CHECK_EQ(N.tok[0], 9000 + acc_want); + CHECK_EQ(N.tok[3], 7200); + for (int j = 4; j <= RAD_SCHED_MAX_SPEC; ++j) CHECK_EQ(N.tok[j], (int32_t)0x7f7f7f7f); /* untouched */ + } +} + RAD_TEST_MAIN() diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 2e1f4121..52a34875 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -10997,6 +10997,57 @@ TEST(flashnext_steps_lint_clean_at_one_two_and_four_ranks) { } } +/* --draft-suffix: the verify window is widened to 7 drafts (`max_spec` 7: the delta-net fold serves 8 + * query rows) while the head still drafts 3 rounds. A suffix step is an eight-row verify, then the + * head's history pass over all eight rows (round 1 on the last) and rounds 2 and 3; the head's own + * step in the same deployment is four rows and the same passes. Both lint clean, and every pass issues + * the same ops by name, the same number of times, as the head's step at its own window does: only row + * counts differ, and round 3 of a deployment whose head declared more rounds than it runs carries one + * `cast` more (its hidden state on to a round 4 the core does not issue; a few microseconds). */ +TEST(flashnext_a_suffix_step_issues_the_heads_ops_over_eight_rows_and_lints_clean) { + MetaKV mk = q4_small(); + const RadModelMeta& meta = *mk.meta(); + std::vector> pattern[3]; + int idx = 0; + for (const auto& cfg : { std::pair{ 3, 4 }, std::pair{ 7, 8 }, std::pair{ 7, 4 } }) { + RadBuilder b; + b.encs = { { "draft_head", u2_head() } }; + RadBuildCtx ctx = q4_ctx(0, 1); + ctx.max_spec = cfg.first; + REQUIRE_EQ(qwen4exp_fp8::declare(&b, &meta, &ctx), RAD_OK); + REQUIRE_EQ((int)b.drafter.kind, (int)RAD_DRAFT_SERIAL); + const auto ver = kit(b, std::vector(1, cfg.second), {}); + CHECK_EQ((int)ver->b.n_spec, cfg.second - 1); + const auto his = history_pass(b, *ver); + CHECK_EQ((int)his->b.n_tok, cfg.second); /* every verified position */ + CHECK_EQ(his->dout[0], cfg.second - 1); /* round 1 on the last row */ + const auto r2 = round_pass(b, 1, 2), r3 = round_pass(b, 1, 3); + const auto v = run_passes(b, qwen4exp_fp8::step, { ver.get(), his.get(), r2.get(), r3.get() }); + CHECK_PASSES(b, v); + std::set names; + for (const RecOp& o : b.ops) names.insert(o.op); + for (size_t pass = 0; pass < v.size(); ++pass) { + std::map m; + for (const std::string& nm : names) m[nm] = issues_of(b, *v[pass], nm.c_str()).size(); + pattern[idx].push_back(m); + } + ++idx; + } + for (size_t pass = 0; pass < 4; ++pass) + for (int o = 1; o < 3; ++o) { + std::map> d; + for (const auto& [nm, n] : pattern[0][pass]) + if (pattern[o][pass].at(nm) != n) d[nm] = { n, pattern[o][pass].at(nm) }; + if (pass == 3) { + CHECK_EQ(d.size(), (size_t)1); + CHECK_EQ(d.at("cast").first, (size_t)0); + CHECK_EQ(d.at("cast").second, (size_t)1); + } else { + CHECK_EQ(d.size(), (size_t)0); + } + } +} + /* Sparse attention issues one row per query, chunked by the split-KV scratch it declared, never * by `max_seqs`: with four sequences allowed, a 1024-token chunk after a long history is one * launch of the gated form, or four of 256 rows where only the plain form resolves. Rows of four diff --git a/tests/config_test.cpp b/tests/config_test.cpp index c23ee719..f36e0bbe 100644 --- a/tests/config_test.cpp +++ b/tests/config_test.cpp @@ -588,6 +588,8 @@ const std::map>& legal_values() { { "--spec-ngram-min", { "1" } }, { "--spec-ngram-max", { "6" } }, { "--draft-window", { "fixed" } }, { "--draft-short-from", { "4" } }, { "--draft-coupling", { "on" } }, { "--draft-verify", { "block" } }, + { "--draft-suffix", { "on" } }, { "--draft-suffix-min-match", { "5" } }, + { "--draft-suffix-max", { "6" } }, { "--draft-suffix-min-score", { "0.4" } }, { "--draft-depth", { "adaptive" } }, { "--draft-depth-max", { "5" } }, { "--draft-depth-min", { "2" } }, { "--draft-depth-stop", { "0.7" } }, { "--draft-depth-lag", { "0" } }, { "--draft-depth-stat", { "path" } }, @@ -1083,6 +1085,30 @@ TEST(draft_depth_adaptive_parses_and_needs_a_coupled_chain) { } +/* The SuffixDecoding selector: off by default (bit-identical engine), min match 1..12, rows 1..32, + * a score in [0, 1]. */ +TEST(the_draft_suffix_flags_default_off_and_parse) { + Config c; + CHECK(!c.draft_suffix); + CHECK_EQ(c.draft_suffix_min_match, 6); + CHECK_EQ(c.draft_suffix_max, 7); + CHECK_NEAR(c.draft_suffix_min_score, 0.3, 1e-6); + CHECK_EQ(c.n_spec_head, 0); + CHECK_EQ(parse({ "--draft-suffix", "on", "--draft-suffix-min-match", "5", "--draft-suffix-max", "6", + "--draft-suffix-min-score", "0.45" }, &c), RAD_OK); + CHECK(c.draft_suffix); + CHECK_EQ(c.draft_suffix_min_match, 5); + CHECK_EQ(c.draft_suffix_max, 6); + CHECK_NEAR(c.draft_suffix_min_score, 0.45, 1e-6); + CHECK_EQ(parse({ "--draft-suffix", "off" }, &c), RAD_OK); + CHECK(!c.draft_suffix); + for (const char* bad : { "yes", "1", "" }) CHECK_EQ(parse_fresh({ "--draft-suffix", bad }), RAD_E_INVAL); + for (const char* bad : { "0", "13", "x", "" }) CHECK_EQ(parse_fresh({ "--draft-suffix-min-match", bad }), RAD_E_INVAL); + for (const char* bad : { "0", "33", "x", "" }) CHECK_EQ(parse_fresh({ "--draft-suffix-max", bad }), RAD_E_INVAL); + for (const char* bad : { "-0.1", "1.5", "x", "" }) CHECK_EQ(parse_fresh({ "--draft-suffix-min-score", bad }), RAD_E_INVAL); +} + + /* --draft-verify is token (alias rowwise) unless asked for; block and traversal parse. block * implies the coupled drafting and refuses coupling off; traversal needs the coupling and says so. */ TEST(the_draft_verify_is_token_block_or_traversal) { @@ -1746,4 +1772,19 @@ TEST(rope_scaling_takes_yarn_with_a_factor_above_one_or_none) { CHECK(d.rope_scaling.empty()); } +/* The suffix selector and the adaptive chain depth are served together, with traversal verification + * (bring-up refuses what the model cannot do; the parse and the shown rows say what was asked). */ +TEST(the_suffix_selector_parses_beside_adaptive_depth_and_traversal) { + Config c; + CHECK_EQ(parse({ "--draft-suffix", "on", "--draft-depth", "adaptive", "--draft-coupling", "on", + "--draft-verify", "traversal", "--num-speculative-tokens", "5" }, &c), RAD_OK); + CHECK(c.draft_suffix); + CHECK(c.draft_depth_adaptive); + CHECK(c.draft_coupling); + CHECK(c.draft_verify_traversal); + CHECK(!c.draft_verify_block); + CHECK_EQ(c.n_spec, 5); + CHECK_EQ(c.draft_suffix_max, 7); +} + RAD_TEST_MAIN() diff --git a/tests/mtp_rrs_test.cpp b/tests/mtp_rrs_test.cpp index 2d6bc4ce..68316b23 100644 --- a/tests/mtp_rrs_test.cpp +++ b/tests/mtp_rrs_test.cpp @@ -17,6 +17,10 @@ * sees each of them * degenerate Q == P accepts the first child; disjoint supports reject all and emit * from P + * suffix step a chain copied from the sequence's own history (--draft-suffix) emits + * the target law beside the head's stale coupled states, alone and + * mixed with adaptive-depth head steps; the same chain visible to the + * coupled rows (what Request::draft_suffix prevents) does not * adaptive depth a chain cut by the rule of sched/draft_depth.h keeps the target law * under both verifies; two rules that read what they may not do not * fixed point the walk's integer exponential tracks exp to 2^-22, its law is the @@ -127,8 +131,12 @@ struct Tree { int tok[64] = {}, par[64] = {}; uint64_t hash[64] = {}; /* the prefix hash of every node, node 0 the root */ RadMtpCoupleState st[64] = {}; /* row k's coupled state (status 0: none) */ + bool suffix = false; /* a SuffixDecoding chain (Request::draft_suffix) */ }; +/* The negative control of the suffix step: the coupled rows see its chain as their children. */ +bool g_suffix_visible = false; + enum Kind { CHAIN, STAGE1 }; int g_scheme = 0; /* sibling scheme of the root's drafts: 0 Gumbel-top-k, m + 1 RheoSampling */ @@ -201,6 +209,7 @@ int walk(const Tree& t, uint64_t seed, uint64_t n_out, double noise, int want, i int nk = 0; for (int j = cur + 1; j <= t.n; ++j) { if (t.par[j] != cur) continue; + if (t.suffix && !g_suffix_visible) continue; /* Request::draft_suffix: no row binds a state */ bool dup = false; for (int q = 0; q < nk; ++q) dup = dup || kid[q] == t.tok[j]; if (!dup) kid[nk++] = t.tok[j]; @@ -308,6 +317,7 @@ struct TravTree { int nk = 0; for (int q = j + 1; q <= t.n; ++q) { if (t.par[q] != j) continue; + if (t.suffix && !g_suffix_visible) continue; /* Request::draft_suffix */ bool dup = false; for (int z = 0; z < nk; ++z) dup = dup || kid[z] == t.tok[q]; if (!dup) kid[nk++] = t.tok[q]; @@ -1342,4 +1352,175 @@ TEST(a_depth_rule_that_reads_the_admitted_draft_or_the_target_is_not_exact) { g_sharp = 1.0; } +static int argmax_tok(const Law& L) { + int b = 0; + for (int i = 1; i < V; ++i) if (L.p[i] > L.p[b]) b = i; + return b; +} + +/* ------------------------------------------------------------------ a SuffixDecoding step + * + * --draft-suffix replaces the head's chain of a step by the sequence's own history (suffix.h): a + * chain of up to 8 rows chosen from the committed text alone. The head had drafted (and DRAWN, under + * --draft-coupling) a chain for the same positions, so the coupled states of that draft are still + * in the sampler when the step is built. The step is exact because the scheduler marks it + * Request::draft_suffix, which keeps the sampler from binding any state to a proposed row: each + * row's emitted token is the target's plain draw and is followed iff it equals the proposal. + * Visible to the coupled rows, a proposal that happens to equal the head's unused draw x would + * select the row's coupling by the VALUE of that draw, which is biased. The statistic is the first + * three tokens' joint law over 400000 steps; the negative control must fail it. */ +static void suffix_chain(Tree* t, int s, int how, int len, double noise) { + const int orig[4] = { 0, t->tok[1], t->tok[2], t->tok[3] }; + uint64_t h = t->hash[0]; + for (int i = 0; i < len; ++i) { + int tk = argmax_tok(law_at(h, noise)); /* a history that repeats the likely text */ + if (how == 1 && i < 3) tk = orig[i + 1]; /* the head's own draw, by chance of the text */ + if (H((uint64_t)s * 977 + (uint64_t)i * 31 + 5) % 4 == 0) tk = (tk + 1) % V; /* a damaged copy */ + t->tok[i + 1] = tk; + t->par[i + 1] = i; + h = child_hash(h, tk); + t->hash[i + 1] = h; + } + t->n = len; + t->suffix = true; /* Request::draft_suffix: no row binds a state */ +} + +TEST(a_suffix_chain_beside_the_heads_stale_coupled_states_emits_the_target_law) { + for (int how = 0; how < 2; ++how) { + for (int len : { 3, 6, 8 }) { + const std::function h = [how, len](Tree* t, int s) { suffix_chain(t, s, how, len, 1.0); }; + g_suffix_visible = false; + const Result ok = run_kind(CHAIN, 400000, 1.0, &h); + std::printf(" suffix chain, rows %d, how %d, hidden: z=%.2f first=%.2f acc=%.2f\n", len, how, + ok.z, ok.first_z, ok.mean_acc); + CHECK(ok.z < 4.5); + CHECK(ok.first_z < 4.5); + } + } + /* the negative control: the same chains with the rows visible to the coupled verify */ + double worst = 0; + g_suffix_visible = true; + for (int how = 0; how < 2; ++how) { + const std::function h = [how](Tree* t, int s) { suffix_chain(t, s, how, 6, 1.0); }; + const Result r = run_kind(CHAIN, 400000, 1.0, &h); + std::printf(" suffix chain visible to the coupled rows (known wrong), how %d: z=%.1f first=%.1f\n", + how, r.z, r.first_z); + worst = std::max(worst, std::max(r.z, r.first_z)); + } + g_suffix_visible = false; + CHECK(worst > 8.0); +} + +/* A suffix step is the plain rule: the row's draw is the target's and the proposal is followed iff + * it equals it. A chain whose first row is never the likeliest token still emits the target's law. */ +TEST(a_suffix_chain_with_a_wrong_first_row_stays_exact) { + const std::function wrong = [](Tree* t, int s) { + suffix_chain(t, s, 0, 6, 1.0); + const Law L0 = law_at(t->hash[0], 1.0); + t->tok[1] = (argmax_tok(L0) + 1 + (int)(H((uint64_t)s) % (V - 1))) % V; /* never the likeliest, any other */ + t->hash[1] = child_hash(t->hash[0], t->tok[1]); + for (int i = 1; i < t->n; ++i) t->hash[i + 1] = child_hash(t->hash[i], t->tok[i + 1]); + }; + g_suffix_visible = false; + const Result r = run_kind(CHAIN, 300000, 1.0, &wrong); + std::printf(" suffix chain, first row wrong: z=%.2f first=%.2f\n", r.z, r.first_z); + CHECK(r.z < 4.5); + CHECK(r.first_z < 4.5); +} + +/* ------------------------------------------------------------------ the draft law's recipe + * + * rad_mtp_couple_build_law: the draft temperature (dscale = 1 / T_draft) and the request's top-k / + * top-p cut change WHICH Q the head drafts from, never the verify's exactness, because the state + * stores the Q that was drawn from and the verify reads it. */ + +/* ==================================================================== --draft-suffix beside --draft-depth adaptive + * + * A step is either a suffix step (the committed text recurs: an uncoupled chain of 1..7 rows copied + * from the history, Request::draft_suffix, no row binds a state) or an adaptive MTP chain (coupled, cut by + * the head's own laws), chosen by a function of the committed text alone -- the history hash here, + * the matcher over prompt ++ output in the engine. Both are verified by the traversal walk or row by + * row, and a generation runs over several such steps, so each step's kind and depth depend on what + * the steps before it committed. The negative control shows the suffix rows visible to the coupled + * rows' child lists (the head's stale states of the same positions), which is biased. */ +namespace { + +DepthRun run_mixed(const DraftDepthCfg& cfg, bool trav, int trials, double noise, int share_pct, int how) { + std::vector cnt3((size_t)V * V * V, 0), cnt1((size_t)V, 0); + DepthRun R{}; + double steps = 0, sfx = 0; + for (int s = 0; s < trials; ++s) { + const uint64_t seed = 0x7a31c5ull + (uint64_t)s * 130363ull; + int out[16], len = 0; + uint64_t h = 1; + while (len < 3) { + Tree t; + /* the head drafts for this step either way (the history pass is paid behind a suffix step) */ + const int D = draft_depth_chain(&t, seed, (uint64_t)len, cfg, noise, h, 0, 0); + const bool is_sfx = (int)(H(h * 31 + 7) % 100) < share_pct; + if (is_sfx) { + const int rows = 1 + (int)(H(h * 17 + 3) % 7); + suffix_chain(&t, (int)(h % 100003), how, rows, 1.0); + sfx += 1; + } + R.mean_depth += is_sfx ? t.n : D; ++steps; + int step_out[64], accepted = 0, n; + if (trav) n = walk_trav(t, seed, (uint64_t)len, noise, 0, step_out, &accepted, RadMtpTravOpt{}); + else n = walk(t, seed, (uint64_t)len, noise, 0, step_out, &accepted); + R.mean_acc += accepted; + for (int i = 0; i < n && len < 16; ++i) { out[len++] = step_out[i]; h = child_hash(h, step_out[i]); } + } + ++cnt1[(size_t)out[0]]; + ++cnt3[(size_t)((out[0] * V + out[1]) * V + out[2])]; + } + std::vector e1((size_t)V, 0), e3((size_t)V * V * V, 0); + const Law l0 = law_at(1, noise); + for (int a = 0; a < V; ++a) { + e1[(size_t)a] = l0.p[a]; + const uint64_t ha = child_hash(1, a); + const Law l1 = law_at(ha, noise); + for (int b = 0; b < V; ++b) { + const Law l2 = law_at(child_hash(ha, b), noise); + for (int c = 0; c < V; ++c) e3[(size_t)((a * V + b) * V + c)] = l0.p[a] * l1.p[b] * l2.p[c]; + } + } + R.z3 = zscore(cnt3, e3, trials); + R.z1 = zscore(cnt1, e1, trials); + R.mean_acc /= steps; R.mean_depth /= steps; + R.share[0] = sfx / steps; + return R; +} + +} /* namespace */ + +TEST(suffix_steps_beside_adaptive_depth_chains_emit_the_target_law) { + g_sharp = 2.0; + g_suffix_visible = false; + for (int how = 0; how < 2; ++how) + for (int pct : { 30, 70 }) { + const DraftDepthCfg cfg = depth_cfg(4, 1, DRAFT_DEPTH_TOP, 0.40); + const DepthRun tv = run_mixed(cfg, true, 250000, 0.6, pct, how); + const DepthRun rw = run_mixed(cfg, false, 250000, 0.6, pct, how); + std::printf(" suffix %d%% of steps (how %d): trav z3=%.2f z1=%.2f acc=%.3f | rowwise z3=%.2f z1=%.2f acc=%.3f | " + "suffix share %.2f rows/draft %.2f\n", pct, how, tv.z3, tv.z1, tv.mean_acc, rw.z3, rw.z1, + rw.mean_acc, tv.share[0], tv.mean_depth); + CHECK(tv.z3 < 4.5); CHECK(tv.z1 < 4.5); + CHECK(rw.z3 < 4.5); CHECK(rw.z1 < 4.5); + } + /* negative control: the suffix rows are children of the coupled rows (the head's own unused + * draw may equal the copied token, selecting the coupling by the VALUE of that draw) */ + g_suffix_visible = true; + double worst = 0; + for (int trav = 0; trav < 2; ++trav) { + /* every step a suffix step over a head that drafted its full chain (all its states are stale) */ + const DepthRun r = run_mixed(depth_cfg(4, 1, DRAFT_DEPTH_TOP, 0.0), trav != 0, 250000, 0.6, 100, 0); + std::printf(" suffix rows visible to the coupled rows (known wrong, %s): z3=%.1f z1=%.1f\n", + trav ? "traversal" : "rowwise", r.z3, r.z1); + worst = std::max(worst, std::max(r.z3, r.z1)); + } + g_suffix_visible = false; + g_sharp = 1.0; + CHECK(worst > 8.0); +} + RAD_TEST_MAIN() diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index 6ce4bff2..b79a048b 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -8528,3 +8528,332 @@ TEST(sim_burst_of_long_prompts) { (double)N * (double)L / tt.back(), pct(0.5), pct(0.95), tt.back(), dec_s > 0 ? (double)dec_tok / dec_s : 0.0, t); } + +/* ================================================================== --draft-suffix (SuffixDecoding as a step selector) */ + +namespace { +/* Commit the step in flight with `acc` accepted drafts and the final token `tok`. */ +void commit_one(Fixture& f, int32_t acc, int32_t tok) { + int32_t acc_n = acc, tk = tok; + uint8_t eos = 0; + Scheduler::StepResult res; + res.n_seq = (int)f.sch.plan().e.size(); + res.n_accepted = &acc_n; + res.token = &tk; + res.eos = &eos; + CHECK_OK(f.sch.commit(res)); +} + +/* A request whose prompt repeats 100..107, so the lookup continues the cycle: after the commit of + * 100 it proposes 101 102 103 with the longest match the index counts. */ +uint64_t ngram_cycle_request(Fixture& f) { + 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))); + return a; +} +} // namespace + +namespace { +/* A serial MTP head that drafts 3 rounds under a verify window of 8 rows (--draft-suffix on). */ +void suffix_setup(Fixture& f, int head = 3, int mx = 8, int min_match = 4, bool on = true) { + f.build(4096, 64); + f.cfg.n_spec = std::max(head, mx); + f.cfg.n_spec_head = on ? head : 0; + f.cfg.draft_suffix = on; + f.cfg.draft_suffix_min_match = min_match; + f.cfg.draft_suffix_max = mx; + f.cfg.draft_suffix_min_score = 0.3f; + if (!on) f.cfg.n_spec = head; + f.prog.drafter.kind = RAD_DRAFT_SERIAL; + f.prog.drafter.depth = f.cfg.n_spec; +} +const int32_t kHeadDraft[3] = { 21, 22, 23 }; +} // namespace + +TEST(the_suffix_index_proposes_the_latest_recurrence_and_cuts_by_path_score) { + using namespace rad; + /* (1 2 3) was followed by 10, 11, 10: 10 two times in three. The longest recurring suffix of the + * history, (2 3 10 1 2 3), was followed by 11 at its earlier occurrence, which is what is + * proposed, at the frequency of 11 after (1 2 3): 1/3. */ + const std::vector v = { 1, 2, 3, 10, 1, 2, 3, 11, 1, 2, 3, 10, 1, 2, 3 }; + TokenSeq s; + s.a = v.data(); s.na = (int64_t)v.size(); + SuffixIndex ix; + int32_t out[16]; + SuffixIndex::Out o = ix.propose(s, 7, 3, 8, 0.3f, out); + CHECK(o.n >= 1); + CHECK_EQ(out[0], 11); + CHECK(o.match >= 6); + CHECK_NEAR(o.score, 1.0 / 3.0, 1e-4); + /* a stricter score keeps nothing: the first token's own path score is 1/3 */ + SuffixIndex ix2; + CHECK_EQ(ix2.propose(s, 7, 3, 8, 0.4f, out).n, 0); + /* a context that never occurred before proposes nothing */ + const std::vector u = { 5, 6, 7, 8, 9, 40, 41, 42 }; + TokenSeq su; + su.a = u.data(); su.na = (int64_t)u.size(); + SuffixIndex ix3; + CHECK_EQ(ix3.propose(su, 8, 3, 8, 0.3f, out).n, 0); + /* it is incremental: the sequence grows and the proposal follows */ + std::vector w = { 5, 6, 7, 8, 9, 40, 41, 42, 5, 6, 7 }; + TokenSeq sw; + sw.a = w.data(); sw.na = (int64_t)w.size(); + const SuffixIndex::Out ow = ix3.propose(sw, 8, 3, 8, 0.3f, out); + CHECK(ow.n >= 3); + CHECK_EQ(out[0], 8); CHECK_EQ(out[1], 9); CHECK_EQ(out[2], 40); + CHECK_NEAR(ow.score, 1.0, 1e-4); /* a pattern seen once, followed once: D = 1 */ +} + +TEST(a_recurring_history_selects_a_suffix_step_in_place_of_the_heads_draft) { + Fixture f; + suffix_setup(f); + CHECK_OK(f.start()); + const uint64_t a = ngram_cycle_request(f); + REQUIRE(f.sch.step() != nullptr); + f.commit_plain(100); + CHECK_OK(f.sch.set_draft(a, kHeadDraft, 3)); + const RadBatch* b = f.sch.step(); + REQUIRE(b != nullptr); + /* the verify window is the suffix's: 1 + 8 rows, the head's 3 drafts replaced */ + CHECK_EQ(b->n_spec, 8); + CHECK_EQ(b->n_tok, 9); + const StepEntry& e = f.sch.plan().e[0]; + CHECK(e.suffix); + CHECK(e.ngram); + CHECK_EQ(e.n_spec, 8); + CHECK(e.draft_parent == nullptr); + const Request* rq = f.sch.find(a); + REQUIRE(rq != nullptr); + /* no coupled row: the request marks zero model nodes, so the sampler's child list is empty */ + CHECK(rq->draft_suffix); + const int32_t want[8] = { 101, 102, 103, 104, 105, 106, 107, 100 }; + for (int j = 0; j < 8; ++j) CHECK_EQ(rq->draft[j], want[j]); + commit_one(f, 5, 900); + const SchedMetrics m = f.sch.metrics(); + CHECK_EQ(m.suffix_steps, (int64_t)1); + CHECK_EQ(m.suffix_rows, (int64_t)8); + CHECK_EQ(m.suffix_accepted, (int64_t)5); + rq = f.sch.find(a); + REQUIRE(rq->output.size() >= 7); + for (int j = 0; j < 5; ++j) CHECK_EQ(rq->output[rq->output.size() - 6 + (size_t)j], want[j]); + CHECK_EQ(rq->output.back(), 900); + CHECK(!rq->draft_suffix); /* nothing carries over */ +} + +TEST(without_a_recurrence_or_with_the_flag_off_the_heads_draft_is_verified_as_before) { + { /* no recurrence in a prompt of distinct tokens */ + Fixture f; + suffix_setup(f); + CHECK_OK(f.start()); + const uint64_t a = f.submit(160, 2000); + REQUIRE(f.sch.step() != nullptr); + f.commit_plain(7); + CHECK_OK(f.sch.set_draft(a, kHeadDraft, 3)); + const RadBatch* b = f.sch.step(); + REQUIRE(b != nullptr); + CHECK_EQ(b->n_spec, 3); + CHECK(!f.sch.plan().e[0].suffix); + CHECK(!f.sch.plan().e[0].ngram); + CHECK(!f.sch.find(a)->draft_suffix); + for (int j = 0; j < 3; ++j) CHECK_EQ(f.sch.find(a)->draft[j], kHeadDraft[j]); + } + { /* the flag off: a recurring history changes nothing */ + Fixture f; + suffix_setup(f, 3, 8, 4, /*on=*/false); + CHECK_OK(f.start()); + const uint64_t a = ngram_cycle_request(f); + REQUIRE(f.sch.step() != nullptr); + f.commit_plain(100); + CHECK_OK(f.sch.set_draft(a, kHeadDraft, 3)); + const RadBatch* b = f.sch.step(); + REQUIRE(b != nullptr); + CHECK_EQ(b->n_spec, 3); + CHECK(!f.sch.plan().e[0].suffix); + CHECK(!f.sch.find(a)->draft_suffix); + commit_one(f, 3, 900); + CHECK_EQ(f.sch.metrics().suffix_steps, (int64_t)0); + CHECK_EQ(f.sch.metrics().suffix_held_ahead, (int64_t)0); + } +} + +/* The head runs only its own 3 rounds after a suffix step, but its history pass covers every + * position the step verified (all 1 + 8), and the watermark moves to the commit, so the next + * step's pass owes only its own rows: the head's cache has no hole behind a suffix step. */ +TEST(the_head_catches_up_on_every_position_a_suffix_step_verified) { + Fixture f; + suffix_setup(f); + CHECK_OK(f.start()); + const uint64_t a = ngram_cycle_request(f); + REQUIRE(f.sch.step() != nullptr); + f.commit_plain(100); + CHECK_OK(f.sch.set_draft(a, kHeadDraft, 3)); + const RadBatch* b = f.sch.step(); + REQUIRE(b != nullptr); + REQUIRE_EQ(b->n_spec, 8); + const int32_t ctx0 = f.sch.plan().e[0].ctx_len; + + int rounds = 8; /* the engine passes the declared depth; the scheduler clamps it to the head's */ + Scheduler::SerialRow rows[4]; + CHECK_EQ(f.sch.serial_begin(&rounds, rows, 4), 1); + CHECK_EQ(rounds, 3); + const RadBatch* hb = f.sch.serial_batch(0, 1); + REQUIRE(hb != nullptr); + CHECK(hb->draft_pass < 0); + CHECK_EQ(hb->n_tok, 9); /* the bonus row and all 8 proposals' positions */ + CHECK_EQ(hb->n_draft_out, 1); + CHECK_EQ(hb->draft_out_ids[0], 8); + CHECK_EQ(hb->ctx_lens[0], ctx0); /* from the step's first position */ + CHECK(f.sch.serial_batch(1, 1) == nullptr); + for (int rd = 2; rd <= rounds; ++rd) REQUIRE(f.sch.serial_batch(rd, 1) != nullptr); + + /* the verify took all 8: the watermark is the commit */ + commit_one(f, 8, 900); + f.sch.serial_end(rounds); + CHECK_OK(f.sch.set_draft(a, kHeadDraft, 3)); + const RadBatch* b2 = f.sch.step(); /* 900 broke the cycle: the head's step */ + REQUIRE(b2 != nullptr); + CHECK_EQ(b2->n_spec, 3); + CHECK(!f.sch.plan().e[0].suffix); + int rounds2 = 8; + CHECK_EQ(f.sch.serial_begin(&rounds2, rows, 4), 1); + CHECK_EQ(rounds2, 3); + const RadBatch* hb2 = f.sch.serial_batch(0, 1); + REQUIRE(hb2 != nullptr); + CHECK_EQ(hb2->n_tok, 4); /* its own 1 + 3 rows: nothing left owed */ + CHECK_EQ(hb2->ctx_lens[0], ctx0 + 9); + f.sch.serial_end(rounds2); +} + +/* A step issued ahead is made on the card from the head's drafts, before the previous commit: the + * lookup cannot run there. A sequence whose history ended in a recurring pattern at the last commit + * is not issued ahead (its next step is built after the commit, where the suffix selector reads the + * committed end); one whose history does not recur is, as before. */ +TEST(a_sequence_in_a_recurring_pattern_is_not_issued_ahead) { + for (int hot = 0; hot < 2; ++hot) { + Fixture f; + suffix_setup(f); + CHECK_OK(f.start()); + const uint64_t a = hot ? ngram_cycle_request(f) : f.submit(160, 2000); + REQUIRE(f.sch.step() != nullptr); + f.commit_plain(hot ? 100 : 7); + CHECK_OK(f.sch.set_draft(a, kHeadDraft, 3)); + REQUIRE(f.sch.step() != nullptr); + f.sch.find(a)->speculation_fixed = true; + f.sch.expect_draft(a, hot ? 8 : 3); + const RadBatch* nb = f.sch.step_next(); + if (hot) { + CHECK(nb == nullptr); + CHECK_EQ(f.sch.metrics().suffix_held_ahead, (int64_t)1); + } else { + CHECK(nb != nullptr); + CHECK_EQ(f.sch.metrics().suffix_held_ahead, (int64_t)0); + } + } +} + +/* Selection is a function of the committed text alone: the same history gives the same step whatever + * the head drafted, and a request that may not speculate (a constraining grammar) is never given a + * suffix chain. */ +TEST(the_suffix_choice_reads_the_history_only_and_respects_the_speculation_gate) { + for (int variant = 0; variant < 3; ++variant) { + Fixture f; + suffix_setup(f); + CHECK_OK(f.start()); + const uint64_t a = ngram_cycle_request(f); + REQUIRE(f.sch.step() != nullptr); + f.commit_plain(100); + if (variant == 2) f.sch.find(a)->may_speculate = false; + const int32_t other[3] = { 77, 78, 79 }; + CHECK_OK(f.sch.set_draft(a, variant == 1 ? other : kHeadDraft, 3)); + const RadBatch* b = f.sch.step(); + REQUIRE(b != nullptr); + if (variant == 2) { + CHECK_EQ(b->n_spec, 0); + CHECK(!f.sch.plan().e[0].suffix); + } else { + CHECK_EQ(b->n_spec, 8); + CHECK(f.sch.plan().e[0].suffix); + CHECK_EQ(f.sch.find(a)->draft[0], 101); + } + } +} + +/* ================================================================== --draft-suffix beside --draft-depth adaptive */ + +/* One step, two sequences: the one whose history recurs verifies its suffix chain (8 rows), the other + * the head's chain at the depth the adaptive rule gave it (set_draft's count, 2 of the head's 3 + * rounds): the rows of the step differ per sequence, the window is the larger of the two. Only the + * suffix row carries the Request::draft_suffix mark; the adaptive row's coupled states stay bound. */ +TEST(a_suffix_row_and_an_adaptive_depth_row_share_a_step) { + Fixture f; + suffix_setup(f); + CHECK_OK(f.start()); + const uint64_t a = ngram_cycle_request(f); + const uint64_t b = f.submit(160, 2000); + REQUIRE(f.sch.step() != nullptr); + f.commit_plain(100); + CHECK_OK(f.sch.set_draft(a, kHeadDraft, 3)); + CHECK_OK(f.sch.set_draft(b, kHeadDraft, 2)); /* the adaptive chain stopped after two rounds */ + const RadBatch* bt = f.sch.step(); + REQUIRE(bt != nullptr); + const StepPlan& p = f.sch.plan(); + REQUIRE_EQ(p.e.size(), (size_t)2); + size_t ia = 0, ib = 1; + if (p.e[0].seq != a) { ia = 1; ib = 0; } + CHECK(p.e[ia].suffix); + CHECK_EQ(p.e[ia].n_spec, 8); + CHECK(p.e[ia].req->draft_suffix); + CHECK(!p.e[ib].suffix); + CHECK_EQ(p.e[ib].n_spec, 2); + CHECK(!p.e[ib].req->draft_suffix); + CHECK_EQ(bt->n_spec, 8); + CHECK_EQ(bt->n_tok, 9 + 3); + for (int j = 0; j < 2; ++j) CHECK_EQ(f.sch.find(b)->draft[j], kHeadDraft[j]); + /* A accepts 5 of its 8, B both: each is counted for what it carried */ + CHECK_OK(f.commit(900, 0, [&](const StepEntry& e) { return e.seq == a ? 5 : 2; })); + const SchedMetrics m = f.sch.metrics(); + CHECK_EQ(m.suffix_steps, (int64_t)1); + CHECK_EQ(m.suffix_rows, (int64_t)8); + CHECK_EQ(m.suffix_accepted, (int64_t)5); + CHECK_EQ(m.draft_tokens, (int64_t)10); + CHECK_EQ(m.draft_accepted, (int64_t)7); +} + +/* The host's order under the adaptive depth: sequences whose history is not in a pattern are issued + * ahead with their own row counts (expect_draft of the chain each drafted) in a suffix deployment's + * wider window; one in a pattern holds the whole step back and takes its suffix step after the commit. */ +TEST(adaptive_depth_rows_are_issued_ahead_in_a_suffix_deployment_unless_a_sequence_is_in_a_pattern) { + for (int hot = 0; hot < 2; ++hot) { + Fixture f; + suffix_setup(f); + CHECK_OK(f.start()); + const uint64_t a = hot ? ngram_cycle_request(f) : f.submit(160, 2000); + const uint64_t b = f.submit(160, 2000); + REQUIRE(f.sch.step() != nullptr); + f.commit_plain(hot ? 100 : 7); + CHECK_OK(f.sch.set_draft(a, kHeadDraft, 3)); + CHECK_OK(f.sch.set_draft(b, kHeadDraft, 2)); + REQUIRE(f.sch.step() != nullptr); + f.sch.find(a)->speculation_fixed = true; + f.sch.find(b)->speculation_fixed = true; + f.sch.expect_draft(a, 3); + f.sch.expect_draft(b, 2); + const RadBatch* nb = f.sch.step_next(); + if (hot) { + CHECK(nb == nullptr); + } else { + REQUIRE(nb != nullptr); + std::vector q; + for (int64_t i = 0; i < nb->n_seq; ++i) q.push_back((int)nb->q_lens[i]); + std::sort(q.begin(), q.end()); + REQUIRE_EQ(q.size(), (size_t)2); + CHECK_EQ(q[0], 3); /* 1 + the 2 drafts of one chain */ + CHECK_EQ(q[1], 4); /* 1 + the 3 of the other */ + } + } +}