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++
MTP draft head: --mtp-q4 (4-bit projections and draft head) and --mtp-draft-vocab FILE
Niko1221e35a061f1dda
diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hppindex 5163b022c..8f290a739 100644--- a/include/strata/core/mtp.hpp+++ b/include/strata/core/mtp.hpp@@ -52,6 +52,13 @@ public:/// 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_; }+ /// --mtp-q4 (opt-in; before load): the draft layer's Q8_0 projections and its draft head run from 4-bit (Q4_0)+ /// copies made at load/bind - fewer bytes per draft step; drafts only, the verify window decides every token.+ /// (The prompt path's batched K/V pass keeps the Q8_0 originals.)+ void set_q4(bool on) { q4_ = on; }+ /// --mtp-draft-vocab FILE (opt-in; before bind): the draft head's token subset from FILE instead of+ /// rt/draft_vocab.bin (e.g. data/draft_vocab_en.bin, 40K tokens)+ void set_draft_vocab(const std::string& path) { dvocab_path_ = path; }/// 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; }@@ -138,6 +145,16 @@ private: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;+ bool q4_ = false;+ uint8_t* dense4_ = nullptr; ///< --mtp-q4: Q4_0 copies of the Q8_0 tensors+ std::vector<std::pair<std::string, uint64_t>> q4_off_;+ int dhead_type_ = -1; ///< the draft head subset's ggml type (the main head's, or Q4_0)+ std::string dvocab_path_;+ std::string vocab_file() const { return dvocab_path_.empty() ? rt_dir_ + "/draft_vocab.bin" : dvocab_path_; }+ /// a projection's weights for the draft layer's own pass: the Q4_0 copy under --mtp-q4, else the Q8_0 original+ const void* wq(const char* name, int& type) const;+ bool make_q4_dense(const std::vector<uint8_t>& blob, std::string& err);+ bool make_q4_head(std::string& err);void record_top2(int j);std::vector<int32_t> top2_, dvocab_host_;std::vector<float> lg_host_;diff --git a/src/core/mtp.cpp b/src/core/mtp.cppindex be57de2f1..d2f605183 100644--- a/src/core/mtp.cpp+++ b/src/core/mtp.cpp@@ -36,11 +36,16 @@#include <sstream>#include <vector>+#ifdef STRATA_NATIVE_EXPERTS+#include "ggml.h" // --mtp-q4: the head rows' and projections' formats, dequantized and requantized at load+#endif+namespace strata::core {namespace {constexpr float EPS = 1e-6f;constexpr int GGML_Q8_0 = 8;+constexpr int GGML_Q4_0 = 2;using Clock = std::chrono::steady_clock;double ms_since(Clock::time_point t) { return std::chrono::duration<double, std::milli>(Clock::now() - t).count(); }@@ -104,6 +109,7 @@ MtpDrafter::~MtpDrafter() {for (auto& e : prefill_exec_) if (e) cudaGraphExecDestroy(e);for (auto& e : prefill_dev_exec_) if (e) cudaGraphExecDestroy(e);if (pf_dev_) cudaFree(pf_dev_);+ if (dense4_) cudaFree(dense4_);for (auto& e : round_exec_) if (e) cudaGraphExecDestroy(e);for (auto& e : step_exec_) if (e) cudaGraphExecDestroy(e);for (auto& e : round_exec_c_) if (e) cudaGraphExecDestroy(e);@@ -138,6 +144,74 @@ const void* MtpDrafter::q8(const char* name) const {for (const auto& t : tensors_) if (t.name == name && t.kind == "q8_0") return dense_ + t.off;return nullptr;}+const void* MtpDrafter::wq(const char* name, int& type) const {+ if (dense4_ != nullptr)+ for (const auto& e : q4_off_)+ if (e.first == name) { type = GGML_Q4_0; return dense4_ + e.second; }+ type = GGML_Q8_0;+ return q8(name);+}++// --mtp-q4: every Q8_0 tensor of dense.bin as Q4_0 (ggml's reference quantizer), in one device buffer+bool MtpDrafter::make_q4_dense(const std::vector<uint8_t>& blob, std::string& err) {+#ifdef STRATA_NATIVE_EXPERTS+ uint64_t total = 0;+ std::vector<std::pair<const Tensor*, uint64_t>> plan;+ for (const auto& t : tensors_) {+ if (t.kind != "q8_0" || t.cols % 32 != 0) continue;+ plan.push_back({&t, total});+ total += ((uint64_t) t.rows * (uint64_t) (t.cols / 32) * 18 + 255) & ~255ull;+ }+ std::vector<uint8_t> host((size_t) total);+ std::vector<float> row;+ const auto* q8t = ggml_get_type_traits(GGML_TYPE_Q8_0);+ for (const auto& [t, off] : plan) {+ row.resize((size_t) t->cols);+ const uint64_t in_row = (uint64_t) (t->cols / 32) * 34, out_row = (uint64_t) (t->cols / 32) * 18;+ for (int64_t r = 0; r < t->rows; ++r) {+ q8t->to_float(blob.data() + t->off + (uint64_t) r * in_row, row.data(), t->cols);+ ggml_quantize_chunk(GGML_TYPE_Q4_0, row.data(), host.data() + off + (uint64_t) r * out_row, 0, 1, t->cols,+ nullptr);+ }+ q4_off_.push_back({t->name, off});+ }+ if (cudaMalloc((void**) &dense4_, (size_t) total) != cudaSuccess) { err = "mtp: the Q4_0 projections do not fit"; return false; }+ cudaMemcpy(dense4_, host.data(), (size_t) total, cudaMemcpyHostToDevice);+ vram_ += total;+ std::fprintf(stderr, "strata mtp: --mtp-q4: %zu projections as Q4_0 (%.1f MiB)\n", plan.size(), (double) total / 1048576.0);+ return true;+#else+ (void) blob;+ err = "mtp: --mtp-q4 needs a build with native experts (ggml)";+ return false;+#endif+}++// --mtp-q4: the draft head's subset rows as Q4_0 (dequantized from the main head's format)+bool MtpDrafter::make_q4_head(std::string& err) {+#ifdef STRATA_NATIVE_EXPERTS+ const int64_t N = g_->n_embd;+ const auto* tt = ggml_get_type_traits((ggml_type) head_->type());+ if (tt == nullptr || tt->to_float == nullptr || N % 32 != 0) { err = "mtp: --mtp-q4 cannot read the head's format"; return false; }+ const size_t in_row = head_->row_bytes(), out_row = (size_t) (N / 32) * 18;+ std::vector<uint8_t> src((size_t) n_dvocab_ * in_row), dst((size_t) n_dvocab_ * out_row);+ if (cudaMemcpy(src.data(), dhead_, src.size(), cudaMemcpyDeviceToHost) != cudaSuccess) { err = "mtp: reading the draft head"; return false; }+ std::vector<float> row((size_t) N);+ for (int64_t r = 0; r < n_dvocab_; ++r) {+ tt->to_float(src.data() + (size_t) r * in_row, row.data(), N);+ ggml_quantize_chunk(GGML_TYPE_Q4_0, row.data(), dst.data() + (size_t) r * out_row, 0, 1, N, nullptr);+ }+ // the Q4_0 rows replace the subset in place (they are smaller)+ if (cudaMemcpy(dhead_, dst.data(), dst.size(), cudaMemcpyHostToDevice) != cudaSuccess) { err = "mtp: writing the draft head"; return false; }+ dhead_type_ = GGML_Q4_0;+ std::fprintf(stderr, "strata mtp: --mtp-q4: draft head over %lld tokens as Q4_0 (%.1f MiB read per step, was %.1f)\n",+ (long long) n_dvocab_, (double) dst.size() / 1048576.0, (double) src.size() / 1048576.0);+ return true;+#else+ err = "mtp: --mtp-q4 needs a build with native experts (ggml)";+ return false;+#endif+}bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, SessionState& ss, int max_t, std::string& err,int64_t window) {@@ -176,6 +250,7 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session}cudaMemcpy(dense_, blob.data(), blob.size(), cudaMemcpyHostToDevice);vram_ += blob.size();+ if (q4_ && !make_q4_dense(blob, err)) return false;}// ---- the 512 routed experts, one blob each{@@ -338,7 +413,7 @@ void MtpDrafter::record_top2(int j) {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 && !full_head_env()) {- if (FILE* f = std::fopen((rt_dir_ + "/draft_vocab.bin").c_str(), "rb")) {+ if (FILE* f = std::fopen(vocab_file().c_str(), "rb")) {std::fseek(f, 0, SEEK_END);const long size = std::ftell(f);std::fclose(f);@@ -462,7 +537,7 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float// the draft head's token subset, when tools/draft_vocab.py wrote oneif (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) {+ if (read_file(vocab_file(), raw) && raw.size() >= 4 && raw.size() % 4 == 0) {n_dvocab_ = (int64_t) (raw.size() / 4);const int64_t row_bytes = (int64_t) head->row_bytes(); // a vocabulary row of the native headif (cudaMalloc((void**) &dvocab_, raw.size()) != cudaSuccess ||@@ -479,6 +554,8 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const floatvram_ += (uint64_t) (n_dvocab_ * row_bytes) + raw.size();std::fprintf(stderr, "strata mtp: draft head over %lld tokens (%.1f MiB)\n", (long long) n_dvocab_,(double) (n_dvocab_ * row_bytes) / 1048576.0);+ dhead_type_ = head->type();+ if (q4_ && !make_q4_head(err)) return false;}}if (coupled_draft_env() && cparams_ == nullptr && !setup_coupled(err)) return false;@@ -499,6 +576,14 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::striconst GrShapes gs{g.n_embd, g.hc, g.hc_lr};const int32_t* step = step_ + row0 * 4;const int32_t* pos = pos_ + row0 * NH;+ // --mtp-q4: each projection's format and weights for this pass (Q8_0 unless the Q4_0 copies exist)+ int wt_fc_embedding, wt_fc_hidden, wt_k_proj, wt_v_proj, wt_q_proj, wt_o_proj;+ const void* wp_fc_embedding = wq("fc_embedding.weight", wt_fc_embedding);+ const void* wp_fc_hidden = wq("fc_hidden.weight", wt_fc_hidden);+ const void* wp_k_proj = wq("self_attn.k_proj.weight", wt_k_proj);+ const void* wp_v_proj = wq("self_attn.v_proj.weight", wt_v_proj);+ const void* wp_q_proj = wq("self_attn.q_proj.weight", wt_q_proj);+ const void* wp_o_proj = wq("self_attn.o_proj.weight", wt_o_proj);try {// ---- the two input branchesconst WeightRef* we = wt_->find("token_embd.weight");@@ -514,7 +599,7 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri}native_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_mmvq(wt_fc_embedding, wp_fc_embedding, xq_, e2_, (int) N, (int) N, T, cs);if (hnorm_stream_) // --mtp-hnorm stream: one RMS per stream, each scaled by its slice of the weightnative_qsa_rms_norm_grouped(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) N, (int) HC, (int) (T * HC), EPS, cs);else@@ -522,7 +607,7 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::strifor (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);- native_mmvq(GGML_Q8_0, q8("fc_hidden.weight"), xq_, h2_ + (size_t) c0 * N, (int) N, (int) N, nc, cs);+ native_mmvq(wt_fc_hidden, wp_fc_hidden, xq_, h2_ + (size_t) c0 * N, (int) N, (int) N, nc, cs);}add_streams_broadcast(h2_, e2_, R_, N, (int) HC, T, cs);// ---- the attention hyper-connection@@ -546,8 +631,8 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::strielse rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st_.cos_tab, st_.sin_tab, p, cs);};native_quantize_q8_1(mixed_, xq_, (int) N, T, cs);- native_mmvq(GGML_Q8_0, q8("self_attn.k_proj.weight"), xq_, kcur_, (int) N, (int) (NKV * HD), T, cs);- native_mmvq(GGML_Q8_0, q8("self_attn.v_proj.weight"), xq_, vcur_, (int) N, (int) (NKV * HD), T, cs);+ native_mmvq(wt_k_proj, wp_k_proj, xq_, kcur_, (int) N, (int) (NKV * HD), T, cs);+ native_mmvq(wt_v_proj, wp_v_proj, xq_, vcur_, (int) N, (int) (NKV * HD), T, cs);for (int t = 0; t < T; ++t) {norm_rope(kcur_ + t * NKV * HD, f32("self_attn.k_norm.weight"), (int) NKV, (int) HD, pos + t * NH);if (st_.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1@@ -566,7 +651,7 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::strivcur_ + t * NKV * HD, s, cs, &st_.host);}if (!full) return true;- native_mmvq(GGML_Q8_0, q8("self_attn.q_proj.weight"), xq_, qfull_, (int) N, (int) (NH * 2 * HD), T, cs);+ native_mmvq(wt_q_proj, wp_q_proj, xq_, qfull_, (int) N, (int) (NH * 2 * HD), T, cs);for (int t = 0; t < T; ++t) {float* qc = qcur_ + t * NH * HD;if (cudaMemcpy2DAsync(qc, (size_t) HD * 4, qfull_ + t * NH * 2 * HD, (size_t) HD * 2 * 4, (size_t) HD * 4,@@ -584,7 +669,7 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::strifor (int t = 0; t < T; ++t)native_qsa_gate_apply(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, attn32_ + t * NH * HD, (int) NH, (int) HD, cs);native_quantize_q8_1(attn32_, xq_, (int) (NH * HD), T, cs);- native_mmvq(GGML_Q8_0, q8("self_attn.o_proj.weight"), xq_, bo_, (int) (NH * HD), (int) N, T, cs);+ native_mmvq(wt_o_proj, wp_o_proj, xq_, bo_, (int) (NH * HD), (int) N, T, cs);// ---- the MLP hyper-connection (the attention write folded in){FusedGrArgs fa[kFusedGrMaxT];@@ -612,9 +697,9 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::strimoe_grouped_s2(grp_ptr_, grp_start_, grp_counts_, hit_dst_, hit_slot_, (int64_t) T * K, (int64_t) T * K, hit_xq_,hit_xs_, hit_scratch_, parts_, cs);NativeSharedWeights nsw;- nsw.gate_type = GGML_Q8_0; nsw.gate_data = q8("mlp.shared_expert.gate_proj.weight");- nsw.up_type = GGML_Q8_0; nsw.up_data = q8("mlp.shared_expert.up_proj.weight");- nsw.down_type = GGML_Q8_0; nsw.down_data = q8("mlp.shared_expert.down_proj.weight");+ nsw.gate_data = wq("mlp.shared_expert.gate_proj.weight", nsw.gate_type);+ nsw.up_data = wq("mlp.shared_expert.up_proj.weight", nsw.up_type);+ nsw.down_data = wq("mlp.shared_expert.down_proj.weight", nsw.down_type);nsw.q8_1 = xq_;const SForm none{};for (int t = 0; t < T; ++t) {@@ -637,7 +722,8 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::strinative_quantize_q8_1(sample_, xq_, (int) N, T, cs);const bool sub = dhead_ != nullptr;const int64_t nv = sub ? n_dvocab_ : n_vocab_;- native_mmvq(head_->type(), sub ? dhead_ : head_->weights(), xq_, head_logits_, (int) N, (int) nv, T, cs);+ native_mmvq(sub ? dhead_type_ : head_->type(), sub ? dhead_ : head_->weights(), xq_, head_logits_, (int) N,+ (int) nv, T, cs);if (coupled_rec_) {// coupled draft sampling: the target's chain and Philox draw for the row that will verify this draft// (counter = this cell + 1, from its step record), penalties over the ring; T == 1 (full layer)diff --git a/src/program/generate.cpp b/src/program/generate.cppindex 6ce42903a..a47a94f59 100644--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@ -419,6 +419,10 @@ struct Options {/// --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;+ /// --mtp-q4 (opt-in): the draft layer's projections and draft head from 4-bit copies (fewer bytes per draft step)+ bool mtp_q4 = false;+ /// --mtp-draft-vocab FILE (opt-in): the draft head's token subset from FILE instead of <mtp>/draft_vocab.bin+ std::string mtp_draft_vocab;/// 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.@@ -522,6 +526,8 @@ void usage() {" --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"+ " --mtp-q4 opt-in: the draft layer's projections and draft head as 4-bit copies\n"+ " --mtp-draft-vocab FILE opt-in: the draft head's token subset (default <mtp>/draft_vocab.bin)\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"@@ -1217,6 +1223,8 @@ int main(int argc, char** argv) {}o.mtp_hnorm_stream = v == "stream";}+ else if (a == "--mtp-q4") o.mtp_q4 = true;+ else if (a == "--mtp-draft-vocab") o.mtp_draft_vocab = next("--mtp-draft-vocab");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@@ -2567,6 +2575,8 @@ int main(int argc, char** argv) {}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+ mtp.set_q4(o.mtp_q4); // --mtp-q4 (opt-in), before load+ if (!o.mtp_draft_vocab.empty()) mtp.set_draft_vocab(o.mtp_draft_vocab);// 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{};