Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
Speculation: --lookup-chain (prompt lookup chained after the MTP drafts), --mtp-hnorm stream, draft sources
Niko12212312c83bfd59
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 40db3c68a..db9f88ac4 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -774,7 +774,8 @@ 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 src/spec/draft_policy.cpp)+add_library(strata_spec STATIC src/spec/suffix_drafter.cpp src/spec/controller.cpp src/spec/draft_policy.cpp+ src/spec/draft_source.cpp)target_include_directories(strata_spec PUBLIC include)if(STRATA_BUILD_TESTS)add_executable(suffix_drafter_test src/spec/suffix_drafter_test.cpp)diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hppindex e2084f6d2..5163b022c 100644--- a/include/strata/core/mtp.hpp+++ b/include/strata/core/mtp.hpp@@ -48,6 +48,13 @@ public:void set_prompt_len(int64_t n) { prompt_len_ = n; }/// At most this many drafts per round (below max_t - 1): a window longer than the MTP's comes from elsewhere.void set_max_drafts(int k) { max_drafts_ = k; }+ /// --mtp-hnorm stream (opt-in; before the first draft or prefill): pre_fc_norm_hidden normalizes each+ /// hyper-connection stream on its own, as llama.cpp's qwen4exp MTP graph does, instead of one RMS over all four.+ void set_hnorm_per_stream(bool on) { hnorm_stream_ = on; }+ bool hnorm_per_stream() const { return hnorm_stream_; }+ /// STRATA_MTP_TOP2=1 (diagnostic): draft j's runner-up token in the last draft() (-1 = unknown)+ static bool top2_env();+ int32_t top2(int j) const { return j >= 0 && j < (int) top2_.size() ? top2_[(size_t) j] : -1; }uint64_t vram_bytes() const { return vram_; }/// The draft layer's K/V state (read-only: --serve's STRATA_STATE_HASH check hashes it)const QsaState& kv_state() const { return st_; }@@ -130,6 +137,10 @@ private:int max_t_ = 0;int device_ = -1; ///< the device `load` ran on: the public calls switch to it (layer split)int max_drafts_ = 1 << 30;+ bool hnorm_stream_ = false;+ void record_top2(int j);+ std::vector<int32_t> top2_, dvocab_host_;+ std::vector<float> lg_host_;int64_t n_vocab_ = 0;uint64_t vram_ = 0;cudaStream_t cs_ = nullptr;diff --git a/include/strata/kernels/native_qsa.hpp b/include/strata/kernels/native_qsa.hppindex c56eb4d29..e789fa3e3 100644--- a/include/strata/kernels/native_qsa.hpp+++ b/include/strata/kernels/native_qsa.hpp@@ -21,6 +21,11 @@ bool native_qsa_enabled();void native_qsa_rms_norm_weighted(const float* input, const float* gamma, float* output,int n_cols, int n_rows, float epsilon, void* stream);+// The same per row with gamma[n_cols * groups]: row r is normalized on its own and scaled by gamma's slice+// r % groups (the MTP's hidden input, one row per hyper-connection stream: --mtp-hnorm stream).+void native_qsa_rms_norm_grouped(const float* input, const float* gamma, float* output,+ int n_cols, int groups, int n_rows, float epsilon, void* stream);+// attn/output [head_dim,n_head]; q_full [2*head_dim,n_head], each row is// [query channels, gate channels]. Output is attn*sigmoid(second-half gate).// Exact output==attn is supported; all other spans must be disjoint.diff --git a/include/strata/spec/draft_source.hpp b/include/strata/spec/draft_source.hppnew file mode 100644index 000000000..109d3c745--- /dev/null+++ b/include/strata/spec/draft_source.hpp@@ -0,0 +1,62 @@+// include/strata/spec/draft_source.hpp - a source of draft tokens beside the MTP layer (--lookup-chain).+//+// A source proposes how the context continues; the verify window checks the proposal, so a source can only change+// the speed, never the output. The engine asks its sources after the MTP has drafted: the context it passes ends+// with those MTP drafts (not yet verified), and whatever a source returns is appended to the same window.+//+// The built-in source is the request's own text (PromptLookupSource: the suffix drafter over prompt + output).+// Other sources (a retrieval store over a codebase or earlier conversations) register with+// extra_draft_sources() before the first request; the engine takes the proposal with the longest match.+#pragma once++#include "strata/spec/suffix_drafter.hpp"++#include <cstddef>+#include <cstdint>+#include <memory>+#include <vector>++namespace strata::spec {++class DraftSource {+public:+ virtual ~DraftSource() = default;+ virtual const char* name() const = 0;+ /// A new request starts (its prompt follows through append()).+ virtual void reset() {}+ /// Committed context, in order: the request's prompt, then every token the verify windows accept.+ virtual void append(const int32_t* tokens, size_t n) { (void) tokens; (void) n; }+ /// Propose up to `max_k` tokens that follow the context. `tail` holds the context's last `n_tail` tokens (at most+ /// 64); its last `n_pending` are drafts not yet verified (never passed to append()). Writes `out`, returns how+ /// many (0 = nothing to propose) and sets `*match` to the number of trailing context tokens the proposal is based+ /// on (its confidence: the engine requires --lookup-chain-min and prefers the longest).+ virtual int propose(const int32_t* tail, int n_tail, int n_pending, int max_k, int32_t* out, int* match) = 0;+};++/// The request's own text: the suffix drafter (prompt lookup) behind the DraftSource interface.+class PromptLookupSource final : public DraftSource {+public:+ explicit PromptLookupSource(SuffixDrafter& d) : d_(d) {}+ const char* name() const override { return "prompt-lookup"; }+ void reset() override { d_.reset(); }+ void append(const int32_t* tokens, size_t n) override { d_.append(tokens, n); }+ int propose(const int32_t* tail, int n_tail, int n_pending, int max_k, int32_t* out, int* match) override {+ n_pending = n_pending < n_tail ? n_pending : n_tail;+ const int k = d_.propose_after(tail + (n_tail - n_pending), n_pending, max_k, out);+ *match = k > 0 ? d_.last_match() : 0;+ return k;+ }++private:+ SuffixDrafter& d_;+};++/// Sources besides the request's own text, asked after it (empty unless something registered one at startup).+std::vector<std::unique_ptr<DraftSource>>& extra_draft_sources();++/// Ask `own` and then every extra source; the proposal with the longest match of at least `min_match` wins+/// (ties keep the earlier source). Returns its length (0 = none); `*match` and `*source` (index: 0 = own) describe it.+int propose_from_sources(DraftSource& own, const int32_t* tail, int n_tail, int n_pending, int max_k, int min_match,+ int32_t* out, int* match, int* source);++} // namespace strata::specdiff --git a/include/strata/spec/suffix_drafter.hpp b/include/strata/spec/suffix_drafter.hppindex 731bbef1b..e84593bf1 100644--- a/include/strata/spec/suffix_drafter.hpp+++ b/include/strata/spec/suffix_drafter.hpp@@ -30,9 +30,15 @@ public:/// Write up to `max_k` proposed next tokens to `out`; returns how many (0 = no match of at least min_match).int propose(int max_k, int32_t* out);+ /// --lookup-chain: as propose(), for the history followed by `extra` (the draft head's proposal for the next+ /// tokens), so the lookup continues where those drafts end. The history itself is unchanged; the extra tokens are+ /// only part of the suffix being matched and may be read back as part of a periodic continuation.+ int propose_after(const int32_t* extra, int n_extra, int max_k, int32_t* out);+/// Length of the match behind the last proposal (0 if none).int last_match() const { return last_match_; }size_t size() const { return hist_.size(); }+ const std::vector<int32_t>& history() const { return hist_; }private:struct Slot {diff --git a/src/core/mtp.cpp b/src/core/mtp.cppindex e2b89b6ff..be57de2f1 100644--- a/src/core/mtp.cpp+++ b/src/core/mtp.cpp@@ -301,9 +301,43 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Sessionreturn true;}+namespace {+// STRATA_MTP_FULL_HEAD=1 (a diagnostic): draft over the whole vocabulary (the main head itself) instead of+// rt/draft_vocab.bin's subset - the reference head, to measure what the subset costs in acceptance+bool full_head_env() {+ static const bool on = [] { const char* v = std::getenv("STRATA_MTP_FULL_HEAD"); return v && v[0] == '1'; }();+ return on;+}+} // namespace++bool MtpDrafter::top2_env() {+ static const bool on = [] { const char* v = std::getenv("STRATA_MTP_TOP2"); return v && v[0] == '1'; }();+ return on;+}++// STRATA_MTP_TOP2=1 (a diagnostic for tree drafts): draft j's runner-up under the draft layer, from the head logits+// the step just wrote (row 0), on the host. Slow; only for measuring what a second branch would have caught.+void MtpDrafter::record_top2(int j) {+ const int64_t nv = dhead_ != nullptr ? n_dvocab_ : n_vocab_;+ if ((int64_t) lg_host_.size() < nv) lg_host_.resize((size_t) nv);+ if ((int) top2_.size() < max_t_) top2_.assign((size_t) max_t_, -1);+ if (j < 0 || j >= max_t_) return;+ if (cudaMemcpy(lg_host_.data(), head_logits_, (size_t) nv * sizeof(float), cudaMemcpyDeviceToHost) != cudaSuccess) {+ top2_[(size_t) j] = -1;+ return;+ }+ int64_t b1 = -1, b2 = -1;+ for (int64_t i = 0; i < nv; ++i) {+ const float v = lg_host_[(size_t) i];+ if (b1 < 0 || v > lg_host_[(size_t) b1]) { b2 = b1; b1 = i; }+ else if (b2 < 0 || v > lg_host_[(size_t) b2]) b2 = i;+ }+ top2_[(size_t) j] = b2 < 0 ? -1 : dhead_ != nullptr ? dvocab_host_[(size_t) b2] : (int32_t) b2;+}+uint64_t MtpDrafter::bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const {uint64_t bytes = head_logits_ ? 0 : (uint64_t) max_t_ * (uint64_t) n_vocab * sizeof(float);- if (dhead_ == nullptr) {+ if (dhead_ == nullptr && !full_head_env()) {if (FILE* f = std::fopen((rt_dir_ + "/draft_vocab.bin").c_str(), "rb")) {std::fseek(f, 0, SEEK_END);const long size = std::ftell(f);@@ -426,7 +460,7 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const floatreturn false;}// the draft head's token subset, when tools/draft_vocab.py wrote one- if (dhead_ == nullptr) {+ if (dhead_ == nullptr && !full_head_env()) {std::vector<uint8_t> raw;if (read_file(rt_dir_ + "/draft_vocab.bin", raw) && raw.size() >= 4 && raw.size() % 4 == 0) {n_dvocab_ = (int64_t) (raw.size() / 4);@@ -438,6 +472,8 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const floatreturn false;}cudaMemcpy(dvocab_, raw.data(), raw.size(), cudaMemcpyHostToDevice);+ dvocab_host_.resize((size_t) n_dvocab_);+ std::memcpy(dvocab_host_.data(), raw.data(), raw.size());strata::kernels::gather_rows((const uint8_t*) head->weights(), row_bytes, dvocab_, n_dvocab_, dhead_, nullptr);cudaDeviceSynchronize();vram_ += (uint64_t) (n_dvocab_ * row_bytes) + raw.size();@@ -479,7 +515,10 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::strinative_qsa_rms_norm_weighted(emb_, f32("pre_fc_norm_embedding.weight"), en_, (int) N, T, EPS, cs);native_quantize_q8_1(en_, xq_, (int) N, T, cs);native_mmvq(GGML_Q8_0, q8("fc_embedding.weight"), xq_, e2_, (int) N, (int) N, T, cs);- native_qsa_rms_norm_weighted(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) (HC * N), T, EPS, cs);+ if (hnorm_stream_) // --mtp-hnorm stream: one RMS per stream, each scaled by its slice of the weight+ native_qsa_rms_norm_grouped(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) N, (int) HC, (int) (T * HC), EPS, cs);+ else+ native_qsa_rms_norm_weighted(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) (HC * N), T, EPS, cs);for (int c0 = 0; c0 < T * HC; c0 += 8) {const int nc = (int) std::min<int64_t>(8, T * HC - c0);native_quantize_q8_1(hn_ + (size_t) c0 * N, xq_, (int) N, nc, cs);@@ -837,6 +876,7 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t*return false;}drafts[0] = ((volatile int32_t*) h_out_)[0];+ if (top2_env()) record_top2(0);float pj = ((volatile float*) h_prob_)[0];if (probs) probs[0] = pj;int n = 1;@@ -851,6 +891,7 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t*return false;}drafts[j] = ((volatile int32_t*) h_out_)[j];+ if (top2_env()) record_top2(j);pj = ((volatile float*) h_prob_)[j];if (probs) probs[j] = pj;++n;diff --git a/src/kernels/cuda/native_qsa.cu b/src/kernels/cuda/native_qsa.cuindex 32e2511c2..2e2e1e6bf 100644--- a/src/kernels/cuda/native_qsa.cu+++ b/src/kernels/cuda/native_qsa.cu@@ -66,6 +66,31 @@ __global__ void norm(const float* input, const float* __restrict__ gamma, float*for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize)output[col] = scale * input[col] * gamma[col];}+// As norm, with gamma[groups * n_cols]: row r is group r % groups and reads its own slice of gamma.+template<int BlockSize>+__global__ void norm_grouped(const float* input, const float* __restrict__ gamma, float* output,+ int n_cols, int groups, float epsilon) {+ const int tid = threadIdx.x;+ const std::size_t row_offset = std::size_t(blockIdx.x) * n_cols;+ input += row_offset; output += row_offset;+ gamma += std::size_t(blockIdx.x % unsigned(groups)) * n_cols;+ float partial = 0.0f;+ for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) {+ const float x = input[col];+ partial += x * x;+ }+ __shared__ float sums[32];+ partial = warp_sum(partial);+ const int lane = tid % 32;+ if (lane == 0) sums[tid / 32] = partial;+ __syncthreads();+ partial = lane < BlockSize / 32 ? sums[lane] : 0.0f;+ partial = warp_sum(partial);+ const float mean = partial / n_cols;+ const float scale = rsqrtf(mean + epsilon);+ for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize)+ output[col] = scale * input[col] * gamma[col];+}__global__ void gate(const float* attn, const float* __restrict__ q_full, float* output,int n_head, int head_dim) {const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x;@@ -117,6 +142,21 @@ void native_qsa_rms_norm_weighted(const float* input, const float* gamma, float*norm<1024><<<unsigned(n_rows), 1024, 0, static_cast<cudaStream_t>(stream)>>>(input, gamma, output, n_cols, epsilon);check_launch();}+void native_qsa_rms_norm_grouped(const float* input, const float* gamma, float* output,+ int n_cols, int groups, int n_rows, float epsilon, void* stream) {+ if (groups < 1) throw std::invalid_argument("native QSA requires positive bounded dimensions");+ const auto count = elements(n_cols, n_rows);+ if (!std::isfinite(epsilon) || epsilon < 0.0f)+ throw std::invalid_argument("native QSA requires finite nonnegative epsilon");+ buffers(input, count * 4, gamma, std::size_t(n_cols) * groups * 4, output, stream);+ if (n_cols < 1024)+ norm_grouped<256><<<unsigned(n_rows), 256, 0, static_cast<cudaStream_t>(stream)>>>(input, gamma, output, n_cols,+ groups, epsilon);+ else+ norm_grouped<1024><<<unsigned(n_rows), 1024, 0, static_cast<cudaStream_t>(stream)>>>(input, gamma, output, n_cols,+ groups, epsilon);+ check_launch();+}void native_qsa_gate_apply(const float* attn, const float* q_full, float* output,int n_head, int head_dim, void* stream) {const auto count = elements(head_dim, n_head);diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cppindex 54c9cb7e5..e4ddd1c1b 100644--- a/src/prefill/prefill.cpp+++ b/src/prefill/prefill.cpp@@ -7,6 +7,7 @@#include "strata/core/layout.hpp"#include "strata/kernels/cpu/expert.hpp"+#include "strata/kernels/native_qsa.hpp"#include "strata/kernels/native_qsa_indexer.hpp"#include "strata/kernels/ngram.hpp"#include "strata/kernels/ple.hpp"@@ -923,7 +924,10 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_tif (!q8) to_f16(emb, en16, nb * Nn, m.cs);proj(emb, en16, w_fe, e2, nb, Nn, Nn, 0);cudaMemcpyAsync(hn, R_rows + (size_t) b0 * HCN, (size_t) nb * HCN * 4, cudaMemcpyDeviceToDevice, m.cs);- rms_rows(hn, w_nh, nb, HCN, HCN, EPS, m.cs);+ if (mtp.hnorm_per_stream()) // --mtp-hnorm stream: as the drafter's own pass (mtp.cpp)+ strata::kernels::native_qsa_rms_norm_grouped(hn, w_nh, hn, (int) Nn, (int) g.hc, (int) (nb * g.hc), EPS, m.cs);+ else+ rms_rows(hn, w_nh, nb, HCN, HCN, EPS, m.cs);if (!q8) to_f16(hn, hn16, nb * HCN, m.cs);proj(hn, hn16, w_fh, h2, nb * g.hc, Nn, Nn, 1); // every stream through fc_hiddenstrata::kernels::add_streams_broadcast(h2, e2, Rm, Nn, (int) g.hc, (int) nb, m.cs);diff --git a/src/program/generate.cpp b/src/program/generate.cppindex 711f23035..6ce42903a 100644--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@ -53,6 +53,7 @@#include "strata/program/logits_selection.hpp"#include "strata/program/conv_cache.hpp"#include "strata/spec/draft_policy.hpp"+#include "strata/spec/draft_source.hpp"#include "strata/spec/suffix_drafter.hpp"#include "strata/kernels/cvec.hpp"#include "strata/core/progress.hpp"@@ -410,6 +411,14 @@ struct Options {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;+ /// --lookup-chain K (opt-in, 0 = off): prompt lookup CHAINED after the MTP's proposal. The suffix drafter matches+ /// the context followed by the MTP's drafts and appends up to K of the tokens that followed that match to the same+ /// verify window (the window grows to at most 8). Greedy verification keeps the output; its own counts are kept.+ int lookup_chain = 0;+ int lookup_chain_min = 3; ///< --lookup-chain-min M: the shortest match (in tokens, drafts included) it extends on+ /// --mtp-hnorm stream (opt-in): the draft layer's pre_fc_norm_hidden normalizes each hyper-connection stream on+ /// its own (llama.cpp's qwen4exp MTP graph) instead of one RMS over all four (the default, tools/mtp_probe.py).+ bool mtp_hnorm_stream = false;/// A control vector on the residual stream (strata/kernels/cvec.hpp), with llama.cpp's flags: the/// `experimental-speed-projection` profile passes `--control-vector-scaled FILE:1.0 --control-vector-layer-range/// 4 44 --cvec-mode project --cvec-dir per-layer`. None by default; --serve switches a loaded one per request.@@ -508,6 +517,11 @@ void usage() {" --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"+ " --lookup-chain K opt-in: after the MTP's drafts, add up to K prompt-lookup drafts that continue\n"+ " them (the window grows to at most 8; default 0 = off)\n"+ " --lookup-chain-min M the shortest context match --lookup-chain extends on (default 3)\n"+ " --mtp-hnorm pooled|stream the draft layer's hidden-input norm: one RMS over all four streams\n"+ " (default) or one per stream (llama.cpp's MTP graph)\n"" --control-vector-scaled FILE:SCALE[,...] a control vector GGUF on the residual stream (llama.cpp's\n"" format; --control-vector FILE = scale 1). --serve: requests switch it (cvec=0|1)\n"" --control-vector-layer-range A B the layers it follows (inclusive; default 1 .. the last)\n"@@ -584,6 +598,23 @@ void usage() {" does not fit. Same answers as --mmap-experts for the same placement.\n");}+// --lookup-chain: the context's last tokens for the draft sources (at most 64), the MTP's pending drafts last+int chain_tail(const strata::spec::SuffixDrafter& sfx, const int32_t* pending, int n_pending, std::vector<int32_t>& tail) {+ const std::vector<int32_t>& h = sfx.history();+ const int keep = std::max(0, std::min((int) h.size(), 64 - n_pending));+ tail.assign(h.end() - keep, h.end());+ tail.insert(tail.end(), pending, pending + n_pending);+ return (int) tail.size();+}++// --lookup-chain: the registered extra draft sources (strata/spec/draft_source.hpp) see the committed context too+void extra_sources_reset() {+ for (auto& src : strata::spec::extra_draft_sources()) src->reset();+}+void extra_sources_append(const int32_t* t, size_t n) {+ for (auto& src : strata::spec::extra_draft_sources()) src->append(t, n);+}+bool parse_i64_list(const char* s, std::vector<int64_t>& out, std::string& err) {out.clear();std::string text(s);@@ -1176,6 +1207,16 @@ int main(int argc, char** argv) {else if (a == "--short-read") o.short_read = std::max(0LL, std::atoll(next("--short-read")));else if (a == "--suffix-draft") o.suffix_draft = std::max(0, std::atoi(next("--suffix-draft")));else if (a == "--mtp-max-t") o.mtp_max_t = std::max(0, std::atoi(next("--mtp-max-t")));+ else if (a == "--lookup-chain") o.lookup_chain = std::clamp(std::atoi(next("--lookup-chain")), 0, 7);+ else if (a == "--lookup-chain-min") o.lookup_chain_min = std::max(3, std::atoi(next("--lookup-chain-min")));+ else if (a == "--mtp-hnorm") {+ const std::string v = next("--mtp-hnorm");+ if (v != "pooled" && v != "stream") {+ std::fprintf(stderr, "strata generate: --mtp-hnorm takes pooled or stream\n");+ return 2;+ }+ o.mtp_hnorm_stream = v == "stream";+ }else if (a == "--control-vector") o.cvec_files.push_back({next("--control-vector"), 1.0f});else if (a == "--control-vector-scaled") {// FILE:SCALE, comma-separated; the LAST colon splits, so a Windows path (C:\...) keeps its drive@@ -1506,6 +1547,11 @@ int main(int argc, char** argv) {o.mtp_max_t = o.spec;o.spec = std::min(o.spec + 2, 8); // kVerifyMaxT}+ // --lookup-chain (opt-in): the MTP keeps its windows; a lookup chained after its drafts may lengthen one by up to K+ if (o.lookup_chain > 0 && o.spec >= 2) {+ if (o.mtp_max_t == 0) o.mtp_max_t = o.spec;+ o.spec = std::max(o.spec, std::min(o.mtp_max_t + o.lookup_chain, 8)); // kVerifyMaxT+ }strata::core::layer_set_shared_early(!o.shared_late);if (!o.native_preset.empty()) {try {@@ -2520,6 +2566,7 @@ int main(int argc, char** argv) {o.mtp.clear();}if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size());+ mtp.set_hnorm_per_stream(o.mtp_hnorm_stream); // --mtp-hnorm stream (opt-in), before any capture// the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned,// so it always sees the canonical geometry; `static` because MtpDrafter keeps a referencestatic const strata::core::ModelGeometry draft_geometry{};@@ -5409,12 +5456,21 @@ int main(int argc, char** argv) {std::vector<int32_t> drafts((size_t) S, 0), window((size_t) S), outv((size_t) S);std::vector<float> dprob((size_t) S, 0.0f);std::vector<int32_t> sbuf((size_t) S, 0);- if (o.suffix_draft > 0) {+ const bool sfx_on = o.suffix_draft > 0 || o.lookup_chain > 0;+ if (sfx_on) {sfx.reset();for (int64_t t : ids) sfx.append((int32_t) t);}+ if (o.lookup_chain > 0) {+ extra_sources_reset();+ for (int64_t t : ids) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); }+ }bool first_window = true;int64_t produced_n = 0, sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0;+ int64_t chain_windows = 0, chain_drafts = 0, chain_ok = 0; // --lookup-chain's own counts+ int64_t t2_rej[8] = {}, t2_hit[8] = {}; // STRATA_MTP_TOP2: rejections inside the MTP drafts by depth, runner-up hits+ std::vector<int32_t> cbuf((size_t) S, 0), ctail;+ strata::spec::PromptLookupSource lookup_src(sfx);int64_t draft_offered = 0, draft_accepted = 0;// what the session holds once this request is done: the prompt read so far, then every committed tokenstd::vector<int32_t> consumed;@@ -5461,11 +5517,23 @@ int main(int argc, char** argv) {if (pk.lookup) { T = pk.t; from_sfx = true; }}}+ // --lookup-chain: what followed an earlier occurrence of the context + the MTP's drafts, after them+ int chain_n = 0;+ if (o.lookup_chain > 0 && !first_window && !from_sfx && T < S) {+ int cm = 0, csrc = -1;+ const int nt = chain_tail(sfx, drafts.data(), T - 1, ctail);+ chain_n = strata::spec::propose_from_sources(lookup_src, ctail.data(), nt, T - 1,+ std::min(o.lookup_chain, S - T), o.lookup_chain_min,+ cbuf.data(), &cm, &csrc);+ }+ const int T_mtp = T;+ T += chain_n;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];+ for (int i = 1; i < T_mtp; ++i) window[(size_t) i] = from_sfx ? sbuf[(size_t) i - 1] : drafts[(size_t) i - 1];+ for (int i = 0; i < chain_n; ++i) window[(size_t) (T_mtp + i)] = cbuf[(size_t) i];drive.d.layers = 0;drive.d.experts = 0;drive.d.failed = false;@@ -5490,6 +5558,11 @@ int main(int argc, char** argv) {int a = 0;while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a;if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; }+ if (chain_n > 0) { ++chain_windows; chain_drafts += chain_n; chain_ok += std::max(0, a - (T_mtp - 1)); }+ if (strata::core::MtpDrafter::top2_env() && !from_sfx && !first_window && a < T_mtp - 1 && a < 8) {+ ++t2_rej[a];+ if (mtp.top2(a) == outv[(size_t) a]) ++t2_hit[a];+ }const Clock::time_point tw1 = Clock::now();std::thread adapt_thr; // the adaptive tier beside the commit and the draft (as in generate)bool adapt_ok = true;@@ -5510,7 +5583,8 @@ int main(int argc, char** argv) {std::printf("T %d\n", (int) outv[(size_t) i]);strata::core::progress_beat();++produced_n;- if (o.suffix_draft > 0) sfx.append(outv[(size_t) i]);+ if (sfx_on) sfx.append(outv[(size_t) i]);+ if (o.lookup_chain > 0) extra_sources_append(&outv[(size_t) i], 1);eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end();}std::fflush(stdout);@@ -5537,7 +5611,7 @@ int main(int argc, char** argv) {std::printf("ERR %s\n", err.c_str());return 1;}- if (timed_round && !eos)+ if (timed_round && !eos && chain_n == 0) // a chained window is neither an MTP nor a lookup windowpolicy.observe(from_sfx, T, a, sfx_match,std::chrono::duration<double, std::milli>(Clock::now() - round0).count());if (eos) { finish = "stop"; break; }@@ -5692,11 +5766,17 @@ int main(int argc, char** argv) {// DONE <generated> <prompt> <prompt ms> <decode ms> <finish> <drafts accepted> <drafts offered> <reused> [hits] [lookups]// [RAM blobs] [file blobs] [file MB] (CS-T tiers; appended, so an older server reads the rest)// [prompt tokens read] (#471: fewer than <prompt> - <reused> when a cancel stopped the read)- std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld\n", (long long) produced_n,+ // [lookup-chain accepted] [lookup-chain offered] [suffix accepted] [suffix offered] [windows]+ // (only with --lookup-chain)+ char chain_txt[128] = "";+ if (o.lookup_chain > 0)+ std::snprintf(chain_txt, sizeof(chain_txt), " %lld %lld %lld %lld %lld", (long long) chain_ok,+ (long long) chain_drafts, (long long) sfx_ok, (long long) sfx_drafts, (long long) dec_windows);+ std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld%s\n", (long long) produced_n,(long long) n, prompt_ms, decode_ms, finish, (long long) draft_accepted, (long long) draft_offered,(long long) resume, (long long) req_hits, (long long) req_look,(long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0),- (double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n);+ (double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n, chain_txt);std::fflush(stdout);if (drive.routing != nullptr) std::fflush(drive.routing); // the routing trace survives a crash and is watchable mid-session// "12288 of 98179" when cancelled mid-read (#471), the rate from what was read@@ -5759,6 +5839,14 @@ int main(int argc, char** argv) {if (sfx_windows > 0)std::fprintf(stderr, "strata serve: suffix drafts: %lld windows, %lld of %lld drafts accepted\n",(long long) sfx_windows, (long long) sfx_ok, (long long) sfx_drafts);+ if (o.lookup_chain > 0)+ std::fprintf(stderr, "strata serve: lookup chain: %lld of %lld windows, %lld of %lld chained drafts accepted\n",+ (long long) chain_windows, (long long) dec_windows, (long long) chain_ok, (long long) chain_drafts);+ if (strata::core::MtpDrafter::top2_env())+ std::fprintf(stderr, "strata serve: mtp top2: rejected/runner-up by depth %lld/%lld %lld/%lld %lld/%lld %lld/%lld "+ "of %lld windows\n", (long long) t2_rej[0], (long long) t2_hit[0], (long long) t2_rej[1],+ (long long) t2_hit[1], (long long) t2_rej[2], (long long) t2_hit[2], (long long) t2_rej[3],+ (long long) t2_hit[3], (long long) dec_windows);for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0)std::fprintf(stderr, "strata serve: CUDA%d: %lld expert entries, %lld active layer launches, %.1f MiB returned ""(%.1f MiB with full rows) in this request; host %.0f ms staging+launching, %.0f ms "@@ -6252,10 +6340,19 @@ int main(int argc, char** argv) {strata::spec::DraftPolicy policy(o.spec); // MTP or lookup window (see draft_policy.hpp)std::vector<int32_t> sbuf((size_t) o.spec, 0);int64_t sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0;- if (o.suffix_draft > 0) {+ int64_t chain_windows = 0, chain_drafts = 0, chain_ok = 0; // --lookup-chain's own counts+ std::vector<int32_t> cbuf((size_t) o.spec, 0), ctail;+ strata::spec::PromptLookupSource lookup_src(sfx);+ const bool sfx_on = o.suffix_draft > 0 || o.lookup_chain > 0;+ if (sfx_on) {for (int64_t t : o.tokens) sfx.append((int32_t) t);for (int64_t t : produced) sfx.append((int32_t) t);}+ if (o.lookup_chain > 0) {+ extra_sources_reset();+ for (int64_t t : o.tokens) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); }+ for (int64_t t : produced) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); }+ }const double pool_ms0 = drive.cpu_ms;const int64_t misses0 = drive.d.multi_misses, entries0 = drive.d.multi_entries;while ((int64_t) produced.size() < o.max_new) {@@ -6276,6 +6373,17 @@ int main(int argc, char** argv) {if (pk.lookup) { T = pk.t; from_sfx = true; }}}+ // --lookup-chain: what followed an earlier occurrence of the context + the MTP's drafts, after them+ int chain_n = 0;+ if (o.lookup_chain > 0 && use_mtp && !first_window && !from_sfx && T < o.spec) {+ int cm = 0, csrc = -1;+ const int nt = chain_tail(sfx, drafts.data(), T - 1, ctail);+ chain_n = strata::spec::propose_from_sources(lookup_src, ctail.data(), nt, T - 1,+ std::min(o.lookup_chain, o.spec - T), o.lookup_chain_min,+ cbuf.data(), &cm, &csrc);+ }+ const int T_mtp = T;+ T += chain_n;const bool timed_round = !first_window;++window_hist[(size_t) T];if (p + T > o.max_context) {@@ -6287,6 +6395,7 @@ int main(int argc, char** argv) {const size_t at = produced.size() - 1 + (size_t) i;int32_t d = from_sfx ? sbuf[(size_t) i - 1] : use_mtp ? drafts[(size_t) i - 1]: at < oracle.size() ? (int32_t) oracle[at] : 0;+ if (i >= T_mtp) d = cbuf[(size_t) (i - T_mtp)];if (o.spec_corrupt > 0 && (++corrupt_counter % o.spec_corrupt) == 0) d = (d + 1) % (int32_t) n_vocab;window[(size_t) i] = d;}@@ -6336,10 +6445,12 @@ int main(int argc, char** argv) {drafts_ok += a;++accepted_hist[(size_t) a];if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; }+ if (chain_n > 0) { ++chain_windows; chain_drafts += chain_n; chain_ok += std::max(0, a - (T_mtp - 1)); }bool eos = false;for (int i = 0; i <= a && (int64_t) produced.size() < o.max_new && !eos; ++i) {produced.push_back(outv[(size_t) i]);- if (o.suffix_draft > 0) sfx.append(outv[(size_t) i]);+ if (sfx_on) sfx.append(outv[(size_t) i]);+ if (o.lookup_chain > 0) extra_sources_append(&outv[(size_t) i], 1);eos = o.stop_eos && std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end();}if (eos) {@@ -6359,7 +6470,7 @@ int main(int argc, char** argv) {p += a + 1;const double round_ms = std::chrono::duration<double, std::milli>(Clock::now() - t0).count();total_ms += round_ms;- if (timed_round) policy.observe(from_sfx, T, a, sfx_match, round_ms);+ if (timed_round && chain_n == 0) 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);@@ -6381,6 +6492,9 @@ int main(int argc, char** argv) {if (o.suffix_draft > 0)std::printf("%-24s %lld windows, drafts accepted %lld of %lld\n", "suffix drafts", (long long) sfx_windows,(long long) sfx_ok, (long long) sfx_drafts);+ if (o.lookup_chain > 0)+ std::printf("%-24s %lld windows, chained drafts accepted %lld of %lld\n", "lookup chain",+ (long long) chain_windows, (long long) chain_ok, (long long) chain_drafts);std::printf("%-24s", "accepted per round");for (size_t i = 0; i < accepted_hist.size(); ++i) std::printf(" %zu:%lld", i, (long long) accepted_hist[i]);std::printf("\n");diff --git a/src/spec/draft_source.cpp b/src/spec/draft_source.cppnew file mode 100644index 000000000..2fcbc406e--- /dev/null+++ b/src/spec/draft_source.cpp@@ -0,0 +1,36 @@+// src/spec/draft_source.cpp - see include/strata/spec/draft_source.hpp.+#include "strata/spec/draft_source.hpp"++#include <vector>++namespace strata::spec {++std::vector<std::unique_ptr<DraftSource>>& extra_draft_sources() {+ static std::vector<std::unique_ptr<DraftSource>> sources;+ return sources;+}++int propose_from_sources(DraftSource& own, const int32_t* tail, int n_tail, int n_pending, int max_k, int min_match,+ int32_t* out, int* match, int* source) {+ *match = 0;+ *source = -1;+ if (max_k <= 0) return 0;+ int best = 0;+ std::vector<int32_t> buf((size_t) max_k);+ auto ask = [&](DraftSource& s, int index) {+ int m = 0;+ const int k = s.propose(tail, n_tail, n_pending, max_k, buf.data(), &m);+ if (k <= 0 || m < min_match || m <= *match) return;+ for (int i = 0; i < k && i < max_k; ++i) out[i] = buf[(size_t) i];+ best = k < max_k ? k : max_k;+ *match = m;+ *source = index;+ };+ ask(own, 0);+ int index = 1;+ for (auto& s : extra_draft_sources())+ if (s) ask(*s, index++);+ return best;+}++} // namespace strata::specdiff --git a/src/spec/suffix_drafter.cpp b/src/spec/suffix_drafter.cppindex 6f04f76d5..86c7da158 100644--- a/src/spec/suffix_drafter.cpp+++ b/src/spec/suffix_drafter.cpp@@ -85,4 +85,14 @@ int SuffixDrafter::propose(int max_k, int32_t* out) {return k;}+int SuffixDrafter::propose_after(const int32_t* extra, int n_extra, int max_k, int32_t* out) {+ if (n_extra <= 0) return propose(max_k, out);+ // the index holds the history's trigrams only: appended without indexing, the extra tokens just form the suffix+ const size_t n0 = hist_.size();+ hist_.insert(hist_.end(), extra, extra + n_extra);+ const int k = propose(max_k, out);+ hist_.resize(n0);+ return k;+}+} // namespace strata::specdiff --git a/src/spec/suffix_drafter_test.cpp b/src/spec/suffix_drafter_test.cppindex 9fa8611e7..79dc15322 100644--- a/src/spec/suffix_drafter_test.cpp+++ b/src/spec/suffix_drafter_test.cpp@@ -111,6 +111,23 @@ void unit_tests() {int32_t out[4];check(d.propose(4, out) > 0, "propose after overflow of nominal capacity");}+ {+ // --lookup-chain: the match continues from the drafts appended to the history, which stays unchanged+ SuffixDrafter d(3, 32, 256);+ const int32_t hist[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 50, 51, 52, 1, 2};+ d.append(hist, sizeof(hist) / sizeof(hist[0]));+ const int32_t drafts[] = {3, 4};+ int32_t out[8] = {};+ const int k = d.propose_after(drafts, 2, 3, out);+ check(k == 3 && out[0] == 5 && out[1] == 6 && out[2] == 7, "propose_after continues after the drafts");+ check(d.last_match() >= 4, "propose_after match length counts the drafts");+ check(d.size() == sizeof(hist) / sizeof(hist[0]), "propose_after leaves the history unchanged");+ const int32_t miss[] = {99, 98, 97};+ check(d.propose_after(miss, 3, 3, out) == 0, "propose_after without a match proposes nothing");+ // the plain proposal is unaffected: the history's own suffix (52, 1, 2) has no earlier occurrence+ check(d.propose(3, out) == 0, "propose after propose_after");+ check(d.propose_after(nullptr, 0, 3, out) == d.propose(3, out), "propose_after with no drafts == propose");+ }std::printf("suffix_drafter unit tests: %s\n", g_fail ? "FAILED" : "OK");}} // namespace