diff --git a/CMakeLists.txt b/CMakeLists.txt index fc5e9d67..9a7260b5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -424,7 +424,7 @@ endif() # worse opt-out. `cpu_require_expert_support()` therefore refuses at startup on a CPU without the # features, and the fallback exists for tests, exactly as P2.S3 specifies. # Plan v0.3 P6: speculation components that need no GPU. -add_library(strata_spec STATIC src/spec/suffix_drafter.cpp src/spec/controller.cpp) +add_library(strata_spec STATIC src/spec/suffix_drafter.cpp src/spec/controller.cpp src/spec/draft_policy.cpp) target_include_directories(strata_spec PUBLIC include) if(STRATA_BUILD_TESTS) add_executable(suffix_drafter_test src/spec/suffix_drafter_test.cpp) @@ -433,6 +433,9 @@ if(STRATA_BUILD_TESTS) add_executable(controller_test src/spec/controller_test.cpp) target_link_libraries(controller_test PRIVATE strata_spec) add_test(NAME controller_test COMMAND controller_test) + add_executable(draft_policy_test src/spec/draft_policy_test.cpp) + target_link_libraries(draft_policy_test PRIVATE strata_spec) + add_test(NAME draft_policy_test COMMAND draft_policy_test) endif() add_library(strata_kernels_cpu STATIC src/kernels/cpu/expert.cpp src/kernels/cpu/pool.cpp diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 3fa7e0f3..25195451 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -332,7 +332,9 @@ test images. as the GPU works on the cached ones (AVX-512 / AVX2 kernels, ggml's for the i-quants). - **SSD:** the 28.8 GB n-gram table, read a few rows per token through the OS cache. - **Speculation:** the model's own MTP layer drafts up to 3 tokens; one pass over all 48 layers checks them. 2.4-3.2 - tokens per pass on average. + tokens per pass on average. When the reply repeats the context (code edits, quoted text), **prompt lookup** (engine + 0.1.7) drafts up to 5 tokens from the earlier copy, but only where its measured acceptance and cost say it pays: + code edits 6-11% faster, other text unchanged. The drafts are checked like the MTP's, so the output is the same. - **Prompts** are processed in 2,048-token chunks with the experts streamed to the GPU over PCIe. The full story, with measurements, bottlenecks and what comes next: **[docs/paper/Strata-Paper.pdf](paper/Strata-Paper.pdf)**. diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index 7bdf6ae1..e30c4e23 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -63,8 +63,7 @@ public: /// request; greedy by default. The sampling itself runs OUTSIDE the captured graph - its /// parameters would otherwise be baked forever - so this can change between requests freely. void set_sampling(const strata::kernels::SamplerParams& sp) { - sampling_ = sp; - draw_counter_ = 0; // each request's sampling starts its own draw sequence + sampling_ = sp; // row t of a window at pos0 draws Philox(seed, pos0 + t): see run() } /// The penalty-history row for `sampling_.penalty_last_n`: ONE row of `history_len` int32 slots, most @@ -106,7 +105,6 @@ private: s.temperature = 0.0f; return s; }(); ///< greedy by default; per-request via set_sampling - uint64_t draw_counter_ = 0; ///< advanced by T on every sampled window; reset by set_sampling const int32_t* hist_d_ = nullptr; ///< penalty-history row (set_history); null = no penalties apply int hist_len_ = 0; bool capture_commit(std::string& err); diff --git a/include/strata/spec/draft_policy.hpp b/include/strata/spec/draft_policy.hpp new file mode 100644 index 00000000..c77b8696 --- /dev/null +++ b/include/strata/spec/draft_policy.hpp @@ -0,0 +1,52 @@ +// include/strata/spec/draft_policy.hpp - per verify round: the MTP's window, or a lookup (suffix) window? +// +// The suffix drafter (prompt lookup) proposes the tokens that followed an earlier repeat of the context. Taken +// whenever it proposes more than the MTP, it lost 2-8% on ordinary text: a long lookup window costs much more to +// verify than the MTP's usual 3-4 tokens, and it is only worth that when enough of it is accepted. llama.cpp's +// lookup decoding answers the same problem with confidence thresholds on its n-gram statistics; here the policy +// learns both sides online and compares expected committed tokens per millisecond: +// +// MTP E = the mean tokens a window of that size has committed (EMA), at the measured cost of that size +// lookup E(k) = 1 + q + q^2 + ... + q^k for k <= the proposal, q = the acceptance rate of lookup drafts whose +// match was about as long (4 buckets of match length, decayed counts), at the measured cost of k + 1 +// +// and takes the lookup window only when its best E/cost beats the MTP's by `margin`. Costs are the measured round +// times per window size (EMA; sizes not seen yet are scaled from seen ones by a prior shape), so the policy adapts +// to the machine and the context length. It only chooses which drafts to verify: the output is unchanged. +#pragma once + +#include + +namespace strata::spec { + +class DraftPolicy { +public: + static constexpr int kMaxT = 8; + static constexpr int kBuckets = 4; + + explicit DraftPolicy(int max_t, double margin = 0.03); + + struct Pick { + bool lookup = false; + int t = 1; // window size (1 + drafts) + }; + /// `t_mtp`: the MTP's window; `lookup_k`: the lookup proposal's length (0 = none); `match`: its match length. + Pick choose(int t_mtp, int lookup_k, int match) const; + /// After the round: the window it used, the drafts accepted, and the round's time (verify + commit + draft). + void observe(bool lookup, int t, int accepted, int match, double round_ms); + + double lookup_rate(int match) const; // current q for a match length + double cost_ms(int t) const; // measured or scaled round time of a window of t tokens + +private: + static int bucket(int match); + double mtp_tokens(int t) const; + + int max_t_; + double margin_; + std::array cost_{}, cost_n_{}; // round ms by window size + std::array mtp_tok_{}, mtp_n_{}; // tokens committed by MTP windows of that size + std::array ok_{}, bad_{}; // lookup drafts accepted / windows cut short, decayed +}; + +} // namespace strata::spec diff --git a/setup.py b/setup.py index 66c81b7a..a40aab52 100644 --- a/setup.py +++ b/setup.py @@ -54,7 +54,7 @@ PREBUILT_ASSET = "strata-windows-x64.zip" if WIN else "strata-linux-x64.zip" # the CUDA libraries the ready-made engine loads (the same CUDA 13.0 it is built with), from NVIDIA's pip packages CUDA_WHEELS = ["nvidia-cublas==13.0.2.14", "nvidia-cuda-runtime==13.0.96"] MIN_DRIVER = 580 # CUDA 13.0 -MIN_ENGINE = (0, 1, 6) # KV streaming (--kv-resident), v0.1.5; its drafter fallback, v0.1.6 +MIN_ENGINE = (0, 1, 7) # per-request sampling on the GEN line (the server sends it), v0.1.7 PY_PACKAGES = ["numpy", "jinja2", "regex", "pyyaml", "tqdm", "requests", "cmake", "ninja", "pillow"] MODELS = { @@ -696,7 +696,14 @@ def main() -> int: warn("less than 12 GB of VRAM: Strata will run, but most experts stay on the CPU and it will be slow") ram = ram_gb() cpu, avx2, avx512 = cpu_info() - ok(f"RAM: {ram:.0f} GB") + need = min(d["ram_gb"] for d in MODELS.values()) + if ram < need - 4 and not a.check: + # every model keeps ALL its experts in RAM (34+ GB); VRAM only holds a copy of the most-used ones, so a + # bigger GPU does not lower this + fail(f"RAM: {ram:.0f} GB - the smallest model (Q2_0 / IQ2_XS) needs about {need} GB", + "Strata keeps all of the model's experts in RAM (34-50 GB, whatever the GPU) and the GPU holds a copy " + "of the most-used ones: it needs 48 GB of RAM or more") + ok(f"RAM: {ram:.0f} GB" if ram >= need - 4 else f"RAM: {ram:.0f} GB (less than the {need} GB the smallest model needs)") ok(f"CPU: {cpu} ({'AVX-512' if avx512 else 'AVX2' if avx2 else 'no AVX2'})") if not avx2: fail("this CPU has no AVX2; Strata needs at least AVX2") diff --git a/src/core/verify.cpp b/src/core/verify.cpp index e4f8bc63..70b089b7 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -113,7 +113,6 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& max_t_ = max_t; sampling_.greedy = true; // a fresh verifier samples greedily until set_sampling says otherwise sampling_.temperature = 0.0f; - draw_counter_ = 0; if (max_t < 2 || max_t > strata::kernels::kVerifyMaxT || max_t > strata::kernels::cpu::MAXT) { err = "verify: the window must hold 2.." + std::to_string(strata::kernels::kVerifyMaxT) + " tokens"; return false; @@ -597,8 +596,13 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { return false; } } - // the sampling is NOT recorded here: it runs host-side after the graph (run()), because - // its parameters change per request and a captured kernel would bake them forever + // Greedy, the default, is recorded here as before (no extra launch or sync per window). A request that + // samples or penalizes is sampled again host-side after the replay (run()) with its own parameters and a + // fresh draw counter: a captured sampler would bake them in and replay the same draws forever. + SamplerParams sp; + sp.greedy = true; + sp.temperature = 0.0f; + sample_tokens(head_logits_, T, (int) n_vocab_, nullptr, 0, sp, m_out_, cs); } return true; } @@ -794,17 +798,19 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, const cudaError_t se = cudaStreamSynchronize(cs_); if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; } cudaStreamSynchronize(copy_); // no host function of this window may raise flag B in the next one - // ---- the head's sampling, host-side so its parameters are this call's own (a captured kernel - // would replay the same draws forever). The counter advances by the window's rows. - SamplerParams sp = sampling_; - sp.counter = draw_counter_; - draw_counter_ += (uint64_t) T; - sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_); - const cudaError_t sm = cudaMemcpyAsync(h_out_, m_out_, (size_t) T * sizeof(int32_t), - cudaMemcpyDeviceToHost, cs_); - if (sm != cudaSuccess || cudaStreamSynchronize(cs_) != cudaSuccess) { - err = "verify: the head sampling failed"; - return false; + // ---- a sampled or penalized request: the head's sampling again, host-side so its parameters are this call's + // own (a captured kernel would replay the same draws forever). Row t's draw is Philox(seed, pos0 + t): tied to + // the POSITION it samples, not to how the text was cut into windows, so a seed replays the same text whatever + // the drafts were. Exact: a rejected row's draw is discarded, and no kept decision depends on a reused draw. + const bool sampled = !sampling_.greedy && sampling_.temperature > 0.0f; + if (sampled || hist_d_ != nullptr) { + SamplerParams sp = sampling_; + sp.counter = (uint64_t) pos0; + sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_); + if (cudaStreamSynchronize(cs_) != cudaSuccess) { // m_out_ is the mapped h_out_: synced, it is readable + err = "verify: the head sampling failed"; + return false; + } } for (int t = 0; t < T; ++t) out[t] = ((volatile int32_t*) h_out_)[t]; VDBG("window done\n"); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index ffd8cc14..21569114 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -41,6 +41,7 @@ #include "strata/prefill/prefill.hpp" #include "strata/core/native_dense.hpp" #include "strata/program/logits_selection.hpp" +#include "strata/spec/draft_policy.hpp" #include "strata/spec/suffix_drafter.hpp" #include @@ -250,10 +251,11 @@ struct Options { /// result) goes through the verify windows, S tokens at a time, instead of the batched prompt path (0 = always /// the batched path) int64_t short_read = 64; - /// The suffix drafter: when the text being written repeats an earlier stretch of the context (code edits, quoted - /// input, tool-call JSON) by at least this many tokens, the window is filled with what followed it there instead - /// of the MTP's drafts, up to --spec - 1 of them, as long as the MTP's own first guess agrees. 0 = MTP only. - int suffix_draft = 0; + /// The suffix drafter (prompt lookup): when the text being written repeats an earlier stretch of the context (code + /// edits, quoted input, tool-call JSON) by at least this many tokens, the window may be filled with what followed + /// it there instead of the MTP's drafts, where the MTP's own first guess agrees and the draft policy expects it to + /// pay (strata/spec/draft_policy.hpp). On by default; 0 = MTP only. + int suffix_draft = 3; /// The MTP's own window cap (0 = --spec): with --spec 6 --mtp-max-t 4 the long windows come from suffix matches. int mtp_max_t = 0; }; @@ -322,7 +324,8 @@ void usage() { " --turn-token ID --serve: the token that opens a chat turn (default 248045, <|im_start|>)\n" " --short-read N --serve: read at most N fresh text tokens through the decode windows instead\n" " of the batched prompt path (default 64, 0 = off)\n" - " --suffix-draft N draft from an earlier repeat of the last N+ tokens of context (0 = MTP only)\n" + " --suffix-draft N prompt lookup: draft from an earlier repeat of the last N+ tokens of context\n" + " when it pays (default 3; 0 = MTP only)\n" " --mtp-max-t M cap the MTP's windows at M tokens (0 = --spec; longer ones come from suffixes)\n" " --no-token-graph A/B: two graphs per layer (the host launches each) instead of one per token\n" " --no-fused-gr A/B: the six-kernel hyper-connection read and a separate write (native)\n" @@ -732,6 +735,13 @@ int main(int argc, char** argv) { return 2; } strata::core::qsa_set_kv_resident(o.kv_resident); + // Prompt lookup (the suffix drafter, on by default): the MTP keeps its --spec windows and a lookup window may be + // up to 2 tokens longer; the draft policy (strata/spec/draft_policy.hpp) takes one only where it pays. Code + // edits +6-11%, ordinary text unchanged (bench/results/2026-09-27-spec). --suffix-draft 0 turns it off. + if (o.suffix_draft > 0 && o.spec >= 2 && o.mtp_max_t == 0) { + o.mtp_max_t = o.spec; + o.spec = std::min(o.spec + 2, 8); // kVerifyMaxT + } strata::core::layer_set_shared_early(!o.shared_late); if (!o.native_preset.empty()) { if (o.no_ple || o.ple_gguf.empty()) { @@ -2174,6 +2184,7 @@ int main(int argc, char** argv) { const int S_mtp = o.mtp_max_t > 0 ? std::min(o.mtp_max_t, S) : S; // the MTP's windows; suffixes go up to S if (S_mtp < S) mtp.set_max_drafts(S_mtp - 1); strata::spec::SuffixDrafter sfx(std::max(1, o.suffix_draft), 64, (size_t) o.max_context + 4096); + strata::spec::DraftPolicy policy(S); // MTP or lookup window, learned over the whole process // The vision path (--vision): GENI carries images. The file is one // or more strata-vision records (int32 'SVE1', n, nx, ny, n_embd, then n x n_embd floats) in prompt order; // each image's rows go to its run of <|image_pad|> tokens, whose M-RoPE positions are mtmd's: t = p, @@ -2552,13 +2563,20 @@ int main(int argc, char** argv) { while (T < S_mtp && dprob[(size_t) T - 1] >= (float) o.spec_min_p) ++T; } if (first_window) T = 1; - // a repeat of earlier context proposes more than the MTP is confident about: take it, but only where the - // MTP's own first guess agrees (a repeat the model is not following costs a whole window) + // a repeat of earlier context (prompt lookup) where the MTP's own first guess agrees: the policy takes it + // when its expected tokens per ms, from the measured acceptance and window costs, beat the MTP window's bool from_sfx = false; + int sfx_match = 0; if (o.suffix_draft > 0 && !first_window) { const int k = sfx.propose(S - 1, sbuf.data()); - if (k + 1 > T && sbuf[0] == drafts[0]) { T = k + 1; from_sfx = true; } + sfx_match = sfx.last_match(); + if (k > 0 && sbuf[0] == drafts[0]) { + const strata::spec::DraftPolicy::Pick pk = policy.choose(T, k, sfx_match); + if (pk.lookup) { T = pk.t; from_sfx = true; } + } } + const bool timed_round = !first_window; + const Clock::time_point round0 = Clock::now(); if (p + T > o.max_context) break; window[0] = x; for (int i = 1; i < T; ++i) window[(size_t) i] = from_sfx ? sbuf[(size_t) i - 1] : drafts[(size_t) i - 1]; @@ -2621,6 +2639,9 @@ int main(int argc, char** argv) { std::printf("ERR %s\n", err.c_str()); return 1; } + if (timed_round && !eos) + policy.observe(from_sfx, T, a, sfx_match, + std::chrono::duration(Clock::now() - round0).count()); if (eos) { finish = "stop"; break; } if (stop_req.load()) { finish = "cancel"; break; } x = outv[(size_t) a]; @@ -3181,6 +3202,7 @@ int main(int argc, char** argv) { const int S_mtp = o.mtp_max_t > 0 ? std::min(o.mtp_max_t, o.spec) : o.spec; if (use_mtp && S_mtp < o.spec) mtp.set_max_drafts(S_mtp - 1); strata::spec::SuffixDrafter sfx(std::max(1, o.suffix_draft), 64, (size_t) o.max_context + 4096); + strata::spec::DraftPolicy policy(o.spec); // MTP or lookup window (see draft_policy.hpp) std::vector sbuf((size_t) o.spec, 0); int64_t sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0; if (o.suffix_draft > 0) { @@ -3198,10 +3220,16 @@ int main(int argc, char** argv) { } if (first_window) T = 1; bool from_sfx = false; + int sfx_match = 0; if (o.suffix_draft > 0 && !first_window) { const int k = sfx.propose(o.spec - 1, sbuf.data()); - if (k + 1 > T && (!use_mtp || sbuf[0] == drafts[0])) { T = k + 1; from_sfx = true; } + sfx_match = sfx.last_match(); + if (k > 0 && (!use_mtp || sbuf[0] == drafts[0])) { + const strata::spec::DraftPolicy::Pick pk = policy.choose(T, k, sfx_match); + if (pk.lookup) { T = pk.t; from_sfx = true; } + } } + const bool timed_round = !first_window; ++window_hist[(size_t) T]; if (p + T > o.max_context) { std::fprintf(stderr, "strata generate: ran out of context at position %lld\n", (long long) p); @@ -3272,7 +3300,9 @@ int main(int argc, char** argv) { } x = outv[(size_t) a]; p += a + 1; - total_ms += std::chrono::duration(Clock::now() - t0).count(); + const double round_ms = std::chrono::duration(Clock::now() - t0).count(); + total_ms += round_ms; + if (timed_round) policy.observe(from_sfx, T, a, sfx_match, round_ms); if (rounds % 64 == 0) std::fprintf(stderr, "strata generate: position %lld, %lld tokens, %lld rounds\n", (long long) p, (long long) produced.size(), (long long) rounds); diff --git a/src/spec/draft_policy.cpp b/src/spec/draft_policy.cpp new file mode 100644 index 00000000..1ac77198 --- /dev/null +++ b/src/spec/draft_policy.cpp @@ -0,0 +1,101 @@ +// src/spec/draft_policy.cpp - see include/strata/spec/draft_policy.hpp. +#include "strata/spec/draft_policy.hpp" + +#include + +namespace strata::spec { +namespace { + +// The shape of a round's cost by window size, relative to one token, used only for sizes not measured yet (the +// measured round times replace it). Between the RTX 5070's measured curves: +10 ms per token with every missed expert +// on the CPU (bench/results/2026-09-27-spec/window-cost), flatter with the default CPU/DMA split. +constexpr double kShape[DraftPolicy::kMaxT + 1] = {0.0, 1.0, 1.35, 1.7, 2.05, 2.45, 2.85, 3.25, 3.6}; +constexpr double kCostAlpha = 0.1; // EMA weight of a new round time +constexpr double kTokAlpha = 0.05; // EMA weight of a new MTP window outcome +constexpr double kDecay = 0.97; // lookup counts: older windows fade +// Before a bucket has data: the longer the match, the likelier its continuation (llama.cpp's lookup decoding gates +// on the same thing); worth 4 observations, so a few real windows override it +constexpr double kPriorQ[DraftPolicy::kBuckets] = {0.75, 0.88, 0.93, 0.96}; +constexpr double kPriorN = 4.0; +constexpr int kProbes = 3; // a lookup window size is tried this often before its guessed cost can veto it + +} // namespace + +DraftPolicy::DraftPolicy(int max_t, double margin) + : max_t_(std::clamp(max_t, 1, kMaxT)), margin_(margin) {} + +int DraftPolicy::bucket(int match) { + return match < 6 ? 0 : match < 12 ? 1 : match < 24 ? 2 : 3; +} + +double DraftPolicy::lookup_rate(int match) const { + const int b = bucket(match); + return (ok_[b] + kPriorN * kPriorQ[b]) / (ok_[b] + bad_[b] + kPriorN); +} + +double DraftPolicy::cost_ms(int t) const { + t = std::clamp(t, 1, kMaxT); + if (cost_n_[t] > 0) return cost_[t]; + // scale from the measured sizes, weighting each by how often it was seen + double num = 0.0, den = 0.0; + for (int u = 1; u <= kMaxT; ++u) + if (cost_n_[u] > 0) { + const double w = std::min(cost_n_[u], 20.0); + num += w * cost_[u] * kShape[t] / kShape[u]; + den += w; + } + return den > 0 ? num / den : kShape[t]; +} + +double DraftPolicy::mtp_tokens(int t) const { + if (mtp_n_[t] > 0) return mtp_tok_[t]; + return 1.0 + 0.7 * (t - 1); // before any MTP window of this size: a typical acceptance +} + +DraftPolicy::Pick DraftPolicy::choose(int t_mtp, int lookup_k, int match) const { + Pick p; + p.t = std::clamp(t_mtp, 1, max_t_); + if (lookup_k <= 0) return p; + const double base = mtp_tokens(p.t) / cost_ms(p.t); + const double q = lookup_rate(match); + double e = 1.0, qi = 1.0, best = 0.0; + int best_t = 0; + for (int k = 1; k <= std::min(lookup_k, max_t_ - 1); ++k) { + qi *= q; + e += qi; + const double r = e / cost_ms(k + 1); + if (r > best) { best = r; best_t = k + 1; } + } + if (best_t > 0 && best > base * (1.0 + margin_)) { + p.lookup = true; + p.t = best_t; + return p; + } + // a guessed cost can keep the policy from ever measuring a size: the first few times a confident lookup would + // need a size not measured yet, it is tried (verification keeps the output; only the one round's speed is at stake) + const int t_full = std::min(lookup_k, max_t_ - 1) + 1; + if (t_full > p.t && cost_n_[t_full] < kProbes && q >= 0.85) { + p.lookup = true; + p.t = t_full; + } + return p; +} + +void DraftPolicy::observe(bool lookup, int t, int accepted, int match, double round_ms) { + t = std::clamp(t, 1, kMaxT); + if (round_ms > 0) { + cost_[t] = cost_n_[t] > 0 ? (1.0 - kCostAlpha) * cost_[t] + kCostAlpha * round_ms : round_ms; + cost_n_[t] += 1.0; + } + if (lookup) { + const int b = bucket(match); + ok_[b] = kDecay * ok_[b] + accepted; + bad_[b] = kDecay * bad_[b] + (accepted < t - 1 ? 1.0 : 0.0); + } else { + const double got = accepted + 1.0; + mtp_tok_[t] = mtp_n_[t] > 0 ? (1.0 - kTokAlpha) * mtp_tok_[t] + kTokAlpha * got : got; + mtp_n_[t] += 1.0; + } +} + +} // namespace strata::spec diff --git a/src/spec/draft_policy_test.cpp b/src/spec/draft_policy_test.cpp new file mode 100644 index 00000000..e04b3de8 --- /dev/null +++ b/src/spec/draft_policy_test.cpp @@ -0,0 +1,63 @@ +// src/spec/draft_policy_test.cpp - DraftPolicy: when does a lookup window beat the MTP's? +// +// Simulated rounds with the costs measured on the RTX 5070 (window-cost: ~10 ms more per token) check that +// 1. with no lookup proposal the MTP window is kept; +// 2. lookup drafts that are mostly rejected stop being taken (their bucket's rate falls); +// 3. lookup drafts that are always accepted are taken, and the window grows with them; +// 4. match-length buckets learn separately (short matches failing does not stop long ones); +// 5. the policy never proposes a window beyond its cap. +#include "strata/spec/draft_policy.hpp" + +#include + +using strata::spec::DraftPolicy; + +namespace { +int g_fail = 0; +void check(bool ok, const char* what) { + std::printf(" %-66s %s\n", what, ok ? "ok" : "FAIL"); + if (!ok) ++g_fail; +} +double cost(int t) { return 19.0 + 10.5 * (t - 1); } // ms per round, measured shape +} // namespace + +int main() { + std::printf("draft_policy_test\n"); + { + DraftPolicy p(6); + for (int i = 0; i < 50; ++i) p.observe(false, 4, 2, 0, cost(4)); // MTP windows of 4: 3 tokens each + const DraftPolicy::Pick k = p.choose(4, 0, 0); + check(!k.lookup && k.t == 4, "no proposal: the MTP window"); + } + { + DraftPolicy p(6); + for (int i = 0; i < 50; ++i) p.observe(false, 4, 2, 0, cost(4)); + for (int t = 2; t <= 6; ++t) p.observe(false, t, 0, 0, cost(t)); + for (int i = 0; i < 40; ++i) p.observe(true, 6, 0, 4, cost(6)); // short matches, all rejected + check(p.lookup_rate(4) < 0.15, "rejected short-match drafts: their rate falls below 0.15"); + check(!p.choose(4, 5, 4).lookup, "rejected short-match drafts: no longer taken"); + for (int i = 0; i < 40; ++i) p.observe(true, 6, 5, 30, cost(6)); // long matches, all accepted + check(p.lookup_rate(30) > 0.9, "accepted long-match drafts: their rate rises above 0.9"); + const DraftPolicy::Pick k = p.choose(4, 5, 30); + check(k.lookup && k.t == 6, "accepted long matches: the full lookup window is taken"); + check(!p.choose(4, 5, 4).lookup, "buckets are separate: short matches still not taken"); + check(p.choose(4, 20, 30).t <= 6, "never beyond the window cap"); + } + { + DraftPolicy p(8); + for (int i = 0; i < 50; ++i) p.observe(false, 3, 2, 0, cost(3)); // a very good MTP: 3 of 3 tokens + for (int t = 2; t <= 8; ++t) p.observe(false, t, t - 1, 0, cost(t)); + for (int i = 0; i < 40; ++i) p.observe(true, 4, 2, 8, cost(4)); // lookup at q ~ 0.67 + check(!p.choose(3, 7, 8).lookup, "a mediocre lookup does not replace a strong MTP window"); + } + { + DraftPolicy p(6); + for (int i = 0; i < 50; ++i) p.observe(false, 4, 3, 0, cost(4)); // a near-perfect MTP, only size 4 seen + const DraftPolicy::Pick k = p.choose(4, 5, 40); + check(k.lookup && k.t == 6, "an unmeasured size is probed for a confident lookup"); + for (int i = 0; i < 3; ++i) p.observe(true, 6, 5, 40, 3.0 * cost(6)); // it turns out very expensive + check(!p.choose(4, 5, 40).lookup, "after the probes, the measured cost decides"); + } + std::printf(g_fail ? "FAIL\n" : "PASS\n"); + return g_fail ? 1 : 0; +} diff --git a/tools/_paths.py b/tools/_paths.py index aaea7300..336719ec 100644 --- a/tools/_paths.py +++ b/tools/_paths.py @@ -14,7 +14,7 @@ ENGINE = Path(__file__).resolve().parents[1] def gguf_py() -> str: cands = [os.environ.get("STRATA_GGUF_PY"), ENGINE / "third_party" / "llama.cpp" / "gguf-py", - ENGINE.parents[1] / ".ref" / "llama.cpp" / "gguf-py"] + ENGINE.parents[min(1, len(ENGINE.parents) - 1)] / ".ref" / "llama.cpp" / "gguf-py"] # the dev tree; a shallow install (G:\Strata) has no grandparent for c in cands: if c and (Path(c) / "gguf").is_dir(): return str(c) diff --git a/tools/mtp_rt.py b/tools/mtp_rt.py index e3e8f6d7..6276e4c8 100644 --- a/tools/mtp_rt.py +++ b/tools/mtp_rt.py @@ -19,7 +19,6 @@ from pathlib import Path import numpy as np -STRATA = Path(__file__).resolve().parents[3] sys.path.insert(0, str(Path(__file__).resolve().parent)) from _paths import add_gguf_py # noqa: E402 add_gguf_py() diff --git a/tools/pack_layer.py b/tools/pack_layer.py index f9263690..1fdf1148 100644 --- a/tools/pack_layer.py +++ b/tools/pack_layer.py @@ -34,7 +34,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from gguf_reader import GGUFFile # noqa: E402 REPO = pathlib.Path(__file__).resolve().parents[1] -STRATA = REPO.parents[1] # the development layout's default shards (setup.py always passes --gguf) +STRATA = REPO.parents[min(1, len(REPO.parents) - 1)] # the dev layout's default shards (setup.py passes --gguf) SHARD1 = STRATA / "Q2_0" / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf" H, FF, NE = 2560, 640, 512 diff --git a/tools/strata_pack.py b/tools/strata_pack.py index 6ad7cf5b..37b5a720 100644 --- a/tools/strata_pack.py +++ b/tools/strata_pack.py @@ -41,7 +41,8 @@ from canonical_xcheck import (MAPPINGS, KV_IQ4NL, open_shard, # noqa FORMAT_VERSION = 1 ALIGN = 64 # every plane starts on a 64-byte boundary (P1.S7) -STRATA = pathlib.Path(__file__).resolve().parents[3] # the development layout; build takes the shard from --gguf +_HERE = pathlib.Path(__file__).resolve() +STRATA = _HERE.parents[min(3, len(_HERE.parents) - 1)] # the development layout; build takes the shard from --gguf SHARD2 = STRATA / "Q2_0" / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf" EXPERT_RE = ("ffn_gate_exps.weight", "ffn_up_exps.weight", "ffn_down_exps.weight")