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++
Support pruned expert variants (GSQ-RCO Coder: 256 of 512 experts)
pete8bef4161cf2d
diff --git a/include/strata/artifact/gguf_reader.hpp b/include/strata/artifact/gguf_reader.hppindex eb490b644..f4d7e648e 100644--- a/include/strata/artifact/gguf_reader.hpp+++ b/include/strata/artifact/gguf_reader.hpp@@ -454,8 +454,9 @@ private:// ---- architecture guard (P1.S2). The engine is specialised to ONE model; anything else must be// refused with a precise error rather than silently mis-run.struct Qwen4ExpGuard {- uint32_t block_count = 48, hidden = 2560, experts = 512, experts_used = 10, head_count = 24,- head_count_kv = 2;+ uint32_t block_count = 48, hidden = 2560, experts = 0, experts_used = 0, head_count = 24,+ head_count_kv = 2; // 0 = presence-only: pruned variants (GSQ-RCO Coder) legitimately ship+ // fewer experts than the canonical 512; the graph reads the true value};inline std::string check_architecture(const GgufFile& g, const Qwen4ExpGuard& want = {}) {@@ -477,7 +478,7 @@ inline std::string check_architecture(const GgufFile& g, const Qwen4ExpGuard& wafor (const auto& r : reqs) {const MetaValue* v = g.get(r.key);if (!v) return std::string("missing ") + r.key;- if (v->u != r.want)+ if (r.want && v->u != r.want)return std::string(r.key) + " = " + std::to_string(v->u) + ", expected " + std::to_string(r.want);}return {}; // empty == okdiff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hppindex b73ac6292..672826b7c 100644--- a/include/strata/prefill/kernels.hpp+++ b/include/strata/prefill/kernels.hpp@@ -37,7 +37,7 @@ void gdn_recurrence(float* state, const float* h, const float* gate, const float// ---- MoE/// softmax over 512, top-10 (ties to the lower id), weights renormalised over the ten (the native router).-void route(const float* logits, int32_t* ids, float* weights, int64_t T, void* stream);+void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, void* stream);/// Expert blob (Strata pack layout, Q2_0) -> BF16 matrices: gate/up interleaved [1280, 2560], down [2560, 640].void blob_dequant(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream);/// h16[n, r] = fp16(silu(gu[n, 2r]) * gu[n, 2r + 1]) (the interleaved expert gate/up)diff --git a/src/core/layer.cpp b/src/core/layer.cppindex b40b9169d..f33c91e5e 100644--- a/src/core/layer.cpp+++ b/src/core/layer.cpp@@ -362,11 +362,8 @@ if (!native_bf16_projections) f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream);// LEDGER L41 -> L42.project_bf16(x, b.x_bf16, (const uint16_t*) w_router->data, b.logits, g.n_embd, g.n_expert, true, stream);// ---- routing: softmax over ALL experts, stable descending argsort with ties by index, gather, renormalise-if (native_router_enabled()) {- if (g.n_expert != 512 || k != 10) {- err = v.name("router") + ": native router requires 512 experts and k=10";- return false;- }+// the native fused router is canonical-512x10 only; anything else takes the generic top-k kernel+if (native_router_enabled() && g.n_expert == 512 && k == 10) {try { native_router_top10(b.logits, b.ids, b.weights, stream); }catch (const std::exception& error) { err = v.name("router") + ": " + error.what(); return false; }} else router_top10(b.logits, 1, (int) g.n_expert, (int) k, b.ids, b.weights, stream);diff --git a/src/kernels/cpu/expert_layout.cpp b/src/kernels/cpu/expert_layout.cppindex ec06ac784..ec78774cf 100644--- a/src/kernels/cpu/expert_layout.cpp+++ b/src/kernels/cpu/expert_layout.cpp@@ -93,7 +93,16 @@ bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t nL.max_blob = 0;std::string line;while (std::getline(in, line)) {- if (line.empty() || line[0] == '#') continue;+ if (line.empty() || line[0] == '#') {+ if (!line.empty() && line[0] == '#') {+ // v3 packs record their expert count in the header; a pruned model (GSQ-RCO Coder) ships+ // fewer experts than the canonical geometry the caller passes, which is a compile-time+ // default, so the header wins.+ const size_t at = line.find("(n_expert ");+ if (at != std::string::npos) L.n_expert = std::atoll(line.c_str() + at + 10);+ }+ continue;+ }std::istringstream ss(line);long long l = -1, gt = -1, dt = -1;unsigned long long off = 0, blob = 0, go = 0, uo = 0, dox = 0;@@ -130,7 +139,7 @@ bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t nerr = "native_experts.txt: layer " + std::to_string(l) + " is missing or not contiguous";return false;}- at += L.bytes[(size_t) l] * (uint64_t) n_expert;+ at += L.bytes[(size_t) l] * (uint64_t) L.n_expert;}L.total = at;g_layout = L;diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cuindex 744497d9d..d09b06b25 100644--- a/src/prefill/kernels.cu+++ b/src/prefill/kernels.cu@@ -1,6 +1,7 @@// src/prefill/kernels.cu - see include/strata/prefill/kernels.hpp.#include "strata/prefill/kernels.hpp"#include "strata/kernels/mrope.hpp"+#include "strata/kernels/router_top10.hpp"#include <cuda_fp16.h>#include <cuda_runtime.h>@@ -201,31 +202,32 @@ __global__ void __launch_bounds__(S * RG) gdn_rec_kernel(float* __restrict__ sta}// ---------------------------------------------------------------- MoE+template <int REG>__global__ void route_kernel(const float* __restrict__ logits, int32_t* __restrict__ ids, float* __restrict__ wout,int64_t T) {const int64_t t = (int64_t) blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5);if (t >= T) return;const int lane = threadIdx.x & 31;- const float* lg = logits + t * 512;- float v[16];+ const float* lg = logits + t * (REG * 32);+ float v[REG];#pragma unroll- for (int i = 0; i < 16; ++i) v[i] = lg[lane + i * 32];+ for (int i = 0; i < REG; ++i) v[i] = lg[lane + i * 32];float mx = -INFINITY;#pragma unroll- for (int i = 0; i < 16; ++i) mx = fmaxf(mx, v[i]);+ for (int i = 0; i < REG; ++i) mx = fmaxf(mx, v[i]);mx = warp_max(mx);float sum = 0.0f;#pragma unroll- for (int i = 0; i < 16; ++i) { v[i] = expf(v[i] - mx); sum += v[i]; }+ for (int i = 0; i < REG; ++i) { v[i] = expf(v[i] - mx); sum += v[i]; }const float rcp = 1.0f / warp_sum(sum);#pragma unroll- for (int i = 0; i < 16; ++i) { v[i] *= rcp; if (isnan(v[i])) v[i] = -FLT_MAX; }+ for (int i = 0; i < REG; ++i) { v[i] *= rcp; if (isnan(v[i])) v[i] = -FLT_MAX; }float selected = 0.0f, selected_sum = 0.0f;for (int rank = 0; rank < 10; ++rank) {float best = v[0];int ex = lane;#pragma unroll- for (int i = 1; i < 16; ++i) if (v[i] > best) { best = v[i]; ex = lane + i * 32; }+ for (int i = 1; i < REG; ++i) if (v[i] > best) { best = v[i]; ex = lane + i * 32; }#pragma unrollfor (int m = 16; m; m >>= 1) {const float ob = __shfl_xor_sync(0xffffffffu, best, m);@@ -455,8 +457,13 @@ void gdn_recurrence(float* state, const float* h, const float* gate, const floatgdn_rec_kernel<<<HV, dim3(S, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, z, gamma, eps, y, y16, T);check("gdn_recurrence");}-void route(const float* logits, int32_t* ids, float* weights, int64_t T, void* stream) {- route_kernel<<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T);+void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, void* stream) {+ if (n_expert == 512)+ route_kernel<16><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T);+ else if (n_expert == 256)+ route_kernel<8><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T);+ else+ strata::kernels::router_top10(logits, (int) T, (int) n_expert, 10, ids, weights, stream);check("route");}void blob_dequant(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream) {diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cppindex c89313576..78b04c5f6 100644--- a/src/prefill/prefill.cpp+++ b/src/prefill/prefill.cpp@@ -181,7 +181,7 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, coImpl& m = *impl_;m.wt = &wt; m.g = &g; m.ss = &ss; m.src = src; m.cache = cache; m.host_res = host_res;m.T = chunk; m.cs = (cudaStream_t) stream; m.stats = &stats_;- if (g.n_embd != N || g.hc != HC || g.hc_lr != LR || g.n_expert != NE || ss.k != K) {+ if (g.n_embd != N || g.hc != HC || g.hc_lr != LR || g.n_expert < 1 || ss.k != K) {err = "prefill: geometry differs from the artifact's"; return false;}if (cudaStreamCreateWithFlags(&m.copy, cudaStreamNonBlocking) != cudaSuccess) { err = "prefill: copy stream"; return false; }@@ -218,7 +218,7 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, com.max_blocks = ss.qsa_states[0].max_cells / s.idx_block + 2;m.sel_scores = o.take<float>((size_t) m.sel_batch * (size_t) m.max_blocks, ok);m.attn_scratch = o.take<float>((size_t) m.attn_batch * strata::kernels::qsa_decode_attn_scratch_floats(m.cap, s), ok);- m.logits = o.take<float>(T * NE, ok); m.w = o.take<float>(T * K, ok); m.ids = o.take<int32_t>(T * K, ok);+ m.logits = o.take<float>(T * m.g->n_expert, ok); m.w = o.take<float>(T * K, ok); m.ids = o.take<int32_t>(T * K, ok);m.slot_dev = o.take<int32_t>(T * K, ok); m.src_dev = o.take<int32_t>(T * K, ok);m.Xs = o.take<uint16_t>(T * K * N, ok); m.GU = o.take<float>(T * K * 1280, ok);m.Hh = o.take<uint16_t>(T * K * 640, ok); m.Dm = o.take<float>(T * K * N, ok);@@ -244,7 +244,7 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, coelsem.owned.push_back(m.ident_table);}- m.ids_host.resize(T * K); m.slot_host.resize(T * K); m.src_host.resize(T * K); m.cnt.resize(NE); m.off.resize(NE + 1);+ m.ids_host.resize(T * K); m.slot_host.resize(T * K); m.src_host.resize(T * K); m.cnt.resize(m.g->n_expert); m.off.resize(m.g->n_expert + 1);m.ple_emb_host.resize(T * N); m.ple_rows.resize(T * strata::kernels::PLE_N_HEADS);if (!ok) { err = "prefill: device buffers for a chunk of " + std::to_string(chunk) + " tokens do not fit"; return false; }return true;@@ -252,7 +252,6 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, couint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk) {// the same allocation sequence as `init`, counted- (void) g;const size_t T = (size_t) chunk;bool ok = true;Alloc o;@@ -271,7 +270,7 @@ uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::Sessionconst int64_t max_blocks = ss.qsa_states[0].max_cells / s.idx_block + 2;f(256 * (size_t) max_blocks);f(32 * strata::kernels::qsa_decode_attn_scratch_floats(cap, s));- f(T * NE); f(T * K); o.take<int32_t>(T * K, ok); o.take<int32_t>(T * K, ok); o.take<int32_t>(T * K, ok);+ f(T * g.n_expert); f(T * K); o.take<int32_t>(T * K, ok); o.take<int32_t>(T * K, ok); o.take<int32_t>(T * K, ok);o.take<uint16_t>(T * K * N, ok); f(T * K * 1280); o.take<uint16_t>(T * K * 640, ok); f(T * K * N);f(T * 640); f(T * 640); o.take<uint16_t>(T * 640, ok); f(T * N); f(T);for (int i = 0; i < DQ; ++i) { o.take<uint16_t>(1280 * 2560, ok); o.take<uint16_t>(2560 * 640, ok); }@@ -554,7 +553,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e*wsd = need(v, "ffn_down_shexp.weight", err);if (!wr || !wgi || !wsg || !wsu || !wsd) return false;if (!bf16_proj(m.gemm, wr, m.mixed_bf, m.logits, T, v.name("ffn_gate_inp.weight"), err)) return false;- route(m.logits, m.ids, m.w, T, m.cs);+ route(m.logits, m.ids, m.w, T, m.g->n_expert, m.cs);// the shared expert and its scalar gateif (!native_proj(m.gemm, wsg, m.mixed_h, m.sgate, T, v.name("ffn_gate_shexp.weight"), err)) return false;if (!native_proj(m.gemm, wsu, m.mixed_h, m.sup, T, v.name("ffn_up_shexp.weight"), err)) return false;@@ -568,11 +567,11 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& estd::fill(m.cnt.begin(), m.cnt.end(), 0);for (int64_t i = 0; i < T * K; ++i) {const int32_t e = m.ids_host[(size_t) i];- if (e < 0 || e >= NE) { err = "prefill: routed id out of range"; return false; }+ if (e < 0 || e >= m.g->n_expert) { err = "prefill: routed id out of range"; return false; }++m.cnt[(size_t) e];}m.off[0] = 0;- for (int64_t e = 0; e < NE; ++e) m.off[(size_t) e + 1] = m.off[(size_t) e] + m.cnt[(size_t) e];+ for (int64_t e = 0; e < m.g->n_expert; ++e) m.off[(size_t) e + 1] = m.off[(size_t) e] + m.cnt[(size_t) e];std::vector<int32_t> fill(m.off.begin(), m.off.end() - 1);for (int64_t i = 0; i < T * K; ++i) {const int32_t e = m.ids_host[(size_t) i];@@ -585,14 +584,14 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& egather_rows16(m.mixed_h, m.src_dev, m.Xs, T * K, N, m.cs);// the experts, in id order: resident ones from VRAM, the others through the staging ringstd::vector<int32_t> order;- for (int32_t e = 0; e < NE; ++e) if (m.cnt[(size_t) e] > 0) order.push_back(e);+ for (int32_t e = 0; e < m.g->n_expert; ++e) if (m.cnt[(size_t) e] > 0) order.push_back(e);const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();// Stage ahead: the copy stream moves blobs host -> device while the compute stream works.int stage_next = 0;std::vector<int> stage_of(order.size(), -1);auto stage_one = [&](size_t j) -> bool {const int32_t e = order[j];- const bool resident = m.host_res && m.cache && m.host_res[(size_t) l * NE + e] >= 0;+ const bool resident = m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0;if (resident) return true;const int sl = stage_next;stage_next = (stage_next + 1) % STAGE;@@ -626,7 +625,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& econst int32_t e = order[j];const uint8_t* blob_dev = nullptr;if (stage_of[j] < 0) {- blob_dev = m.cache->device_slot(m.host_res[(size_t) l * NE + e]);+ blob_dev = m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]);++stats_.experts_resident;} else {cudaStreamWaitEvent(m.cs, m.copied[stage_of[j]], 0);diff --git a/src/program/generate.cpp b/src/program/generate.cppindex 15df9e543..f218d080a 100644--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@ -1069,8 +1069,21 @@ int main(int argc, char** argv) {strata::kernels::mrope_table_set(d_mrope);}strata::kernels::ple_set_native_postops(o.native_ple_postops);- const strata::core::ModelGeometry g;- const int64_t K = 10;+ strata::core::ModelGeometry g; // canonical defaults; the model file overrides the MoE shape below+ int64_t K = 10;+ if (!o.native_preset.empty()) {+ // a pruned variant (GSQ-RCO Coder) ships fewer experts than the canonical 512x10; the model file+ // is the authority on its own MoE shape - everything else in the geometry is unchanged+ try {+ strata::GgufFile model_gguf(o.native_preset);+ if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_count")) g.n_expert = (int64_t) v->u;+ if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_used_count")) K = (int64_t) v->u;+ } catch (const std::exception& e) {+ std::fprintf(stderr, "strata generate: reading the model's expert shape from %s: %s\n",+ o.native_preset.c_str(), e.what());+ return 1;+ }+ }// before session_init: every graph captured from here on has the vector's kernels where it appliesstd::string cvec_summary = "0";if (!o.cvec_files.empty()) {@@ -1282,7 +1295,10 @@ int main(int argc, char** argv) {o.mtp.clear();}if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size());- if (!o.mtp.empty() && !mtp.load(o.mtp, g, ss, o.spec, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; }+ // 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 reference+ static const strata::core::ModelGeometry draft_geometry{};+ if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, ss, o.spec, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; }}strata::kernels::cpu::ExpertPool pool(o.pool_workers, /*pin=*/true, /*host_works=*/!o.no_host_worker);if (o.no_ple_prefetch) strata::kernels::ple_prefetch_enable(false);@@ -2096,9 +2112,10 @@ int main(int argc, char** argv) {// otherwise from an empty sequence (`session_zero`); the rest of the prompt goes through the batched prompt path// and its last token through the first verify window - the path all three model files share. Decoding is greedy.if (o.serve) {- if (o.spec < 2 || o.mtp.empty() || o.prefill_chunk <= 0 || thits.d_res == nullptr || host_res.empty()) {- std::fprintf(stderr, "strata serve: needs --spec T, --mtp DIR, --prefill CHUNK, --expert-profile P and "- "--expert-cache\n");+ if (o.spec < 2 || o.mtp.empty() || o.prefill_chunk <= 0 ||+ (graph_hits && (thits.d_res == nullptr || host_res.empty()))) {+ std::fprintf(stderr, "strata serve: needs --spec T, --mtp DIR and --prefill CHUNK (and a fillable "+ "--expert-cache; the graphed hit path additionally needs --expert-profile P)\n");return 2;}strata::prefill::Prefill sp;diff --git a/tools/iq_pack.py b/tools/iq_pack.pyindex 637d8039a..ea0ff7a17 100644--- a/tools/iq_pack.py+++ b/tools/iq_pack.py@@ -227,20 +227,24 @@ def main() -> int:# ---- the expertsn_layers = 1 + max(int(n.split(".")[1]) for n in T if n.startswith("blk.") and n.endswith("_exps.weight"))+ n_expert = int(T["blk.0.ffn_gate_inp.weight"].shape[1]) # router rows = experts kept (pruned models ship < 512)+ if any(int(T["blk.%d.ffn_gate_inp.weight" % l].shape[1]) != n_expert for l in range(n_layers)):+ print("the routers disagree on the expert count; a per-layer pruned model cannot be packed")+ return 1layout, offset = [], 0for l in range(n_layers):ts = [T["blk.%d.ffn_%s_exps.weight" % (l, r)] for r in ROLES]- per = [t.expected_bytes() // N_EXPERT for t in ts]+ per = [t.expected_bytes() // n_expert for t in ts]if per[0] != per[1] or ts[0].type_name != ts[1].type_name:print("layer %d: gate and up differ in type" % l)return 1blob = per[0] + per[1] + per[2]layout.append((l, ts[0].type_id, ts[2].type_id, offset, blob, ts))- offset += blob * N_EXPERT+ offset += blob * n_expertwith open(out / "native_experts.txt", "w", encoding="utf-8", newline="\n") as fo:fo.write("# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] ""(n_expert %d, total %d; absolute offsets in %s, or in the named shard beside it)\n"- % (N_EXPERT, offset, src.name))+ % (n_expert, offset, src.name))for l, gt, dt, off, blob, ts in layout:ws = [model.where[t.name] for t in ts]if len({w[3] for w in ws}) != 1:@@ -259,9 +263,9 @@ def main() -> int:return 0with open(path, "wb") as fo:for l, gt, dt, off, blob, ts in layout:- parts = [model.bytes(t.name).reshape(N_EXPERT, -1) for t in ts]- chunk = np.concatenate(parts, axis=1) # (512, blob): gate | up | down per expert- assert chunk.shape == (N_EXPERT, blob)+ parts = [model.bytes(t.name).reshape(n_expert, -1) for t in ts]+ chunk = np.concatenate(parts, axis=1) # (n_expert, blob): gate | up | down per expert+ assert chunk.shape == (n_expert, blob)fo.write(chunk.tobytes())if l % 8 == 0:print(" layer %2d %-8s/%-7s blob %8d at %.2f GiB" % (l, ts[0].type_name, ts[2].type_name, blob,