diff --git a/CMakeLists.txt b/CMakeLists.txt index 604977c3..16155bf2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -256,6 +256,10 @@ if(STRATA_BUILD_TESTS) add_executable(gguf_split_test tests/core/gguf_split_test.cpp) target_link_libraries(gguf_split_test PRIVATE strata_artifact) add_test(NAME gguf_split_test COMMAND gguf_split_test) + # the model families (qwen4exp, qwen35moe): the guards, the geometry from metadata, the layout tables (synthetic) + add_executable(model_family_test tests/core/model_family_test.cpp) + target_link_libraries(model_family_test PRIVATE strata_artifact) + add_test(NAME model_family_test COMMAND model_family_test) # how --batch cuts a prompt read into pieces (a layer split with no slot decoding must still reach a BYIELD) add_executable(batch_read_test tests/program/batch_read_test.cpp) target_include_directories(batch_read_test PRIVATE include) @@ -619,6 +623,27 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(strata PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(strata PRIVATE strata_engine strata_prefill strata_spec ${_strata_gpu_runtime_target}) + # NEW-MODELS-PLAN.md T1: Qwen3.6-35B-A3B's reference path (one GPU, the model resident, plain kernels), checked + # against llama.cpp by tools/qwen35/; the engine itself does not run the family yet + add_executable(strata-q36ref src/qwen35/q36ref.cu) + target_include_directories(strata-q36ref PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) + target_link_libraries(strata-q36ref PRIVATE strata_kernels strata_warnings ${_strata_gpu_runtime_target}) + # the engine path for the same family (serve protocol, prompt chunks, decode graph): src/qwen35/q36_engine.cu, a + # library that `strata` switches to for a qwen35moe model (the family switch at the top of its main) and that + # strata-q36 wraps on its own + add_library(strata_qwen35 STATIC src/qwen35/q36_engine.cu) + target_include_directories(strata_qwen35 PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(strata_qwen35 PRIVATE strata_prefill strata_kernels strata_warnings ${_strata_gpu_runtime_target}) + if(STRATA_NATIVE_EXPERTS) + # the hybrid mode (experts that do not all fit in VRAM): the CPU expert pool on ggml-cpu's arithmetic + target_link_libraries(strata_qwen35 PRIVATE strata_kernels_cpu) + target_compile_definitions(strata_qwen35 PRIVATE STRATA_Q36_CPU_POOL=1) + endif() + add_executable(strata-q36 src/qwen35/q36_main.cpp) + target_link_libraries(strata-q36 PRIVATE strata_qwen35 ${_strata_gpu_runtime_target}) + target_link_libraries(strata PRIVATE strata_qwen35) + target_compile_definitions(strata PRIVATE STRATA_HAVE_QWEN35=1) + if(STRATA_ENABLE_HIP) enable_testing() set(_strata_hip_tests) diff --git a/include/strata/artifact/gguf_reader.hpp b/include/strata/artifact/gguf_reader.hpp index 8f46837f..7ce5c60c 100644 --- a/include/strata/artifact/gguf_reader.hpp +++ b/include/strata/artifact/gguf_reader.hpp @@ -35,6 +35,7 @@ #include "strata/artifact/gguf_split.hpp" #include "strata/core/geometry.hpp" +#include "strata/artifact/model_family.hpp" #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN @@ -216,6 +217,10 @@ inline bool block_geometry(uint32_t t, int& elems, int& bytes) { elems = 64; bytes = 36; return true; + case 39: // MXFP4: one E8M0 scale + 16 bytes of 4-bit values (Qwen3.6's MXFP4_MOE experts) + elems = 32; + bytes = 17; + return true; case 42: elems = 64; bytes = 18; @@ -583,6 +588,36 @@ private: std::map> index_; }; +/// The family of the model whose metadata shard is `g` (Unknown when it has no or another architecture). +inline ModelFamily model_family(const GgufFile& g) { + const MetaValue* arch = g.get("general.architecture"); + return arch ? model_family_from_arch(arch->s) : ModelFamily::Unknown; +} + +/// Qwen3.6-35B-A3B's guard: every key the geometry is read from must be present (core::geometry_from_gguf), +/// and the few that the layer pattern depends on must have the values the model has. +inline std::string check_architecture_qwen35moe(const GgufFile& g) { + static const char* const keys[] = { + "qwen35moe.block_count", "qwen35moe.embedding_length", "qwen35moe.attention.head_count", + "qwen35moe.attention.head_count_kv", "qwen35moe.attention.key_length", "qwen35moe.attention.value_length", + "qwen35moe.expert_count", "qwen35moe.expert_used_count", "qwen35moe.expert_feed_forward_length", + "qwen35moe.expert_shared_feed_forward_length", "qwen35moe.ssm.conv_kernel", "qwen35moe.ssm.state_size", + "qwen35moe.ssm.group_count", "qwen35moe.ssm.time_step_rank", "qwen35moe.ssm.inner_size", + "qwen35moe.full_attention_interval", "qwen35moe.nextn_predict_layers", + }; + for (const char* k : keys) { + const MetaValue* v = g.get(k); + if (!v) return std::string("missing ") + k; + if (!v->is_num()) return std::string(k) + " is not a number"; + } + const MetaValue* nl = g.get("qwen35moe.block_count"); + const MetaValue* mtp = g.get("qwen35moe.nextn_predict_layers"); + if (mtp->u >= nl->u) return "qwen35moe.nextn_predict_layers is not smaller than qwen35moe.block_count"; + if (g.get("qwen35moe.full_attention_interval")->u < 2) + return "qwen35moe.full_attention_interval must be at least 2 (the GDN / attention pattern)"; + return {}; +} + // ---- the model's geometry from its metadata, and the architecture guard (P1.S2). The engine runs ONE // architecture, qwen4exp. Its dimensions are read from the file (llama.cpp's key names under the arch prefix) // and then checked against the shape the kernels are compiled for (core/geometry.hpp), so a file of another @@ -747,12 +782,29 @@ inline std::string geometry_unsupported(const core::ModelGeometry& g) { return {}; } -/// The architecture guard: "" when the engine can run the model whose metadata shard is `f`. +/// The architecture guard: "" when the engine can read the model whose metadata shard is `f`. Qwen3.8-Flash-Next +/// (qwen4exp) is read and checked against the shape the kernels are compiled for; Qwen3.6-35B-A3B (qwen35moe) must +/// carry every key its geometry is read from (core::geometry_from_gguf). inline std::string check_architecture(const GgufFile& f) { + const MetaValue* arch = f.get("general.architecture"); + if (!arch) return "missing general.architecture"; + const ModelFamily family = model_family_from_arch(arch->s); + if (family == ModelFamily::Qwen35Moe) return check_architecture_qwen35moe(f); + if (family != ModelFamily::Qwen4Exp) + return "architecture is '" + arch->s + "', Strata reads 'qwen4exp' (Qwen3.8-Flash-Next) and 'qwen35moe' " + "(Qwen3.6-35B-A3B)"; core::ModelGeometry g; std::string err = read_geometry(f, g); if (err.empty()) err = geometry_unsupported(g); return err; } +/// The engine's guard: `check_architecture`, then a family this engine has a path for. A recognised family +/// it does not run yet (Qwen3.6 on SYCL) is refused with a message that says so. +inline std::string check_engine_architecture(const GgufFile& g) { + std::string err = check_architecture(g); + if (!err.empty()) return err; + return model_family_not_supported(model_family(g)); +} + } // namespace strata diff --git a/include/strata/artifact/model_family.hpp b/include/strata/artifact/model_family.hpp new file mode 100644 index 00000000..a1aaeec3 --- /dev/null +++ b/include/strata/artifact/model_family.hpp @@ -0,0 +1,65 @@ +// include/strata/artifact/model_family.hpp - which model family a GGUF holds, from its general.architecture. +// +// Strata was written for one model (Qwen3.8-Flash-Next, `qwen4exp`). Qwen3.6-35B-A3B (`qwen35moe`) is a close +// cousin (same tokenizer, the same Gated-DeltaNet + gated-attention 3:1 layer pattern, the same head dims), so the +// reader, the geometry and the layout tables know both. The ENGINE runs only the families `model_family_runs` +// names; a recognised family it does not run yet is refused with `model_family_not_supported`, not mis-run. +// +// No dependencies: the GGUF reader (the architecture guard) and the core geometry both include this. +#pragma once + +#include + +namespace strata { + +enum class ModelFamily { + Unknown = 0, + Qwen4Exp, ///< Qwen3.8-Flash-Next and its fine-tunes / pruned variants (Swift 1.5, the Coder) + Qwen35Moe, ///< Qwen3.6-35B-A3B (Unsloth's MTP GGUFs): plain pre-norm residual, dense attention, nextn MTP block +}; + +inline ModelFamily model_family_from_arch(const std::string& arch) { + if (arch == "qwen4exp") return ModelFamily::Qwen4Exp; + if (arch == "qwen35moe") return ModelFamily::Qwen35Moe; + return ModelFamily::Unknown; +} + +/// The GGUF architecture string (also the metadata key prefix: ".block_count"). +inline const char* model_family_arch(ModelFamily f) { + switch (f) { + case ModelFamily::Qwen4Exp: + return "qwen4exp"; + case ModelFamily::Qwen35Moe: + return "qwen35moe"; + default: + return ""; + } +} + +/// The model's name for messages. +inline const char* model_family_title(ModelFamily f) { + switch (f) { + case ModelFamily::Qwen4Exp: + return "Qwen3.8-Flash-Next"; + case ModelFamily::Qwen35Moe: + return "Qwen3.6-35B-A3B"; + default: + return "an unknown model"; + } +} + +/// Whether Flash-Next's engine path runs the family. Qwen3.6 has an engine path of its own (src/qwen35), which the +/// CUDA and HIP builds of `strata` switch to at the top of main(); the Intel Arc (SYCL) build has none yet, so there +/// (and on Flash-Next's path) the family is refused with `model_family_not_supported`. +inline bool model_family_runs(ModelFamily f) { return f == ModelFamily::Qwen4Exp; } + +/// The refusal for a recognised family the engine does not run (empty when it runs it). +inline std::string model_family_not_supported(ModelFamily f) { + if (model_family_runs(f)) return {}; + if (f == ModelFamily::Unknown) return "this is not a model family Strata knows"; + return std::string(model_family_title(f)) + " (architecture '" + model_family_arch(f) + + "') runs on the NVIDIA (CUDA) and AMD (HIP) builds of Strata; this build does not run it yet (the Intel " + "Arc / SYCL port is in development). Use a CUDA or HIP build, or a Qwen3.8-Flash-Next model file"; +} + +} // namespace strata diff --git a/include/strata/core/family_layout.hpp b/include/strata/core/family_layout.hpp new file mode 100644 index 00000000..554350d3 --- /dev/null +++ b/include/strata/core/family_layout.hpp @@ -0,0 +1,285 @@ +// include/strata/core/family_layout.hpp - per model family: the geometry read from a GGUF's metadata, and the +// tensor layout table (every tensor of a layer, by name and GGUF shape) checked against a model file's directory. +// +// Header-only and GPU-free: the engine, the tools and the unit tests (tests/core/model_family_test.cpp) share it. +// +// * geometry_from_gguf: fills core::ModelGeometry from ".*" keys. For qwen4exp the keys a file does not +// carry keep Flash-Next's values (the struct defaults, which every published qwen4exp file matches); for +// qwen35moe every key is required (check_architecture_qwen35moe). +// * compiled_geometry_mismatch: the first field where a geometry differs from the shapes this engine's kernels +// are built for (the expert count and top-k are run-time values and are not compared). +// * layer_tensors / global_tensors: the layout tables. Names are GGUF names (blk.N.), shapes are in +// GGUF order (dim 0 contiguous), as tools/gguf_reader.py prints them. +// * check_gguf_layout: every table entry present with its shape, inside its file, of a type with a known block +// size; and, for a family whose table is complete (qwen35moe), no blk.* tensor the table does not name. +#pragma once + +#include "strata/artifact/gguf_reader.hpp" +#include "strata/artifact/model_family.hpp" +#include "strata/core/geometry.hpp" + +#include +#include +#include +#include +#include + +namespace strata::core { + +/// Fills `g` (and `top_k`, the experts per token) from the metadata shard `meta`. False with `err` when the +/// architecture guard refuses the file or a key has an impossible value. +inline bool geometry_from_gguf(const strata::GgufFile& meta, ModelGeometry& g, int64_t& top_k, std::string& err) { + err = strata::check_architecture(meta); + if (!err.empty()) return false; + const strata::ModelFamily family = strata::model_family(meta); + const std::string p = std::string(strata::model_family_arch(family)) + "."; + g = ModelGeometry{}; + g.family = family; + // a key the file carries replaces the default; `required` keys were checked present by the guard + auto num = [&](const char* key, int64_t& dst) { + if (const strata::MetaValue* v = meta.get(p + key)) + if (v->is_num()) dst = (int64_t) v->u; + }; + int64_t block_count = g.n_layers, key_length = g.head_dim, value_length = -1; + num("block_count", block_count); + num("embedding_length", g.n_embd); + num("attention.head_count", g.n_head); + num("attention.head_count_kv", g.n_head_kv); + num("attention.key_length", key_length); + num("attention.value_length", value_length); + num("expert_count", g.n_expert); + top_k = 10; + num("expert_used_count", top_k); + g.n_expert_used = top_k; + num("expert_feed_forward_length", g.n_ff); + num("expert_shared_feed_forward_length", g.n_ff_shexp); + num("ssm.conv_kernel", g.ssm_d_conv); + num("ssm.state_size", g.ssm_state_size); + num("ssm.group_count", g.ssm_k_heads); + num("ssm.time_step_rank", g.ssm_v_heads); + num("ssm.inner_size", g.ssm_value_dim); + num("full_attention_interval", g.qsa_interval); + g.head_dim = key_length; + if (family == strata::ModelFamily::Qwen35Moe) { + num("nextn_predict_layers", g.n_mtp_layers); + g.hc = g.hc_lr = 0; // a plain pre-norm residual + g.idx_q_heads = g.idx_key_dim = 0; // dense attention, no sparse indexer + } else { + num("hyper_connection.count", g.hc); + num("hyper_connection.low_rank", g.hc_lr); + num("attention.indexer.head_count", g.idx_q_heads); + num("attention.indexer.key_length", g.idx_key_dim); + } + g.n_layers = block_count - g.n_mtp_layers; + g.ssm_conv_channels = 2 * g.ssm_state_size * g.ssm_k_heads + g.ssm_value_dim; + if (const strata::MetaValue* v = meta.get("tokenizer.ggml.tokens")) + if (v->type == strata::MetaType::ARRAY && v->count > 0) g.n_vocab = (int64_t) v->count; + + char buf[256]; + auto bad = [&](const char* what) { + std::snprintf(buf, sizeof buf, "%s: %s", meta.path().c_str(), what); + err = buf; + return false; + }; + if (g.n_layers <= 0 || g.n_embd <= 0 || g.n_head <= 0 || g.n_head_kv <= 0 || g.head_dim <= 0 || g.n_expert <= 0 || + top_k <= 0 || top_k > g.n_expert || g.n_ff <= 0 || g.ssm_state_size <= 0 || g.ssm_k_heads <= 0 || + g.ssm_v_heads <= 0 || g.ssm_d_conv <= 0 || g.qsa_interval < 2) + return bad("a geometry key is zero or out of range"); + if (value_length >= 0 && value_length != key_length) return bad("attention.key_length != attention.value_length"); + if (g.ssm_value_dim != g.ssm_state_size * g.ssm_v_heads) return bad("ssm.inner_size != ssm.state_size * ssm.time_step_rank"); + if (g.ssm_v_heads % g.ssm_k_heads) return bad("ssm.time_step_rank is not a multiple of ssm.group_count"); + if (g.n_head % g.n_head_kv) return bad("attention.head_count is not a multiple of attention.head_count_kv"); + if (g.n_layers % g.qsa_interval) return bad("the layer count is not a multiple of full_attention_interval"); + return true; +} + +/// The first geometry field that differs from the shapes this engine's kernels are built for (ModelGeometry's +/// defaults, Flash-Next's), as " is , this engine's kernels are built for "; empty when none. +/// n_expert and top-k are run-time sizes (the Coder ships 256 experts) and n_vocab is the embedding's business. +inline std::string compiled_geometry_mismatch(const ModelGeometry& g) { + const ModelGeometry c; + if (g.family != c.family) + return std::string("the model is ") + strata::model_family_title(g.family) + ", this engine's kernels are built " + "for " + strata::model_family_title(c.family); + struct F { + const char* what; + int64_t got, want; + }; + const F fields[] = { + {"embedding_length", g.n_embd, c.n_embd}, + {"the layer count", g.n_layers, c.n_layers}, + {"full_attention_interval", g.qsa_interval, c.qsa_interval}, + {"ssm.state_size", g.ssm_state_size, c.ssm_state_size}, + {"ssm.group_count", g.ssm_k_heads, c.ssm_k_heads}, + {"ssm.time_step_rank", g.ssm_v_heads, c.ssm_v_heads}, + {"ssm.conv_kernel", g.ssm_d_conv, c.ssm_d_conv}, + {"the GDN conv channels", g.ssm_conv_channels, c.ssm_conv_channels}, + {"ssm.inner_size", g.ssm_value_dim, c.ssm_value_dim}, + {"attention.head_count", g.n_head, c.n_head}, + {"attention.head_count_kv", g.n_head_kv, c.n_head_kv}, + {"attention.key_length", g.head_dim, c.head_dim}, + {"attention.indexer.head_count", g.idx_q_heads, c.idx_q_heads}, + {"attention.indexer.key_length", g.idx_key_dim, c.idx_key_dim}, + {"hyper_connection.count", g.hc, c.hc}, + {"hyper_connection.low_rank", g.hc_lr, c.hc_lr}, + {"expert_feed_forward_length", g.n_ff, c.n_ff}, + {"expert_shared_feed_forward_length", g.n_ff_shexp, c.n_ff_shexp}, + {"the in-file MTP layers", g.n_mtp_layers, c.n_mtp_layers}, + }; + for (const F& f : fields) + if (f.got != f.want) { + char buf[256]; + std::snprintf(buf, sizeof buf, "%s is %lld, this engine's kernels are built for %lld", f.what, + (long long) f.got, (long long) f.want); + return buf; + } + return {}; +} + +enum class LayerKind { Gdn, Attention, Mtp }; + +inline LayerKind layer_kind(const ModelGeometry& g, int64_t layer) { + if (layer >= g.n_layers) return LayerKind::Mtp; + return is_qsa_layer(g, layer) ? LayerKind::Attention : LayerKind::Gdn; +} + +/// One tensor of the layout table: its name (a blk.N. suffix for a layer's, the full name for a global one) and +/// its GGUF shape. +struct TensorWant { + std::string name; + std::vector shape; +}; + +/// Every tensor of layer `layer` (kind from `layer_kind`), by family. +inline std::vector layer_tensors(const ModelGeometry& g, int64_t layer) { + const LayerKind kind = layer_kind(g, layer); + const int64_t N = g.n_embd, NE = g.n_expert, FF = g.n_ff, FS = g.n_ff_shexp; + std::vector t; + auto add = [&](const char* s, std::vector shape) { t.push_back({s, std::move(shape)}); }; + // MoE, every layer (the MTP block's too) + add("ffn_gate_inp.weight", {N, NE}); + add("ffn_gate_inp_shexp.weight", {N}); + add("ffn_gate_shexp.weight", {N, FS}); + add("ffn_up_shexp.weight", {N, FS}); + add("ffn_down_shexp.weight", {FS, N}); + add("ffn_gate_exps.weight", {N, FF, NE}); + add("ffn_up_exps.weight", {N, FF, NE}); + add("ffn_down_exps.weight", {FF, N, NE}); + if (g.has_hyper_connections()) { + // gated residual (Flash-Next): `gr_read` transposes, so the file's orientation is [hc_dim, hc_lr] / [hc_lr, hc_dim] + const int64_t H = g.hc_dim(); + add("hc_attn_down.weight", {H, g.hc_lr}); + add("hc_attn_up.weight", {g.hc_lr, H}); + add("hc_attn_inject.weight", {H, g.hc}); + add("hc_attn_norm.weight", {H}); + add("hc_ffn_down.weight", {H, g.hc_lr}); + add("hc_ffn_up.weight", {g.hc_lr, H}); + add("hc_ffn_inject.weight", {H, g.hc}); + add("hc_ffn_norm.weight", {H}); + } else { + // plain pre-norm residual (qwen35moe): x += mixer(rms(x)); x += moe(rms(x)) + add("attn_norm.weight", {N}); + add("post_attention_norm.weight", {N}); + } + if (kind == LayerKind::Gdn) { + add("attn_qkv.weight", {N, g.ssm_conv_channels}); + add("attn_gate.weight", {N, g.ssm_value_dim}); + add("ssm_out.weight", {g.ssm_value_dim, N}); + add("ssm_conv1d.weight", {g.ssm_d_conv, g.ssm_conv_channels}); + add("ssm_alpha.weight", {N, g.ssm_v_heads}); + add("ssm_beta.weight", {N, g.ssm_v_heads}); + add("ssm_a", {g.ssm_v_heads}); + add("ssm_dt.bias", {g.ssm_v_heads}); + add("ssm_norm.weight", {g.ssm_state_size}); + } else { + // attention (query + output gate in attn_q), also the MTP block's + add("attn_q.weight", {N, 2 * g.n_head * g.head_dim}); + add("attn_k.weight", {N, g.n_head_kv * g.head_dim}); + add("attn_v.weight", {N, g.n_head_kv * g.head_dim}); + add("attn_output.weight", {g.n_head * g.head_dim, N}); + add("attn_q_norm.weight", {g.head_dim}); + add("attn_k_norm.weight", {g.head_dim}); + if (g.has_indexer() && kind == LayerKind::Attention) { + // `q_proj` is the QUERY count, `k_proj` the KEY width (round 194: they are different numbers) + add("indexer.q_proj.weight", {N, g.idx_q_heads * g.idx_key_dim}); + add("indexer.k_proj.weight", {N, g.idx_key_dim}); + add("indexer.q_norm.weight", {g.idx_key_dim}); + add("indexer.k_norm.weight", {g.idx_key_dim}); + } + } + if (kind == LayerKind::Mtp) { + // the GGUF-native MTP block: eh_proj over concat(enorm(embedding), hnorm(hidden)) + add("nextn.eh_proj.weight", {2 * N, N}); + add("nextn.enorm.weight", {N}); + add("nextn.hnorm.weight", {N}); + add("nextn.shared_head_norm.weight", {N}); + } + return t; +} + +/// The tensors outside the layers, by family. (Flash-Next's output_norm, PLE and n-gram tables are not listed: +/// the published files place them differently, and their loaders check them.) +inline std::vector global_tensors(const ModelGeometry& g) { + std::vector t; + t.push_back({"token_embd.weight", {g.n_embd, g.n_vocab}}); + t.push_back({"output.weight", {g.n_embd, g.n_vocab}}); + if (g.has_hyper_connections()) { + t.push_back({"output_hc_down.weight", {g.hc_dim(), g.hc_lr}}); + t.push_back({"output_hc_up.weight", {g.hc_lr, g.hc_dim()}}); + t.push_back({"output_hc_norm.weight", {g.hc_dim()}}); + } else { + t.push_back({"output_norm.weight", {g.n_embd}}); + } + return t; +} + +/// Whether the family's table names every blk.* tensor its files carry (then an unnamed one is an error). +inline bool layout_table_complete(const ModelGeometry& g) { return g.family == strata::ModelFamily::Qwen35Moe; } + +/// Checks the model `m` (all shards) against the layout table of `g`. `checked` counts the tensors found. +inline bool check_gguf_layout(const strata::GgufModel& m, const ModelGeometry& g, std::string& err, + size_t* checked = nullptr) { + std::set named; + size_t n = 0; + auto check = [&](const std::string& name, const std::vector& shape) { + named.insert(name); + size_t s = 0; + const strata::TensorInfo* t = m.find(name, &s); + if (!t) { + err = "missing " + name; + return false; + } + bool same = t->shape.size() == shape.size(); + for (size_t i = 0; same && i < shape.size(); ++i) same = t->shape[i] == (uint64_t) shape[i]; + if (!same) { + std::string got, want; + for (uint64_t d : t->shape) got += (got.empty() ? "" : ", ") + std::to_string(d); + for (int64_t d : shape) want += (want.empty() ? "" : ", ") + std::to_string(d); + err = name + " is [" + got + "], the " + strata::model_family_title(g.family) + " layout wants [" + want + "]"; + return false; + } + if (!m.in_bounds(*t, s)) { + err = name + " (" + t->type_name() + ") has no known size inside " + m.shard(s).path(); + return false; + } + ++n; + return true; + }; + for (const TensorWant& w : global_tensors(g)) + if (!check(w.name, w.shape)) return false; + for (int64_t l = 0; l < g.n_layers + g.n_mtp_layers; ++l) + for (const TensorWant& w : layer_tensors(g, l)) + if (!check("blk." + std::to_string(l) + "." + w.name, w.shape)) return false; + if (layout_table_complete(g)) { + for (size_t s = 0; s < m.size(); ++s) + for (const strata::TensorInfo& t : m.shard(s).tensors()) + if (!named.count(t.name)) { + err = t.name + " is not in the " + std::string(strata::model_family_title(g.family)) + " layout"; + return false; + } + } + if (checked) *checked = n; + return true; +} + +} // namespace strata::core diff --git a/include/strata/core/geometry.hpp b/include/strata/core/geometry.hpp index d3916d6e..0a73ca4f 100644 --- a/include/strata/core/geometry.hpp +++ b/include/strata/core/geometry.hpp @@ -11,6 +11,8 @@ // Dependency-free on purpose: the kernels include it. #pragma once +#include "strata/artifact/model_family.hpp" + #include namespace strata::core { @@ -20,7 +22,7 @@ namespace strata::core { /// are compiled for; the GGUF key each field is read from is named beside it. struct ModelGeometry { int64_t n_embd = 2560; ///< embedding_length - int64_t n_layers = 48; ///< block_count + int64_t n_layers = 48; ///< block_count (the trunk; an in-file MTP block is counted in n_mtp_layers) int64_t qsa_interval = 4; ///< full_attention_interval: every 4th layer is full attention, 3, 7, ... 47 int64_t n_vocab = 248320; ///< the length of tokenizer.ggml.tokens double rms_eps = 1e-6; ///< attention.layer_norm_rms_epsilon @@ -52,6 +54,13 @@ struct ModelGeometry { int64_t n_expert_used = 10; ///< expert_used_count int64_t n_ff = 640; ///< expert_feed_forward_length (= expert_shared_feed_forward_length) + // appended for the model families (Qwen3.6 = qwen35moe); the defaults keep Flash-Next's values + int64_t n_ff_shexp = 640; ///< the shared expert's FFN width (qwen4exp: equal to n_ff, read_geometry checks) + ModelFamily family = ModelFamily::Qwen4Exp; + int64_t n_mtp_layers = 0; ///< MTP blocks inside the model file, after the trunk (qwen35moe: blk.40) + + constexpr bool has_indexer() const { return idx_q_heads > 0; } ///< false: dense attention only + constexpr bool has_hyper_connections() const { return hc > 0; } ///< false: plain pre-norm residual constexpr int64_t hc_dim() const { return hc * n_embd; } /// `layer % qsa_interval == qsa_interval - 1` is full attention. Derived, not a second list. constexpr int64_t n_qsa_layers() const { return n_layers / qsa_interval; } diff --git a/include/strata/hip_compat/cublas_v2.h b/include/strata/hip_compat/cublas_v2.h index 87944796..b6170078 100644 --- a/include/strata/hip_compat/cublas_v2.h +++ b/include/strata/hip_compat/cublas_v2.h @@ -52,6 +52,9 @@ inline rocblas_status cublasGemmEx(rocblas_handle h, rocblas_operation trans_a, #define cublasCreate hipblasCreate #define cublasDestroy hipblasDestroy #define cublasGemmEx hipblasGemmEx +#define cublasSgemm hipblasSgemm // the Qwen3.6 engine's FP32 prompt products +#define cublasSgemmStridedBatched hipblasSgemmStridedBatched +#define cublasGemmStridedBatchedEx hipblasGemmStridedBatchedEx // (the Qwen3.6 prompt attention, FP16) #define cublasHandle_t hipblasHandle_t #define cublasSetMathMode hipblasSetMathMode #define cublasSetStream hipblasSetStream diff --git a/include/strata/kernels/fused_gdn.hpp b/include/strata/kernels/fused_gdn.hpp index 0cf7c66c..d1f39cbd 100644 --- a/include/strata/kernels/fused_gdn.hpp +++ b/include/strata/kernels/fused_gdn.hpp @@ -32,4 +32,10 @@ void fused_gdn_step_norm(float* state, const float* q, const float* k, const flo const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, void* stream); +/// The same step with the SiLU output gate, y = rmsnorm(o) * gamma * silu(z): Qwen3.6-35B-A3B's (qwen35moe) GDN +/// (CUDA / HIP; the SYCL port has no qwen35moe path). +void fused_gdn_step_norm_silu(float* state, const float* q, const float* k, const float* v, const float* gate, + const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, + int h_v, void* stream); + } // namespace strata::kernels diff --git a/include/strata/kernels/native_router.hpp b/include/strata/kernels/native_router.hpp index 96abaed0..a940e1b3 100644 --- a/include/strata/kernels/native_router.hpp +++ b/include/strata/kernels/native_router.hpp @@ -16,6 +16,10 @@ bool native_router_enabled(); void native_router_top10(const float* logits, int32_t* ids, float* weights, void* stream); /// n_tok rows at once (logits [n,512], ids/weights [n,10]); each row exactly as the single call. void native_router_top10_multi(const float* logits, int32_t* ids, float* weights, int n_tok, void* stream); +/// The same contract for a model family's (experts, top-k): 512 / 10 (Flash-Next: the two calls above, unchanged) and +/// 256 / 8 (Qwen3.6-35B-A3B). logits [n_tok, n_expert], ids / weights [n_tok, k]. CUDA / HIP. +bool native_router_topk_supported(int n_expert, int k); +void native_router_topk(const float* logits, int32_t* ids, float* weights, int n_expert, int k, int n_tok, void* stream); /// STRATA_ROUTE_RESIDENT: swap non-resident tail-rank experts for resident ones within `margin` logits (see the .cu). /// `stats` is nullptr or 4 device uint64 counters: tail entries seen, swaps, non-resident before, non-resident after. void native_route_resident(const float* logits, int32_t* ids, float* weights, const int32_t* res_layer, int n_tok, float margin, diff --git a/include/strata/qwen35/engine.hpp b/include/strata/qwen35/engine.hpp new file mode 100644 index 00000000..89368e10 --- /dev/null +++ b/include/strata/qwen35/engine.hpp @@ -0,0 +1,13 @@ +// include/strata/qwen35/engine.hpp - the Qwen3.6-35B-A3B (GGUF architecture qwen35moe) engine path as a library: +// `strata` hands a qwen35moe model to it at the top of main() (the family switch), and strata-q36 is a thin wrapper +// around the same entry point. See src/qwen35/q36_engine.cu. +#pragma once + +namespace strata::qwen35 { + +/// The engine's command line (strata's own flag names where they mean the same thing: --native / --model, +/// --max-context, --prefill / --chunk, --serve, --mtp N, --pool-workers, --tokens, --max-new, --no-token-graph; the +/// family's own: --expert-vram, --expert-slots, --hybrid-rows, --cpu-threads). Returns the process exit code. +int run(int argc, char** argv); + +} // namespace strata::qwen35 diff --git a/serve/server.py b/serve/server.py index 321f345e..0be84540 100644 --- a/serve/server.py +++ b/serve/server.py @@ -6448,6 +6448,15 @@ def check_request_sampling(req) -> None: raise ValueError(f"{key}: {'an integer' if integer else 'a number'}") +# the API's model name per model family (the GGUF architecture, "arch" in the config) when the config names none +FAMILY_MODEL_NAMES = {"qwen4exp": "qwen3.8-flash-next", "qwen35moe": "qwen3.6-35b-a3b"} + + +def default_model_name(cfg: dict) -> str: + """The config's "model_name", else its family's name ("arch": qwen4exp, qwen35moe), else Flash-Next's.""" + return cfg.get("model_name") or FAMILY_MODEL_NAMES.get(cfg.get("arch") or "qwen4exp", "qwen3.8-flash-next") + + def main() -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--engine", choices=["mock", "strata"], default="mock") @@ -6593,7 +6602,7 @@ def main() -> int: # the model's own chat template (exported with its tokenizer), else the original model's tpl = tpath / "chat_template.jinja" svc = Service(engine, tok, ChatTemplate(tpl if tpl.exists() else ROOT / "serve/chat_template.jinja"), - model_name=cfg.get("model_name", "qwen3.8-flash-next"), vision=vision, + model_name=default_model_name(cfg), vision=vision, sampling_defaults=sampling_defaults, fit_max_tokens=a.fit_max_tokens or cfg.get("fit_max_tokens") is True) svc.reasoning_close_retry = cfg.get("reasoning_close_retry") is True # #1053: opt-in, off by default diff --git a/serve/test_family_name.py b/serve/test_family_name.py new file mode 100644 index 00000000..cd4024ff --- /dev/null +++ b/serve/test_family_name.py @@ -0,0 +1,30 @@ +"""serve/test_family_name.py - the API's model name per model family (NEW-MODELS-PLAN.md T0): the config's +"model_name" wins; without one, the family's ("arch": qwen4exp -> qwen3.8-flash-next, qwen35moe -> qwen3.6-35b-a3b), +and Flash-Next's for a config that names neither (every config setup wrote before). + + python -m unittest serve.test_family_name +""" +from __future__ import annotations + +import unittest + +from serve.server import FAMILY_MODEL_NAMES, default_model_name + + +class FamilyName(unittest.TestCase): + def test_config_name_wins(self): + self.assertEqual(default_model_name({"model_name": "qwen3.8-flash-next-q2_0", "arch": "qwen35moe"}), + "qwen3.8-flash-next-q2_0") + + def test_per_family(self): + self.assertEqual(default_model_name({"arch": "qwen35moe"}), "qwen3.6-35b-a3b") + self.assertEqual(default_model_name({"arch": "qwen4exp"}), "qwen3.8-flash-next") + + def test_old_configs(self): + self.assertEqual(default_model_name({}), "qwen3.8-flash-next") + self.assertEqual(default_model_name({"arch": "something-else"}), "qwen3.8-flash-next") + self.assertEqual(set(FAMILY_MODEL_NAMES), {"qwen4exp", "qwen35moe"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/setup.py b/setup.py index 7d8cfe36..5e0388f1 100644 --- a/setup.py +++ b/setup.py @@ -68,6 +68,7 @@ HF_REVISIONS = { "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF": "b22d729eae29b5796f76fb70f91aef549b9fc52c", # 2026-09-24 "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF": "5348543e0147355ac9cbcb031184a3546350988e", # 2026-09-29 "unsloth/Qwen3.8-Flash-Next-GGUF": "38bb39ee97821de2c9009abb7e93950eec396e66", # 2026-09-30 + "unsloth/Qwen3.6-35B-A3B-MTP-GGUF": "5bc3e238d916f48a861bac2f8a1990a0e9b7e98d", # 2026-10-12 } @@ -422,6 +423,39 @@ FAMILIES = { "mmproj_sha256": (907543008, "b1a82259702816a5330d7bd7607cd9676b11780e79ff7348c21103ff3ce49bd0")}, } MMPROJ = "mmproj-Qwen3.8-Flash-Next-BF16.gguf" +# Qwen3.6-35B-A3B (GGUF architecture qwen35moe), Unsloth's GGUFs with the MTP block: a family with an engine path of its +# own (src/qwen35; `strata` switches to it from the file's architecture). No pack, no expert profile, no separate MTP +# draft layer: the engine reads the GGUF as it is, keeps every expert it can in VRAM and computes the rest on the CPU +# (the hybrid mode), and drafts with the file's own MTP block. Not in FAMILIES (whose entries are Flash-Next files with +# packs): OWN_PATH_FAMILIES, offered in the same menu and installed by install_own_path. NVIDIA (CUDA) and AMD (HIP) +# only: the Intel Arc (SYCL) engine refuses it. +QWEN36_FILES = { + "Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf": (22853663008, "55983c5a75a1ab969824077b3bb3de4146e82a9234072b48ad4e8f92ad3fe9f1"), + "Qwen3.6-35B-A3B-UD-Q6_K_XL.gguf": (32611711264, "35fce994cd36104a7dc1bd8a4bdf13778145664c00fdef6773aebc9246e5019c"), + "Qwen3.6-35B-A3B-Q8_0.gguf": (37801097504, "c1283d8b80c3e38b2735ddbc9766d3b3126f44d6c484be419d4e101d09a76131"), + "mmproj-F16.gguf": (899283584, "71f3cbc1f7cc0f30d09d41cfa924c0060827ebc33bf15ace7e86661e856f0160"), +} +OWN_PATH_FAMILIES = { + "qwen36": {"title": "Qwen3.6-35B-A3B", "by": "Qwen; GGUFs with the MTP layer by Unsloth", "arch": "qwen35moe", + "about": "35B mixture of experts with 3B active (256 experts, top-8): a smaller cousin of " + "Qwen3.8-Flash-Next with the same tokenizer", + "hf": hf("unsloth/Qwen3.6-35B-A3B-MTP-GGUF"), "file": "Qwen3.6-35B-A3B-{q}.gguf", "tag": "qwen36-", + "mmproj_hf": hf("unsloth/Qwen3.6-35B-A3B-MTP-GGUF"), "mmproj": "mmproj-F16.gguf", + "name": "qwen3.6-35b-a3b", "license": "Apache 2.0: https://huggingface.co/Qwen/Qwen3.6-35B-A3B", + # RAM: the engine keeps a copy of every expert in RAM when they do not all fit in VRAM (the hybrid mode), + # so the file's size plus room for the OS and the rest (measured: UD-Q4_K_XL on a 46 GB PC with a 12 GB + # card, 18.75 GiB of experts pinned) + "models": {"UD-Q4_K_XL": {"about": "4-bit (Unsloth Dynamic), the smallest", "ram_gb": 32}, + "UD-Q6_K_XL": {"about": "6-bit (Unsloth Dynamic), closer to the full model", "ram_gb": 44}, + "Q8_0": {"about": "8-bit, the closest to the full model", "ram_gb": 52}}, + "sha256": QWEN36_FILES, + # the engine's KV cache per context token: 10 attention layers + the MTP block, 2 KV heads x 256, K and + # V in fp32 (strata-q36) + "kv_bytes_per_token": 11 * 2 * 256 * 2 * 4, + "mtp": 2, # drafts per step (greedy requests): measured best on the R9700 + "vision": False}, # the image encoder for this family is not wired up yet +} +PREVIEW_FAMILIES = OWN_PATH_FAMILIES # the earlier name (tools and tests that import it) # EXPERIMENTAL, off by default (setup asks): a control vector shipped with the repository, see its README ESP_VECTOR = ROOT / "data" / "experimental-speed-projection" / "Qwen3.8-Flash-Next-experimental-speed-projection.gguf" # the image encoder on the GPU (~1.2 GB at 1024 image tokens) warms up before the engine starts, so the engine @@ -4253,10 +4287,25 @@ def previous_config(elsewhere_first: list, settings: dict): return next((c for c in sorted(cands, key=lambda p: p.stat().st_mtime, reverse=True) if readable_config(c)), None) +def own_path_config(cfg: dict) -> bool: + """A config for a family with its own engine path (Qwen3.6): its --mtp is a draft count, not a draft layer.""" + return cfg.get("arch") in {d["arch"] for d in OWN_PATH_FAMILIES.values()} + + def choices_from_config(cfg_path: Path) -> dict: """The setup answers a config was written with (family, size, context, KV, images, projection, network).""" cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig")) tag = cfg_path.stem[len("strata-"):] + own = next((f for f, d in OWN_PATH_FAMILIES.items() if tag.startswith(d["tag"])), None) + if own is not None: # Qwen3.6: its own sizes; no KV / images / projection settings + d = OWN_PATH_FAMILIES[own] + size = next((m for m in d["models"] if m.lower() == tag[len(d["tag"]):].lower()), None) + a = cfg.get("args", []) + ctx = a[a.index("--max-context") + 1] if "--max-context" in a and a.index("--max-context") + 1 < len(a) else None + return {"family": own, "model": size, "context": int(ctx) if ctx and ctx.isdigit() else None, "kv": None, + "vision": "none", "esp": "off", "host": cfg.get("host"), "api_key": cfg.get("api_key"), + "port": cfg.get("port"), "gpu": cfg.get("gpu"), "layer_split": None, + "cuda": 12 if config_toolkit(cfg) == 12 else None, "vram_reserve_mib": None} family = next((f for f, d in FAMILIES.items() if d["tag"] and tag.startswith(d["tag"])), "qwen") model = (tag[len(FAMILIES[family]["tag"]):] if tag.startswith(FAMILIES[family]["tag"]) else tag).upper() if model not in MODELS: # (sizes have no dash except UD-Q4_K_XL: the old rule) @@ -4281,10 +4330,12 @@ def choices_from_config(cfg_path: Path) -> dict: def calibration_targets(have: list, model: str | None, family: str | None) -> list: """#2036: the installed configs `--calibrate --model X` (and/or --family) means; every config with neither.""" if not (model or family): - return list(have) + return [c for c in have if choices_from_config(c)["family"] not in OWN_PATH_FAMILIES] out = [] for c in have: ch = choices_from_config(c) + if ch["family"] in OWN_PATH_FAMILIES: # the tuning measures Flash-Next's engine settings + continue if (not model or ch["model"] == model) and (not family or ch["family"] == family): out.append(c) return out @@ -4514,7 +4565,8 @@ def update_install(have: list, a) -> int: mtp_done: set = set() for cfg_path in have: cfg = upgrade_config(cfg_path, json.loads(cfg_path.read_text(encoding="utf-8-sig"))) - refresh_shared_draft_vocab(cfg, mtp_done) + if not own_path_config(cfg): + refresh_shared_draft_vocab(cfg, mtp_done) if cfg.get("backend") == "hip" and WIN: hip_runtime_beside_exe(Path(cfg["exe"]).parent) # #468 #461 ok(f"{cfg.get('model_name', cfg_path.stem)}: up to date") @@ -4575,7 +4627,7 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ "api key" if k == "api_key" else ("the browser opens" if v else "no browser") if k == "open_browser" else f"{k.replace('_', ' ')} {v}" for k, v in keep.items())) cfg_path.touch() # the most recently used model - if "--mtp" in cfg["args"][:-1]: + if "--mtp" in cfg["args"][:-1] and not own_path_config(cfg): refresh_draft_vocab(Path(cfg["args"][cfg["args"].index("--mtp") + 1]), cfg.get("draft_vocab", "cjk")) cmd = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), "--port", str(port or cfg.get("port", 8080))] @@ -5082,10 +5134,243 @@ def sycl_setup(argv) -> int: return subprocess.call([sys.executable, str(script), *rest]) +def engine_step(a, gpu, hip, amd, cuda_tk, vision): + """Step 4: llama.cpp's sources and the engine (ready-made, or compiled here). Returns (llama, engine folder, its + BUILD.json, its library folders, the GPU (AMD on Windows: as the engine sees it), the image-encoder choice).""" + llama = get_llama_cpp() + ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py, ggml, mtmd)") + if hip and WIN: # AMD on Windows: the ready-made HIP engine (no compiler) + eng = None if a.build else get_prebuilt_hip(a.prebuilt, gpu) + if eng is None: + fail("no ready-made AMD engine for this Strata version" + (" (--build)" if a.build else ""), + "compiling it on Windows: tools\\hip\\build_windows.bat makes strata-windows-x64-hip.zip, then run " + "START-HERE.bat --backend hip --prebuilt (docs/AMD_HIP.md)") + gpu = hip_card(eng, gpu, amd) + a.gpu = gpu["index"] if gpu["count"] > 1 else a.gpu + else: + eng = None if a.build or hip else get_prebuilt(a.prebuilt, gpu, vision, **({"toolkit": 12} if cuda_tk == 12 + else {})) + if eng is not None and not hip and json.loads((eng / "BUILD.json").read_text(encoding="utf-8")).get("source") != "local": + pip_cuda_libs(cuda_tk) + if vision != "none" and not (eng / VEXE).exists(): + warn("the ready-made engine has no image encoder: compiling it") + eng = None + else: + vision = prebuilt_vision(json.loads((eng / "BUILD.json").read_text(encoding="utf-8")), gpu, vision) + if eng is None: + eng = build_engine_hip(gpu, llama, vision) if hip else build_engine(gpu, vision, a.yes, llama, toolkit=cuda_tk) + meta = json.loads((eng / "BUILD.json").read_text(encoding="utf-8")) + if hip and WIN: # the ready-made engine's rocm/bin, first on the engine's PATH + lib_dirs = [str(d) for d in hip_lib_dirs(eng)] + else: + lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs(cuda_tk) + return llama, eng, meta, lib_dirs, gpu, vision + + +def engine_families(eng: Path) -> set: + """The model families an engine runs (`strata --families`; an engine from before it: Flash-Next's only).""" + try: + text = subprocess.run([str(eng / EXE), "--families"], capture_output=True, text=True, timeout=60).stdout + except (OSError, subprocess.SubprocessError): + return {"qwen4exp"} + names = set(text.split()) + return names if "qwen4exp" in names else {"qwen4exp"} + + +def own_path_context(fam: dict, vram_gb: float) -> int: + """The recommended context for an own-path family: its KV cache (VRAM) beside the dense weights and the most-used + experts - 32K up to 16 GB, 64K up to 24 GB, 128K above.""" + return 32768 if vram_gb <= 16.5 else 65536 if vram_gb <= 24.5 else 131072 + + +def own_path_size(fam: dict, ram: float) -> str: + """The recommended size: the largest file whose RAM need this PC has (the smallest when none fits).""" + fits = [m for m, d in fam["models"].items() if ram >= d["ram_gb"]] + return max(fits, key=lambda m: fam["sha256"][fam["file"].format(q=m)][0]) if fits else next(iter(fam["models"])) + + +def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted): + """Steps 2-7 for a family with its own engine path (OWN_PATH_FAMILIES: Qwen3.6-35B-A3B): the size, the context, the + engine, the GGUF (pinned revision, size and SHA-256), the tokenizer from the GGUF, the config and the start + script. The engine places the experts itself (every one in VRAM when they fit, else the most-used ones there and + the rest on the CPU), so there is no pack, profile or RAM budget to choose.""" + fam = OWN_PATH_FAMILIES[family] + say() + say(f" {fam['title']} - {fam['by']}: {fam['about']}") + ok(f"model: {fam['title']}") + if fam.get("license"): + say(f" Its license: {fam['license']}") + if multi: + warn(f"{fam['title']} runs on one GPU so far: using GPU {gpu.get('index', 0)} ({gpu_name(gpu)}) only") + names = list(fam["models"]) + if a.model and a.model not in names: + fail(f"{fam['title']} has no {a.model} model file", "choose one of: " + ", ".join(names)) + say() + for i, m in enumerate(names, 1): + d = fam["models"][m] + size = fam["sha256"][fam["file"].format(q=m)][0] + fit = "" if ram >= d["ram_gb"] else f" <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}" + say(f" {i}) {m:10s} {d['about']}; download {size / 1e9:.1f} GB{fit}") + rec = own_path_size(fam, ram) + if not a.model: + say(f" Recommended for {ram:.0f} GB of RAM: {rec} (the largest that fits; any size can be chosen)") + model = a.model or names[int(ask("Which size?", [str(i) for i in range(1, len(names) + 1)], + str(names.index(rec) + 1), a.yes)) - 1] + if ram < fam["models"][model]["ram_gb"]: + confirm_risk(f"{model} needs about {fam['models'][model]['ram_gb']} GB of RAM; this PC has {ram:.0f} GB: the " + "OS may page and it may not start", bool(a.model), a.yes, + f"{model} needs about {fam['models'][model]['ram_gb']} GB of RAM", + f"choose a smaller size, or --model {model} --yes to install it anyway", " Install it anyway?") + warn(f"installing {model} with {ram:.0f} GB of RAM, as you chose") + ok(f"size: {model}") + tag = fam["tag"] + model + rec_ctx = own_path_context(fam, gpu.get("vram_gb", 0.0)) + if a.context: + ctx = a.context + else: + ctxs = [c for c in CONTEXTS if c <= 262144] # the model's trained length; no rope scaling on this path yet + say() + say(" Context length = how much text the model can see at once. Its cache takes " + f"{fam['kv_bytes_per_token'] * 32768 / 2**30:.1f} GB of VRAM per 32K tokens, room the experts would use:") + for i, c in enumerate(ctxs, 1): + say(f" {i}) {c // 1024}K tokens" + (" (recommended for your GPU)" if c == rec_ctx else "")) + ctx = ctxs[int(ask("Context?", [str(i) for i in range(1, len(ctxs) + 1)], str(ctxs.index(rec_ctx) + 1), + a.yes)) - 1] + if ctx > 262144: + warn(f"{ctx // 1024}K is past {fam['title']}'s trained 262,144 positions and this engine path has no rope " + "scaling yet: kept as you chose, but answers past 256K are untested") + ok(f"context: {ctx} tokens") + if a.vision not in (None, "no", "none"): + warn(f"images are not available with {fam['title']} yet: off") + if a.rope_scaling or a.rope_scale or a.kv or a.resident_budget_gib is not None or a.low_ram not in (None, "auto"): + warn(f"--rope-scaling / --kv / --resident-budget-gib / --low-ram are Flash-Next settings: {fam['title']} " + "does not use them") + folder = Path(a.gguf_dir) if a.gguf_dir else Path(a.models_dir) / tag + gguf = folder / fam["file"].format(q=model) + size = fam["sha256"][gguf.name][0] + part = gguf.with_name(gguf.name + ".part") + left = 0 if gguf.exists() and done(gguf) else (size - (part.stat().st_size if part.is_file() else 0)) / 1e9 + if left and free_gb(folder) < left + 1: + fail(f"not enough free disk space in {folder}: need ~{left + 1:.0f} GB", "use --models-dir on a bigger drive") + + step(3, "Python packages") + pip_install(requirement_lines() if REQUIREMENTS.exists() else PY_PACKAGES, + "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil") + + step(4, "the Strata engine") + llama, eng, meta, lib_dirs, gpu, _ = engine_step(a, gpu, hip, amd, cuda_tk, "none") + if fam["arch"] not in engine_families(eng): + fail(f"this engine ({meta.get('version')}) does not run {fam['title']} yet", + "update Strata, or compile the engine with --build, and run setup again") + ok(f"engine: {eng / EXE}") + + step(5, f"downloading {fam['title']} {model}") + if gguf.exists() and done(gguf): + ok(f"{gguf.name} already downloaded") + else: + if a.gguf_dir: + fail(f"{gguf} is missing", f"put {gguf.name} in {folder}, or drop --gguf-dir to download it") + download(fam["hf"] + gguf.name, gguf) + verify_sha256(gguf, *fam["sha256"][gguf.name]) + ok(f"model file: {gguf}") + + step(6, "preparing the model for Strata") + data, _ = data_folder(a.data_dir) + pack = data / "packs" / tag.lower() # only the tokenizer: the engine reads the GGUF itself + if not (pack / "tokenizer" / "vocab.json").exists(): + run([sys.executable, str(ROOT / "tools" / "strata_tokenizer.py"), "--gguf", str(gguf), "--out", str(pack)], + env=dict(os.environ, STRATA_GGUF_PY=str(llama / "gguf-py"))) + ok(f"tokenizer: {pack / 'tokenizer'}") + + step(7, "writing the start script") + args = ["--native", str(gguf), "--max-context", str(ctx), "--prefill", "auto", "--mtp", str(fam["mtp"])] + if a.vram_reserve_mib is not None: # VRAM left free for other programs: the experts take that much less + vram = gpu.get("vram_gb", 0.0) + if vram > 0: + args += ["--expert-vram", f"{max(vram - 3.0 - a.vram_reserve_mib / 1024, 0):.1f}"] + ok(f"VRAM kept free for other programs: about {a.vram_reserve_mib} MiB (the experts' share is set lower)") + cfg = {"exe": str(eng / EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"), + "model_name": f"{fam['name']}-{model.lower()}", "arch": fam["arch"], + "log": str(ROOT / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": port} + if cuda_tk == 12: + cfg["cuda"] = 12 + if hip: + cfg["backend"] = "hip" + if gpu.get("count", 1) > 1 or a.gpu is not None: + cfg["gpu"] = gpu["index"] + cfg["gpus_asked"] = True + if a.host: + cfg["host"] = a.host + if a.api_key: + cfg["api_key"] = a.api_key + if a.browser is not None: + cfg["open_browser"] = a.browser + cfg["args"] = recommend_pool_workers(cfg["args"]) # --pool-workers: this engine path's CPU expert threads too + cfg_path = ROOT / f"strata-{tag.lower()}.json" + write_setup_config(cfg_path, cfg, adopted if adopted is not None and adopted.name == cfg_path.name else None) + script = write_run_script(tag, cfg_path, port, cfg.get("open_browser") is not False) + ok(f"start script: {script.name}") + say() + say("All set.") + say(f" API (OpenAI): http://127.0.0.1:{port}/v1 (any API key; model name: anything)") + say(f" API (Anthropic): http://127.0.0.1:{port}/v1/messages") + say(f" Next time: just run {'START-HERE.bat' if WIN else './setup.sh'} (or {script.name}) - it starts right away") + if a.no_start: + return 0 + return start(cfg_path, port) + + +def preview_family(a) -> int: + """--family qwen36: a family setup knows but the engine does not run yet (PREVIEW_FAMILIES). Downloads the chosen + size (pinned revision, size and SHA-256 checked) and, with --vision, the image encoder - and says plainly that + Strata cannot start it yet. Nothing is configured: no engine, no pack, no start script.""" + fam = PREVIEW_FAMILIES[a.family] + names = list(fam["models"]) + say() + say(f" {fam['title']} - {fam['by']}: {fam['about']}") + warn(f"this Strata version does not run {fam['title']} yet (support is in development): setup downloads its " + "files, and the engine refuses them with a message until a version that runs it") + if a.model and a.model not in names: + fail(f"{fam['title']} has no {a.model} model file", "choose one of: " + ", ".join(names)) + ram = ram_gb() + for i, m in enumerate(names, 1): + d = fam["models"][m] + size = fam["sha256"][fam["file"].format(q=m)][0] + fit = "" if ram >= d["ram_gb"] else f" <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}" + say(f" {i}) {m:10s} {d['about']}; download {size / 1e9:.1f} GB{fit}") + if a.check: + return 0 + model = a.model or names[int(ask("Which size?", [str(i) for i in range(1, len(names) + 1)], "1", a.yes)) - 1] + say(f" Its license: {fam['license']}") + want = [fam["file"].format(q=model)] + if a.vision in ("yes", "gpu", "cpu"): + want.append(fam["mmproj"]) + folder = Path(a.models_dir) / (fam["tag"] + model) + files = [folder / w for w in want] + left = sum(fam["sha256"][f.name][0] - (f.with_name(f.name + ".part").stat().st_size + if f.with_name(f.name + ".part").is_file() else 0) + for f in files if not (f.exists() and done(f))) / 1e9 + if left and free_gb(folder) < left + 1: + fail(f"not enough free disk space in {folder}: need ~{left + 1:.0f} GB", "use --models-dir on a bigger drive") + step(5, f"downloading {fam['title']} {model}") + for f in files: + url = (fam["mmproj_hf"] if f.name == fam["mmproj"] else fam["hf"]) + f.name + download(url, f, "vision encoder" if f.name == fam["mmproj"] else None) + verify_sha256(f, *fam["sha256"][f.name]) + ok(f"{fam['title']} {model}: {folder}") + say() + say(f"{fam['title']} is downloaded, but this Strata version cannot run it yet (its engine path is in " + "development); nothing was configured. Run setup again without --family qwen36 to install a model it runs.") + return 0 + + def main() -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--family", choices=list(FAMILIES), help="qwen = Qwen3.8-Flash-Next, swift = Swift 1.5") - ap.add_argument("--model", choices=list(MODELS)) + ap.add_argument("--family", choices=list(FAMILIES) + list(PREVIEW_FAMILIES), + help="qwen = Qwen3.8-Flash-Next, swift = Swift 1.5 (qwen36 = Qwen3.6-35B-A3B: download only, the " + "engine does not run it yet)") + ap.add_argument("--model", choices=list(dict.fromkeys([*MODELS, *(m for f in PREVIEW_FAMILIES.values() + for m in f["models"])]))) ap.add_argument("--context", type=int) ap.add_argument("--rope-scaling", choices=["none", "linear", "yarn"], help="the RoPE extension for a context past the model's trained 262144: linear (position " @@ -5187,6 +5472,9 @@ def main() -> int: "sycl = Intel Arc, EXPERIMENTAL: Linux, built from source (docs/INTEL_ARC.md)") ap.add_argument("--skip-build", action="store_true", help=argparse.SUPPRESS) a = ap.parse_args() + if a.model and a.model not in MODELS and a.family not in PREVIEW_FAMILIES: + ap.error(f"--model {a.model} is a size of " + ", ".join(f"--family {f}" for f, d in PREVIEW_FAMILIES.items() + if a.model in d["models"])) if a.source: os.environ["STRATA_SOURCE"] = a.source if a.inspect: # headers only: nothing is installed @@ -5491,8 +5779,14 @@ def main() -> int: d = FAMILIES[f] say(f" {i}) {d['title']:20s} {d['by']} - {d['about']}" + (" [experimental]" if d.get("experimental") else "") + (f" (recommended for Strix Halo: {STRIX_HALO_MODEL})" if f == rec_fam and rec_fam != fams[0] else "")) - family = fams[int(ask("Which model?", [str(i) for i in range(1, len(fams) + 1)], - str(fams.index(rec_fam) + 1), a.yes)) - 1] + for j, f in enumerate(OWN_PATH_FAMILIES, len(fams) + 1): # families with an engine path of their own + d = OWN_PATH_FAMILIES[f] + say(f" {j}) {d['title']:20s} {d['by']} - {d['about']} [new]") + allf = fams + list(OWN_PATH_FAMILIES) + family = allf[int(ask("Which model?", [str(i) for i in range(1, len(allf) + 1)], + str(allf.index(rec_fam) + 1), a.yes)) - 1] + if family in OWN_PATH_FAMILIES: # Qwen3.6: its own engine path, its own steps 2-7 + return install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted) fam = FAMILIES[family] if fam.get("ready") and hip: # not a risk the user could take: the HIP engine has no NVFP4 expert kernels at all, so it would not start @@ -5789,38 +6083,13 @@ def main() -> int: # ---- 4. the engine step(4, "the Strata engine") - llama = get_llama_cpp() - ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py, ggml, mtmd)") - if hip and WIN: # AMD on Windows: the ready-made HIP engine (no compiler) - eng = None if a.build else get_prebuilt_hip(a.prebuilt, gpu) - if eng is None: - fail("no ready-made AMD engine for this Strata version" + (" (--build)" if a.build else ""), - "compiling it on Windows: tools\\hip\\build_windows.bat makes strata-windows-x64-hip.zip, then run " - "START-HERE.bat --backend hip --prebuilt (docs/AMD_HIP.md)") - gpu = hip_card(eng, gpu, amd) - a.gpu = gpu["index"] if gpu["count"] > 1 else a.gpu - else: - eng = None if a.build or hip else get_prebuilt(a.prebuilt, gpu, vision, **({"toolkit": 12} if cuda_tk == 12 - else {})) - if eng is not None and not hip and json.loads((eng / "BUILD.json").read_text(encoding="utf-8")).get("source") != "local": - pip_cuda_libs(cuda_tk) - if vision != "none" and not (eng / VEXE).exists(): - warn("the ready-made engine has no image encoder: compiling it") - eng = None - else: - vision = prebuilt_vision(json.loads((eng / "BUILD.json").read_text(encoding="utf-8")), gpu, vision) - if eng is None: - eng = build_engine_hip(gpu, llama, vision) if hip else build_engine(gpu, vision, a.yes, llama, toolkit=cuda_tk) - meta = json.loads((eng / "BUILD.json").read_text(encoding="utf-8")) + llama, eng, meta, lib_dirs, gpu, vision = engine_step(a, gpu, hip, amd, cuda_tk, vision) if ready and meta.get("source") != "local" and \ tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit()) < MODELS[model]["engine"]: # a ready-made engine from before NVFP4 cannot read these experts: one compiled from this source can warn(f"the ready-made engine {meta.get('version')} has no NVFP4 experts yet: compiling the engine from this source") eng = build_engine(gpu, vision, a.yes, llama, toolkit=cuda_tk) meta = json.loads((eng / "BUILD.json").read_text(encoding="utf-8")) - if hip and WIN: # the ready-made engine's rocm/bin, first on the engine's PATH - lib_dirs = [str(d) for d in hip_lib_dirs(eng)] - else: lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs(cuda_tk) engine_ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit()) need_engine = MODELS[model].get("engine", UNSLOTH_ENGINE) diff --git a/src/core/native_dense.cpp b/src/core/native_dense.cpp index f75b03b2..aba2882b 100644 --- a/src/core/native_dense.cpp +++ b/src/core/native_dense.cpp @@ -272,7 +272,7 @@ bool NativeDense::load(const std::vector& shards, WeightTable& tabl const auto* tensors = gguf.get("split.tensors.count"); if (gguf.get("general.architecture") && (!number || number->u == 0)) { // splitter may copy general.architecture into every shard (Huihui abliterated re-split) - err = strata::check_architecture(gguf); + err = strata::check_engine_architecture(gguf); if (!err.empty()) return false; have_architecture = true; if (count && number && tensors && number->u == 0 && count->u > 1) { diff --git a/src/core/native_head.cpp b/src/core/native_head.cpp index daa381e7..8e239d3d 100644 --- a/src/core/native_head.cpp +++ b/src/core/native_head.cpp @@ -34,7 +34,7 @@ bool NativeHead::load(const std::vector& shards, int64_t n_in, int6 // The architecture is the metadata shard's; output.weight comes from whichever shard holds it (shard 2 // of Unsloth's UD-Q4_K_XL, whose shard 1 holds no tensor). GgufModel refuses a duplicate across shards. const strata::GgufModel model(shards); - err = strata::check_architecture(model.meta()); + err = strata::check_engine_architecture(model.meta()); if (!err.empty()) return false; size_t at = 0; const strata::TensorInfo* tensor = model.find("output.weight", &at); @@ -122,7 +122,7 @@ bool NativeEmbed::load(const std::vector& shards, int64_t n_embd, i const strata::GgufModel model(shards); // --embd-gguf's one-tensor file (tools/embd_bf16_pack.py) says "strata-embd": only its tensor is checked const strata::MetaValue* arch = model.meta().get("general.architecture"); - err = arch != nullptr && arch->s == "strata-embd" ? std::string() : strata::check_architecture(model.meta()); + err = arch != nullptr && arch->s == "strata-embd" ? std::string() : strata::check_engine_architecture(model.meta()); if (!err.empty()) { err = "native embedding: " + err; return false; } size_t at = 0; const strata::TensorInfo* t = model.find("token_embd.weight", &at); diff --git a/src/kernels/cpu/pool.cpp b/src/kernels/cpu/pool.cpp index 840b4f81..1ea9c6ae 100644 --- a/src/kernels/cpu/pool.cpp +++ b/src/kernels/cpu/pool.cpp @@ -682,8 +682,9 @@ void ExpertPool::drain(int id, ExpertScratch& scratch, uint32_t epoch) { const int r0 = H * part / parts_b_, r1 = H * (part + 1) / parts_b_; s2_expert_down_rows(jobs_[e].blob, split_[(size_t) e].a2, jobs_[e].out, r0, r1); } else if (mode_ >= 5) { - // plan v0.3 P6: native layers, 5 = gate/up rows, 6 = down rows - const int per = mode_ == 5 ? FF : H; + // plan v0.3 P6: native layers, 5 = gate/up rows, 6 = down rows (the layer's own n_ff / n_embd: Flash-Next's + // FF / H, or another family's smaller expert) + const int per = mode_ == 5 ? (int) nfmt_->n_ff : (int) nfmt_->n_embd; const int64_t g0 = mrows_ * (int64_t) i / mtasks_, g1 = mrows_ * (int64_t) (i + 1) / mtasks_; for (int64_t r = g0; r < g1;) { const int e = (int) (r / per), r0 = (int) (r % per); @@ -821,7 +822,7 @@ void ExpertPool::run_split_multi_native(const NativeFmt& f, ExpertJobMulti* jobs const int nb = (std::min)(kMaxSplitMulti, n - b0); mjobs_ = jobs + b0; nfmt_ = &f; - mrows_ = (int64_t) nb * FF; + mrows_ = (int64_t) nb * f.n_ff; mtasks_ = phase_tasks(mrows_); const auto a = std::chrono::steady_clock::now(); run_phase(5, mtasks_); @@ -831,7 +832,7 @@ void ExpertPool::run_split_multi_native(const NativeFmt& f, ExpertJobMulti* jobs if (q2_native_kernels(f.d_type)) act_quant_any(split_multi_[(size_t) e].ff[t], FF, split_multi_[(size_t) e].a2[t]); else native_quant_h(f, split_multi_[(size_t) e].ff[t], split_multi_[(size_t) e].hq[t]); const auto c = std::chrono::steady_clock::now(); - mrows_ = (int64_t) nb * H; + mrows_ = (int64_t) nb * f.n_embd; mtasks_ = phase_tasks(mrows_); run_phase(6, mtasks_); const auto d = std::chrono::steady_clock::now(); diff --git a/src/kernels/cuda/fused_gdn.cu b/src/kernels/cuda/fused_gdn.cu index d3311c25..7de1a3ea 100644 --- a/src/kernels/cuda/fused_gdn.cu +++ b/src/kernels/cuda/fused_gdn.cu @@ -15,6 +15,9 @@ static_assert(S == strata::core::kCompiledGeometry.ssm_state_size, "fused_gdn is constexpr int RG = 4; // row groups constexpr int RPG = S / RG; // 32 rows per thread +// SILU: the output gate is SiLU(z) (Qwen3.6, qwen35moe) instead of sigmoid(z) (Flash-Next); a compile-time flag, so +// the sigmoid instantiation is the kernel it was. +template __global__ void __launch_bounds__(S * RG) gdn_step_norm_kernel(float* __restrict__ state, const float* __restrict__ q, const float* __restrict__ k, const float* __restrict__ v, const float* __restrict__ gate, @@ -68,7 +71,8 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_kernel(float* __restrict const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; const float scale = rsqrtf(ss / (float) S + eps); const float zz = z[head * S + col]; - y[head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); + if constexpr (SILU) y[head * S + col] = oc * scale * gamma[col] * (zz / (1.0f + __expf(-zz))); + else y[head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); } } @@ -149,20 +153,34 @@ void fused_gdn_ab(const float* x, const uint16_t* w_alpha, const uint16_t* w_bet if (e != cudaSuccess) { std::fprintf(stderr, "fused_gdn_ab: %s\n", cudaGetErrorString(e)); std::exit(1); } } -void fused_gdn_step_norm(float* state, const float* q, const float* k, const float* v, const float* gate, - const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, - void* stream) { +namespace { +template +void step_norm(float* state, const float* q, const float* k, const float* v, const float* gate, const float* beta, + const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, void* stream) { if (!state || !q || !k || !v || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v <= 0 || h_v % h_k) { std::fprintf(stderr, "fused_gdn_step_norm: invalid arguments\n"); std::exit(1); } - gdn_step_norm_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>(state, q, k, v, gate, beta, z, - gamma, eps, y, h_k, h_v); + gdn_step_norm_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>(state, q, k, v, gate, beta, + z, gamma, eps, y, h_k, h_v); const cudaError_t e = cudaGetLastError(); if (e != cudaSuccess) { std::fprintf(stderr, "fused_gdn_step_norm: %s\n", cudaGetErrorString(e)); std::exit(1); } } +} // namespace + +void fused_gdn_step_norm(float* state, const float* q, const float* k, const float* v, const float* gate, + const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, + void* stream) { + step_norm(state, q, k, v, gate, beta, z, gamma, eps, y, h_k, h_v, stream); +} + +void fused_gdn_step_norm_silu(float* state, const float* q, const float* k, const float* v, const float* gate, + const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, + int h_v, void* stream) { + step_norm(state, q, k, v, gate, beta, z, gamma, eps, y, h_k, h_v, stream); +} } // namespace strata::kernels diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index d54a980c..947952a0 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -645,7 +645,12 @@ template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0, #else #define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(2) X(3) X(8) X(40) #endif -#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) X(40) +// Q5_K / Q6_K downs: Qwen3.6-35B-A3B (FF 512, whole 256-blocks per row); Flash-Next's FF 640 never selects them +#ifdef STRATA_Q6K_EXPERTS +#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) X(13) X(14) X(40) +#else +#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) X(13) X(40) +#endif #define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(2) X(3) X(8) X(40) template<> struct Fmt<40> { static constexpr int qk = 64, ipb = 2, step = 4; // NVFP4: 2 calls of 32 values __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_nvfp4_q8_1(v, y, kbx, iqs); } }; diff --git a/src/kernels/cuda/native_router.cu b/src/kernels/cuda/native_router.cu index 526b29c7..6611bceb 100644 --- a/src/kernels/cuda/native_router.cu +++ b/src/kernels/cuda/native_router.cu @@ -148,6 +148,63 @@ __global__ void route_multi(const float* __restrict__ logits, int32_t* __restric const float inverse_selected_sum = 1.0f / selected_sum; if (lane < 10) weights[lane] = selected * inverse_selected_sum; } +// The same contract for other (experts, top-k) shapes - Qwen3.6-35B-A3B's 256 / 8 - one warp per token, n_tok tokens +// (8 per block). The 512 / 10 path keeps its own kernels above (the Flash-Next bits), this template is only used +// for the other shapes. +template +__launch_bounds__(256, 1) +__global__ void route_topk(const float* __restrict__ logits, int32_t* __restrict__ ids, float* __restrict__ weights, + int n_tok) { + static_assert(NE % 32 == 0 && K <= 32, "experts in whole warps, at most 32 picks"); + constexpr int V = NE / 32; + const int tk = (int) blockIdx.x * 8 + (int) threadIdx.y; + if (tk >= n_tok) return; + logits += (size_t) tk * NE; ids += (size_t) tk * K; weights += (size_t) tk * K; + const int lane = threadIdx.x; + float values[V]; +#pragma unroll + for (int i = 0; i < V; ++i) values[i] = logits[lane + i * 32]; + float maximum = -INFINITY; +#pragma unroll + for (int i = 0; i < V; ++i) maximum = max(maximum, values[i]); + maximum = warp_max(maximum); + float sum = 0.0f; +#pragma unroll + for (int i = 0; i < V; ++i) { + values[i] = expf(values[i] - maximum); + sum += values[i]; + } + const float reciprocal = 1.0f / warp_sum(sum); +#pragma unroll + for (int i = 0; i < V; ++i) { + values[i] *= reciprocal; + if (__isnanf(values[i])) values[i] = -FLT_MAX; + } + float selected = 0.0f, selected_sum = 0.0f; + for (int rank = 0; rank < K; ++rank) { + float best = values[0]; + int expert = lane; +#pragma unroll + for (int i = 1; i < V; ++i) { + if (values[i] > best) { best = values[i]; expert = lane + i * 32; } + } +#pragma unroll + for (int mask = 16; mask; mask >>= 1) { + const float other = __shfl_xor_sync(0xffffffffu, best, mask, 32); + const int other_id = __shfl_xor_sync(0xffffffffu, expert, mask, 32); + if (other > best || (other == best && other_id < expert)) { best = other; expert = other_id; } + } + if ((expert & 31) == lane) { + values[expert / 32] = -INFINITY; + ids[rank] = expert; + selected_sum += best; + } + if (rank == lane) selected = best; + } + selected_sum = max(warp_sum(selected_sum), 6.103515625e-5f); + const float inverse_selected_sum = 1.0f / selected_sum; + if (lane < K) weights[lane] = selected * inverse_selected_sum; +} bool valid(const void* p, size_t bytes) { const auto address = reinterpret_cast(p); return p && address % 4 == 0 && bytes <= UINTPTR_MAX - address; @@ -176,6 +233,22 @@ void native_router_top10_multi(const float* logits, int32_t* ids, float* weights const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); } +bool native_router_topk_supported(int n_expert, int k) { return (n_expert == 512 && k == 10) || (n_expert == 256 && k == 8); } +void native_router_topk(const float* logits, int32_t* ids, float* weights, int n_expert, int k, int n_tok, void* stream) { + if (n_expert == 512 && k == 10) { // Flash-Next: the pinned kernels above, unchanged + if (n_tok == 1) native_router_top10(logits, ids, weights, stream); + else native_router_top10_multi(logits, ids, weights, n_tok, stream); + return; + } + if (!stream || n_tok < 1 || !native_router_topk_supported(n_expert, k) || + !valid(logits, (size_t) n_tok * n_expert * 4) || !valid(ids, (size_t) n_tok * k * 4) || + !valid(weights, (size_t) n_tok * k * 4)) + throw std::invalid_argument("native_router_topk: a stream, a supported (experts, k) and aligned buffers"); + route_topk<256, 8><<<(unsigned) ((n_tok + 7) / 8), dim3(32, 8), 0, static_cast(stream)>>>( + logits, ids, weights, n_tok); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); +} // STRATA_ROUTE_RESIDENT (EXPERIMENTAL, opt-in, changes the output): residency-biased routing for 512 x 10. // After the top-10: for the ranks lo..hi a non-resident expert is replaced by the best resident expert not already diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 16a03e1b..9cd64fc0 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -87,6 +87,10 @@ #define NOMINMAX // gguf_reader.hpp includes windows.h #endif #include "strata/artifact/gguf_reader.hpp" +#include "strata/core/family_layout.hpp" +#if defined(STRATA_HAVE_QWEN35) +#include "strata/qwen35/engine.hpp" +#endif #if defined(_WIN32) #include #include @@ -1793,6 +1797,15 @@ int main(int argc, char** argv) { std::printf("strata %s\n", STRATA_VERSION); return 0; } + // `strata --families`: the GGUF architectures this build runs (setup asks before it installs one) + if (std::strcmp(argv[i], "--families") == 0) { +#if defined(STRATA_HAVE_QWEN35) + std::printf("qwen4exp qwen35moe\n"); +#else + std::printf("qwen4exp\n"); +#endif + return 0; + } } #if (defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)) && !defined(_WIN32) // AMD, a file-backed arena (STRATA_ARENA_MMAP): ROCclr copies a pageable source of 1 MiB or more by locking its @@ -1840,6 +1853,23 @@ int main(int argc, char** argv) { #endif break; } +#if defined(STRATA_HAVE_QWEN35) + // **THE FAMILY SWITCH.** A Qwen3.6-35B-A3B file (GGUF architecture qwen35moe) runs on its own engine path + // (src/qwen35), decided here from the file's header before any of this engine's state exists; every other file + // goes on below exactly as before. Only the architecture string is read (the header of --native's shard). + for (int i = 1; i + 1 < argc; ++i) { + if (std::strcmp(argv[i], "--native") != 0 && std::strcmp(argv[i], "--model") != 0) continue; + bool qwen35 = false; + try { + const strata::GgufFile meta(strata::gguf_split_paths(argv[i + 1]).front()); + qwen35 = strata::model_family(meta) == strata::ModelFamily::Qwen35Moe; + } catch (const std::exception&) { + // not readable here: the normal path below reports it + } + if (qwen35) return strata::qwen35::run(argc, argv); + break; + } +#endif Options o; bool have_tokens = false; bool have_logits_stride = false; @@ -2539,6 +2569,16 @@ int main(int argc, char** argv) { // every shard of the model (-0000N-of-0000M.gguf beside --native). A missing shard is an error // here: it used to be skipped, leaving a model with some tensors absent and a later error, or none. o.native_shards = strata::gguf_split_paths(o.native_preset); + // a model family Strata recognises but has no engine path for yet (Qwen3.6-35B-A3B) is refused here, + // with a message that says so, before anything else about the file is judged + { + const strata::GgufFile meta(o.native_shards.front()); + const std::string why = strata::model_family_not_supported(strata::model_family(meta)); + if (strata::model_family(meta) != strata::ModelFamily::Unknown && !why.empty()) { + std::fprintf(stderr, "strata generate: --native %s: %s\n", o.native_preset.c_str(), why.c_str()); + return 2; + } + } // --ple-gguf defaults to the shard that holds the PLE table, found by name: shard 2 of the ISTA files // and of Unsloth's UD-Q4_K_XL, shard 1 of Swift's if (o.ple_gguf.empty() && !o.no_ple) { @@ -2865,21 +2905,26 @@ int main(int argc, char** argv) { std::string gguf_rope_type; double gguf_rope_base = 0, gguf_rope_factor = 0, gguf_rope_orig_ctx = 0; if (!o.native_preset.empty()) { - // the model file is the authority on its own geometry; the kernels' compiled shape is checked against - // it before any weight moves, naming the key that differs + // The geometry is the model file's (core::geometry_from_gguf: every ".*" shape key), checked + // against the shapes this engine's kernels are built for. The expert count and top-k are run-time + // sizes: a pruned variant (GSQ-RCO Coder) ships fewer experts than the canonical 512x10. try { strata::GgufFile model_gguf(o.native_shards.front()); // the metadata shard - std::string gerr = strata::read_geometry(model_gguf, g); - if (gerr.empty()) gerr = strata::geometry_unsupported(g); - if (!gerr.empty()) { - std::fprintf(stderr, "strata generate: %s: %s\n", o.native_shards.front().c_str(), gerr.c_str()); + std::string gerr; + if (!strata::core::geometry_from_gguf(model_gguf, g, K, gerr)) { + std::fprintf(stderr, "strata generate: %s\n", gerr.c_str()); return 1; } - K = g.n_expert_used; - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.freq_base")) gguf_rope_base = v->num(); - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.type")) gguf_rope_type = v->s; - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.factor")) gguf_rope_factor = v->num(); - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.original_context_length")) + const std::string mismatch = strata::core::compiled_geometry_mismatch(g); + if (!mismatch.empty()) { + std::fprintf(stderr, "strata generate: %s: %s\n", o.native_preset.c_str(), mismatch.c_str()); + return 1; + } + const std::string p = std::string(strata::model_family_arch(g.family)) + "."; + if (const strata::MetaValue* v = model_gguf.get(p + "rope.freq_base")) gguf_rope_base = v->num(); + if (const strata::MetaValue* v = model_gguf.get(p + "rope.scaling.type")) gguf_rope_type = v->s; + if (const strata::MetaValue* v = model_gguf.get(p + "rope.scaling.factor")) gguf_rope_factor = v->num(); + if (const strata::MetaValue* v = model_gguf.get(p + "rope.scaling.original_context_length")) gguf_rope_orig_ctx = v->num(); } catch (const std::exception& e) { std::fprintf(stderr, "strata generate: reading the model's geometry from %s: %s\n", diff --git a/src/qwen35/q36_engine.cu b/src/qwen35/q36_engine.cu new file mode 100644 index 00000000..c42aff35 --- /dev/null +++ b/src/qwen35/q36_engine.cu @@ -0,0 +1,2513 @@ +// src/qwen35/q36_engine.cu - strata-q36: the engine path for Qwen3.6-35B-A3B (GGUF architecture qwen35moe), +// NEW-MODELS-PLAN.md T1. A driver of its own beside Flash-Next's (generate/verify/prefill stay untouched, so the +// Flash-Next identity gate cannot move), built from Strata's kernels: +// +// * weights straight from the GGUF: dense Q8_0 / K-quant matrices in their blocks (native MMVQ), the 1-D tensors and +// the F32 projections (ssm_alpha/beta, the router, the shared-expert gate) as f32, the routed experts repacked at +// load into native expert blobs [gate | up | down] per (layer, expert) for `native_expert_grouped`; +// * the plain pre-norm residual layer driver: x += mixer(rms(x) * attn_norm); x += moe(rms(x) * post_attention_norm); +// * GDN: fused conv + L2 and the fused step with the SiLU-gated norm (per token, the state carried); +// * attention without an indexer: dense, 16 query heads over 2 KV heads, split-K over 256-cell chunks with a +// log-sum-exp merge, causal for a batch of queries (the prompt) and for one (decode); +// * MoE: the native router (256 / top-8), the experts grouped per expert on the device (one weight read per expert +// for the whole batch), the shared expert with its sigmoid gate, the native combine; +// * the prompt read in chunks of --chunk tokens through the same driver (batched matmuls, ncols <= 8 per launch); +// * decode one token at a time from a captured graph (positions on the device), or with --no-graph eagerly. +// +// Modes: --serve (serve/server.py's engine protocol: READY / GEN / T / DONE / STOP / PP), --tokens IDS [--n N] +// [--force IDS] [--dump-full-logits F] (tools/qwen35/kl.py's reference interface), --bench-pp N / --bench-tg N. +#include "strata/artifact/gguf_reader.hpp" +#include "strata/core/family_layout.hpp" +#include "strata/kernels/fused_gdn.hpp" +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/native_mmvq.hpp" +#include "strata/kernels/native_moe.hpp" +#include "strata/kernels/native_router.hpp" +#include "strata/prefill/gemm.hpp" +#include "strata/prefill/moe_mmq.hpp" +#include "strata/qwen35/engine.hpp" +#if defined(STRATA_Q36_CPU_POOL) +#include "strata/kernels/cpu/native_expert.hpp" +#include "strata/kernels/cpu/pool.hpp" +#endif + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace K = strata::kernels; +namespace MMQ = strata::prefill::mmq; + +#define CK(x) \ + do { \ + cudaError_t e_ = (x); \ + if (e_ != cudaSuccess) { \ + std::fprintf(stderr, "strata-q36: %s failed: %s (%s:%d)\n", #x, cudaGetErrorString(e_), __FILE__, __LINE__); \ + std::exit(1); \ + } \ + } while (0) + +using Clock = std::chrono::steady_clock; +double ms_since(Clock::time_point t) { return std::chrono::duration(Clock::now() - t).count(); } + +constexpr int kThreads = 256; +constexpr int kChunkCells = 256; // attention split-K chunk + +// ------------------------------------------------------------------------------------------------ small kernels +__device__ __forceinline__ float silu(float v) { return v / (1.0f + expf(-v)); } +__device__ __forceinline__ float sigm(float v) { return 1.0f / (1.0f + expf(-v)); } +__device__ __forceinline__ float softplus(float v) { return v > 20.f ? v : log1pf(expf(v)); } + +__device__ float block_sum(float v, float* sh) { + sh[threadIdx.x] = v; + __syncthreads(); + for (int s = blockDim.x / 2; s > 0; s >>= 1) { + if ((int) threadIdx.x < s) sh[threadIdx.x] += sh[threadIdx.x + s]; + __syncthreads(); + } + const float r = sh[0]; + __syncthreads(); + return r; +} +__device__ float block_max(float v, float* sh) { + sh[threadIdx.x] = v; + __syncthreads(); + for (int s = blockDim.x / 2; s > 0; s >>= 1) { + if ((int) threadIdx.x < s) sh[threadIdx.x] = fmaxf(sh[threadIdx.x], sh[threadIdx.x + s]); + __syncthreads(); + } + const float r = sh[0]; + __syncthreads(); + return r; +} + +/// y[r] = rms(x[r]) * w, one block per row of n. +__global__ void k_rms(const float* x, const float* w, float* y, int n, float eps) { + __shared__ float sh[kThreads]; + const float* xr = x + (size_t) blockIdx.x * n; + float* yr = y + (size_t) blockIdx.x * n; + float s = 0.f; + for (int i = threadIdx.x; i < n; i += blockDim.x) s += xr[i] * xr[i]; + s = block_sum(s, sh); + const float r = rsqrtf(s / (float) n + eps); + for (int i = threadIdx.x; i < n; i += blockDim.x) yr[i] = xr[i] * r * w[i]; +} +/// x[r] += y[r]; h[r] = rms(x[r]) * w (one block per row of n): the residual add and the next norm in one launch. +/// out[r * ld_out + i] = rms(x[r * ldx + ..]) * w (one block per row of n): a norm into a slice of a wider row. +__global__ void k_rms_ld(const float* x, int ldx, const float* w, float* out, int ld_out, int n, float eps) { + __shared__ float sh[kThreads]; + const float* xr = x + (size_t) blockIdx.x * ldx; + float* yr = out + (size_t) blockIdx.x * ld_out; + float s = 0.f; + for (int i = threadIdx.x; i < n; i += blockDim.x) s += xr[i] * xr[i]; + s = block_sum(s, sh); + const float r = rsqrtf(s / (float) n + eps); + for (int i = threadIdx.x; i < n; i += blockDim.x) yr[i] = xr[i] * r * w[i]; +} +__global__ void k_add_rms(float* x, const float* y, const float* w, float* h, int n, float eps) { + __shared__ float sh[kThreads]; + float* xr = x + (size_t) blockIdx.x * n; + const float* yr = y + (size_t) blockIdx.x * n; + float* hr = h + (size_t) blockIdx.x * n; + float s = 0.f; + for (int i = threadIdx.x; i < n; i += blockDim.x) { + const float v = xr[i] + yr[i]; + xr[i] = v; + s += v * v; + } + s = block_sum(s, sh); + const float r = rsqrtf(s / (float) n + eps); + for (int i = threadIdx.x; i < n; i += blockDim.x) hr[i] = xr[i] * r * w[i]; +} +/// The MoE block's end for one token row (block per row): x += sum_k w_k part_k (in pick order, FMA after the first +/// product, as native_moe_combine) + sigmoid(sgate) * shared; then, with `wn`, h = rms(x) * wn (the next layer's +/// attention norm). Replaces combine + gate + add + rms. +__global__ void k_moe_out(float* x, const float* parts, const int32_t* prow, const float* wts, int K_, + const float* shared, const float* sgate, int sg_stride, const float* wn, float* h, int n, + float eps) { + __shared__ float sh[kThreads]; + __shared__ const float* pk[16]; + const int t = blockIdx.x; + float* xr = x + (size_t) t * n; + if (threadIdx.x < K_) // pick k's row: t * K + k, or its sorted row (`prow`, the prompt's MMQ order) + pk[threadIdx.x] = parts + (size_t) (prow ? prow[t * K_ + threadIdx.x] : t * K_ + threadIdx.x) * n; + __syncthreads(); + const float* wr = wts + (size_t) t * K_; + const float gs = sigm(sgate[(size_t) t * sg_stride]); + float s = 0.f; + for (int i = threadIdx.x; i < n; i += blockDim.x) { + float acc = wr[0] * pk[0][i]; + for (int k = 1; k < K_; ++k) acc = fmaf(wr[k], pk[k][i], acc); + acc += gs * shared[(size_t) t * n + i]; + const float v = xr[i] + acc; + xr[i] = v; + s += v * v; + } + if (wn == nullptr) return; + s = block_sum(s, sh); + const float r = rsqrtf(s / (float) n + eps); + for (int i = threadIdx.x; i < n; i += blockDim.x) h[(size_t) t * n + i] = xr[i] * r * wn[i]; +} +/// GDN alpha and beta for T <= 8 rows in one launch, their epilogues applied: rows [0, HV) of the output are +/// softplus(alpha . x + dt) * ssm_a, rows [HV, 2 HV) sigmoid(beta . x). Warp per row (grid (ceil(2 HV / 8), T)). +__global__ void k_gdn_ab(const float* Wa, const float* Wb, const float* x, const float* dt, const float* ssm_a, + float* alpha, float* beta, int n_in, int HV) { + const int warp = threadIdx.x / 32, lane = threadIdx.x % 32; + const int o = blockIdx.x * 8 + warp; + if (o >= 2 * HV) return; + const bool isb = o >= HV; + const int r = isb ? o - HV : o; + const float4* wr = (const float4*) ((isb ? Wb : Wa) + (size_t) r * n_in); + const float4* xr = (const float4*) (x + (size_t) blockIdx.y * n_in); + float acc = 0.f; + for (int i = lane; i < n_in / 4; i += 32) { + const float4 a = wr[i], b = xr[i]; + acc += a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; + } + for (int m = 16; m > 0; m >>= 1) acc += __shfl_xor_sync(0xffffffffu, acc, m); + if (lane != 0) return; + if (isb) beta[(size_t) blockIdx.y * HV + r] = sigm(acc); + else alpha[(size_t) blockIdx.y * HV + r] = softplus(acc + dt[r]) * ssm_a[r]; +} +__global__ void k_add(float* x, const float* y, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) x[i] += y[i]; +} +__global__ void k_swiglu(const float* g, const float* u, float* h, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) h[i] = silu(g[i]) * u[i]; +} +/// y[t][o] = W[o] . x[t] for f32 W [n_out][n_in], n_in a multiple of 128: one warp per row, float4 loads, 8 rows per +/// block (grid (ceil(n_out / 8), T)). +__global__ void k_gemv_f32(const float* W, const float* x, float* y, int n_in, int n_out) { + const int warp = threadIdx.x / 32, lane = threadIdx.x % 32; + const int o = blockIdx.x * 8 + warp; + if (o >= n_out) return; + const float4* wr = (const float4*) (W + (size_t) o * n_in); + const float4* xr = (const float4*) (x + (size_t) blockIdx.y * n_in); + float acc = 0.f; + for (int i = lane; i < n_in / 4; i += 32) { + const float4 a = wr[i], b = xr[i]; + acc += a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; + } + for (int m = 16; m > 0; m >>= 1) acc += __shfl_xor_sync(0xffffffffu, acc, m); + if (lane == 0) y[(size_t) blockIdx.y * n_out + o] = acc; +} +unsigned rows8(int n) { return (unsigned) ((n + 7) / 8); } +/// GDN gate / beta in place for T rows of HV: alpha -> softplus(alpha + dt) * ssm_a, beta -> sigmoid(beta). +__global__ void k_gdn_gb(float* alpha, const float* dt, const float* ssm_a, float* beta, int HV, int T) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= HV * T) return; + const int h = i % HV; + alpha[i] = softplus(alpha[i] + dt[h]) * ssm_a[h]; + beta[i] = sigm(beta[i]); +} +/// sh[t] *= sigmoid(gate[t]) (the shared expert's scalar gate), rows of n. +__global__ void k_gate_rows(float* sh, const float* gate, int n, int T) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= (int64_t) n * T) return; + sh[i] *= sigm(gate[i / n]); +} + +/// The attention layer's per-token preparation for T rows at positions *pos0 + t: q (from the [q | gate] pairs) and k +/// RMS-normed per head with their weights, NEOX RoPE over the first n_rot dims, k / v into the cache, the gate kept. +/// grid (H + HKV, T), block 256 (HD <= 256). +__global__ void k_attn_prep(const float* qg, const float* kx, const float* vx, const float* qw, const float* kw, + float* q, float* gate, float* kc, float* vc, int H, int HKV, int HD, int n_rot, + const int32_t* pos0, int ctx, float base, float eps) { + __shared__ float sh[kThreads]; + __shared__ float buf[256]; + const int head = blockIdx.x, t = blockIdx.y; + const int pos = *pos0 + t; + const bool isq = head < H; + const float* src = isq ? qg + ((size_t) t * H + head) * 2 * HD : kx + ((size_t) t * HKV + head - H) * HD; + const int i = threadIdx.x; + const float v0 = i < HD ? src[i] : 0.f; + const float s = block_sum(v0 * v0, sh); + const float r = rsqrtf(s / (float) HD + eps); + if (i < HD) buf[i] = v0 * r * (isq ? qw[i] : kw[i]); + __syncthreads(); + if (i >= HD) return; + float v = buf[i]; + const int half = n_rot / 2; + if (i < n_rot) { + const int p = i < half ? i : i - half; + const float theta = (float) pos * powf(base, -2.0f * (float) p / (float) n_rot); + float sn, cs; + sincosf(theta, &sn, &cs); + v = i < half ? buf[i] * cs - buf[i + half] * sn : buf[i - half] * sn + buf[i] * cs; + } + if (isq) { + q[((size_t) t * H + head) * HD + i] = v; + gate[((size_t) t * H + head) * HD + i] = qg[((size_t) t * H + head) * 2 * HD + HD + i]; + } else { + const int kh = head - H; + kc[((size_t) kh * ctx + pos) * HD + i] = v; + vc[((size_t) kh * ctx + pos) * HD + i] = vx[((size_t) t * HKV + kh) * HD + i]; + } +} + +/// Split-K attention, one block per (chunk of 256 cells, query row): query row qi = t * H + h (t from t0) sees the +/// cells [0, *pos0 + t]. Writes the chunk's partial accumulator, max and sum; chunks past the query's cells write +/// nothing (the merge stops before them). grid (n_chunk, n_rows), block 256, HD == 256. +__global__ void k_attn_part(const float* q, const float* kc, const float* vc, const int32_t* pos0, int t0, int H, + int HKV, int ctx, float scale, int n_chunk, float* pacc, float* pm, float* pl) { + constexpr int HD = 256; + __shared__ float qs[HD], sc[kChunkCells], sh[kThreads]; + const int c = blockIdx.x, row = blockIdx.y; + const int t = t0 + row / H, h = row % H, kvh = h / (H / HKV); + const int npos = *pos0 + t + 1; + const int p0 = c * kChunkCells; + if (p0 >= npos) return; + const int j = threadIdx.x; + qs[j] = q[((size_t) t * H + h) * HD + j]; + __syncthreads(); + const int p = p0 + j; + float s = -INFINITY; + if (p < npos) { + const float* kp = kc + ((size_t) kvh * ctx + p) * HD; + float a = 0.f; + for (int i = 0; i < HD; ++i) a += qs[i] * kp[i]; + s = a * scale; + } + const float m = block_max(s, sh); + const float e = p < npos ? expf(s - m) : 0.f; + sc[j] = e; + const float l = block_sum(e, sh); + const int n = min(kChunkCells, npos - p0); + float acc = 0.f; + const float* vp = vc + ((size_t) kvh * ctx + p0) * HD + j; + for (int k = 0; k < n; ++k) acc += sc[k] * vp[(size_t) k * HD]; + const size_t o = (size_t) row * n_chunk + c; + pacc[o * HD + j] = acc; + if (j == 0) { + pm[o] = m; + pl[o] = l; + } +} +/// The chunks merged, times sigmoid(gate): grid (n_rows), block HD. +__global__ void k_attn_merge(const float* pacc, const float* pm, const float* pl, const float* gate, + const int32_t* pos0, int t0, int H, int n_chunk, float* out) { + constexpr int HD = 256; + const int row = blockIdx.x, t = t0 + row / H, h = row % H, d = threadIdx.x; + const int npos = *pos0 + t + 1; + const int nc = (npos + kChunkCells - 1) / kChunkCells; + float M = -INFINITY; + for (int c = 0; c < nc; ++c) M = fmaxf(M, pm[(size_t) row * n_chunk + c]); + float num = 0.f, den = 0.f; + for (int c = 0; c < nc; ++c) { + const size_t o = (size_t) row * n_chunk + c; + const float w = expf(pm[o] - M); + num += w * pacc[o * HD + d]; + den += w * pl[o]; + } + const size_t gi = ((size_t) t * H + h) * HD + d; + out[gi] = num / den * sigm(gate[gi]); +} + +/// The routed entries (T tokens x K picks, entry e = t * K + k) grouped per expert, on the device: one group per +/// expert used (ascending id), its blob address, its entries in entry order. One block. +__global__ void k_group(const int32_t* ids, int n_ent, int K_, int n_expert, const uint8_t* blobs, unsigned long long blob, + unsigned long long* grp_ptr, int32_t* grp_start, int32_t* n_groups, int32_t* ent_dst, + int32_t* ent_tok) { + __shared__ int cnt[512], off[512]; + for (int x = threadIdx.x; x < n_expert; x += blockDim.x) cnt[x] = 0; + __syncthreads(); + for (int e = threadIdx.x; e < n_ent; e += blockDim.x) atomicAdd(&cnt[ids[e]], 1); + __syncthreads(); + if (threadIdx.x == 0) { + int g = 0, pos = 0; + for (int x = 0; x < n_expert; ++x) { + off[x] = pos; + if (cnt[x] == 0) continue; + grp_ptr[g] = (unsigned long long) (blobs + (size_t) x * blob); + grp_start[g] = pos; + pos += cnt[x]; + ++g; + } + grp_start[g] = pos; + *n_groups = g; + for (int e = 0; e < n_ent; ++e) { + const int p = off[ids[e]]++; + ent_dst[p] = e; + ent_tok[p] = e / K_; + } + } +} +/// k_group for the hybrid mode: only the entries whose expert has a VRAM slot (slot_of[x] >= 0) are grouped, each +/// group's blob at blobs + slot * blob; the others are the CPU pool's (their rows come from k_merge_cpu). One block. +__global__ void k_group_hy(const int32_t* ids, int n_ent, int K_, int n_expert, const int32_t* slot_of, + const uint8_t* blobs, unsigned long long blob, unsigned long long* grp_ptr, int32_t* grp_start, + int32_t* n_groups, int32_t* ent_dst, int32_t* ent_tok) { + __shared__ int cnt[512], off[512]; + for (int x = threadIdx.x; x < n_expert; x += blockDim.x) cnt[x] = 0; + __syncthreads(); + for (int e = threadIdx.x; e < n_ent; e += blockDim.x) + if (slot_of[ids[e]] >= 0) atomicAdd(&cnt[ids[e]], 1); + __syncthreads(); + if (threadIdx.x == 0) { + int g = 0, pos = 0; + for (int x = 0; x < n_expert; ++x) { + off[x] = pos; + if (cnt[x] == 0) continue; + grp_ptr[g] = (unsigned long long) (blobs + (size_t) slot_of[x] * blob); + grp_start[g] = pos; + pos += cnt[x]; + ++g; + } + grp_start[g] = pos; + *n_groups = g; + for (int e = 0; e < n_ent; ++e) { + if (slot_of[ids[e]] < 0) continue; + const int p = off[ids[e]]++; + ent_dst[p] = e; + ent_tok[p] = e / K_; + } + } +} +/// The CPU pool's expert rows into the entries' rows: parts[e] = cpu[e] where miss[e]. grid (n_ent), block 256. +__global__ void k_merge_cpu(float* parts, const float* cpu, const int32_t* miss, int n) { + const int e = blockIdx.x; + if (!miss[e]) return; + for (int i = threadIdx.x; i < n; i += blockDim.x) parts[(size_t) e * n + i] = cpu[(size_t) e * n + i]; +} +/// The prompt attention's FP16 operands: cells [0, P) of each KV head's K / V (cache rows ctx apart) into compact +/// [kvh][P][HD] halves. grid1(HKV * P * HD). +__global__ void k_kv_f16(const float* kc, const float* vc, __half* k16, __half* v16, int ctx, int P, int HD, int HKV) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= (int64_t) HKV * P * HD) return; + const int64_t per = (int64_t) P * HD; + const int64_t kvh = i / per, rest = i % per; + const size_t src = (size_t) kvh * ctx * HD + rest; + k16[i] = __float2half(kc[src]); + v16[i] = __float2half(vc[src]); +} +/// The prompt's causal softmax: row (h, t) of S (ld floats, P cells) -> softmax(S * scale) over the cells +/// [0, pos0 + t], 0 past them, as FP16 probabilities (S16, the same row offsets, ld halves). grid (T, H), block 256. +__global__ void k_attn_softmax16(const float* S, __half* S16, int ld, int T, int P, int pos0, float scale) { + __shared__ float sh[kThreads]; + const int t = blockIdx.x, h = blockIdx.y; + const float* row = S + ((size_t) h * T + t) * ld; + __half* out = S16 + ((size_t) h * T + t) * ld; + const int n = min(P, pos0 + t + 1); + float mx = -INFINITY; + for (int p = threadIdx.x; p < n; p += blockDim.x) mx = fmaxf(mx, row[p] * scale); + mx = block_max(mx, sh); + float sum = 0.f; + for (int p = threadIdx.x; p < n; p += blockDim.x) sum += expf(row[p] * scale - mx); + sum = block_sum(sum, sh); + const float inv = 1.0f / sum; + for (int p = threadIdx.x; p < P; p += blockDim.x) out[p] = __float2half(p < n ? expf(row[p] * scale - mx) * inv : 0.f); +} +/// att *= sigmoid(gate) (the attention output gate), n values. +__global__ void k_gate_mul(float* att, const float* gate, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) att[i] *= sigm(gate[i]); +} + +/// The prompt's routed entries sorted by expert for MMQ: bounds[x] .. bounds[x + 1] are expert x's rows; sorted row r +/// holds entry dst[r] (= t * K + k, the row of the per-slot outputs) of token src[r]. The order inside an expert is the +/// atomics' (no output depends on it: every row's products are its own). cnt / cur: n_expert ints of scratch. +__global__ void k_route_count(const int32_t* ids, int n_ent, int32_t* cnt) { + const int e = blockIdx.x * blockDim.x + threadIdx.x; + if (e < n_ent) atomicAdd(&cnt[ids[e]], 1); +} +__global__ void k_route_scan(const int32_t* cnt, int n_expert, int32_t* bounds, int32_t* cur, int32_t* max_rows) { + if (threadIdx.x != 0) return; + int pos = 0, mx = 0; + for (int x = 0; x < n_expert; ++x) { + bounds[x] = pos; + cur[x] = pos; + pos += cnt[x]; + mx = max(mx, cnt[x]); + } + bounds[n_expert] = pos; + *max_rows = mx; +} +__global__ void k_route_scatter(const int32_t* ids, int n_ent, int K_, int32_t* cur, int32_t* dst, int32_t* src, + int32_t* inv) { + const int e = blockIdx.x * blockDim.x + threadIdx.x; + if (e >= n_ent) return; + const int r = atomicAdd(&cur[ids[e]], 1); + dst[r] = e; + src[r] = e / K_; + inv[e] = r; // entry e's sorted row: where its down product lands +} + +/// The greedy pick of one logits row: out = argmax (lowest id on ties). Stage 1: `gridDim.x` blocks each write the +/// best of their stride into (pv, pi); stage 2 (one block, n = the stage-1 block count) reads those. +__global__ void k_argmax(const float* x, int n, int32_t* out, float* pv, int32_t* pi, bool stage2) { + __shared__ float bv[kThreads]; + __shared__ int bi[kThreads]; + // row blockIdx.y: its logits (stage 1, n = the vocabulary) and its kArgBlocks partials + x += (size_t) blockIdx.y * (stage2 ? 0 : n); + pv += (size_t) blockIdx.y * 128; + pi += (size_t) blockIdx.y * 128; + out += blockIdx.y; + float v = -INFINITY; + int id = 0x7fffffff; + if (stage2) { + for (int i = threadIdx.x; i < n; i += blockDim.x) + if (pv[i] > v || (pv[i] == v && pi[i] < id)) { v = pv[i]; id = pi[i]; } + } else { + for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) + if (x[i] > v) { v = x[i]; id = i; } + } + bv[threadIdx.x] = v; + bi[threadIdx.x] = id; + __syncthreads(); + for (int s = blockDim.x / 2; s > 0; s >>= 1) { + if ((int) threadIdx.x < s) { + const float ov = bv[threadIdx.x + s]; + const int oi = bi[threadIdx.x + s]; + if (ov > bv[threadIdx.x] || (ov == bv[threadIdx.x] && oi < bi[threadIdx.x])) { + bv[threadIdx.x] = ov; + bi[threadIdx.x] = oi; + } + } + __syncthreads(); + } + if (threadIdx.x == 0) { + if (stage2) *out = bi[0]; + else { pv[blockIdx.x] = bv[0]; pi[blockIdx.x] = bi[0]; } + } +} +constexpr int kArgBlocks = 128; // (the row stride of k_argmax's partials) + +unsigned grid1(int64_t n, int b = kThreads) { return (unsigned) ((n + b - 1) / b); } + +/// out[t][o] = W[o] . x[t] in FP32 for a prompt chunk's small F32 projections (the router, the GDN alpha / beta, +/// the shared expert's gate: n_out <= 256): a (16 TM) x 64 output tile per block, K in steps of 16 through shared +/// memory, TM x 4 outputs per thread (TM = 4 for the router, 1 for the 32-wide alpha / beta: more blocks). hipBLAS +/// picked 8 x 8 / 16 x 16 tiles for these shapes (~10% of a prompt). K % 4 == 0. +template +__global__ void __launch_bounds__(256) k_sgemm_nt(const float* __restrict__ W, const float* __restrict__ x, + float* __restrict__ out, int K, int n_out, int T, int ldo, int kz) { + constexpr int BM = 16 * TM, BN = 64, BK = 16; + const int kb = blockIdx.z * kz, ke = min(K, kb + kz); // split-K: this block's K range, its own partial + out += (size_t) blockIdx.z * T * ldo; + __shared__ float As[BK][BM + 4], Bs[BK][BN + 4]; + const int tid = threadIdx.x; + const int m0 = blockIdx.y * BM, n0 = blockIdx.x * BN; + const int tm = (tid / 16) * TM, tn = (tid % 16) * 4; + const int lr = tid / 4, lk = (tid % 4) * 4; // this thread's loads: row lr of each tile, k lk .. lk + 3 + float acc[TM][4] = {}; + for (int k0 = kb; k0 < ke; k0 += BK) { + if (lr < BM) { + float4 a = make_float4(0.f, 0.f, 0.f, 0.f); + if (m0 + lr < T && k0 + lk < ke) a = *reinterpret_cast(x + (size_t) (m0 + lr) * K + k0 + lk); + As[lk][lr] = a.x; As[lk + 1][lr] = a.y; As[lk + 2][lr] = a.z; As[lk + 3][lr] = a.w; + } + float4 b = make_float4(0.f, 0.f, 0.f, 0.f); + if (n0 + lr < n_out && k0 + lk < ke) b = *reinterpret_cast(W + (size_t) (n0 + lr) * K + k0 + lk); + Bs[lk][lr] = b.x; Bs[lk + 1][lr] = b.y; Bs[lk + 2][lr] = b.z; Bs[lk + 3][lr] = b.w; + __syncthreads(); +#pragma unroll + for (int k = 0; k < BK; ++k) { + float ar[TM]; +#pragma unroll + for (int i = 0; i < TM; ++i) ar[i] = As[k][tm + i]; + const float4 bv = *reinterpret_cast(&Bs[k][tn]); + const float br[4] = {bv.x, bv.y, bv.z, bv.w}; +#pragma unroll + for (int i = 0; i < TM; ++i) +#pragma unroll + for (int j = 0; j < 4; ++j) acc[i][j] = fmaf(ar[i], br[j], acc[i][j]); + } + __syncthreads(); + } +#pragma unroll + for (int i = 0; i < TM; ++i) +#pragma unroll + for (int j = 0; j < 4; ++j) + if (m0 + tm + i < T && n0 + tn + j < n_out) out[(size_t) (m0 + tm + i) * ldo + n0 + tn + j] = acc[i][j]; +} + +/// out[i] = the sum of the split-K partials part[z][i] in order (deterministic), n values each. +__global__ void k_sum_splits(const float* part, float* out, int64_t n, int splits) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + float a = 0.f; + for (int z = 0; z < splits; ++z) a += part[(size_t) z * n + i]; + out[i] = a; +} + +/// x f32 -> FP16 bits (the prompt GEMMs' activations). +__global__ void k_to_f16(const float* x, __half* y, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) y[i] = __float2half(x[i]); +} + +/// The GDN conv for T tokens in ONE launch (the prompt): one block per 128-channel head, thread = channel, the +/// 3-entry history carried in registers across the tokens and written back at the end; SiLU, then the L2 norm of the +/// q/k heads (block < qk_heads) per token - fused_gdn_conv_l2's arithmetic, token after token. History [channel][3]. +__global__ void __launch_bounds__(128) k_conv_seq(float* hist, const float* qkv, const float* w, float* h, int C, + int qk_heads, float eps, int T, bool write) { + __shared__ float part[4]; + const int c = blockIdx.x * 128 + threadIdx.x; + float v0 = hist[c * 3], v1 = hist[c * 3 + 1], v2 = hist[c * 3 + 2]; + const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3]; + const bool qk = (int) blockIdx.x < qk_heads; + for (int t = 0; t < T; ++t) { + const float x = qkv[(size_t) t * C + c]; + const float sum = v0 * w0 + v1 * w1 + v2 * w2 + x * w3; + v0 = v1; + v1 = v2; + v2 = x; + float y = sum / (1.0f + __expf(-sum)); + if (qk) { + float sq = y * y; + for (int o = 16; o > 0; o >>= 1) sq += __shfl_xor_sync(0xffffffffu, sq, o); + if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sq; + __syncthreads(); + const float ss = part[0] + part[1] + part[2] + part[3]; + __syncthreads(); + y *= rsqrtf(ss + eps); + } + h[(size_t) t * C + c] = y; + } + if (!write) return; // a verify window: the history is commit()'s to move + hist[c * 3] = v0; + hist[c * 3 + 1] = v1; + hist[c * 3 + 2] = v2; +} + +/// The gated delta rule + SiLU-gated norm for T tokens in ONE launch (the prompt): fused_gdn_step_norm's kernel +/// (block = one V head, 128 columns x 4 row groups, state [row][head][col]) with its 32 state rows per thread kept in +/// registers across the tokens. h (T, C) = q | k | v, gate / beta (T, HV), z / y (T, ZV). +__global__ void __launch_bounds__(512) k_gdn_seq(float* state, const float* h, int C, const float* gate, + const float* beta, const float* z, const float* gamma, float eps, + float* y, int h_k, int h_v, int T, bool write) { + constexpr int S = 128, RG = 4, RPG = 32; + __shared__ float sk[S], sq[S]; + __shared__ float red_kv[RG][S]; + __shared__ float red_o[RG][S]; + __shared__ float wsum[S * RG / 32]; + const int head = blockIdx.x, col = threadIdx.x, rg = threadIdx.y, tid = rg * S + col; + const int qh = head % h_k; + const int ZV = h_v * S; + float s[RPG]; + float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col; + const size_t row_stride = (size_t) h_v * S; +#pragma unroll + for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride]; + for (int t = 0; t < T; ++t) { + const float* ht = h + (size_t) t * C; + if (tid < S) { sk[tid] = ht[h_k * S + qh * S + tid]; sq[tid] = ht[qh * S + tid]; } + __syncthreads(); + const float g = __expf(gate[(size_t) t * h_v + head]); + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); + red_kv[rg][col] = kv; + __syncthreads(); + const float kv_col = red_kv[0][col] + red_kv[1][col] + red_kv[2][col] + red_kv[3][col]; + const float delta = (ht[2 * h_k * S + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head]; + float o = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) { + s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); + o = fmaf(s[r], sq[rg * RPG + r], o); + } + red_o[rg][col] = o; + __syncthreads(); + float oc = 0.0f, sq_part = 0.0f; + if (rg == 0) { + oc = (red_o[0][col] + red_o[1][col] + red_o[2][col] + red_o[3][col]) * rsqrtf((float) S); + sq_part = oc * oc; + } + for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part += __shfl_xor_sync(0xffffffffu, sq_part, o2); + if ((tid & 31) == 0) wsum[tid >> 5] = sq_part; + __syncthreads(); + if (rg == 0 && y != nullptr) { // (the commit runs without outputs) + const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; + const float scale = rsqrtf(ss / (float) S + eps); + const float zz = z[(size_t) t * ZV + head * S + col]; + y[(size_t) t * ZV + head * S + col] = oc * scale * gamma[col] * (zz / (1.0f + __expf(-zz))); + } + __syncthreads(); // sk / sq / the reductions are rewritten by the next token + } + if (!write) return; // a verify window: the state is commit()'s to write +#pragma unroll + for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r]; +} + +/// The prompt's gated delta rule with more parallelism: a state column's update needs only that column (kv, delta and +/// the output o all reduce over the rows), so a V head splits into kGdnColGroups blocks of 128 / kGdnColGroups columns, +/// each with 16 row groups of 8 rows (512 threads, 8 state values per thread in registers). Writes the raw outputs +/// o (T, HV * 128); k_gdn_norm applies the SiLU-gated RMS norm. grid (HV, kGdnColGroups), block (32, 16). +constexpr int kGdnColGroups = 4; +__global__ void __launch_bounds__(512) k_gdn_seq_cols(float* state, const float* h, int C, const float* gate, + const float* beta, float* o_raw, int h_k, int h_v, int T) { + constexpr int S = 128, NC = S / kGdnColGroups, RG = 16, RPG = S / RG; + __shared__ float sk[S], sq[S]; + __shared__ float red_kv[RG][NC]; + __shared__ float red_o[RG][NC]; + const int head = blockIdx.x, cl = threadIdx.x, rg = threadIdx.y, tid = rg * NC + cl; + const int col = blockIdx.y * NC + cl; + const int qh = head % h_k; + float sv[RPG]; + float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col; + const size_t row_stride = (size_t) h_v * S; +#pragma unroll + for (int r = 0; r < RPG; ++r) sv[r] = base[r * row_stride]; + for (int t = 0; t < T; ++t) { + const float* ht = h + (size_t) t * C; + if (tid < S) { sk[tid] = ht[h_k * S + qh * S + tid]; sq[tid] = ht[qh * S + tid]; } + __syncthreads(); + const float g = __expf(gate[(size_t) t * h_v + head]); + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) kv = fmaf(sv[r], sk[rg * RPG + r], kv); + red_kv[rg][cl] = kv; + __syncthreads(); + float kv_col = 0.0f; +#pragma unroll + for (int i = 0; i < RG; ++i) kv_col += red_kv[i][cl]; + const float delta = (ht[2 * h_k * S + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head]; + float o = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) { + sv[r] = fmaf(g, sv[r], sk[rg * RPG + r] * delta); + o = fmaf(sv[r], sq[rg * RPG + r], o); + } + red_o[rg][cl] = o; + __syncthreads(); + if (rg == 0) { + float oc = 0.0f; +#pragma unroll + for (int i = 0; i < RG; ++i) oc += red_o[i][cl]; + o_raw[(size_t) t * h_v * S + head * S + col] = oc * rsqrtf((float) S); + } + } +#pragma unroll + for (int r = 0; r < RPG; ++r) base[r * row_stride] = sv[r]; +} +/// y = rms(o) * gamma * SiLU(z) per (token, V head): grid (HV, T), block 128. +__global__ void __launch_bounds__(128) k_gdn_norm(const float* o_raw, const float* z, const float* gamma, float eps, + float* y, int h_v) { + __shared__ float part[4]; + const size_t i = ((size_t) blockIdx.y * h_v + blockIdx.x) * 128 + threadIdx.x; + const float oc = o_raw[i]; + float sq = oc * oc; + for (int o = 16; o > 0; o >>= 1) sq += __shfl_xor_sync(0xffffffffu, sq, o); + if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sq; + __syncthreads(); + const float ss = part[0] + part[1] + part[2] + part[3]; + const float scale = rsqrtf(ss / 128.0f + eps); + const float zz = z[i]; + y[i] = oc * scale * gamma[threadIdx.x] * (zz / (1.0f + __expf(-zz))); +} + +// ------------------------------------------------------------------------------------------------ the model +struct Mat { + const uint8_t* d = nullptr; // device, GGUF blocks + int type = -1; + int n_in = 0, n_out = 0; +}; + +struct Layer { + bool attn = false; + const float *attn_norm = nullptr, *post_norm = nullptr; + // GDN + Mat qkv, zg, ssm_out; + const float *alpha = nullptr, *beta = nullptr, *dt = nullptr, *ssm_a = nullptr, *conv = nullptr, *ssm_norm = nullptr; + // attention + Mat wq, wk, wv, wo; + const float *q_norm = nullptr, *k_norm = nullptr; + // MoE + const float* router = nullptr; // [n_expert][N] f32 + float* router_ext = nullptr; // the same with the shared expert's gate row appended: [n_expert + 1][N] + Mat sh_gate, sh_up, sh_down; + const float* sh_gate_inp = nullptr; // [N] + K::NativeExpertLayout L; + uint8_t* blobs = nullptr; // n_expert blobs, `stride` bytes apart (L.bytes rounded up to whole blocks of every + size_t stride = 0; // part's type, so MMQ can step over them by blocks), then kMmqTail zero bytes + // (hybrid mode: n_slots slots, see place_experts) + // the GGUF's expert tensors (the mapped file stays open): place_experts builds the blobs from them + const uint8_t *src_g = nullptr, *src_u = nullptr, *src_d = nullptr; + size_t src_gsz = 0, src_dsz = 0; + uint8_t* hblobs = nullptr; // hybrid mode: every expert's blob in host memory, `stride` apart + int n_slots = 0; // hybrid mode: the experts resident in VRAM +}; + +struct Model { + strata::core::ModelGeometry g; + std::shared_ptr file; // kept mapped: the experts are placed after the engine's buffers + bool hybrid = false; // not every expert fits in VRAM: slots + the CPU pool + // the packed Q8_0 decode copies (gguf weights, packed copy, bytes): given back when that lets every expert fit + std::vector> packed; + // the GGUF-native MTP block (blk., loaded with --mtp): eh_proj over [enorm(e) | hnorm(h)], then an + // attention + MoE layer, shared_head_norm, the main head + bool has_mtp = false; + Layer mtp; + Mat eh_proj; + const float *mtp_enorm = nullptr, *mtp_hnorm = nullptr, *mtp_shnorm = nullptr; + int64_t top_k = 8; + float eps = 1e-6f, rope_base = 1e7f; + int n_rot = 64; + std::vector layers; + const float* out_norm = nullptr; + Mat head; + const uint8_t* embd = nullptr; + int embd_type = -1; + size_t embd_row = 0; +}; + +constexpr size_t kMmqTail = 4096; +size_t gcd_sz(size_t a, size_t b) { return b ? gcd_sz(b, a % b) : a; } +size_t lcm_sz(size_t a, size_t b) { return a / gcd_sz(a, b) * b; } +size_t block_bytes(int type) { + int be = 0, bb = 0; + return strata::block_geometry((uint32_t) type, be, bb) ? (size_t) bb : 1; +} // zeroed bytes after the last expert (MMQ reads a little past a matrix) + +size_t row_bytes(int type, int64_t n) { + int be = 0, bb = 0; + if (!strata::block_geometry((uint32_t) type, be, bb)) return 0; + return (size_t) (n / be) * (size_t) bb; +} + +float bf16_to_f32(uint16_t b) { + const uint32_t u = (uint32_t) b << 16; + float f; + std::memcpy(&f, &u, 4); + return f; +} + +/// A tensor as f32 on the device (F32 as it is, BF16 / F16 widened). +float* upload_f32(const strata::TensorInfo& t, const uint8_t* src) { + std::vector h((size_t) t.elements()); + if (t.type == 0) std::memcpy(h.data(), src, h.size() * 4); + else if (t.type == 30) + for (size_t i = 0; i < h.size(); ++i) h[i] = bf16_to_f32((uint16_t) (src[2 * i] | (src[2 * i + 1] << 8))); + else if (t.type == 1) // F16 + for (size_t i = 0; i < h.size(); ++i) + h[i] = __half2float(__ushort_as_half((unsigned short) (src[2 * i] | (src[2 * i + 1] << 8)))); + else if (t.type == 8 && h.size() % 32 == 0) { + // Q8_0 (the Q8_0 file stores ssm_alpha / ssm_beta so): blocks of an fp16 scale and 32 int8, widened here + for (size_t b = 0; b < h.size() / 32; ++b) { + const uint8_t* q = src + b * 34; + const float d = __half2float(__ushort_as_half((unsigned short) (q[0] | (q[1] << 8)))); + for (int j = 0; j < 32; ++j) h[b * 32 + j] = d * (float) (int8_t) q[2 + j]; + } + } else { + std::fprintf(stderr, "strata-q36: %s is %s, expected F32, BF16, F16 or Q8_0\n", t.name.c_str(), t.type_name()); + std::exit(1); + } + float* d = nullptr; + CK(cudaMalloc(&d, h.size() * 4)); + CK(cudaMemcpy(d, h.data(), h.size() * 4, cudaMemcpyHostToDevice)); + return d; +} + +bool load(const std::string& path, Model& m, std::string& err, bool want_mtp) { + const auto t0 = Clock::now(); + m.file = std::make_shared(strata::GgufModel::open(path)); + const strata::GgufModel& gm = *m.file; + if (!strata::core::geometry_from_gguf(gm.meta(), m.g, m.top_k, err)) return false; + if (m.g.family != strata::ModelFamily::Qwen35Moe) { + err = "strata-q36 runs Qwen3.6-35B-A3B (qwen35moe) files only"; + return false; + } + size_t checked = 0; + if (!strata::core::check_gguf_layout(gm, m.g, err, &checked)) return false; + const auto& g = m.g; + if (g.head_dim != 256 || g.ssm_state_size != 128 || g.ssm_d_conv != 4 || g.n_expert > 512 || m.top_k > 15) { + err = "a geometry this driver's kernels do not take (head 256, state 128, conv 4, <= 512 experts, top-k <= 15)"; + return false; + } + const std::string p = "qwen35moe."; + if (const strata::MetaValue* v = gm.meta().get(p + "attention.layer_norm_rms_epsilon")) m.eps = (float) v->num(); + if (const strata::MetaValue* v = gm.meta().get(p + "rope.freq_base")) m.rope_base = (float) v->num(); + if (const strata::MetaValue* v = gm.meta().get(p + "rope.dimension_count")) m.n_rot = (int) v->u; + uint64_t bytes = 0; + auto find = [&](const std::string& name, size_t& s) -> const strata::TensorInfo* { + const strata::TensorInfo* t = gm.find(name, &s); + if (!t) { + std::fprintf(stderr, "strata-q36: missing %s\n", name.c_str()); + std::exit(1); + } + return t; + }; + auto f32 = [&](const std::string& name) -> const float* { + size_t s = 0; + const strata::TensorInfo* t = find(name, s); + bytes += t->elements() * 4; + return upload_f32(*t, gm.shard(s).tensor_data(*t)); + }; + auto mat = [&](const std::string& name) -> Mat { + size_t s = 0; + const strata::TensorInfo* t = find(name, s); + Mat w; + w.type = (int) t->type; + w.n_in = (int) t->shape[0]; + w.n_out = (int) t->shape[1]; + if (!K::native_mmvq_supported(w.type)) { + std::fprintf(stderr, "strata-q36: %s is %s, which the native MMVQ does not take\n", name.c_str(), t->type_name()); + std::exit(1); + } + const uint64_t nb = strata::tensor_payload_bytes(*t); + uint8_t* d = nullptr; + CK(cudaMalloc(&d, nb)); + CK(cudaMemcpy(d, gm.shard(s).tensor_data(*t), nb, cudaMemcpyHostToDevice)); + bytes += nb; + w.d = d; + // STRATA_Q8_PACKED (on by default here): the lossless qs / d plane copy the Q8_0 decode kernels read instead, + // bitwise the same outputs + if (w.type == 8 && K::native_q8_0_packed_enabled() && K::native_q8_0_packed_eligible(w.n_in, w.n_out)) { + std::vector packed(nb); + K::native_q8_0_pack_host(gm.shard(s).tensor_data(*t), packed.data(), w.n_in, w.n_out); + uint8_t* pd = nullptr; + CK(cudaMalloc(&pd, nb)); + CK(cudaMemcpy(pd, packed.data(), nb, cudaMemcpyHostToDevice)); + K::native_q8_0_packed_register(d, pd, w.n_in, w.n_out); + m.packed.emplace_back(d, pd, (size_t) nb); + bytes += nb; + } + return w; + }; + auto L = [](int64_t l, const char* s) { return "blk." + std::to_string(l) + "." + s; }; + m.layers.resize((size_t) g.n_layers); + // the MTP block whenever the file has one, with or without drafts (--mtp): the VRAM it takes is then the same + // either way, so the hybrid mode's slot tables - and with them the greedy text - do not depend on --mtp + (void) want_mtp; + m.has_mtp = g.n_mtp_layers > 0; + for (int64_t l = 0; l < g.n_layers + (m.has_mtp ? 1 : 0); ++l) { + const bool is_mtp = l == g.n_layers; + Layer& y = is_mtp ? m.mtp : m.layers[(size_t) l]; + y.attn = is_mtp || strata::core::is_qsa_layer(g, l); + y.attn_norm = f32(L(l, "attn_norm.weight")); + y.post_norm = f32(L(l, "post_attention_norm.weight")); + if (!y.attn) { + y.qkv = mat(L(l, "attn_qkv.weight")); + y.zg = mat(L(l, "attn_gate.weight")); + y.ssm_out = mat(L(l, "ssm_out.weight")); + y.alpha = f32(L(l, "ssm_alpha.weight")); + y.beta = f32(L(l, "ssm_beta.weight")); + y.dt = f32(L(l, "ssm_dt.bias")); + y.ssm_a = f32(L(l, "ssm_a")); + y.conv = f32(L(l, "ssm_conv1d.weight")); + y.ssm_norm = f32(L(l, "ssm_norm.weight")); + } else { + y.wq = mat(L(l, "attn_q.weight")); + y.wk = mat(L(l, "attn_k.weight")); + y.wv = mat(L(l, "attn_v.weight")); + y.wo = mat(L(l, "attn_output.weight")); + y.q_norm = f32(L(l, "attn_q_norm.weight")); + y.k_norm = f32(L(l, "attn_k_norm.weight")); + } + y.router = f32(L(l, "ffn_gate_inp.weight")); + y.sh_gate = mat(L(l, "ffn_gate_shexp.weight")); + y.sh_up = mat(L(l, "ffn_up_shexp.weight")); + y.sh_down = mat(L(l, "ffn_down_shexp.weight")); + y.sh_gate_inp = f32(L(l, "ffn_gate_inp_shexp.weight")); + CK(cudaMalloc(&y.router_ext, (size_t) (g.n_expert + 1) * g.n_embd * 4)); + CK(cudaMemcpy(y.router_ext, y.router, (size_t) g.n_expert * g.n_embd * 4, cudaMemcpyDeviceToDevice)); + CK(cudaMemcpy(y.router_ext + (size_t) g.n_expert * g.n_embd, y.sh_gate_inp, (size_t) g.n_embd * 4, + cudaMemcpyDeviceToDevice)); + bytes += (size_t) (g.n_expert + 1) * g.n_embd * 4; + // the routed experts: [gate | up | down] per expert, the native expert layout + size_t sg = 0, su = 0, sd = 0; + const strata::TensorInfo* tg = find(L(l, "ffn_gate_exps.weight"), sg); + const strata::TensorInfo* tu = find(L(l, "ffn_up_exps.weight"), su); + const strata::TensorInfo* td = find(L(l, "ffn_down_exps.weight"), sd); + if (tg->type != tu->type) { + err = L(l, "ffn_gate_exps / ffn_up_exps differ in type"); + return false; + } + if (!K::native_expert_supported((int) tg->type, (int) td->type, g.n_embd, g.n_ff)) { + err = L(l, "experts are ") + tg->type_name() + "/" + td->type_name() + ", which the native expert kernels " + + "do not take (build with -DSTRATA_Q6K_EXPERTS=ON for Q6_K)"; + return false; + } + y.L = K::native_expert_layout((int) tg->type, (int) td->type, g.n_embd, g.n_ff); + const size_t gsz = (size_t) g.n_ff * y.L.gu_row, dsz = (size_t) g.n_embd * y.L.d_row; + // a stride in whole blocks of both parts' types (MMQ steps over the experts by blocks), 16-byte aligned + const size_t al = lcm_sz(lcm_sz(block_bytes(y.L.gu_type), block_bytes(y.L.d_type)), 16); + y.stride = (y.L.bytes + al - 1) / al * al; + y.src_g = gm.shard(sg).tensor_data(*tg); + y.src_u = gm.shard(su).tensor_data(*tu); + y.src_d = gm.shard(sd).tensor_data(*td); + y.src_gsz = gsz; + y.src_dsz = dsz; + } + if (m.has_mtp) { + const int64_t l = g.n_layers; + m.eh_proj = mat(L(l, "nextn.eh_proj.weight")); + m.mtp_enorm = f32(L(l, "nextn.enorm.weight")); + m.mtp_hnorm = f32(L(l, "nextn.hnorm.weight")); + m.mtp_shnorm = f32(L(l, "nextn.shared_head_norm.weight")); + } + m.out_norm = f32("output_norm.weight"); + m.head = mat("output.weight"); + { + size_t s = 0; + const strata::TensorInfo* t = find("token_embd.weight", s); + m.embd_type = (int) t->type; + m.embd_row = row_bytes(m.embd_type, (int64_t) t->shape[0]); + const uint64_t nb = strata::tensor_payload_bytes(*t); + uint8_t* d = nullptr; + CK(cudaMalloc(&d, nb)); + CK(cudaMemcpy(d, gm.shard(s).tensor_data(*t), nb, cudaMemcpyHostToDevice)); + m.embd = d; + bytes += nb; + } + std::fprintf(stderr, "strata-q36: %s: %zu tensors (layout checked), %.2f GiB on the GPU in %.1f s (the routed " + "experts are placed after the engine's buffers)\n", path.c_str(), checked, (double) bytes / (1 << 30), + ms_since(t0) / 1000.0); + return true; +} + +/// Expert e of layer L as its native blob [gate | up | down] (L.L.bytes) at dst (host memory). +void expert_blob(const Layer& L, int64_t e, uint8_t* dst) { + std::memcpy(dst, L.src_g + (size_t) e * L.src_gsz, L.src_gsz); + std::memcpy(dst + L.L.up_off, L.src_u + (size_t) e * L.src_gsz, L.src_gsz); + std::memcpy(dst + L.L.down_off, L.src_d + (size_t) e * L.src_dsz, L.src_dsz); +} + +// ------------------------------------------------------------------------------------------------ the engine +float* dalloc(size_t n) { + float* p = nullptr; + CK(cudaMalloc(&p, n * 4)); + CK(cudaMemset(p, 0, n * 4)); + return p; +} +template T* dalloc_t(size_t n) { + T* p = nullptr; + CK(cudaMalloc(&p, n * sizeof(T))); + CK(cudaMemset(p, 0, n * sizeof(T))); + return p; +} + +struct Engine { + const Model* m = nullptr; + cudaStream_t st = nullptr; + int ctx = 32768, tmax = 512; + int64_t pos = 0; // cells holding a processed token + // activations [tmax][...] + float *x, *h, *y, *qkv, *hc, *z, *alpha, *beta, *gdn_y, *qg, *kx, *vx, *q, *gate, *att, *logits_r, *eparts, *moe_out, + *sg, *su, *shh, *sy, *sgate, *ewts, *logits; + float* hmain = nullptr; // [tmax][N] the main model's final normed hidden of each row (the MTP seeds) + float* hlast = nullptr; // [N] that of the last processed position (zeros before the first) + void *q8, *xq, *escr; + int32_t *ids, *grp_start, *n_groups, *ent_dst, *ent_tok, *tok, *pos0, *pick; + int32_t* hpin = nullptr; // pinned staging: [0] decode token, [1] position, [2..9] picks, [10] max rows, [16..] tokens + unsigned long long* grp_ptr; + float *pacc, *pm, *pl, *amv; + int32_t* ami; + int n_chunk = 0, att_rows = 0; // attention partials: att_rows query rows x n_chunk chunks + std::vector conv, S, kc, vc; // per layer; the MTP block's K / V at index n_layers + // verify windows (T <= kVerify): the GDN inputs of every row per layer, kept for the commit + static constexpr int kVerify = 8; + std::vector v_qkv, v_hc, v_alpha, v_beta; + // the MTP block (when loaded) + float *mtp_cat = nullptr, *hmtp = nullptr, *logits_m = nullptr; + int32_t *tok_m = nullptr, *pos0_m = nullptr, *pick_m = nullptr; + // graphs: [0] the decode step, [T] a verify window of T rows, mtp1 the MTP draft step + cudaGraphExec_t g1 = nullptr, gv[kVerify + 1] = {}, gm1 = nullptr; + strata::prefill::Gemm gemm; + cublasHandle_t blas = nullptr; + float* att_s = nullptr; // the prompt attention's scores / probabilities, kAttScoreFloats floats + static constexpr int kSplitK = 16; + float* sk_part = nullptr; // the split-K partials of the F32 projections: [kSplitK][tmax][<= 257] + __half* att_p16 = nullptr; // the probabilities in FP16 (kAttScoreFloats halves) + __half *k16 = nullptr, *v16 = nullptr, *q16 = nullptr; // the prompt attention's FP16 operands + size_t kAttScoreFloats = (size_t) 64 << 20; // 256 MB (16 M floats when the experts' fit is close) + // the prompt's MMQ experts + bool use_mmq = false; + std::unique_ptr mctx; + int32_t *rcnt = nullptr, *rcur = nullptr, *rbounds = nullptr, *rmax = nullptr, *ident = nullptr, *rinv = nullptr; + void *mq_x = nullptr, *mq_hq = nullptr; + float *mq_gu = nullptr, *mq_h = nullptr; + __half* x16 = nullptr; + bool use_graph = true; + int mtp_d = 0; // MTP drafts per speculative step (0: none; greedy requests only) + + // ---- the hybrid mode (Model::hybrid): per state index (the layers, then the MTP block) the slot tables; a + // batch of up to hybrid_t rows runs its VRAM-resident experts on the GPU and the others on the CPU pool, side by + // side; a bigger prompt chunk streams each layer's experts into a staging buffer for MMQ (two, double-buffered) + struct Hy { + std::vector slot_of, exp_in_slot; + std::vector score; // routing counts, halved at each rebalance + int32_t* slot_of_d = nullptr; +#if defined(STRATA_Q36_CPU_POOL) + strata::kernels::cpu::NativeFmt fmt; +#endif + }; + std::vector hy; + int hybrid_t = 32; + bool main_hybrid = false; // some main layer is hybrid (else only the MTP block is: the decode graph stays) + bool mtp_graph = true; // the MTP draft step may be a graph (not when its layer is hybrid) + /// state index li's layer runs hybrid (its experts not all in VRAM) + bool lhy(size_t li) const { + if (!m->hybrid) return false; + const Layer& L = li < m->layers.size() ? m->layers[li] : m->mtp; + return L.n_slots < (int) m->g.n_expert; + } +#if defined(STRATA_Q36_CPU_POOL) + std::unique_ptr pool; + std::vector jobs; +#endif + float *h_h = nullptr, *cpu_out = nullptr, *ecpu = nullptr; + int32_t *h_ids = nullptr, *h_miss = nullptr, *d_miss = nullptr, *h_cnt = nullptr; + uint8_t* acts = nullptr; // per token: its quantized activation (kNativeActBytes) + cudaEvent_t ev_route = nullptr; + uint8_t* stage[2] = {}; + cudaStream_t cst = nullptr; + cudaEvent_t ev_copy[2] = {}, ev_used[2] = {}; + std::vector stream_seq; // the state indices a streamed forward visits, in order + int stream_pos = 0; + long long hy_cpu = 0, hy_gpu = 0, hy_swaps = 0; // entries computed on the CPU / GPU, slot replacements + double hy_cpu_ms = 0; + // decode / verify rows: their routing is counted once the rows are kept (commit), so a verify window's rejected + // drafts never move the slots; the slots follow the counts at every kRebalanceEvery-th position exactly (a + // window never steps over one), so plain and speculative decoding see the same slot tables at every position + static constexpr int kRebalanceEvery = 32; + bool rows_deferred = false; // set while a decode step or a verify window runs + std::vector> row_ids; // [main layer][row * top_k + k] of the last such call + void count_rows(int n) { + const int Kp = (int) m->top_k; + for (size_t li = 0; li < row_ids.size() && li < hy.size(); ++li) + if (!row_ids[li].empty()) + for (int e = 0; e < n * Kp; ++e) hy[li].score[(size_t) row_ids[li][(size_t) e]] += 1.0; + } + void after_rows(int n) { // a decode step / verify window kept n rows: count them, rebalance at the boundary + if (!m->hybrid) return; + count_rows(n); + if (pos % kRebalanceEvery == 0) { + CK(cudaStreamSynchronize(st)); + rebalance(8); + } + } + + void init(const Model& model, int ctx_, int tmax_) { + m = &model; + ctx = ctx_; + tmax = std::max(tmax_, kVerify); + const auto& g = m->g; + const size_t T = (size_t) tmax, N = (size_t) g.n_embd, Kp = (size_t) m->top_k, FF = (size_t) g.n_ff; + const size_t C = (size_t) g.ssm_conv_channels; + CK(cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking)); + x = dalloc(T * N); h = dalloc(T * N); y = dalloc(T * N); hmain = dalloc(T * N); hlast = dalloc(N); + qkv = dalloc(T * C); hc = dalloc(T * C); z = dalloc(T * g.ssm_value_dim); + alpha = dalloc(T * g.ssm_v_heads); beta = dalloc(T * g.ssm_v_heads); gdn_y = dalloc(T * g.ssm_value_dim); + qg = dalloc(T * 2 * g.n_head * g.head_dim); kx = dalloc(T * g.n_head_kv * g.head_dim); + vx = dalloc(T * g.n_head_kv * g.head_dim); q = dalloc(T * g.n_head * g.head_dim); + gate = dalloc(T * g.n_head * g.head_dim); att = dalloc(T * g.n_head * g.head_dim); + logits_r = dalloc(T * (g.n_expert + 1)); + eparts = dalloc(T * Kp * N); moe_out = dalloc(T * N); + sg = dalloc(T * g.n_ff_shexp); su = dalloc(T * g.n_ff_shexp); shh = dalloc(T * g.n_ff_shexp); sy = dalloc(T * N); + sgate = dalloc(T); ewts = dalloc(T * Kp); logits = dalloc((size_t) kVerify * g.n_vocab); + const int max_in = (int) std::max({2 * g.n_embd, g.ssm_value_dim, g.n_head * g.head_dim, g.n_ff_shexp}); + CK(cudaMalloc(&q8, K::native_q8_1_bytes(max_in, 1) * T)); + CK(cudaMalloc(&xq, K::native_q8_1_bytes((int) N, 1) * T)); + x16 = dalloc_t<__half>(T * (size_t) max_in); + if (cublasCreate(&blas) != CUBLAS_STATUS_SUCCESS || cublasSetStream(blas, st) != CUBLAS_STATUS_SUCCESS) { + std::fprintf(stderr, "strata-q36: cuBLAS handle failed\n"); + std::exit(1); + } + att_s = dalloc(kAttScoreFloats); + sk_part = dalloc((size_t) kSplitK * T * (g.n_expert + 1)); + att_p16 = dalloc_t<__half>(kAttScoreFloats); + k16 = dalloc_t<__half>((size_t) g.n_head_kv * ctx * g.head_dim); + v16 = dalloc_t<__half>((size_t) g.n_head_kv * ctx * g.head_dim); + q16 = dalloc_t<__half>(T * g.n_head * g.head_dim); + use_mmq = MMQ::built() && std::getenv("STRATA_Q36_NO_MMQ") == nullptr; + auto mmq_ok = [&](const Layer& L) { + return MMQ::supported(L.L.gu_type) && MMQ::supported(L.L.d_type) && MMQ::fits(L.L.gu_type, 2 * g.n_ff) && + MMQ::fits(L.L.d_type, g.n_embd); + }; + for (const Layer& L : m->layers) use_mmq = use_mmq && mmq_ok(L); + if (m->has_mtp) use_mmq = use_mmq && mmq_ok(m->mtp); + if (use_mmq) { + const int64_t ne = (int64_t) T * Kp; + mctx = std::make_unique(); + rcnt = dalloc_t((size_t) g.n_expert); + rcur = dalloc_t((size_t) g.n_expert); + rbounds = dalloc_t((size_t) g.n_expert + 1); + rmax = dalloc_t(1); + ident = dalloc_t((size_t) ne); + rinv = dalloc_t((size_t) ne); + CK(cudaDeviceSynchronize()); // ident's cudaMemset (legacy stream) before the iota on the non-blocking stream + MMQ::iota(ident, ne, st); + CK(cudaMalloc(&mq_x, MMQ::q8_bytes(ne, g.n_embd))); + CK(cudaMalloc(&mq_hq, MMQ::q8_bytes(ne, g.n_ff))); + mq_gu = dalloc((size_t) ne * 2 * FF); + mq_h = dalloc((size_t) ne * FF); + } + std::fprintf(stderr, "strata-q36: prompt experts on %s\n", use_mmq ? "MMQ (int8)" : "the native grouped kernels"); + { + std::string gerr; + int64_t big = 0; + auto take = [&](const Layer& L) { + for (const Mat* w : {&L.qkv, &L.zg, &L.ssm_out, &L.wq, &L.wk, &L.wv, &L.wo, &L.sh_gate, &L.sh_up, &L.sh_down}) + big = std::max(big, (int64_t) w->n_in * w->n_out); + }; + for (const Layer& L : m->layers) take(L); + if (m->has_mtp) { + take(m->mtp); + big = std::max(big, (int64_t) m->eh_proj.n_in * m->eh_proj.n_out); + } + if (!gemm.init(st, big, gerr)) { + std::fprintf(stderr, "strata-q36: prompt GEMM: %s\n", gerr.c_str()); + std::exit(1); + } + } + CK(cudaMalloc(&escr, K::native_expert_scratch_bytes((int64_t) (T * Kp), (int64_t) FF))); + ids = dalloc_t(T * Kp); + grp_ptr = dalloc_t(std::min(T * Kp, (size_t) g.n_expert) + 1); + grp_start = dalloc_t(std::min(T * Kp, (size_t) g.n_expert) + 1); + n_groups = dalloc_t(1); + ent_dst = dalloc_t(T * Kp); + ent_tok = dalloc_t(T * Kp); + tok = dalloc_t(T); + pos0 = dalloc_t(1); + pick = dalloc_t(kVerify); + amv = dalloc((size_t) kArgBlocks * kVerify); + ami = dalloc_t((size_t) kArgBlocks * kVerify); + CK(cudaHostAlloc((void**) &hpin, 64 * sizeof(int32_t), cudaHostAllocDefault)); + n_chunk = (ctx + kChunkCells - 1) / kChunkCells; + att_rows = (int) (g.n_head * std::min((int64_t) T, 64)); // 64 query tokens per attention batch + pacc = dalloc((size_t) att_rows * n_chunk * g.head_dim); + pm = dalloc((size_t) att_rows * n_chunk); + pl = dalloc((size_t) att_rows * n_chunk); + for (const Layer& L : m->layers) { + if (L.attn) { + conv.push_back(nullptr); + S.push_back(nullptr); + kc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); + vc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); + for (auto* v : {&v_qkv, &v_hc, &v_alpha, &v_beta}) v->push_back(nullptr); + } else { + conv.push_back(dalloc(C * (g.ssm_d_conv - 1))); + S.push_back(dalloc((size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size)); + kc.push_back(nullptr); + vc.push_back(nullptr); + v_qkv.push_back(dalloc((size_t) kVerify * C)); + v_hc.push_back(dalloc((size_t) kVerify * C)); + v_alpha.push_back(dalloc((size_t) kVerify * g.ssm_v_heads)); + v_beta.push_back(dalloc((size_t) kVerify * g.ssm_v_heads)); + } + } + if (m->has_mtp) { // the MTP block's own K / V (an attention layer at index n_layers) + conv.push_back(nullptr); + S.push_back(nullptr); + kc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); + vc.push_back(dalloc((size_t) g.n_head_kv * ctx * g.head_dim)); + mtp_cat = dalloc(T * 2 * N); + hmtp = dalloc(T * N); + logits_m = dalloc((size_t) g.n_vocab); + tok_m = dalloc_t(T); + pos0_m = dalloc_t(1); + pick_m = dalloc_t(1); + } + CK(cudaDeviceSynchronize()); // every legacy-stream cudaMemset of the buffers above is done + size_t fr = 0, tot = 0; + CK(cudaMemGetInfo(&fr, &tot)); + std::fprintf(stderr, "strata-q36: context %d cells, prompt chunk %d%s, %.2f GiB of VRAM free\n", ctx, tmax, + m->has_mtp ? ", MTP block loaded" : "", (double) fr / (1 << 30)); + } + + /// The recurrent state and the cache to a fresh sequence. + void reset() { + const auto& g = m->g; + for (size_t l = 0; l < conv.size(); ++l) { + if (conv[l]) CK(cudaMemsetAsync(conv[l], 0, (size_t) g.ssm_conv_channels * (g.ssm_d_conv - 1) * 4, st)); + if (S[l]) CK(cudaMemsetAsync(S[l], 0, (size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size * 4, st)); + } + CK(cudaMemsetAsync(hlast, 0, (size_t) g.n_embd * 4, st)); + CK(cudaStreamSynchronize(st)); + pos = 0; + } + + /// y [T][n_out] = W x [T][n_in] on the native MMVQ, 8 columns per launch. + void mm(const Mat& w, const float* xin, float* out, int T) { + prep(xin, w.n_in, T, q8); + apply(w, q8, out, T); + } + /// y [T][n_out] = W [n_out][n_in] (f32) x [T][n_in]: a decode batch on the warp-per-row kernel, a prompt chunk on + /// cuBLAS's FP32 GEMM (the router and the GDN alpha / beta stay in FP32, as llama.cpp keeps them). + void f32mm(const float* W, const float* xin, float* out, int n_in, int n_out, int T) { + if (T <= kGemmT) { + k_gemv_f32<<>>(W, xin, out, n_in, n_out); + return; + } + static const bool blas_f32 = std::getenv("STRATA_Q36_BLAS_F32") != nullptr; // the hipBLAS / cuBLAS SGEMM (A/B) + if (!blas_f32 && n_in % 4 == 0) { + // K split so that about 128 blocks run (the partials summed in a fixed order: deterministic); TM = 4 rows per + // thread for the 256-wide router, 1 for the narrow ones (alpha / beta 32, the gate 1) + const int tm = n_out > 64 ? 4 : 1; + const int gx = (n_out + 63) / 64, gy = (T + 16 * tm - 1) / (16 * tm); + const int want = std::max(1, std::min(kSplitK, 128 / std::max(1, gx * gy))); + const int kz = (n_in / want + 15) / 16 * 16; + const int splits = (n_in + kz - 1) / kz; + float* dst = splits > 1 ? sk_part : out; + if (tm == 4) k_sgemm_nt<4><<>>(W, xin, dst, n_in, n_out, T, n_out, kz); + else k_sgemm_nt<1><<>>(W, xin, dst, n_in, n_out, T, n_out, kz); + if (splits > 1) + k_sum_splits<<>>(sk_part, out, (int64_t) T * n_out, splits); + return; + } + const float one = 1.0f, zero = 0.0f; + if (cublasSgemm(blas, CUBLAS_OP_T, CUBLAS_OP_N, n_out, T, n_in, &one, W, n_in, xin, n_in, &zero, out, n_out) != + CUBLAS_STATUS_SUCCESS) { + std::fprintf(stderr, "strata-q36: cublasSgemm failed\n"); + std::exit(1); + } + } + + /// A batch above kGemmT tokens (a prompt chunk) runs its projections as GEMMs (prefill::Gemm::native: the GGUF + /// blocks dequantized to FP16, the activations FP16); a decode batch on the native MMVQ (q8_1 activations). + static constexpr int kGemmT = 8; + void prep(const float* xin, int n, int T, void* q) { + if (T > kGemmT) k_to_f16<<>>(xin, x16, (int64_t) n * T); + else quant(xin, n, T, q); + } + void apply(const Mat& w, const void* q, float* out, int T) { + if (T > kGemmT) gemm.native((const uint16_t*) x16, w.type, w.d, out, T, w.n_out, w.n_in); + else mmq(w, q, out, T); + } + /// x [T][n] -> its q8_1 image (T contiguous columns: one vector of T * n), for every matrix that reads x. + void quant(const float* xin, int n, int T, void* q) { K::native_quantize_q8_1(xin, q, n * T, 1, st); } + /// y [T][n_out] = W x from x's q8_1 image, 8 columns per launch. + void mmq(const Mat& w, const void* q, float* out, int T) { + const size_t qb = K::native_q8_1_bytes(w.n_in, 1); + for (int c0 = 0; c0 < T; c0 += 8) { + const int nc = std::min(8, T - c0); + K::native_mmvq(w.type, w.d, (const char*) q + (size_t) c0 * qb, out + (size_t) c0 * w.n_out, w.n_in, + w.n_out, nc, st); + } + } + + /// One layer for T rows: x (the residual) += mixer(h); then MoE; x += moe; `hout` = rms(x) * wn (the next norm). + /// `li` indexes the layer's state; positions *dpos .. + T - 1 (device), p0 the same on the host (eager grids); + /// `verify`: a verify window - the GDN state is read, not written (commit() writes it for the kept rows). + void layer(const Layer& L, size_t li, int T, int64_t p0, const int32_t* dpos, bool graph_mode, bool verify, + const float* wn, float* hout) { + const auto& g = m->g; + const int N = (int) g.n_embd, Kp = (int) m->top_k, FF = (int) g.n_ff, FS = (int) g.n_ff_shexp; + const int HK = (int) g.ssm_k_heads, HV = (int) g.ssm_v_heads, D = (int) g.ssm_state_size; + const int C = (int) g.ssm_conv_channels; + const int H = (int) g.n_head, HKV = (int) g.n_head_kv, HD = (int) g.head_dim; + if (!L.attn) { + float* qkv_b = verify ? v_qkv[li] : qkv; + float* hc_b = verify ? v_hc[li] : hc; + float* al_b = verify ? v_alpha[li] : alpha; + float* be_b = verify ? v_beta[li] : beta; + prep(h, N, T, xq); + apply(L.qkv, xq, qkv_b, T); + apply(L.zg, xq, z, T); + if (T <= kGemmT) { + k_gdn_ab<<>>(L.alpha, L.beta, h, L.dt, L.ssm_a, al_b, be_b, N, + HV); + } else { + f32mm(L.alpha, h, al_b, N, HV, T); + f32mm(L.beta, h, be_b, N, HV, T); + k_gdn_gb<<>>(al_b, L.dt, L.ssm_a, be_b, HV, T); + } + // one token, a window or a chunk: the same kernels (every token in one launch each), so a decode step and a + // verify window compute bitwise the same rows and the MTP's greedy text is the plain greedy text. (Strata's + // fused single-token kernels are not used here: fused_gdn_conv_l2's 4-tap sum contracts into FMAs + // differently from k_conv_seq's, a 1-ulp difference in h that the Q8_1 activation rounding can turn into a + // flipped near-tie later; with them the KL is the same, 1.05x / 0.81x the floor, but MTP would not be exact.) + k_conv_seq<<>>(conv[li], qkv_b, L.conv, hc_b, C, 2 * HK, m->eps, T, !verify); + if (T > kGemmT && !verify) { // a prompt chunk: the column-split delta rule, then the norm + k_gdn_seq_cols<<>>(S[li], hc_b, C, al_b, + be_b, gdn_y, HK, HV, T); + k_gdn_norm<<>>(gdn_y, z, L.ssm_norm, m->eps, gdn_y, HV); + } else { // decode, verify windows and commits: one kernel, so a window's rows are a decode step's rows + k_gdn_seq<<>>(S[li], hc_b, C, al_b, be_b, z, L.ssm_norm, m->eps, gdn_y, HK, HV, + T, !verify); + } + mm(L.ssm_out, gdn_y, y, T); + } else { + prep(h, N, T, xq); + apply(L.wq, xq, qg, T); + apply(L.wk, xq, kx, T); + apply(L.wv, xq, vx, T); + k_attn_prep<<>>(qg, kx, vx, L.q_norm, L.k_norm, q, gate, kc[li], vc[li], H, + HKV, HD, m->n_rot, dpos, ctx, m->rope_base, m->eps); + if (T > kGemmT) { + // a prompt chunk: scores = Q K^T and out = P V as FP16 GEMMs (FP32 accumulation, FP32 scores) per KV + // head (its query heads one strided batch over the shared K / V), the causal softmax in between writing + // FP16 probabilities; the queries in slices whose scores fit + const int P = (int) p0 + T; + const int ldp = (P + 7) / 8 * 8; + const int tq = (int) std::max(1, std::min(T, (int64_t) (kAttScoreFloats / ((size_t) H * ldp)))); + const int G = H / HKV; + const float one = 1.0f, zero = 0.0f; + k_kv_f16<<>>(kc[li], vc[li], k16, v16, ctx, P, HD, HKV); + k_to_f16<<>>(q, q16, (int64_t) T * H * HD); + for (int t0 = 0; t0 < T; t0 += tq) { + const int nt = std::min(tq, T - t0); + for (int kvh = 0; kvh < HKV; ++kvh) { + const __half* Kh = k16 + (size_t) kvh * P * HD; + const __half* Qh = q16 + ((size_t) t0 * H + kvh * G) * HD; + float* Sh = att_s + (size_t) kvh * G * nt * ldp; + if (cublasGemmStridedBatchedEx(blas, CUBLAS_OP_T, CUBLAS_OP_N, P, nt, HD, &one, Kh, CUDA_R_16F, HD, + 0, Qh, CUDA_R_16F, H * HD, HD, &zero, Sh, CUDA_R_32F, ldp, + (long long) nt * ldp, G, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT) != + CUBLAS_STATUS_SUCCESS) { + std::fprintf(stderr, "strata-q36: attention scores GEMM failed\n"); + std::exit(1); + } + } + k_attn_softmax16<<>>(att_s, att_p16, ldp, nt, P, (int) p0 + t0, + 1.0f / sqrtf((float) HD)); + for (int kvh = 0; kvh < HKV; ++kvh) { + const __half* Vh = v16 + (size_t) kvh * P * HD; + const __half* Sh = att_p16 + (size_t) kvh * G * nt * ldp; + float* Oh = att + ((size_t) t0 * H + kvh * G) * HD; + if (cublasGemmStridedBatchedEx(blas, CUBLAS_OP_N, CUBLAS_OP_N, HD, nt, P, &one, Vh, CUDA_R_16F, HD, + 0, Sh, CUDA_R_16F, ldp, (long long) nt * ldp, &zero, Oh, CUDA_R_32F, + H * HD, HD, G, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT) != + CUBLAS_STATUS_SUCCESS) { + std::fprintf(stderr, "strata-q36: attention values GEMM failed\n"); + std::exit(1); + } + } + } + k_gate_mul<<>>(att, gate, (int64_t) T * H * HD); + } else { + // split-K over 256-cell chunks; the chunk grid covers every cell a row can see (graph mode: the whole + // context, past-the-end chunks return at once) + const int rows_per = att_rows / H; + for (int t0 = 0; t0 < T; t0 += rows_per) { + const int nt = std::min(rows_per, T - t0); + const int nc = graph_mode ? n_chunk + : (int) std::min(n_chunk, (p0 + t0 + nt + kChunkCells - 1) / kChunkCells); + k_attn_part<<>>(q, kc[li], vc[li], dpos, t0, H, HKV, ctx, + 1.0f / sqrtf((float) HD), n_chunk, pacc, pm, pl); + k_attn_merge<<>>(pacc, pm, pl, gate, dpos, t0, H, n_chunk, att); + } + } + mm(L.wo, att, y, T); + } + k_add_rms<<>>(x, y, L.post_norm, h, N, m->eps); + // routed experts (one token: the router and the shared expert's gate in one product, the gate its last row) + const bool one = T == 1; + if (one) f32mm(L.router_ext, h, logits_r, N, (int) g.n_expert + 1, 1); + else f32mm(L.router, h, logits_r, N, (int) g.n_expert, T); + K::native_router_topk(logits_r, ids, ewts, (int) g.n_expert, Kp, T, st); + const int64_t n_ent = (int64_t) T * Kp; + const int32_t* prow = nullptr; + // the hybrid rows path: a batch of up to hybrid_t rows; when only the MTP block is hybrid, its every batch + // (its prompt pass too: no staging buffers then) + const bool hy_rows = lhy(li) && (T <= hybrid_t || !main_hybrid); + if (hy_rows) { + moe_hybrid_gpu(L, li, T); + } else if (T > kGemmT && use_mmq) { + // a prompt chunk: the experts on llama.cpp's MMQ (int8, the weights read once per expert): the entries + // sorted by expert on the device, gate+up as one [2 FF] product per expert, SwiGLU, down into rows the + // combine reads through entry -> sorted row + const int ne = (int) g.n_expert; + CK(cudaMemsetAsync(rcnt, 0, (size_t) ne * 4, st)); + k_route_count<<>>(ids, (int) n_ent, rcnt); + k_route_scan<<<1, 32, 0, st>>>(rcnt, ne, rbounds, rcur, rmax); + k_route_scatter<<>>(ids, (int) n_ent, Kp, rcur, ent_dst, ent_tok, rinv); + CK(cudaMemcpyAsync(hpin + 10, rmax, 4, cudaMemcpyDeviceToHost, st)); + if (lhy(li)) CK(cudaMemcpyAsync(h_cnt + li * g.n_expert, rcnt, (size_t) ne * 4, cudaMemcpyDeviceToHost, st)); + CK(cudaStreamSynchronize(st)); + if (lhy(li)) + for (int x = 0; x < ne; ++x) hy[li].score[(size_t) x] += h_cnt[li * g.n_expert + x]; + const int64_t maxr = hpin[10]; + const uint8_t* wbase = lhy(li) ? stream_take((int) li) : L.blobs; + MMQ::quantize(h, ent_tok, mq_x, L.L.gu_type, N, N, n_ent, st); + MMQ::Product gu; + gu.w = wbase; gu.type = L.L.gu_type; gu.w_rows = 2 * FF; gu.w_cols = N; gu.expert_bytes = L.stride; + gu.n = ne; gu.xq = mq_x; gu.bounds = rbounds; gu.ids = ident; gu.total_rows = n_ent; gu.max_rows = maxr; + gu.dst = mq_gu; gu.ld_dst = 2 * FF; + mctx->run(gu, st); + MMQ::swiglu(mq_gu, mq_h, n_ent, FF, false, st); + MMQ::quantize(mq_h, nullptr, mq_hq, L.L.d_type, FF, FF, n_ent, st); + MMQ::Product dn; + dn.w = wbase + L.L.down_off; dn.type = L.L.d_type; dn.w_rows = N; dn.w_cols = FF; + dn.expert_bytes = L.stride; dn.n = ne; dn.xq = mq_hq; dn.bounds = rbounds; dn.ids = ident; + dn.total_rows = n_ent; dn.max_rows = maxr; dn.dst = eparts; dn.ld_dst = N; + mctx->run(dn, st); + if (lhy(li)) stream_done(); + prow = rinv; + } else { + k_group<<<1, kThreads, 0, st>>>(ids, (int) n_ent, Kp, (int) g.n_expert, L.blobs, L.stride, grp_ptr, grp_start, + n_groups, ent_dst, ent_tok); + quant(h, N, T, xq); // the experts' and the shared expert's input + K::native_expert_grouped(L.L, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, + std::min(n_ent, g.n_expert), n_ent, xq, escr, eparts, st); + } + // the shared expert, scaled by sigmoid(w . h) + if (T > kGemmT) k_to_f16<<>>(h, x16, (int64_t) N * T); + apply(L.sh_gate, xq, sg, T); + apply(L.sh_up, xq, su, T); + if (T <= kGemmT) { // SwiGLU and its q8_1 image in one launch + K::native_swiglu_quantize_q8_1(sg, su, q8, FS, T, st); + mmq(L.sh_down, q8, sy, T); + } else { + k_swiglu<<>>(sg, su, shh, (int64_t) T * FS); + mm(L.sh_down, shh, sy, T); + } + if (!one) f32mm(L.sh_gate_inp, h, sgate, N, 1, T); + if (hy_rows) moe_hybrid_cpu(li, T); // the CPU pool's experts (while the GPU runs the rest), merged + // the combine, the shared expert's gate, the residual add and the next norm in one launch + k_moe_out<<>>(x, eparts, prow, ewts, Kp, sy, one ? logits_r + g.n_expert : sgate, 1, wn, hout, + N, m->eps); + } + + /// The main model over T rows (device `tok`, positions p0 .. p0 + T - 1, also at *pos0): hmain gets every row's + /// final normed hidden; `heads` rows from the end get logits (rows [T - heads, T): logits row r - (T - heads)) and + /// their greedy picks (`pick`). `verify`: a verify window (the GDN state left for commit()). + void forward(int T, int64_t p0, int heads, bool graph_mode, bool verify) { + const auto& g = m->g; + const int N = (int) g.n_embd; + if (main_hybrid && T > hybrid_t && use_mmq) { + std::vector seq; + for (size_t l = 0; l < m->layers.size(); ++l) + if (lhy(l)) seq.push_back((int) l); + stream_begin(seq); + } + K::iq_embed_rows(m->embd_type, m->embd, m->embd_row, tok, T, N, x, st); + k_rms<<>>(x, m->layers[0].attn_norm, h, N, m->eps); // later layers: from k_moe_out + for (size_t l = 0; l < m->layers.size(); ++l) { + const bool last = l + 1 == m->layers.size(); + layer(m->layers[l], l, T, p0, pos0, graph_mode, verify, last ? m->out_norm : m->layers[l + 1].attn_norm, + last ? hmain : h); + } + if (heads > 0) head_rows(hmain + (size_t) (T - heads) * N, heads, logits, pick); + } + /// logits [n][V] = W_out hn rows, and each row's greedy pick. + void head_rows(const float* hn, int n, float* lg, int32_t* pk) { + const auto& g = m->g; + mm(m->head, hn, lg, n); + k_argmax<<>>(lg, (int) g.n_vocab, pk, amv, ami, false); + k_argmax<<>>(lg, kArgBlocks, pk, amv, ami, true); + } + + /// The MTP block over T rows: row t reads token tok_m[t] at position p0 + t (also at *pos0_m) and the seed hidden + /// seeds[t] (the main model's normed hidden of the position before, or the block's own for a chained draft); + /// hmtp gets each row's normed output. `draft`: logits of the last row and its pick (`pick_m`). + void forward_mtp(int T, int64_t p0, const float* seeds, bool draft, bool graph_mode) { + const auto& g = m->g; + const int N = (int) g.n_embd; + if (main_hybrid && lhy(m->layers.size()) && T > hybrid_t && use_mmq) stream_begin({(int) m->layers.size()}); + K::iq_embed_rows(m->embd_type, m->embd, m->embd_row, tok_m, T, N, y, st); + k_rms_ld<<>>(y, N, m->mtp_enorm, mtp_cat, 2 * N, N, m->eps); // [e | ...] + k_rms_ld<<>>(seeds, N, m->mtp_hnorm, mtp_cat + N, 2 * N, N, m->eps); // [... | h] + mm(m->eh_proj, mtp_cat, x, T); + k_rms<<>>(x, m->mtp.attn_norm, h, N, m->eps); + layer(m->mtp, m->layers.size(), T, p0, pos0_m, graph_mode, false, m->mtp_shnorm, hmtp); + if (draft) head_rows(hmtp + (size_t) (T - 1) * N, 1, logits_m, pick_m); + } + + /// After a verify window of T rows: the GDN state takes the first n_keep rows (conv history and recurrence run + /// again over the rows' kept inputs). + void commit(int n_keep) { + const auto& g = m->g; + const int HK = (int) g.ssm_k_heads, HV = (int) g.ssm_v_heads, C = (int) g.ssm_conv_channels; + for (size_t l = 0; l < m->layers.size(); ++l) { + const Layer& L = m->layers[l]; + if (L.attn) continue; + k_conv_seq<<>>(conv[l], v_qkv[l], L.conv, hc, C, 2 * HK, m->eps, n_keep, true); + k_gdn_seq<<>>(S[l], v_hc[l], C, v_alpha[l], v_beta[l], z, L.ssm_norm, m->eps, + nullptr, HK, HV, n_keep, true); + } + } + + // ---- the hybrid mode + const Layer& layer_at(int li) const { return li < (int) m->layers.size() ? m->layers[(size_t) li] : m->mtp; } + + /// A streamed forward over the state indices `seq`: the first two layers' experts start copying now. + void stream_begin(const std::vector& seq) { + stream_seq = seq; + stream_pos = 0; + for (int i = 0; i < 2 && i < (int) seq.size(); ++i) stream_kick(i); + } + void stream_kick(int i) { // the i-th layer of the sequence into staging buffer i % 2, after its last reader + const int b = i % 2; + const Layer& L = layer_at(stream_seq[(size_t) i]); + CK(cudaStreamWaitEvent(cst, ev_used[b], 0)); + // the experts with a VRAM slot come from it (device to device, at VRAM speed), only the others over PCIe; runs + // of consecutive experts from the same source in one copy each. STRATA_Q36_STREAM_ALL=1: the whole layer from + // host memory (the first version: PCIe-bound) + static const bool all = std::getenv("STRATA_Q36_STREAM_ALL") != nullptr; + const int ne = (int) m->g.n_expert; + const Hy& H = hy[(size_t) stream_seq[(size_t) i]]; + // fewer than half the experts resident (a 12 GB card): the one whole-layer copy is faster than many small ones + // (RTX 3060, UD-Q4_K_XL at 37 of 256: pp2048 1970 whole vs 1540 in runs) + if (all || 2 * L.n_slots < ne) { + CK(cudaMemcpyAsync(stage[b], L.hblobs, L.stride * (size_t) ne, cudaMemcpyHostToDevice, cst)); + } else { + for (int x = 0; x < ne;) { + const bool dev = H.slot_of[(size_t) x] >= 0; + int y = x + 1; + if (dev) // consecutive slots holding consecutive experts + while (y < ne && H.slot_of[(size_t) y] == H.slot_of[(size_t) y - 1] + 1) ++y; + else + while (y < ne && H.slot_of[(size_t) y] < 0) ++y; + const size_t n = (size_t) (y - x) * L.stride; + if (dev) + CK(cudaMemcpyAsync(stage[b] + (size_t) x * L.stride, L.blobs + (size_t) H.slot_of[(size_t) x] * L.stride, + n, cudaMemcpyDeviceToDevice, cst)); + else + CK(cudaMemcpyAsync(stage[b] + (size_t) x * L.stride, L.hblobs + (size_t) x * L.stride, n, + cudaMemcpyHostToDevice, cst)); + x = y; + } + } + CK(cudaEventRecord(ev_copy[b], cst)); + } + const uint8_t* stream_take(int li) { + if (stream_pos >= (int) stream_seq.size() || stream_seq[(size_t) stream_pos] != li) { + std::fprintf(stderr, "strata-q36: the expert stream is out of step (layer %d)\n", li); + std::exit(1); + } + const int b = stream_pos % 2; + CK(cudaStreamWaitEvent(st, ev_copy[b], 0)); + return stage[b]; + } + void stream_done() { + const int b = stream_pos % 2; + CK(cudaEventRecord(ev_used[b], st)); + if (stream_pos + 2 < (int) stream_seq.size()) stream_kick(stream_pos + 2); + ++stream_pos; + } + + /// The GPU half of a hybrid MoE: the routing to the host, the resident experts' entries grouped and run. + void moe_hybrid_gpu(const Layer& L, size_t li, int T) { + const auto& g = m->g; + const int N = (int) g.n_embd, Kp = (int) m->top_k; + const int64_t n_ent = (int64_t) T * Kp; + CK(cudaMemcpyAsync(h_ids, ids, (size_t) n_ent * 4, cudaMemcpyDeviceToHost, st)); + CK(cudaMemcpyAsync(h_h, h, (size_t) T * N * 4, cudaMemcpyDeviceToHost, st)); + CK(cudaEventRecord(ev_route, st)); + k_group_hy<<<1, kThreads, 0, st>>>(ids, (int) n_ent, Kp, (int) g.n_expert, hy[li].slot_of_d, L.blobs, L.stride, + grp_ptr, grp_start, n_groups, ent_dst, ent_tok); + quant(h, N, T, xq); // the experts' and the shared expert's input + K::native_expert_grouped(L.L, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, + std::min(n_ent, g.n_expert), n_ent, xq, escr, eparts, st); + } + /// The CPU half: the entries without a slot on the pool (ggml-cpu's arithmetic for the layer's formats), their + /// rows uploaded and merged into the entries' rows. + void moe_hybrid_cpu(size_t li, int T) { +#if defined(STRATA_Q36_CPU_POOL) + namespace C = strata::kernels::cpu; + const auto& g = m->g; + const int N = (int) g.n_embd, Kp = (int) m->top_k; + const int n_ent = T * Kp; + Hy& H = hy[li]; + const Layer& L = layer_at((int) li); + while (cudaEventQuery(ev_route) == cudaErrorNotReady) { + } + const auto t0 = Clock::now(); + // the missed entries per expert (up to MAXT tokens per job) + jobs.clear(); + std::vector quantized((size_t) T, 0); + int n_miss = 0; + std::map open; // expert -> its job with room + const bool defer = rows_deferred && li < m->layers.size(); + if (defer) { + if (row_ids.size() < m->layers.size()) row_ids.resize(m->layers.size()); + row_ids[li].assign(h_ids, h_ids + n_ent); + } + for (int e = 0; e < n_ent; ++e) { + const int x = h_ids[e]; + if (!defer) H.score[(size_t) x] += 1.0; + h_miss[e] = H.slot_of[(size_t) x] < 0; + if (!h_miss[e]) continue; + ++n_miss; + const int t = e / Kp; + if (!quantized[(size_t) t]) { + C::native_quant_act(H.fmt, h_h + (size_t) t * N, acts + (size_t) t * C::kNativeActBytes); + quantized[(size_t) t] = 1; + } + auto it = open.find(x); + if (it == open.end() || jobs[it->second].nt == C::MAXT) { + C::ExpertJobMulti j; + j.blob = L.hblobs + (size_t) x * L.stride; + jobs.push_back(j); + it = open.insert_or_assign(x, jobs.size() - 1).first; + } + C::ExpertJobMulti& j = jobs[it->second]; + j.nact[j.nt] = acts + (size_t) t * C::kNativeActBytes; + j.out[j.nt] = cpu_out + (size_t) e * N; + ++j.nt; + } + hy_cpu += n_miss; + hy_gpu += n_ent - n_miss; + if (n_miss == 0) return; + pool->run_split_multi_native(H.fmt, jobs.data(), (int) jobs.size()); + hy_cpu_ms += ms_since(t0); + CK(cudaMemcpyAsync(ecpu, cpu_out, (size_t) n_ent * N * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(d_miss, h_miss, (size_t) n_ent * 4, cudaMemcpyHostToDevice, st)); + k_merge_cpu<<>>(eparts, ecpu, d_miss, N); +#else + (void) li; + (void) T; +#endif + } + + /// The slots to the experts the routing used most (the counts halved each time): at most max_swaps replacements + /// over all layers, between forwards (the copies are on the engine's stream). + void rebalance(int max_swaps) { + static const bool off = std::getenv("STRATA_Q36_FIXED_SLOTS") != nullptr; // the slots as placed (tests) + if (!m->hybrid || off || warming) return; + const int64_t ne = m->g.n_expert; + int left = max_swaps; + for (size_t li = 0; li < hy.size() && left > 0; ++li) { + Hy& H = hy[li]; + const Layer& L = layer_at((int) li); + const int S = L.n_slots; + if (S <= 0 || S >= ne) continue; + std::vector order((size_t) ne); + for (int x = 0; x < ne; ++x) order[(size_t) x] = x; + std::sort(order.begin(), order.end(), [&](int a, int b) { return H.score[(size_t) a] > H.score[(size_t) b]; }); + // residents outside the top S, lowest score first: the slots to give away + std::vector victims; + for (int s = 0; s < S; ++s) victims.push_back(s); + std::sort(victims.begin(), victims.end(), [&](int a, int b) { + return H.score[(size_t) H.exp_in_slot[(size_t) a]] < H.score[(size_t) H.exp_in_slot[(size_t) b]]; + }); + size_t vi = 0; + bool changed = false; + for (int i = 0; i < S && left > 0; ++i) { + const int x = order[(size_t) i]; + if (H.slot_of[(size_t) x] >= 0) continue; + while (vi < victims.size()) { + const int s = victims[vi]; + const int y = H.exp_in_slot[(size_t) s]; + if (H.score[(size_t) y] >= H.score[(size_t) x]) { vi = victims.size(); break; } + // y must not be in the top S itself + ++vi; + H.slot_of[(size_t) y] = -1; + H.slot_of[(size_t) x] = s; + H.exp_in_slot[(size_t) s] = x; + CK(cudaMemcpyAsync(L.blobs + (size_t) s * L.stride, L.hblobs + (size_t) x * L.stride, L.L.bytes, + cudaMemcpyHostToDevice, st)); + --left; + ++hy_swaps; + changed = true; + break; + } + if (vi >= victims.size()) break; + } + if (changed) + CK(cudaMemcpyAsync(H.slot_of_d, H.slot_of.data(), (size_t) ne * 4, cudaMemcpyHostToDevice, st)); + for (double& v : H.score) v *= 0.5; + } + CK(cudaStreamSynchronize(st)); // slot_of's host copy is pageable: the upload is done before it changes + } + + void shrink_att(size_t floats) { + CK(cudaDeviceSynchronize()); + CK(cudaFree(att_s)); + CK(cudaFree(att_p16)); + kAttScoreFloats = floats; + att_s = dalloc(kAttScoreFloats); + att_p16 = dalloc_t<__half>(kAttScoreFloats); + CK(cudaDeviceSynchronize()); + } + void reset_graphs() { + for (cudaGraphExec_t* g : {&g1, &gm1}) + if (*g) { CK(cudaGraphExecDestroy(*g)); *g = nullptr; } + for (auto& g : gv) + if (g) { CK(cudaGraphExecDestroy(g)); g = nullptr; } + } + + template void graph_run(cudaGraphExec_t& gx, F body) { + if (!use_graph) { body(); return; } + if (!gx) { + cudaGraph_t graph = nullptr; + CK(cudaStreamBeginCapture(st, cudaStreamCaptureModeThreadLocal)); + body(); + CK(cudaStreamEndCapture(st, &graph)); + CK(cudaGraphInstantiate(&gx, graph, 0)); + CK(cudaGraphDestroy(graph)); + } + CK(cudaGraphLaunch(gx, st)); + } + + /// The tokens at the current position: a prompt in chunks (eager), one token from the decode graph. The last + /// token's logits stay in `logits` (its greedy pick in `pick`), hlast its normed hidden. With the MTP block the + /// prompt also runs through it (its K / V for every position: row q reads h_{q-1} and token q). + template void process(const int32_t* toks, int64_t n, F on_chunk) { + const int N = (int) m->g.n_embd; + if (n == 1) { + CK(cudaStreamSynchronize(st)); // the pinned staging is free again + hpin[0] = toks[0]; + hpin[1] = (int32_t) pos; + CK(cudaMemcpyAsync(tok, hpin, 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(pos0, hpin + 1, 4, cudaMemcpyHostToDevice, st)); + rows_deferred = true; + graph_run(g1, [&] { forward(1, pos, 1, use_graph, false); }); + rows_deferred = false; + CK(cudaMemcpyAsync(hlast, hmain, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); + pos += 1; + after_rows(1); + on_chunk(1); + return; + } + for (int64_t i = 0; i < n; i += tmax) { + const int T = (int) std::min(tmax, n - i); + CK(cudaStreamSynchronize(st)); + hpin[1] = (int32_t) pos; + CK(cudaMemcpyAsync(tok, toks + i, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(pos0, hpin + 1, 4, cudaMemcpyHostToDevice, st)); + forward(T, pos, i + T == n ? 1 : 0, false, false); + if (m->has_mtp && mtp_d > 0) { + // seeds: h_{q-1} for each row q: hlast, then this chunk's rows 0 .. T - 2 (in `y`, free here) + CK(cudaMemcpyAsync(mtp_seed(), hlast, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); + if (T > 1) + CK(cudaMemcpyAsync(mtp_seed() + N, hmain, (size_t) (T - 1) * N * 4, cudaMemcpyDeviceToDevice, st)); + CK(cudaMemcpyAsync(tok_m, toks + i, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(pos0_m, hpin + 1, 4, cudaMemcpyHostToDevice, st)); + forward_mtp(T, pos, mtp_seed(), false, false); + } + CK(cudaMemcpyAsync(hlast, hmain + (size_t) (T - 1) * N, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); + pos += T; + CK(cudaStreamSynchronize(st)); + on_chunk(i + T); + } + if (m->hybrid) rebalance(hybrid_swaps_after_prompt); + } + int hybrid_swaps_after_prompt = 2048; + /// the MTP seed rows of a prompt chunk: a buffer the block's own forward does not use (`moe_out`, [tmax][N]) + float* mtp_seed() { return moe_out; } + + /// One speculative step with D MTP drafts (greedy): `x` is the next token (decided, not processed); `fix` the + /// tokens of the rows the block must redo first (the drafts the last window accepted, seeded by hmain rows + /// 0 .. fix.size() - 1 of that window). Drafts d1 .. dD, then the window [x, d1 .. dD] through the main model; + /// returns the accepted count a and writes the picks of rows 0 .. a (row a's pick is the token after them). + int spec_step(int x_tok, const std::vector& fix, int D, std::vector& drafts, int32_t* picks) { + const int N = (int) m->g.n_embd; + if (main_hybrid) D = std::min(D, (int) (kRebalanceEvery - pos % kRebalanceEvery) - 1); + const int T0 = (int) fix.size() + 1; // the redo rows and the row of x + CK(cudaStreamSynchronize(st)); + // rows of the first MTP call: (hmain row i, fix[i]) at positions pos - fix.size() + i, then (hlast, x) at pos + for (int i = 0; i < (int) fix.size(); ++i) hpin[16 + i] = fix[(size_t) i]; + hpin[16 + fix.size()] = x_tok; + hpin[1] = (int32_t) (pos - (int64_t) fix.size()); + CK(cudaMemcpyAsync(tok_m, hpin + 16, (size_t) T0 * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(pos0_m, hpin + 1, 4, cudaMemcpyHostToDevice, st)); + // seeds: hmain rows 0 .. fix - 1 are the h of the positions before the fixed rows; hlast is that before x + float* seeds = mtp_seed(); + if (!fix.empty()) + CK(cudaMemcpyAsync(seeds, hmain, fix.size() * (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); + CK(cudaMemcpyAsync(seeds + fix.size() * (size_t) N, hlast, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); + forward_mtp(T0, pos - (int64_t) fix.size(), seeds, D > 0, false); + drafts.assign((size_t) D, 0); + if (D > 0) { + CK(cudaMemcpyAsync(hpin + 2, pick_m, 4, cudaMemcpyDeviceToHost, st)); + CK(cudaStreamSynchronize(st)); + drafts[0] = hpin[2]; + } + int last_row = T0 - 1; // the row of the previous MTP call whose output seeds the next draft + for (int d = 1; d < D; ++d) { // chained: (the block's own output, the last draft) at the next position + hpin[0] = drafts[(size_t) d - 1]; + hpin[1] = (int32_t) (pos + d); + CK(cudaMemcpyAsync(tok_m, hpin, 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(pos0_m, hpin + 1, 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(seeds, hmtp + (size_t) last_row * N, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); + last_row = 0; + if (mtp_graph) graph_run(gm1, [&] { forward_mtp(1, pos + d, seeds, true, use_graph); }); + else forward_mtp(1, pos + d, seeds, true, false); + CK(cudaMemcpyAsync(hpin + 2, pick_m, 4, cudaMemcpyDeviceToHost, st)); + CK(cudaStreamSynchronize(st)); + drafts[(size_t) d] = hpin[2]; + } + // the verify window + const int T = D + 1; + hpin[16] = x_tok; + for (int d = 0; d < D; ++d) hpin[17 + d] = drafts[(size_t) d]; + hpin[1] = (int32_t) pos; + CK(cudaMemcpyAsync(tok, hpin + 16, (size_t) T * 4, cudaMemcpyHostToDevice, st)); + CK(cudaMemcpyAsync(pos0, hpin + 1, 4, cudaMemcpyHostToDevice, st)); + rows_deferred = true; + graph_run(gv[T], [&] { forward(T, pos, T, use_graph, true); }); + rows_deferred = false; + CK(cudaMemcpyAsync(hpin + 2, pick, (size_t) T * 4, cudaMemcpyDeviceToHost, st)); + CK(cudaStreamSynchronize(st)); + int a = 0; + while (a < D && hpin[2 + a] == drafts[(size_t) a]) ++a; + for (int i = 0; i <= a; ++i) picks[i] = hpin[2 + i]; + commit(a + 1); + CK(cudaMemcpyAsync(hlast, hmain + (size_t) a * N, (size_t) N * 4, cudaMemcpyDeviceToDevice, st)); + pos += a + 1; + after_rows(a + 1); + return a; + } + + /// The first prompt after load ran at about half speed (pp4096 rep 0: ~1770 tok/s against ~3290): the GPU's code + /// objects, the BLAS handles' kernels and the decode graph are made on first use. A throw-away prompt of one + /// chunk, a decode step and (with drafts) a speculative step at load do that before the first request; then the + /// state, the cache position and the hybrid counters are as after load. + bool warming = false; + void warmup() { + const auto t0 = Clock::now(); + warming = true; + const int32_t filler = 198; // a newline: any token works + std::vector toks((size_t) tmax, filler); + process(toks.data(), (int64_t) toks.size(), [](int64_t) {}); + if (tmax > kGemmT + 1) process(toks.data(), kGemmT + 1, [](int64_t) {}); // the smallest GEMM chunk too + process(&filler, 1, [](int64_t) {}); + if (mtp_d > 0) { + std::vector fix, drafts; + int32_t picks[16]; + spec_step(filler, fix, mtp_d, drafts, picks); + } + CK(cudaStreamSynchronize(st)); + warming = false; + for (Hy& H : hy) std::fill(H.score.begin(), H.score.end(), 0.0); + hy_cpu = hy_gpu = hy_swaps = 0; + hy_cpu_ms = 0; + reset(); + std::fprintf(stderr, "strata-q36: warmed up in %.1f s (one prompt chunk, a decode step%s)\n", + ms_since(t0) / 1000.0, mtp_d > 0 ? ", a speculative step" : ""); + } + + int greedy() { + CK(cudaMemcpyAsync(hpin + 2, pick, 4, cudaMemcpyDeviceToHost, st)); + CK(cudaStreamSynchronize(st)); + return hpin[2]; + } + void host_logits(std::vector& out) { + out.resize((size_t) m->g.n_vocab); + CK(cudaMemcpyAsync(out.data(), logits, out.size() * 4, cudaMemcpyDeviceToHost, st)); + CK(cudaStreamSynchronize(st)); + } +}; + +// ------------------------------------------------------------------------------------------------ expert placement +/// The routed experts after the engine's buffers: all in VRAM when they fit in `vram_gib` (< 0: the free VRAM less a +/// reserve), else the hybrid mode - every expert in host memory, the same number of VRAM slots per layer, a decode +/// batch's other experts on the CPU pool and a prompt chunk's streamed through two staging buffers. +bool place_experts(Model& m, Engine& E, double vram_gib, int threads, int hybrid_t, int slots, std::string& err) { + const auto t0 = Clock::now(); + const auto& g = m.g; + const int64_t ne = g.n_expert; + std::vector all; + for (Layer& L : m.layers) all.push_back(&L); + if (m.has_mtp) all.push_back(&m.mtp); + size_t total = 0, per_slot = 0, max_layer = 0; + for (Layer* L : all) { + total += L->stride * (size_t) ne + kMmqTail; + per_slot += L->stride; + max_layer = std::max(max_layer, L->stride * (size_t) ne); + } + size_t fr = 0, tot = 0; + CK(cudaMemGetInfo(&fr, &tot)); + const size_t reserve = (size_t) 768 << 20; + const size_t budget = vram_gib >= 0 ? (size_t) (vram_gib * (double) (1ull << 30)) + : (fr > reserve ? fr - reserve : 0); + // every expert fits once the packed Q8_0 decode copies are given back (a file a few GiB larger than the card's + // room, UD-Q6_K_XL on 32 GB): drop them - the decode reads the GGUF layout then, bitwise the same outputs, a little + // slower - rather than run the hybrid mode with its CPU share and streamed prompt layers. STRATA_Q36_KEEP_PACKED=1 + // keeps them (and the hybrid mode). + size_t packed_bytes = 0; + for (const auto& pk : m.packed) packed_bytes += std::get<2>(pk); + size_t main_need = 0; // the main layers' experts (the MTP block's can go to the CPU, see below) + for (Layer& L : m.layers) main_need += L.stride * (size_t) ne + kMmqTail; + const size_t slack = ((size_t) 512 << 20) + (E.kAttScoreFloats - ((size_t) 16 << 20)) * 6; // reserve + scores + const bool mtp_cpu_ok = m.has_mtp && std::getenv("STRATA_Q36_NO_MTP_CPU") == nullptr; + if (slots <= 0 && vram_gib < 0 && total > budget && packed_bytes > 0 && + (total <= budget + packed_bytes || (mtp_cpu_ok && main_need <= budget + packed_bytes + slack)) && + std::getenv("STRATA_Q36_KEEP_PACKED") == nullptr) { + CK(cudaDeviceSynchronize()); + for (const auto& pk : m.packed) { + K::native_q8_0_packed_unregister(std::get<0>(pk)); + CK(cudaFree(std::get<1>(pk))); + } + m.packed.clear(); + E.reset_graphs(); + CK(cudaMemGetInfo(&fr, &tot)); + std::fprintf(stderr, "strata-q36: the packed Q8_0 decode copies (%.2f GiB) given back so that every routed " + "expert fits in VRAM (STRATA_Q36_KEEP_PACKED=1 keeps them and runs the hybrid mode)\n", + (double) packed_bytes / (1 << 30)); + } + size_t budget2 = vram_gib >= 0 ? budget : (fr > reserve ? fr - reserve : 0); + // the MAIN layers' experts fit, the MTP block's not all (UD-Q6_K_XL on 32 GB): the main layers all in VRAM - the + // text is the all-in-VRAM text, the decode graph stays - and the MTP block's experts on slots + the CPU pool (its + // drafts only). When that needs it: the attention scores buffer at 64 MB instead of 256 MB (more, smaller + // slices in a long prompt) and the reserve at 256 MiB instead of 768 (said in the log; --expert-vram sets the + // budget instead). STRATA_Q36_NO_MTP_CPU=1: the plain hybrid mode for every layer. + size_t total_main = 0; + for (Layer& L : m.layers) total_main += L.stride * (size_t) ne + kMmqTail; + bool mtp_only = false; + if (slots <= 0 && vram_gib < 0 && m.has_mtp && total > budget2 && std::getenv("STRATA_Q36_NO_MTP_CPU") == nullptr) { + const size_t att_save = (E.kAttScoreFloats - ((size_t) 16 << 20)) * 6; // att_s (4 B) + att_p16 (2 B) + const size_t small_reserve = (size_t) 256 << 20; + const size_t room = fr + att_save > small_reserve ? fr + att_save - small_reserve : 0; + if (total_main + ((size_t) 64 << 20) <= budget2) { + mtp_only = true; + } else if (total_main + ((size_t) 64 << 20) <= room) { + E.shrink_att((size_t) 16 << 20); + CK(cudaMemGetInfo(&fr, &tot)); + budget2 = fr > small_reserve ? fr - small_reserve : 0; + mtp_only = total_main + ((size_t) 64 << 20) <= budget2; + std::fprintf(stderr, "strata-q36: the experts nearly fit: the attention scores buffer at 64 MB and the VRAM " + "reserve at 256 MiB (instead of 768) so that every main layer's experts fit; a driver or " + "another program needing more VRAM later can make it fail - --expert-vram GiB sets the experts' " + "budget instead\n"); + } + } + if (slots <= 0 && total <= budget2 && total + ((size_t) 256 << 20) <= fr) { + std::vector blob; + for (Layer* L : all) { + CK(cudaMalloc(&L->blobs, L->stride * (size_t) ne + kMmqTail)); + CK(cudaMemset(L->blobs, 0, L->stride * (size_t) ne + kMmqTail)); + blob.assign(L->L.bytes, 0); + for (int64_t e = 0; e < ne; ++e) { + expert_blob(*L, e, blob.data()); + CK(cudaMemcpy(L->blobs + (size_t) e * L->stride, blob.data(), L->L.bytes, cudaMemcpyHostToDevice)); + } + L->n_slots = (int) ne; + } + std::fprintf(stderr, "strata-q36: every routed expert in VRAM (%.2f GiB) in %.1f s\n", (double) total / (1 << 30), + ms_since(t0) / 1000.0); + return true; + } +#if !defined(STRATA_Q36_CPU_POOL) + (void) threads; + (void) hybrid_t; + err = "the routed experts (" + std::to_string(total >> 20) + " MiB) do not fit in VRAM, and this build has no CPU " + "expert pool (STRATA_NATIVE_EXPERTS=OFF)"; + return false; +#else + namespace C = strata::kernels::cpu; + m.hybrid = true; + E.main_hybrid = !mtp_only; + if (E.main_hybrid) E.use_graph = false; // the host takes part in every layer + E.mtp_graph = false; // the MTP block's layer is hybrid either way + E.hybrid_t = std::max(1, std::min(hybrid_t, E.use_mmq ? E.tmax : E.tmax)); + if (!E.use_mmq) E.hybrid_t = E.tmax; // no streamed prompt path: every batch on slots + the pool + const size_t staging = E.use_mmq && E.main_hybrid ? 2 * (max_layer + kMmqTail) : 0; + size_t slot_bytes = budget2 > staging ? budget2 - staging : 0; + if (slot_bytes + staging + ((size_t) 256 << 20) > fr) slot_bytes = fr > staging + ((size_t) 512 << 20) ? fr - staging - ((size_t) 512 << 20) : 0; + // --expert-slots: that many per layer (tests: the same split with and without the MTP block) + int S = slots > 0 ? (int) std::min(ne, slots) : (int) std::min((size_t) ne, slot_bytes / per_slot); + if (mtp_only) { // the main layers all, the MTP block what is left + const size_t left = budget2 > total_main ? budget2 - total_main : 0; + S = (int) std::min((size_t) ne, left / m.mtp.stride); + } + // host memory: every expert, pinned where the driver allows it (the prompt's stream and the slot copies) + size_t host = 0; + for (Layer* L : all) + if (!mtp_only || L == &m.mtp) host += L->stride * (size_t) ne + kMmqTail; + uint8_t* arena = nullptr; + bool pinned = cudaHostAlloc((void**) &arena, host, cudaHostAllocDefault) == cudaSuccess; + if (!pinned) { + (void) cudaGetLastError(); + arena = (uint8_t*) std::malloc(host); + if (!arena) { + err = "no host memory for the experts (" + std::to_string(host >> 20) + " MiB)"; + return false; + } + } + size_t off = 0; + E.hy.resize(all.size()); + for (size_t li = 0; li < all.size(); ++li) { + Layer& L = *all[li]; + if (mtp_only && &L != &m.mtp) { // a main layer: every expert in VRAM, as in the all-in-VRAM placement + CK(cudaMalloc(&L.blobs, L.stride * (size_t) ne + kMmqTail)); + CK(cudaMemset(L.blobs, 0, L.stride * (size_t) ne + kMmqTail)); + std::vector blob(L.L.bytes, 0); + for (int64_t e = 0; e < ne; ++e) { + expert_blob(L, e, blob.data()); + CK(cudaMemcpy(L.blobs + (size_t) e * L.stride, blob.data(), L.L.bytes, cudaMemcpyHostToDevice)); + } + L.n_slots = (int) ne; + continue; + } + L.hblobs = arena + off; + off += L.stride * (size_t) ne + kMmqTail; + std::memset(L.hblobs, 0, L.stride * (size_t) ne + kMmqTail); + for (int64_t e = 0; e < ne; ++e) expert_blob(L, e, L.hblobs + (size_t) e * L.stride); + L.n_slots = S; + if (S > 0) { + CK(cudaMalloc(&L.blobs, L.stride * (size_t) S + kMmqTail)); + CK(cudaMemset(L.blobs, 0, L.stride * (size_t) S + kMmqTail)); + CK(cudaMemcpy(L.blobs, L.hblobs, L.stride * (size_t) S, cudaMemcpyHostToDevice)); + } + Engine::Hy& H = E.hy[li]; + H.slot_of.assign((size_t) ne, -1); + H.exp_in_slot.assign((size_t) S, 0); + for (int s = 0; s < S; ++s) { + H.slot_of[(size_t) s] = s; + H.exp_in_slot[(size_t) s] = s; + } + H.score.assign((size_t) ne, 0.0); + CK(cudaMalloc(&H.slot_of_d, (size_t) ne * 4)); + CK(cudaMemcpy(H.slot_of_d, H.slot_of.data(), (size_t) ne * 4, cudaMemcpyHostToDevice)); + if (!C::native_fmt(L.L.gu_type, L.L.d_type, g.n_embd, g.n_ff, H.fmt, err)) return false; + if (H.fmt.up_off != L.L.up_off || H.fmt.down_off != L.L.down_off || H.fmt.bytes != L.L.bytes) { + err = "the CPU and GPU expert layouts differ"; + return false; + } + } + const size_t T = (size_t) E.tmax, N = (size_t) g.n_embd, Kp = (size_t) m.top_k; + CK(cudaHostAlloc((void**) &E.h_h, T * N * 4, cudaHostAllocDefault)); + CK(cudaHostAlloc((void**) &E.cpu_out, T * Kp * N * 4, cudaHostAllocDefault)); + CK(cudaHostAlloc((void**) &E.h_ids, T * Kp * 4, cudaHostAllocDefault)); + CK(cudaHostAlloc((void**) &E.h_miss, T * Kp * 4, cudaHostAllocDefault)); + CK(cudaHostAlloc((void**) &E.h_cnt, all.size() * (size_t) ne * 4, cudaHostAllocDefault)); + CK(cudaMalloc(&E.ecpu, T * Kp * N * 4)); + CK(cudaMalloc(&E.d_miss, T * Kp * 4)); + E.acts = (uint8_t*) std::malloc(T * C::kNativeActBytes + 64); + CK(cudaEventCreateWithFlags(&E.ev_route, cudaEventDisableTiming)); + if (staging) { + CK(cudaStreamCreateWithFlags(&E.cst, cudaStreamNonBlocking)); + for (int b = 0; b < 2; ++b) { + CK(cudaMalloc(&E.stage[b], max_layer + kMmqTail)); + CK(cudaMemset(E.stage[b], 0, max_layer + kMmqTail)); + CK(cudaEventCreateWithFlags(&E.ev_copy[b], cudaEventDisableTiming)); + CK(cudaEventCreateWithFlags(&E.ev_used[b], cudaEventDisableTiming)); + CK(cudaEventRecord(E.ev_used[b], E.st)); + } + } + E.pool = std::make_unique(threads); + CK(cudaDeviceSynchronize()); + if (mtp_only) + std::fprintf(stderr, "strata-q36: every main layer's routed experts in VRAM (%.2f GiB); the MTP block's: %d of " + "%lld in VRAM, the rest on the CPU pool (its drafts only)\n", (double) total_main / (1 << 30), S, + (long long) ne); + else + std::fprintf(stderr, "strata-q36: hybrid experts: %d of %lld per layer in VRAM (%.2f GiB), all %.2f GiB in %s host " + "memory, the rest of a batch of <= %d rows on %d CPU threads, bigger prompt chunks streamed (%.2f GiB " + "staging); %.1f s\n", S, (long long) ne, (double) S * per_slot / (1 << 30), (double) host / (1 << 30), + pinned ? "pinned" : "pageable", E.hybrid_t, E.pool->workers() + (E.pool->host_works() ? 1 : 0), + (double) staging / (1 << 30), ms_since(t0) / 1000.0); + return true; +#endif +} + +// ------------------------------------------------------------------------------------------------ sampling +struct Sampling { + float temperature = 0.f, top_p = 1.f, min_p = 0.f, repeat = 1.f, freq = 0.f, present = 0.f; + int top_k = 20, last_n = 0; + unsigned long long seed = 0; + bool needs_logits() const { return temperature > 0.f || repeat != 1.f || freq != 0.f || present != 0.f; } +}; + +int sample(std::vector& lg, const Sampling& s, const std::vector& hist, std::mt19937_64& rng) { + if (s.last_n != 0 && (s.repeat != 1.f || s.freq != 0.f || s.present != 0.f)) { + std::map cnt; + const size_t from = s.last_n < 0 || (size_t) s.last_n >= hist.size() ? 0 : hist.size() - (size_t) s.last_n; + for (size_t i = from; i < hist.size(); ++i) ++cnt[hist[i]]; + for (const auto& [id, c] : cnt) { + float& v = lg[(size_t) id]; + if (s.repeat != 1.f) v = v > 0 ? v / s.repeat : v * s.repeat; + v -= (float) c * s.freq + s.present; + } + } + if (s.temperature <= 0.f) return (int) (std::max_element(lg.begin(), lg.end()) - lg.begin()); + const int kk = std::max(1, std::min(s.top_k > 0 ? s.top_k : 64, (int) lg.size())); + std::vector idx(lg.size()); + for (size_t i = 0; i < idx.size(); ++i) idx[i] = (int) i; + std::partial_sort(idx.begin(), idx.begin() + kk, idx.end(), [&](int a, int b) { return lg[a] > lg[b]; }); + idx.resize((size_t) kk); + std::vector p(idx.size()); + const double mx = lg[(size_t) idx[0]]; + double sum = 0; + for (size_t i = 0; i < idx.size(); ++i) sum += (p[i] = std::exp((lg[(size_t) idx[i]] - mx) / s.temperature)); + size_t keep = idx.size(); + double cum = 0; + for (size_t i = 0; i < idx.size(); ++i) { + if (p[i] / sum < s.min_p * (p[0] / sum)) { keep = i; break; } + cum += p[i] / sum; + if (cum >= s.top_p) { keep = i + 1; break; } + } + keep = std::max(1, keep); + double tot = 0; + for (size_t i = 0; i < keep; ++i) tot += p[i]; + std::uniform_real_distribution u(0.0, tot); + double r = u(rng); + for (size_t i = 0; i < keep; ++i) { + if ((r -= p[i]) <= 0) return idx[i]; + } + return idx[keep - 1]; +} + +std::vector parse_ids(const char* s) { + std::vector v; + while (*s) { + while (*s == ',' || *s == ' ') ++s; + if (!*s) break; + char* e = nullptr; + const long x = std::strtol(s, &e, 10); + if (e == s) break; + v.push_back((int32_t) x); + s = e; + } + return v; +} + +bool is_eos(int t) { return t == 248044 || t == 248046; } + +// ------------------------------------------------------------------------------------------------ serve +int serve(Engine& E) { + std::printf("READY %d stop\n", E.ctx); + std::fflush(stdout); + std::mutex mu; + std::condition_variable cv; + std::deque lines; + bool eof = false; + std::atomic stop{false}; + std::thread reader([&] { + std::string l; + while (std::getline(std::cin, l)) { + if (!l.empty() && l.back() == '\r') l.pop_back(); + if (l == "STOP") { stop.store(true); continue; } + std::lock_guard lk(mu); + lines.push_back(l); + cv.notify_one(); + } + std::lock_guard lk(mu); + eof = true; + cv.notify_one(); + }); + reader.detach(); + std::vector live; // the tokens whose state the engine holds (cell i = live[i]) + std::vector lg; + for (;;) { + std::string line; + { + std::unique_lock lk(mu); + cv.wait(lk, [&] { return eof || !lines.empty(); }); + if (lines.empty()) return 0; + line = lines.front(); + lines.pop_front(); + } + if (line.empty()) continue; + if (line.rfind("GEN ", 0) != 0) { + std::printf("ERR expected: GEN [key=value ...] \n"); + std::fflush(stdout); + continue; + } + char* p = nullptr; + const long long max_new = std::strtoll(line.c_str() + 4, &p, 10); + Sampling smp; + for (;;) { + while (*p == ' ') ++p; + const char* st0 = p; + while (*p && *p != ' ') ++p; + const std::string tk(st0, (size_t) (p - st0)); + const size_t eq = tk.find('='); + if (tk.empty() || eq == std::string::npos) { p = const_cast(st0); break; } + const std::string key = tk.substr(0, eq); + const char* v = tk.c_str() + eq + 1; + if (key == "temperature") smp.temperature = std::strtof(v, nullptr); + else if (key == "top_p") smp.top_p = std::strtof(v, nullptr); + else if (key == "top_k") smp.top_k = std::atoi(v); + else if (key == "min_p") smp.min_p = std::strtof(v, nullptr); + else if (key == "penalty_last_n") smp.last_n = std::atoi(v); + else if (key == "penalty_repeat") smp.repeat = std::strtof(v, nullptr); + else if (key == "penalty_freq") smp.freq = std::strtof(v, nullptr); + else if (key == "penalty_present") smp.present = std::strtof(v, nullptr); + else if (key == "seed") smp.seed = std::strtoull(v, nullptr, 10); + } + const std::vector ids = parse_ids(p); + if (max_new < 1 || ids.empty()) { + std::printf("ERR bad request: max_new or the ids\n"); + std::fflush(stdout); + continue; + } + if ((int64_t) ids.size() + max_new > E.ctx) { + std::printf("ERR prompt (%zu tokens) + max_new (%lld) exceeds the context (%d)\n", ids.size(), max_new, E.ctx); + std::fflush(stdout); + continue; + } + bool bad = false; + for (int32_t t : ids) bad |= t < 0 || t >= (int32_t) E.m->g.n_vocab; + if (bad) { std::printf("ERR a token id is outside the vocabulary\n"); std::fflush(stdout); continue; } + stop.store(false); + // the held state continues when the request extends it (the recurrent state cannot step back) + size_t reuse = 0; + if (live.size() < ids.size() && std::equal(live.begin(), live.end(), ids.begin())) reuse = live.size(); + else { + E.reset(); + live.clear(); + } + const auto t0 = Clock::now(); + const int64_t fresh = (int64_t) (ids.size() - reuse); + E.process(ids.data() + reuse, fresh, [&](int64_t done) { + std::printf("PP %lld %lld %.0f %.1f\n", (long long) done, (long long) fresh, ms_since(t0), + (double) done / std::max(1e-9, ms_since(t0) / 1000.0)); + std::fflush(stdout); + }); + live.insert(live.end(), ids.begin() + (long) reuse, ids.end()); + const double prompt_ms = ms_since(t0); + std::mt19937_64 rng(smp.seed); + std::vector hist = ids; + const auto d0 = Clock::now(); + long long produced = 0, offered = 0, accepted = 0; + const char* finish = "length"; + // greedy requests with the MTP block: speculative steps of mtp_d drafts (verified, so the text is the greedy + // text); sampled ones one token at a time + const bool spec = E.mtp_d > 0 && !smp.needs_logits(); + std::vector fix, drafts; + int32_t picks[16]; + int nx = smp.needs_logits() ? -1 : E.greedy(); + bool done = false; + while (!done) { + if (smp.needs_logits()) { + E.host_logits(lg); + nx = sample(lg, smp, hist, rng); + } + auto emit = [&](int t) { // false: the answer ends here + std::printf("T %d\n", t); + std::fflush(stdout); + ++produced; + hist.push_back(t); + if (is_eos(t)) { finish = "stop"; return false; } + if (produced >= max_new) return false; + if (stop.load()) { finish = "cancel"; return false; } + return true; + }; + if (!emit(nx)) break; + if (spec && E.pos + E.mtp_d + 1 <= E.ctx) { + const int a = E.spec_step(nx, fix, E.mtp_d, drafts, picks); + offered += E.mtp_d; + accepted += a; + live.push_back(nx); + fix.assign(drafts.begin(), drafts.begin() + a); + for (int i = 0; i < a; ++i) { + live.push_back(drafts[(size_t) i]); + if (!emit(drafts[(size_t) i])) { done = true; break; } + } + nx = picks[a]; + continue; + } + if (E.pos + 1 > E.ctx) break; + const int32_t one = nx; + E.process(&one, 1, [](int64_t) {}); + live.push_back(nx); + fix.clear(); + if (!smp.needs_logits()) nx = E.greedy(); + } + const double decode_ms = ms_since(d0); + std::printf("DONE %lld %zu %.1f %.1f %s %lld %lld %zu 0 0 0 0 0.0 %lld 0\n", produced, ids.size(), prompt_ms, + decode_ms, finish, accepted, offered, reuse, (long long) fresh); + std::fflush(stdout); + } +} + +} // namespace + +int strata::qwen35::run(int argc, char** argv) { + std::string model, tokens, force, dump_full; + int ctx = 32768, chunk = 0, n_gen = 64, bench_pp = 0, bench_tg = 0, mtp_d = 0, cpu_threads = 0, hybrid_rows = 128; + double expert_vram = -1.0; + bool warm = true; + int expert_slots = 0; + bool serve_mode = false, graph = true; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + auto next = [&]() -> std::string { + if (i + 1 >= argc) { std::fprintf(stderr, "strata-q36: %s needs a value\n", a.c_str()); std::exit(2); } + return argv[++i]; + }; + // strata's names where they mean the same thing (the family switch passes strata's command line on) + if (a == "--model" || a == "--native") model = next(); + else if (a == "--max-new") n_gen = std::atoi(next().c_str()); + else if (a == "--no-token-graph") graph = false; + else if (a == "--pool-workers") cpu_threads = std::atoi(next().c_str()); + else if (a == "--gpu") (void) next(); // applied by strata before the switch (CUDA/HIP_VISIBLE_DEVICES) + else if (a == "--greedy") {} // --tokens decodes greedily here anyway + else if (a == "--serve") serve_mode = true; + else if (a == "--max-context" || a == "--ctx") ctx = std::atoi(next().c_str()); + else if (a == "--chunk" || a == "--prefill") { const std::string v = next(); chunk = v == "auto" ? 0 : std::atoi(v.c_str()); } + else if (a == "--tokens") tokens = next(); + else if (a == "--n") n_gen = std::atoi(next().c_str()); + else if (a == "--force") force = next(); + else if (a == "--dump-full-logits") dump_full = next(); + else if (a == "--bench-pp") bench_pp = std::atoi(next().c_str()); + else if (a == "--bench-tg") bench_tg = std::atoi(next().c_str()); + else if (a == "--no-graph") graph = false; + else if (a == "--no-warmup") warm = false; + else if (a == "--mtp") { + // a number of drafts; Flash-Next's "--mtp " means nothing for this family + const std::string v = next(); + if (!v.empty() && std::isdigit((unsigned char) v[0])) mtp_d = std::atoi(v.c_str()); + else std::fprintf(stderr, "strata-q36: ignoring --mtp %s (this family's MTP is the GGUF's own block: --mtp N " + "drafts)\n", v.c_str()); + } + else if (a == "--expert-vram") expert_vram = std::atof(next().c_str()); // GiB for the routed experts + else if (a == "--cpu-threads") cpu_threads = std::atoi(next().c_str()); + else if (a == "--expert-slots") expert_slots = std::atoi(next().c_str()); + else if (a == "--hybrid-rows") hybrid_rows = std::atoi(next().c_str()); + else if (serve_mode && a.rfind("--", 0) == 0) { + // serve passes the config's args plus a few of its own: one this engine does not have is said and skipped + // (with its value), not fatal + const bool val = i + 1 < argc && std::string(argv[i + 1]).rfind("--", 0) != 0; + std::fprintf(stderr, "strata-q36: ignoring %s%s%s (not an option of this engine)\n", a.c_str(), + val ? " " : "", val ? argv[i + 1] : ""); + if (val) ++i; + } else { + std::fprintf(stderr, + "usage: strata-q36 --model GGUF [--max-context 32768] [--chunk 512] [--no-graph]\n" + " (--serve | --tokens IDS [--n 64] [--force IDS] [--dump-full-logits F] | --bench-pp N " + "--bench-tg N)\n"); + return 2; + } + } + if (model.empty()) { std::fprintf(stderr, "strata-q36: --model is required\n"); return 2; } +#if !defined(_WIN32) + setenv("CUDA_MODULE_LOADING", "EAGER", 0); // every kernel loaded with the context, not in the first prompt + setenv("STRATA_Q8_PACKED", "1", 0); // the packed Q8_0 decode copy unless STRATA_Q8_PACKED is set otherwise + setenv("STRATA_MMQ_KQ", "1", 0); // the K-quant MMQ prompt kernels (every expert of this family is a K-quant) +#else + if (std::getenv("STRATA_MMQ_KQ") == nullptr) _putenv_s("STRATA_MMQ_KQ", "1"); + if (std::getenv("CUDA_MODULE_LOADING") == nullptr) _putenv_s("CUDA_MODULE_LOADING", "EAGER"); +#endif + if (mtp_d < 0 || mtp_d > 7) { std::fprintf(stderr, "strata-q36: --mtp takes 0 .. 7 drafts\n"); return 2; } + if (chunk < 0 || chunk > 4096 || ctx < 256) { std::fprintf(stderr, "strata-q36: bad --chunk / --max-context\n"); return 2; } + Model m; + std::string err; + try { + if (!load(model, m, err, mtp_d > 0)) { std::fprintf(stderr, "strata-q36: %s\n", err.c_str()); return 1; } + } catch (const std::exception& e) { + std::fprintf(stderr, "strata-q36: %s\n", e.what()); + return 1; + } + Engine E; + E.use_graph = graph; + if (chunk == 0) { + // auto: 512 with every expert in VRAM; 2048 when they will not all fit (a prompt chunk streams every layer's + // experts over PCIe once, so a bigger chunk pays that once for more tokens) + size_t fr = 0, tot = 0, experts = 0; + CK(cudaMemGetInfo(&fr, &tot)); + for (const Layer& L : m.layers) experts += L.stride * (size_t) m.g.n_expert; + // (the MTP block's experts can go to the CPU, the packed Q8_0 copies can be given back: see place_experts) + size_t packed = 0; + for (const auto& pk : m.packed) packed += std::get<2>(pk); + fr += packed; + // the engine's buffers at 512 (~1.1 GiB on gfx1201 at 8K, less the scores buffer's shrink) + the small reserve + const double want = (double) experts + 1.1 * (1ull << 30); + const bool fits = expert_slots <= 0 && (expert_vram < 0 ? want <= (double) fr + : (double) experts <= expert_vram * (double) (1ull << 30)); + chunk = fits ? 512 : 2048; + if (std::getenv("STRATA_Q36_PLACE_DEBUG")) + std::fprintf(stderr, "strata-q36: chunk rule: free %.2f GiB (with %.2f packed), main experts %.2f GiB\n", + fr / 1073741824.0, packed / 1073741824.0, experts / 1073741824.0); + } + E.init(m, ctx, chunk); + if (!place_experts(m, E, expert_vram, cpu_threads, hybrid_rows, expert_slots, err)) { + std::fprintf(stderr, "strata-q36: %s\n", err.c_str()); + return 1; + } + struct Report { + Engine& E; + ~Report() { + if (!E.m->hybrid) return; + const long long n = E.hy_cpu + E.hy_gpu; + std::fprintf(stderr, "strata-q36: hybrid experts: %lld of %lld batch entries on the GPU (%.1f%%), %lld on the " + "CPU pool in %.0f ms, %lld slot replacements\n", E.hy_gpu, n, n ? 100.0 * E.hy_gpu / n : 0.0, + E.hy_cpu, E.hy_cpu_ms, E.hy_swaps); + } + } report{E}; + E.reset(); + E.mtp_d = m.has_mtp ? mtp_d : 0; + if (warm) E.warmup(); + if (serve_mode) return serve(E); + if (bench_pp > 0 || bench_tg > 0) { + // llama-bench's shapes: a prompt of bench_pp tokens from a fresh state, then bench_tg tokens one at a time + std::vector toks((size_t) std::max(bench_pp, 1)); + std::mt19937 rng(1234); + for (auto& t : toks) t = (int32_t) (rng() % 200000u); + for (int rep = 0; rep < 3; ++rep) { + E.reset(); + const auto t0 = Clock::now(); + E.process(toks.data(), (int64_t) toks.size(), [](int64_t) {}); + CK(cudaStreamSynchronize(E.st)); + const double pp_ms = ms_since(t0); + const auto t1 = Clock::now(); + int nx = E.greedy(); + for (int i = 0; i < bench_tg; ++i) { + const int32_t one = nx; + E.process(&one, 1, [](int64_t) {}); + nx = E.greedy(); + } + const double tg_ms = ms_since(t1); + std::printf("bench %d: pp%d %.1f tok/s, tg%d %.1f tok/s\n", rep, (int) toks.size(), + (double) toks.size() / (pp_ms / 1000.0), bench_tg, + bench_tg > 0 ? (double) bench_tg / (tg_ms / 1000.0) : 0.0); + std::fflush(stdout); + } + return 0; + } + const std::vector prompt = parse_ids(tokens.c_str()), forced = parse_ids(force.c_str()); + if (prompt.empty()) { std::fprintf(stderr, "strata-q36: --tokens, --serve or --bench-pp is required\n"); return 2; } + if (!forced.empty()) n_gen = (int) forced.size() + 1; + FILE* ff = dump_full.empty() ? nullptr : std::fopen(dump_full.c_str(), "wb"); + std::vector lg; + std::vector gen; + const auto t0 = Clock::now(); + E.process(prompt.data(), (int64_t) prompt.size(), [](int64_t) {}); + const double pp_ms = ms_since(t0); + const auto t1 = Clock::now(); + if (E.mtp_d > 0 && forced.empty() && !ff) { + long long offered = 0, accepted = 0; + std::vector fix, drafts; + int32_t picks[16]; + int nx = E.greedy(); + while ((int) gen.size() < n_gen) { + gen.push_back(nx); + if ((int) gen.size() >= n_gen) break; + const int a = E.spec_step(nx, fix, E.mtp_d, drafts, picks); + offered += E.mtp_d; + accepted += a; + fix.assign(drafts.begin(), drafts.begin() + a); + for (int i = 0; i < a && (int) gen.size() < n_gen; ++i) gen.push_back(drafts[(size_t) i]); + nx = picks[a]; + } + gen.resize((size_t) n_gen); + std::printf("gen:"); + for (int t : gen) std::printf(" %d", t); + std::printf("\n"); + std::fprintf(stderr, "strata-q36: prompt %zu tokens in %.1f ms, %zu generated in %.1f ms (%.1f tok/s), MTP %d drafts: " + "%lld of %lld accepted (%.0f%%)\n", prompt.size(), pp_ms, gen.size(), ms_since(t1), + gen.size() / (ms_since(t1) / 1000.0), E.mtp_d, accepted, offered, + offered ? 100.0 * accepted / offered : 0.0); + return 0; + } + for (int i = 0; i < n_gen; ++i) { + const int a = E.greedy(); + gen.push_back(a); + if (ff) { + E.host_logits(lg); + std::fwrite(lg.data(), 4, lg.size(), ff); + } + if (i + 1 == n_gen) break; + const int32_t nx = i < (int) forced.size() ? forced[(size_t) i] : a; + E.process(&nx, 1, [](int64_t) {}); + } + if (ff) std::fclose(ff); + std::printf("gen:"); + for (int t : gen) std::printf(" %d", t); + std::printf("\n"); + std::fprintf(stderr, "strata-q36: prompt %zu tokens in %.1f ms (%.1f tok/s), %zu generated in %.1f ms (%.1f tok/s)\n", + prompt.size(), pp_ms, prompt.size() / (pp_ms / 1000.0), gen.size(), ms_since(t1), + gen.size() / (ms_since(t1) / 1000.0)); + return 0; +} diff --git a/src/qwen35/q36_main.cpp b/src/qwen35/q36_main.cpp new file mode 100644 index 00000000..63d009f8 --- /dev/null +++ b/src/qwen35/q36_main.cpp @@ -0,0 +1,5 @@ +// src/qwen35/q36_main.cpp - strata-q36: the Qwen3.6 engine path on its own (the same entry point `strata` switches +// to for a qwen35moe model). +#include "strata/qwen35/engine.hpp" + +int main(int argc, char** argv) { return strata::qwen35::run(argc, argv); } diff --git a/src/qwen35/q36ref.cu b/src/qwen35/q36ref.cu new file mode 100644 index 00000000..8ef9b4b2 --- /dev/null +++ b/src/qwen35/q36ref.cu @@ -0,0 +1,832 @@ +// src/qwen35/q36ref.cu - NEW-MODELS-PLAN.md phase T1: the reference path for Qwen3.6-35B-A3B (GGUF architecture +// qwen35moe), exactness first. One GPU, the whole model resident in VRAM (UD-Q4_K_XL: 21.3 GiB on a 32 GB card), +// one token at a time (the prompt too), fp32 activations, every weight read in its GGUF form. Two kernel sets: +// --kernels plain, this file's own plain kernels (the reference), and --kernels strata (default), Strata's native +// MMVQ for the quantized matmuls (dense and routed experts) and its fused GDN step with the SiLU-gated norm - the +// engine's kernels on the new family's shapes. No expert cache, no MTP, no graphs: checked against llama.cpp +// (per-layer hidden states, greedy tokens, teacher-forced KL: tools/qwen35/). +// +// The forward pass, as llama.cpp's src/models/qwen35moe.cpp builds it: +// x = token_embd[tok] +// per layer l < 40: h = rms(x) * attn_norm +// GDN (l % 4 != 3): qkv = W_qkv h (8192), z = W_gate h (4096), b = sigmoid(W_beta h), a = W_alpha h (32 each) +// c = silu(causal conv4(qkv)); q, k = l2norm(c[0:2048]), l2norm(c[2048:4096]) (16 heads), v = c[4096:] (32) +// g = softplus(a + dt_bias) * ssm_a; per V head h (K head h % 16): S = S * exp(g_h); +// d = (v - S k) * b_h; S += d k^T; o = S q / sqrt(128); o = rms(o) * ssm_norm * silu(z_h) +// y = W_ssm_out o +// attention (l % 4 == 3): attn_q -> per head [q 256 | gate 256]; q, k = rms(.) * q_norm/k_norm; NEOX RoPE over the +// first 64 dims (base 1e7; text positions: the M-RoPE sections all carry the same position); GQA 16 / 2; +// y = W_o (softmax(q k^T / 16) v * sigmoid(gate)) +// x += y; h2 = rms(x) * post_attention_norm +// MoE: p = softmax(W_router h2) over 256, top-8, renormalised; sum_e p_e W_down_e (silu(W_gate_e h2) * W_up_e h2) +// + sigmoid(w_shexp_gate . h2) * W_down_s (silu(W_gate_s h2) * W_up_s h2); x += moe +// logits = W_output (rms(x) * output_norm) +// +// Usage: strata-q36ref --model Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf --tokens 248045,846,198,... [--n 64] [--ctx 4096] +// [--dump-layers FILE] [--dump-logits FILE] [--act q8|f32] [--kernels strata|plain] +// [--force IDS] [--dump-full-logits F] +// prints the greedy ids ("gen: id id ..."); --dump-layers writes every processed position's 40 layer outputs (f32, +// [pos][layer][2048]); --dump-logits writes each greedy step's top-2 (id, logit) pairs for the near-tie report; +// --force feeds the given continuation instead of the greedy ids and --dump-full-logits writes every step's +// logits (f32, [step][vocab]) for the teacher-forced KL check (tools/qwen35/kl.py). +#include "strata/artifact/gguf_reader.hpp" +#include "strata/core/family_layout.hpp" +#include "strata/kernels/fused_gdn.hpp" +#include "strata/kernels/native_mmvq.hpp" +#include "strata/kernels/native_router.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +#define CK(x) \ + do { \ + cudaError_t e_ = (x); \ + if (e_ != cudaSuccess) { \ + std::fprintf(stderr, "q36ref: %s failed: %s (%s:%d)\n", #x, cudaGetErrorString(e_), __FILE__, __LINE__); \ + std::exit(1); \ + } \ + } while (0) + +// ------------------------------------------------------------------------------------------------ dequantisation +// ggml's block formats, 32 values at a time ("chunk" c of a row). The formulas are ggml-quants.c's dequantize_row_*. +enum : int { T_F32 = 0, T_F16 = 1, T_Q8_0 = 8, T_Q4_K = 12, T_Q5_K = 13, T_Q6_K = 14, T_BF16 = 30 }; + +__device__ __forceinline__ float h2f(uint16_t h) { + const uint32_t s = (uint32_t) (h >> 15) << 31, e = (h >> 10) & 0x1f, m = h & 0x3ff; + if (e == 0) { + const float v = ldexpf((float) m, -24); + return s ? -v : v; + } + const uint32_t f = e == 31 ? (s | 0x7f800000u | (m << 13)) : (s | ((e + 112) << 23) | (m << 13)); + return __uint_as_float(f); +} +__device__ __forceinline__ uint16_t ld16(const uint8_t* p) { return (uint16_t) (p[0] | (p[1] << 8)); } + +__device__ __forceinline__ void scale_min_k4(int j, const uint8_t* q, int& d, int& m) { + if (j < 4) { + d = q[j] & 63; + m = q[j + 4] & 63; + } else { + d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4); + m = (q[j + 4] >> 4) | ((q[j] >> 6) << 4); + } +} + +/// The 32 values of chunk `c` of one row (`row` = the row's first byte). +template __device__ void deq32(const uint8_t* row, int c, float* out) { + if constexpr (T == T_F32) { + const float* r = (const float*) row + 32 * c; + for (int l = 0; l < 32; ++l) out[l] = r[l]; + } else if constexpr (T == T_F16) { + const uint8_t* r = row + 64 * c; + for (int l = 0; l < 32; ++l) out[l] = h2f(ld16(r + 2 * l)); + } else if constexpr (T == T_BF16) { + const uint8_t* r = row + 64 * c; + for (int l = 0; l < 32; ++l) out[l] = __uint_as_float((uint32_t) ld16(r + 2 * l) << 16); + } else if constexpr (T == T_Q8_0) { + const uint8_t* b = row + 34 * c; + const float d = h2f(ld16(b)); + const int8_t* q = (const int8_t*) (b + 2); + for (int l = 0; l < 32; ++l) out[l] = d * (float) q[l]; + } else if constexpr (T == T_Q4_K) { + const uint8_t* b = row + 144 * (c >> 3); + const int j = c & 7; + const float d = h2f(ld16(b)), dmin = h2f(ld16(b + 2)); + int sc, m; + scale_min_k4(j, b + 4, sc, m); + const float d1 = d * (float) sc, m1 = dmin * (float) m; + const uint8_t* qs = b + 16 + 32 * (j >> 1); + for (int l = 0; l < 32; ++l) out[l] = d1 * (float) ((j & 1) ? (qs[l] >> 4) : (qs[l] & 0xF)) - m1; + } else if constexpr (T == T_Q5_K) { + const uint8_t* b = row + 176 * (c >> 3); + const int j = c & 7; + const float d = h2f(ld16(b)), dmin = h2f(ld16(b + 2)); + int sc, m; + scale_min_k4(j, b + 4, sc, m); + const float d1 = d * (float) sc, m1 = dmin * (float) m; + const uint8_t* qh = b + 16; + const uint8_t* qs = b + 48 + 32 * (j >> 1); + for (int l = 0; l < 32; ++l) { + const int q = ((j & 1) ? (qs[l] >> 4) : (qs[l] & 0xF)) + ((qh[l] >> j) & 1 ? 16 : 0); + out[l] = d1 * (float) q - m1; + } + } else if constexpr (T == T_Q6_K) { + const uint8_t* b = row + 210 * (c >> 3); + const int j = c & 7, n = j >> 2, r = j & 3; + const uint8_t* ql = b + 64 * n; + const uint8_t* qh = b + 128 + 32 * n; + const int8_t* sc = (const int8_t*) (b + 192) + 8 * n; + const float d = h2f(ld16(b + 208)); + for (int l = 0; l < 32; ++l) { + const int is = l / 16; + int q; + if (r == 0) q = (ql[l] & 0xF) | (((qh[l] >> 0) & 3) << 4); + else if (r == 1) q = (ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4); + else if (r == 2) q = (ql[l] >> 4) | (((qh[l] >> 4) & 3) << 4); + else q = (ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4); + out[l] = d * (float) sc[is + 2 * r] * (float) (q - 32); + } + } +} + +__device__ float block_sum(float v, float* sh) { + sh[threadIdx.x] = v; + __syncthreads(); + for (int s = blockDim.x / 2; s > 0; s >>= 1) { + if ((int) threadIdx.x < s) sh[threadIdx.x] += sh[threadIdx.x + s]; + __syncthreads(); + } + const float r = sh[0]; + __syncthreads(); + return r; +} + +constexpr int kThreads = 128; + +/// y[sel][o] = W_e[o] . x[sel] for row o (grid.x), selection `sel` (grid.y): expert ids[sel] (or 0 without ids), +/// x of selection sel at x + sel * x_stride. `beta` != 0 adds into y. +template +__global__ void k_gemv(const uint8_t* W, size_t row_bytes, size_t expert_bytes, const int* ids, int n_in, const float* x, + size_t x_stride, float* y, int n_out) { + __shared__ float sh[kThreads]; + const int o = blockIdx.x, sel = blockIdx.y; + const int e = ids ? ids[sel] : 0; + const uint8_t* row = W + (size_t) e * expert_bytes + (size_t) o * row_bytes; + const float* xs = x + (size_t) sel * x_stride; + float acc = 0.f, v[32]; + for (int c = threadIdx.x; c < n_in / 32; c += blockDim.x) { + deq32(row, c, v); + const float* xc = xs + 32 * c; + for (int l = 0; l < 32; ++l) acc += v[l] * xc[l]; + } + acc = block_sum(acc, sh); + if (threadIdx.x == 0) y[(size_t) sel * n_out + o] = acc; +} + +template __global__ void k_row(const uint8_t* W, size_t row_bytes, int row, int n, float* out) { + const uint8_t* r = W + (size_t) row * row_bytes; + for (int c = blockIdx.x * blockDim.x + threadIdx.x; c < n / 32; c += gridDim.x * blockDim.x) deq32(r, c, out + 32 * c); +} + +/// y = x / sqrt(mean(x^2) + eps) * w, per group of n (grid = groups); w (length n) may be null. +__global__ void k_rms(const float* x, const float* w, float* y, int n, float eps) { + __shared__ float sh[kThreads]; + const float* xg = x + (size_t) blockIdx.x * n; + float* yg = y + (size_t) blockIdx.x * n; + float s = 0.f; + for (int i = threadIdx.x; i < n; i += blockDim.x) s += xg[i] * xg[i]; + s = block_sum(s, sh); + const float r = 1.0f / sqrtf(s / (float) n + eps); + for (int i = threadIdx.x; i < n; i += blockDim.x) yg[i] = xg[i] * r * (w ? w[i] : 1.0f); +} + +__device__ __forceinline__ float silu(float v) { return v / (1.0f + expf(-v)); } +__device__ __forceinline__ float sigm(float v) { return 1.0f / (1.0f + expf(-v)); } +__device__ __forceinline__ float softplus(float v) { return v > 20.f ? v : log1pf(expf(v)); } + +/// The causal 4-tap conv over the 8192 qkv channels with its 3-input state, then SiLU; the state moves by one. +__global__ void k_conv(const float* qkv, float* state, const float* w, float* out, int C, int K) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= C) return; + float acc = 0.f; + for (int k = 0; k < K - 1; ++k) acc += state[(size_t) k * C + c] * w[(size_t) c * K + k]; + acc += qkv[c] * w[(size_t) c * K + K - 1]; + for (int k = 0; k < K - 2; ++k) state[(size_t) k * C + c] = state[(size_t) (k + 1) * C + c]; + state[(size_t) (K - 2) * C + c] = qkv[c]; + out[c] = silu(acc); +} + +/// One gated delta-rule step per V head (grid = HV, block = D = 128): S[i][j] row i owned by thread i. +__global__ void k_gdn(const float* conv, const float* alpha, const float* dt_bias, const float* ssm_a, + const float* beta_raw, float* S, float* out, int HK, int /*HV: the grid*/, int D, float eps) { + extern __shared__ float sm[]; + float* q = sm; + float* k = sm + D; + float* red = sm + 2 * D; + const int h = blockIdx.x, kh = h % HK, i = threadIdx.x; + const float qi = conv[kh * D + i], ki = conv[HK * D + kh * D + i], vi = conv[2 * HK * D + h * D + i]; + const float qn = block_sum(qi * qi, red), kn = block_sum(ki * ki, red); + q[i] = qi / sqrtf(qn + eps) / sqrtf((float) D); + k[i] = ki / sqrtf(kn + eps); + __syncthreads(); + const float g = expf(softplus(alpha[h] + dt_bias[h]) * ssm_a[h]); + const float b = sigm(beta_raw[h]); + float* Si = S + ((size_t) h * D + i) * D; + float sk = 0.f; + for (int j = 0; j < D; ++j) { + Si[j] *= g; + sk += Si[j] * k[j]; + } + const float d = (vi - sk) * b; + float o = 0.f; + for (int j = 0; j < D; ++j) { + Si[j] += d * k[j]; + o += Si[j] * q[j]; + } + out[h * D + i] = o; +} + +/// The fused path's gate and beta, in place: alpha -> softplus(alpha + dt) * ssm_a (exp'd by the step), beta -> sigmoid. +__global__ void k_gdn_gb(float* alpha, const float* dt_bias, const float* ssm_a, float* beta, int HV) { + const int h = threadIdx.x; + if (h >= HV) return; + alpha[h] = softplus(alpha[h] + dt_bias[h]) * ssm_a[h]; + beta[h] = sigm(beta[h]); +} + +/// o = rms(o) * w * silu(z), per V head (grid = HV, block = D). +__global__ void k_gated_norm(float* o, const float* w, const float* z, int D, float eps) { + __shared__ float sh[kThreads]; + float* oh = o + (size_t) blockIdx.x * D; + const float v = oh[threadIdx.x]; + const float s = block_sum(v * v, sh); + oh[threadIdx.x] = v / sqrtf(s / (float) D + eps) * w[threadIdx.x] * silu(z[blockIdx.x * D + threadIdx.x]); +} + +/// The attention layer's per-token preparation: q (from the [q | gate] pairs) and k RMS-normed per head with their +/// weights, NEOX RoPE over the first n_rot dims, k and v appended to the cache at `pos`, the gate kept. +__global__ void k_attn_prep(const float* qg, const float* kx, const float* vx, const float* qw, const float* kw, + float* q, float* gate, float* kc, float* vc, int H, int /*HKV: the grid*/, int D, int n_rot, int pos, + int ctx, float base, float eps) { + __shared__ float sh[kThreads]; + __shared__ float buf[512]; + const int head = blockIdx.x; // 0..H-1: query heads, H..H+HKV-1: key heads + const bool isq = head < H; + const float* src = isq ? qg + (size_t) head * 2 * D : kx + (size_t) (head - H) * D; + float s = 0.f; + for (int i = threadIdx.x; i < D; i += blockDim.x) s += src[i] * src[i]; + s = block_sum(s, sh); + const float r = 1.0f / sqrtf(s / (float) D + eps); + for (int i = threadIdx.x; i < D; i += blockDim.x) buf[i] = src[i] * r * (isq ? qw[i] : kw[i]); + __syncthreads(); + float* dst = isq ? q + (size_t) head * D : kc + ((size_t) (head - H) * ctx + pos) * D; + const int half = n_rot / 2; + for (int i = threadIdx.x; i < D; i += blockDim.x) { + float v = buf[i]; + if (i < n_rot) { + const int p = i < half ? i : i - half; + const float theta = (float) pos * powf(base, -2.0f * (float) p / (float) n_rot); + const float cs = cosf(theta), sn = sinf(theta); + v = i < half ? buf[i] * cs - buf[i + half] * sn : buf[i - half] * sn + buf[i] * cs; + } + dst[i] = v; + } + if (isq) + for (int i = threadIdx.x; i < D; i += blockDim.x) gate[(size_t) head * D + i] = qg[(size_t) head * 2 * D + D + i]; + else + for (int i = threadIdx.x; i < D; i += blockDim.x) + vc[((size_t) (head - H) * ctx + pos) * D + i] = vx[(size_t) (head - H) * D + i]; +} + +/// softmax(q k^T * scale) v for one query head per block (GQA: KV head = head / (H / HKV)), times sigmoid(gate). +__global__ void k_attn(const float* q, const float* kc, const float* vc, const float* gate, float* out, int H, int HKV, + int D, int n_pos, int ctx, float scale) { + extern __shared__ float sc[]; + __shared__ float sh[kThreads]; + const int h = blockIdx.x, kvh = h / (H / HKV); + const float* qh = q + (size_t) h * D; + for (int p = threadIdx.x; p < n_pos; p += blockDim.x) { + const float* kp = kc + ((size_t) kvh * ctx + p) * D; + float s = 0.f; + for (int i = 0; i < D; ++i) s += qh[i] * kp[i]; + sc[p] = s * scale; + } + __syncthreads(); + float mx = -INFINITY; + for (int p = threadIdx.x; p < n_pos; p += blockDim.x) mx = fmaxf(mx, sc[p]); + sh[threadIdx.x] = mx; + __syncthreads(); + for (int s = blockDim.x / 2; s > 0; s >>= 1) { + if ((int) threadIdx.x < s) sh[threadIdx.x] = fmaxf(sh[threadIdx.x], sh[threadIdx.x + s]); + __syncthreads(); + } + mx = sh[0]; + __syncthreads(); + float sum = 0.f; + for (int p = threadIdx.x; p < n_pos; p += blockDim.x) { + sc[p] = expf(sc[p] - mx); + sum += sc[p]; + } + sum = block_sum(sum, sh); + for (int i = threadIdx.x; i < D; i += blockDim.x) { + float acc = 0.f; + for (int p = 0; p < n_pos; ++p) acc += sc[p] * vc[((size_t) kvh * ctx + p) * D + i]; + out[(size_t) h * D + i] = acc / sum * sigm(gate[(size_t) h * D + i]); + } +} + +__global__ void k_swiglu(const float* g, const float* u, float* h, int n) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) h[i] = silu(g[i]) * u[i]; +} +__global__ void k_add(float* x, const float* y, int n) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) x[i] += y[i]; +} +/// x += sum_s w[s] * y[s] (the routed experts), + sigmoid(gs) * ys (the shared expert) +__global__ void k_moe_sum(float* x, const float* y, const float* w, int k, const float* ys, const float* gs, int n) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + float acc = 0.f; + for (int s = 0; s < k; ++s) acc += w[s] * y[(size_t) s * n + i]; + x[i] += acc + sigm(gs[0]) * ys[i]; +} + +// ------------------------------------------------------------------------------------------------ the model +struct Tensor { + const uint8_t* d = nullptr; // device + int type = -1; + std::vector shape; + size_t row_bytes = 0; +}; + +size_t row_bytes_of(int type, int64_t n) { + int be = 0, bb = 0; + if (!strata::block_geometry((uint32_t) type, be, bb)) return 0; + return (size_t) (n / be) * (size_t) bb; +} + +template +void gemv_t(const Tensor& w, size_t expert_bytes, const int* ids, int n_sel, const float* x, size_t x_stride, float* y) { + const int n_in = (int) w.shape[0], n_out = (int) w.shape[1]; + k_gemv<<>>(w.d, w.row_bytes, expert_bytes, ids, n_in, x, x_stride, y, n_out); +} + +/// llama.cpp's GPU matmuls on quantized weights (MMVQ for one token, MMQ for a batch) read the activations as q8_1: +/// per 32 values d = amax / 127, q = round(x / d). --act q8 (the default) gives this path the same rounding, so +/// its numbers follow llama.cpp's instead of drifting from them by the activation rounding; --act f32 reads them as +/// they are. `x` (n_sel vectors of n, `stride` apart) -> `out` (packed, n apart). +__global__ void k_act_q8(const float* x, size_t stride, int n, float* out) { + const int sel = blockIdx.y, blk = blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32, l = threadIdx.x % 32; + if (blk * 32 >= n) return; + const float v = x[(size_t) sel * stride + blk * 32 + l]; + __shared__ float am[kThreads]; + am[threadIdx.x] = fabsf(v); + __syncthreads(); + const int base = threadIdx.x - l; + float amax = 0.f; + for (int i = 0; i < 32; ++i) amax = fmaxf(amax, am[base + i]); + const float d = amax / 127.0f; + const float q = amax == 0.0f ? 0.0f : roundf(v / d); + out[(size_t) sel * n + blk * 32 + l] = q * d; +} + +bool g_act_q8 = true; +float* g_act_buf = nullptr; +constexpr size_t kActBuf = 1 << 16; + +// --kernels strata (the default): the quantized matmuls run on Strata's native MMVQ (llama.cpp's pinned MMVQ: q8_1 +// activations, one launch per routed expert) and the GDN step on Strata's fused kernels (conv + SiLU + L2, then the +// step with the SiLU-gated norm); --kernels plain keeps every op on this file's own kernels (the reference). The +// Strata kernels run on a blocking stream, so they and the null-stream work here stay in order. +bool g_strata = true; +cudaStream_t g_st = nullptr; +void* g_q8 = nullptr; +std::vector g_ids_host; // the routed experts of the current layer (the native expert path launches per id) + +void gemv(const Tensor& w, const float* x, float* y, const int* ids = nullptr, int n_sel = 1, size_t x_stride = 0) { + const size_t eb = w.shape.size() == 3 ? w.row_bytes * (size_t) w.shape[1] : 0; + const bool quant = w.type == T_Q8_0 || w.type == T_Q4_K || w.type == T_Q5_K || w.type == T_Q6_K; + if (quant && g_strata) { + const int n_in = (int) w.shape[0], n_out = (int) w.shape[1], cols = x_stride ? n_sel : 1; + if (x_stride && x_stride != (size_t) n_in) { + std::fprintf(stderr, "q36ref: the native path wants contiguous input columns\n"); + std::exit(1); + } + strata::kernels::native_quantize_q8_1(x, g_q8, n_in, cols, g_st); + const size_t qb = strata::kernels::native_q8_1_bytes(n_in, 1); + for (int sel = 0; sel < n_sel; ++sel) { + const uint8_t* we = w.d + (ids ? (size_t) g_ids_host[(size_t) sel] * eb : 0); + strata::kernels::native_mmvq(w.type, we, (const char*) g_q8 + (x_stride ? (size_t) sel * qb : 0), + y + (size_t) sel * n_out, n_in, n_out, 1, g_st); + } + CK(cudaGetLastError()); + return; + } + if (quant && g_act_q8) { + const int n = (int) w.shape[0], sel = x_stride ? n_sel : 1; + if ((size_t) n * sel > kActBuf) { + std::fprintf(stderr, "q36ref: activation scratch too small\n"); + std::exit(1); + } + k_act_q8<<>>(x, x_stride, n, g_act_buf); + x = g_act_buf; + x_stride = x_stride ? (size_t) n : 0; + } + switch (w.type) { + case T_F32: gemv_t(w, eb, ids, n_sel, x, x_stride, y); break; + case T_F16: gemv_t(w, eb, ids, n_sel, x, x_stride, y); break; + case T_BF16: gemv_t(w, eb, ids, n_sel, x, x_stride, y); break; + case T_Q8_0: gemv_t(w, eb, ids, n_sel, x, x_stride, y); break; + case T_Q4_K: gemv_t(w, eb, ids, n_sel, x, x_stride, y); break; + case T_Q5_K: gemv_t(w, eb, ids, n_sel, x, x_stride, y); break; + case T_Q6_K: gemv_t(w, eb, ids, n_sel, x, x_stride, y); break; + default: + std::fprintf(stderr, "q36ref: no kernel for ggml type %d (%s)\n", w.type, strata::ggml_type_name((uint32_t) w.type)); + std::exit(1); + } + CK(cudaGetLastError()); +} + +/// A 1-D tensor as f32 on the device (F32 as is, BF16 widened at load). +struct Model { + strata::core::ModelGeometry g; + int64_t top_k = 8; + float eps = 1e-6f, rope_base = 1e7f; + int n_rot = 64; + std::map t; + std::map f32; // the small vectors, f32 + + const Tensor& W(const std::string& n) const { + auto it = t.find(n); + if (it == t.end()) { + std::fprintf(stderr, "q36ref: missing tensor %s\n", n.c_str()); + std::exit(1); + } + return it->second; + } + const float* F(const std::string& n) const { + auto it = f32.find(n); + if (it == f32.end()) { + std::fprintf(stderr, "q36ref: missing vector %s\n", n.c_str()); + std::exit(1); + } + return it->second; + } +}; + +float h2f_host(uint16_t h) { + const uint32_t s = (uint32_t) (h >> 15) << 31, e = (h >> 10) & 0x1f, m = h & 0x3ff; + if (e == 0) return (s ? -1.f : 1.f) * std::ldexp((float) m, -24); + const uint32_t f = e == 31 ? (s | 0x7f800000u | (m << 13)) : (s | ((e + 112) << 23) | (m << 13)); + float r; + std::memcpy(&r, &f, 4); + return r; +} + +bool load(const std::string& path, Model& m, std::string& err) { + const auto t0 = std::chrono::steady_clock::now(); + const strata::GgufModel gm = strata::GgufModel::open(path); + if (!strata::core::geometry_from_gguf(gm.meta(), m.g, m.top_k, err)) return false; + if (m.g.family != strata::ModelFamily::Qwen35Moe) { + err = "this reference path is for Qwen3.6-35B-A3B (qwen35moe) only"; + return false; + } + size_t checked = 0; + if (!strata::core::check_gguf_layout(gm, m.g, err, &checked)) return false; + const std::string p = "qwen35moe."; + if (const strata::MetaValue* v = gm.meta().get(p + "attention.layer_norm_rms_epsilon")) m.eps = (float) v->num(); + if (const strata::MetaValue* v = gm.meta().get(p + "rope.freq_base")) m.rope_base = (float) v->num(); + if (const strata::MetaValue* v = gm.meta().get(p + "rope.dimension_count")) m.n_rot = (int) v->u; + uint64_t bytes = 0; + for (size_t s = 0; s < gm.size(); ++s) { + const strata::GgufFile& f = gm.shard(s); + for (const strata::TensorInfo& ti : f.tensors()) { + const uint64_t nb = strata::tensor_payload_bytes(ti); + const uint8_t* src = f.tensor_data(ti); + // the MTP block (blk.40) is not run by this path: not loaded + if (ti.name.rfind("blk." + std::to_string(m.g.n_layers) + ".", 0) == 0) continue; + const bool conv = ti.name.size() > 17 && ti.name.compare(ti.name.size() - 17, 17, "ssm_conv1d.weight") == 0; + if (ti.shape.size() == 1 || conv) { + // the small vectors (and the conv taps): f32 on the device + std::vector h(ti.elements()); + if (ti.type == T_F32) std::memcpy(h.data(), src, h.size() * 4); + else if (ti.type == T_BF16) + for (size_t i = 0; i < h.size(); ++i) { + const uint32_t u = (uint32_t) (src[2 * i] | (src[2 * i + 1] << 8)) << 16; + std::memcpy(&h[i], &u, 4); + } + else if (ti.type == T_F16) + for (size_t i = 0; i < h.size(); ++i) h[i] = h2f_host((uint16_t) (src[2 * i] | (src[2 * i + 1] << 8))); + else { + err = ti.name + ": a 1-D tensor of type " + ti.type_name(); + return false; + } + float* d = nullptr; + CK(cudaMalloc(&d, h.size() * 4)); + CK(cudaMemcpy(d, h.data(), h.size() * 4, cudaMemcpyHostToDevice)); + m.f32[ti.name] = d; + bytes += h.size() * 4; + continue; + } + Tensor w; + w.type = (int) ti.type; + for (uint64_t d : ti.shape) w.shape.push_back((int64_t) d); + w.row_bytes = row_bytes_of(w.type, w.shape[0]); + uint8_t* d = nullptr; + CK(cudaMalloc(&d, nb)); + CK(cudaMemcpy(d, src, nb, cudaMemcpyHostToDevice)); + w.d = d; + m.t[ti.name] = w; + bytes += nb; + } + } + std::fprintf(stderr, "q36ref: %s: %zu tensors (layout checked), %.2f GiB on the GPU in %.1f s\n", path.c_str(), + checked, (double) bytes / (1 << 30), + std::chrono::duration(std::chrono::steady_clock::now() - t0).count()); + return true; +} + +struct State { + int ctx = 4096, pos = 0; + // scratch + float *x, *h, *y, *qkv, *z, *alpha, *beta, *conv_out, *gdn_out, *qg, *k, *v, *q, *gate, *att, *router, *eg, *eu, *eh, + *ey, *sg, *su, *sh, *sy, *sgate, *wts, *logits; + int* ids; + std::vector conv_state, S, kc, vc; // per layer (GDN: conv + S; attention: K/V cache) +}; + +float* dalloc(size_t n) { + float* p = nullptr; + CK(cudaMalloc(&p, n * 4)); + CK(cudaMemset(p, 0, n * 4)); + return p; +} + +void init_state(const Model& m, State& s) { + const auto& g = m.g; + const int N = (int) g.n_embd, FF = (int) g.n_ff, K = (int) m.top_k; + s.x = dalloc(N); s.h = dalloc(N); s.y = dalloc(N); + s.qkv = dalloc(g.ssm_conv_channels); s.z = dalloc(g.ssm_value_dim); s.alpha = dalloc(g.ssm_v_heads); + s.beta = dalloc(g.ssm_v_heads); s.conv_out = dalloc(g.ssm_conv_channels); s.gdn_out = dalloc(g.ssm_value_dim); + s.qg = dalloc(2 * g.n_head * g.head_dim); s.k = dalloc(g.n_head_kv * g.head_dim); s.v = dalloc(g.n_head_kv * g.head_dim); + s.q = dalloc(g.n_head * g.head_dim); s.gate = dalloc(g.n_head * g.head_dim); s.att = dalloc(g.n_head * g.head_dim); + s.router = dalloc(g.n_expert); + s.eg = dalloc((size_t) K * FF); s.eu = dalloc((size_t) K * FF); s.eh = dalloc((size_t) K * FF); s.ey = dalloc((size_t) K * N); + s.sg = dalloc(g.n_ff_shexp); s.su = dalloc(g.n_ff_shexp); s.sh = dalloc(g.n_ff_shexp); s.sy = dalloc(N); s.sgate = dalloc(1); + s.wts = dalloc(K); + s.logits = dalloc(g.n_vocab); + CK(cudaMalloc(&s.ids, K * sizeof(int))); + g_act_buf = dalloc(kActBuf); + CK(cudaStreamCreate(&g_st)); // blocking: ordered with this file's null-stream launches and copies + CK(cudaMalloc(&g_q8, strata::kernels::native_q8_1_bytes((int) kActBuf, 1))); + for (int64_t l = 0; l < g.n_layers; ++l) { + if (strata::core::is_qsa_layer(g, l)) { + s.conv_state.push_back(nullptr); + s.S.push_back(nullptr); + s.kc.push_back(dalloc((size_t) g.n_head_kv * s.ctx * g.head_dim)); + s.vc.push_back(dalloc((size_t) g.n_head_kv * s.ctx * g.head_dim)); + } else { + s.conv_state.push_back(dalloc((size_t) (g.ssm_d_conv - 1) * g.ssm_conv_channels)); + s.S.push_back(dalloc((size_t) g.ssm_v_heads * g.ssm_state_size * g.ssm_state_size)); + s.kc.push_back(nullptr); + s.vc.push_back(nullptr); + } + } +} + +std::string L(int64_t l, const char* s) { return "blk." + std::to_string(l) + "." + s; } + +void embed(const Model& m, State& s, int tok) { + const Tensor& e = m.W("token_embd.weight"); + const int N = (int) m.g.n_embd; + switch (e.type) { + case T_Q8_0: k_row<<<4, 128>>>(e.d, e.row_bytes, tok, N, s.x); break; + case T_Q4_K: k_row<<<4, 128>>>(e.d, e.row_bytes, tok, N, s.x); break; + case T_Q6_K: k_row<<<4, 128>>>(e.d, e.row_bytes, tok, N, s.x); break; + case T_BF16: k_row<<<4, 128>>>(e.d, e.row_bytes, tok, N, s.x); break; + case T_F16: k_row<<<4, 128>>>(e.d, e.row_bytes, tok, N, s.x); break; + default: + std::fprintf(stderr, "q36ref: token_embd type %d has no row reader\n", e.type); + std::exit(1); + } + CK(cudaGetLastError()); +} + +/// One token through the model at position s.pos; the layer outputs into `layers` (host, n_layers x N) when given. +void forward(const Model& m, State& s, int tok, float* layers) { + const auto& g = m.g; + const int N = (int) g.n_embd, K = (int) m.top_k, FF = (int) g.n_ff, FS = (int) g.n_ff_shexp; + const int B = 256; + embed(m, s, tok); + for (int64_t l = 0; l < g.n_layers; ++l) { + k_rms<<<1, kThreads>>>(s.x, m.F(L(l, "attn_norm.weight")), s.h, N, m.eps); + if (!strata::core::is_qsa_layer(g, l)) { + const int HK = (int) g.ssm_k_heads, HV = (int) g.ssm_v_heads, D = (int) g.ssm_state_size; + const int C = (int) g.ssm_conv_channels; + gemv(m.W(L(l, "attn_qkv.weight")), s.h, s.qkv); + gemv(m.W(L(l, "attn_gate.weight")), s.h, s.z); + gemv(m.W(L(l, "ssm_beta.weight")), s.h, s.beta); + gemv(m.W(L(l, "ssm_alpha.weight")), s.h, s.alpha); + if (g_strata && D == 128 && g.ssm_d_conv == 4) { + // Strata's fused GDN (its own state layouts: conv history [channel][3], S [row][head][col]) + strata::kernels::fused_gdn_conv_l2(s.conv_state[l], s.qkv, m.F(L(l, "ssm_conv1d.weight")), s.conv_out, + C, 2 * HK, m.eps, g_st); + k_gdn_gb<<<1, 64, 0, g_st>>>(s.alpha, m.F(L(l, "ssm_dt.bias")), m.F(L(l, "ssm_a")), s.beta, HV); + strata::kernels::fused_gdn_step_norm_silu(s.S[l], s.conv_out, s.conv_out + HK * D, + s.conv_out + 2 * HK * D, s.alpha, s.beta, s.z, + m.F(L(l, "ssm_norm.weight")), m.eps, s.gdn_out, HK, HV, g_st); + } else { + k_conv<<<(C + B - 1) / B, B>>>(s.qkv, s.conv_state[l], m.F(L(l, "ssm_conv1d.weight")), s.conv_out, C, + (int) g.ssm_d_conv); + k_gdn<<>>(s.conv_out, s.alpha, m.F(L(l, "ssm_dt.bias")), + m.F(L(l, "ssm_a")), s.beta, s.S[l], s.gdn_out, HK, HV, D, + m.eps); + k_gated_norm<<>>(s.gdn_out, m.F(L(l, "ssm_norm.weight")), s.z, D, m.eps); + } + gemv(m.W(L(l, "ssm_out.weight")), s.gdn_out, s.y); + } else { + const int H = (int) g.n_head, HKV = (int) g.n_head_kv, D = (int) g.head_dim; + gemv(m.W(L(l, "attn_q.weight")), s.h, s.qg); + gemv(m.W(L(l, "attn_k.weight")), s.h, s.k); + gemv(m.W(L(l, "attn_v.weight")), s.h, s.v); + k_attn_prep<<>>(s.qg, s.k, s.v, m.F(L(l, "attn_q_norm.weight")), + m.F(L(l, "attn_k_norm.weight")), s.q, s.gate, s.kc[l], s.vc[l], H, HKV, D, + m.n_rot, s.pos, s.ctx, m.rope_base, m.eps); + k_attn<<>>(s.q, s.kc[l], s.vc[l], s.gate, s.att, H, HKV, D, + s.pos + 1, s.ctx, 1.0f / sqrtf((float) D)); + gemv(m.W(L(l, "attn_output.weight")), s.att, s.y); + } + CK(cudaGetLastError()); + k_add<<<(N + B - 1) / B, B>>>(s.x, s.y, N); + k_rms<<<1, kThreads>>>(s.x, m.F(L(l, "post_attention_norm.weight")), s.h, N, m.eps); + // router: softmax over every expert, top-k, renormalised (host side: exact and simple) + gemv(m.W(L(l, "ffn_gate_inp.weight")), s.h, s.router); + if (g_strata && strata::kernels::native_router_topk_supported((int) g.n_expert, K)) { + // Strata's router (llama.cpp's topk-moe contract) for 256 / 8; the ids come back for the per-expert launches + strata::kernels::native_router_topk(s.router, s.ids, s.wts, (int) g.n_expert, K, 1, g_st); + g_ids_host.resize((size_t) K); + CK(cudaMemcpy(g_ids_host.data(), s.ids, K * sizeof(int), cudaMemcpyDeviceToHost)); + } else { + std::vector r((size_t) g.n_expert); + CK(cudaMemcpy(r.data(), s.router, r.size() * 4, cudaMemcpyDeviceToHost)); + const float mx = *std::max_element(r.begin(), r.end()); + double sum = 0; + for (float& v : r) sum += (v = std::exp(v - mx)); + for (float& v : r) v = (float) (v / sum); + std::vector idx((size_t) g.n_expert); + for (int i = 0; i < (int) idx.size(); ++i) idx[i] = i; + std::partial_sort(idx.begin(), idx.begin() + K, idx.end(), + [&](int a, int b) { return r[a] > r[b] || (r[a] == r[b] && a < b); }); + std::vector w(K); + float ws = 0; + for (int i = 0; i < K; ++i) ws += (w[i] = r[idx[i]]); + for (float& v : w) v /= ws; + g_ids_host.assign(idx.begin(), idx.begin() + K); + CK(cudaMemcpy(s.ids, idx.data(), K * sizeof(int), cudaMemcpyHostToDevice)); + CK(cudaMemcpy(s.wts, w.data(), K * 4, cudaMemcpyHostToDevice)); + } + gemv(m.W(L(l, "ffn_gate_exps.weight")), s.h, s.eg, s.ids, K, 0); + gemv(m.W(L(l, "ffn_up_exps.weight")), s.h, s.eu, s.ids, K, 0); + k_swiglu<<<(K * FF + B - 1) / B, B>>>(s.eg, s.eu, s.eh, K * FF); + gemv(m.W(L(l, "ffn_down_exps.weight")), s.eh, s.ey, s.ids, K, FF); + // shared expert with its sigmoid scalar gate + gemv(m.W(L(l, "ffn_gate_shexp.weight")), s.h, s.sg); + gemv(m.W(L(l, "ffn_up_shexp.weight")), s.h, s.su); + k_swiglu<<<(FS + B - 1) / B, B>>>(s.sg, s.su, s.sh, FS); + gemv(m.W(L(l, "ffn_down_shexp.weight")), s.sh, s.sy); + { + Tensor gs; + gs.d = (const uint8_t*) m.F(L(l, "ffn_gate_inp_shexp.weight")); + gs.type = T_F32; + gs.shape = {N, 1}; + gs.row_bytes = (size_t) N * 4; + gemv(gs, s.h, s.sgate); + } + k_moe_sum<<<(N + B - 1) / B, B>>>(s.x, s.ey, s.wts, K, s.sy, s.sgate, N); + CK(cudaGetLastError()); + if (layers) CK(cudaMemcpy(layers + (size_t) l * N, s.x, (size_t) N * 4, cudaMemcpyDeviceToHost)); + } + k_rms<<<1, kThreads>>>(s.x, m.F("output_norm.weight"), s.h, N, m.eps); + gemv(m.W("output.weight"), s.h, s.logits); + CK(cudaDeviceSynchronize()); + ++s.pos; +} + +std::vector parse_ids(const std::string& s) { + std::vector v; + size_t i = 0; + while (i < s.size()) { + while (i < s.size() && (s[i] == ',' || s[i] == ' ' || s[i] == '\n' || s[i] == '\r')) ++i; + if (i >= s.size()) break; + v.push_back(std::atoi(s.c_str() + i)); + while (i < s.size() && s[i] != ',' && s[i] != ' ' && s[i] != '\n') ++i; + } + return v; +} + +} // namespace + +int main(int argc, char** argv) { + std::string model, tokens, dump_layers, dump_logits, force, dump_full; + int n_gen = 64, ctx = 4096; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + auto next = [&]() -> std::string { + if (i + 1 >= argc) { + std::fprintf(stderr, "q36ref: %s needs a value\n", a.c_str()); + std::exit(2); + } + return argv[++i]; + }; + if (a == "--model") model = next(); + else if (a == "--tokens") tokens = next(); + else if (a == "--tokens-file") { + FILE* f = std::fopen(next().c_str(), "rb"); + if (!f) { std::fprintf(stderr, "q36ref: cannot read the tokens file\n"); return 2; } + char buf[4096]; + size_t n; + while ((n = std::fread(buf, 1, sizeof buf, f)) > 0) tokens.append(buf, n); + std::fclose(f); + } else if (a == "--n") n_gen = std::atoi(next().c_str()); + else if (a == "--ctx") ctx = std::atoi(next().c_str()); + else if (a == "--dump-layers") dump_layers = next(); + else if (a == "--dump-logits") dump_logits = next(); + else if (a == "--force") force = next(); + else if (a == "--kernels") { + const std::string v = next(); + if (v != "strata" && v != "plain") { std::fprintf(stderr, "q36ref: --kernels strata or plain\n"); return 2; } + g_strata = v == "strata"; + } + else if (a == "--dump-full-logits") dump_full = next(); + else if (a == "--act") { + const std::string v = next(); + if (v != "q8" && v != "f32") { std::fprintf(stderr, "q36ref: --act q8 or f32\n"); return 2; } + g_act_q8 = v == "q8"; + } + else { + std::fprintf(stderr, "usage: strata-q36ref --model GGUF --tokens ID,ID,... | --tokens-file F [--n 64] [--ctx 4096] " + "[--dump-layers FILE] [--dump-logits FILE] [--act q8|f32] [--kernels strata|plain] " + "[--force ID,ID,...] [--dump-full-logits FILE]\n"); + return 2; + } + } + const std::vector prompt = parse_ids(tokens); + // --force: the continuation is these tokens (teacher forcing: the KL check reads both engines on one sequence); + // the greedy ids are still printed + const std::vector forced = parse_ids(force); + if (!forced.empty()) n_gen = (int) forced.size() + 1; + if (model.empty() || prompt.empty()) { + std::fprintf(stderr, "q36ref: --model and --tokens are required\n"); + return 2; + } + Model m; + std::string err; + try { + if (!load(model, m, err)) { + std::fprintf(stderr, "q36ref: %s\n", err.c_str()); + return 1; + } + } catch (const std::exception& e) { + std::fprintf(stderr, "q36ref: %s\n", e.what()); + return 1; + } + State s; + s.ctx = ctx; + init_state(m, s); + const int N = (int) m.g.n_embd, NL = (int) m.g.n_layers, V = (int) m.g.n_vocab; + FILE* fl = dump_layers.empty() ? nullptr : std::fopen(dump_layers.c_str(), "wb"); + FILE* fg = dump_logits.empty() ? nullptr : std::fopen(dump_logits.c_str(), "wb"); + FILE* ff = dump_full.empty() ? nullptr : std::fopen(dump_full.c_str(), "wb"); + std::vector layers((size_t) NL * N), logits((size_t) V); + const auto t0 = std::chrono::steady_clock::now(); + int next = -1; + std::vector gen; + const int total = (int) prompt.size() + n_gen - 1; + if (total > ctx) { + std::fprintf(stderr, "q36ref: %d positions do not fit --ctx %d\n", total, ctx); + return 2; + } + for (int i = 0; i < total; ++i) { + const int tok = i < (int) prompt.size() ? prompt[i] : next; + forward(m, s, tok, fl ? layers.data() : nullptr); + if (fl) std::fwrite(layers.data(), 4, layers.size(), fl); + if (i + 1 >= (int) prompt.size()) { + CK(cudaMemcpy(logits.data(), s.logits, (size_t) V * 4, cudaMemcpyDeviceToHost)); + int a = 0, b = -1; + for (int j = 1; j < V; ++j) + if (logits[j] > logits[a]) a = j; + for (int j = 0; j < V; ++j) + if (j != a && (b < 0 || logits[j] > logits[b])) b = j; + next = gen.size() < forced.size() ? forced[gen.size()] : a; + gen.push_back(a); + if (ff) std::fwrite(logits.data(), 4, logits.size(), ff); + if (fg) { + const float rec[4] = {(float) a, logits[a], (float) b, logits[b]}; + std::fwrite(rec, 4, 4, fg); + } + } + } + const double sec = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + if (fl) std::fclose(fl); + if (fg) std::fclose(fg); + if (ff) std::fclose(ff); + std::printf("gen:"); + for (int t : gen) std::printf(" %d", t); + std::printf("\n"); + std::fprintf(stderr, "q36ref: %zu prompt + %zu generated positions in %.2f s (%.2f tok/s, one token at a time)\n", + prompt.size(), gen.size(), sec, (double) total / sec); + return 0; +} diff --git a/sycl/src/core/native_dense.cpp b/sycl/src/core/native_dense.cpp index ae3c892f..9e1c7913 100644 --- a/sycl/src/core/native_dense.cpp +++ b/sycl/src/core/native_dense.cpp @@ -170,7 +170,7 @@ bool NativeDense::load(const std::vector &shards, const auto* number = gguf.get("split.no"); const auto* tensors = gguf.get("split.tensors.count"); if (gguf.get("general.architecture")) { - err = strata::check_architecture(gguf); + err = strata::check_engine_architecture(gguf); if (!err.empty()) return false; have_architecture = true; if (count && number && tensors && number->u == 0 && count->u > 1) { diff --git a/sycl/src/core/native_head.cpp b/sycl/src/core/native_head.cpp index 9afd2199..fbfa3fe9 100644 --- a/sycl/src/core/native_head.cpp +++ b/sycl/src/core/native_head.cpp @@ -32,7 +32,7 @@ bool NativeHead::load(const std::vector &shards, int64_t n_in, // The architecture is the metadata shard's; output.weight comes from whichever shard holds it (shard 2 // of Unsloth's UD-Q4_K_XL, whose shard 1 holds no tensor). GgufModel refuses a duplicate across shards. const strata::GgufModel model(shards); - err = strata::check_architecture(model.meta()); + err = strata::check_engine_architecture(model.meta()); if (!err.empty()) return false; size_t at = 0; const strata::TensorInfo* tensor = model.find("output.weight", &at); @@ -171,7 +171,7 @@ bool NativeEmbed::load(const std::vector &shards, int64_t n_embd, const strata::GgufModel model(shards); // --embd-gguf's one-tensor file (tools/embd_bf16_pack.py) says "strata-embd": only its tensor is checked const strata::MetaValue* arch = model.meta().get("general.architecture"); - err = arch != nullptr && arch->s == "strata-embd" ? std::string() : strata::check_architecture(model.meta()); + err = arch != nullptr && arch->s == "strata-embd" ? std::string() : strata::check_engine_architecture(model.meta()); if (!err.empty()) { err = "native embedding: " + err; return false; } size_t at = 0; const strata::TensorInfo* t = model.find("token_embd.weight", &at); diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index 29a07e66..8f29ed18 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -86,6 +86,7 @@ namespace strata::prefill { void set_nonresident_share(double share); } // SYC #define NOMINMAX // gguf_reader.hpp includes windows.h #endif #include "strata/artifact/gguf_reader.hpp" +#include "strata/core/family_layout.hpp" #if defined(_WIN32) #include #include @@ -2329,6 +2330,16 @@ int main(int argc, char **argv) try { // every shard of the model (-0000N-of-0000M.gguf beside --native). A missing shard is an error // here: it used to be skipped, leaving a model with some tensors absent and a later error, or none. o.native_shards = strata::gguf_split_paths(o.native_preset); + // a model family Strata recognises but has no engine path for yet (Qwen3.6-35B-A3B) is refused here, + // with a message that says so, before anything else about the file is judged + { + const strata::GgufFile meta(o.native_shards.front()); + const std::string why = strata::model_family_not_supported(strata::model_family(meta)); + if (strata::model_family(meta) != strata::ModelFamily::Unknown && !why.empty()) { + std::fprintf(stderr, "strata generate: --native %s: %s\n", o.native_preset.c_str(), why.c_str()); + return 2; + } + } // --ple-gguf defaults to the shard that holds the PLE table, found by name: shard 2 of the ISTA files // and of Unsloth's UD-Q4_K_XL, shard 1 of Swift's if (o.ple_gguf.empty() && !o.no_ple) { @@ -2637,21 +2648,26 @@ int main(int argc, char **argv) try { std::string gguf_rope_type; double gguf_rope_base = 0, gguf_rope_factor = 0, gguf_rope_orig_ctx = 0; if (!o.native_preset.empty()) { - // the model file is the authority on its own geometry; the kernels' compiled shape is checked against - // it before any weight moves, naming the key that differs + // The geometry is the model file's (core::geometry_from_gguf: every ".*" shape key), checked + // against the shapes this engine's kernels are built for. The expert count and top-k are run-time + // sizes: a pruned variant (GSQ-RCO Coder) ships fewer experts than the canonical 512x10. try { strata::GgufFile model_gguf(o.native_shards.front()); // the metadata shard - std::string gerr = strata::read_geometry(model_gguf, g); - if (gerr.empty()) gerr = strata::geometry_unsupported(g); - if (!gerr.empty()) { - std::fprintf(stderr, "strata generate: %s: %s\n", o.native_shards.front().c_str(), gerr.c_str()); + std::string gerr; + if (!strata::core::geometry_from_gguf(model_gguf, g, K, gerr)) { + std::fprintf(stderr, "strata generate: %s\n", gerr.c_str()); return 1; } - K = g.n_expert_used; - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.freq_base")) gguf_rope_base = v->num(); - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.type")) gguf_rope_type = v->s; - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.factor")) gguf_rope_factor = v->num(); - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.original_context_length")) + const std::string mismatch = strata::core::compiled_geometry_mismatch(g); + if (!mismatch.empty()) { + std::fprintf(stderr, "strata generate: %s: %s\n", o.native_preset.c_str(), mismatch.c_str()); + return 1; + } + const std::string p = std::string(strata::model_family_arch(g.family)) + "."; + if (const strata::MetaValue* v = model_gguf.get(p + "rope.freq_base")) gguf_rope_base = v->num(); + if (const strata::MetaValue* v = model_gguf.get(p + "rope.scaling.type")) gguf_rope_type = v->s; + if (const strata::MetaValue* v = model_gguf.get(p + "rope.scaling.factor")) gguf_rope_factor = v->num(); + if (const strata::MetaValue* v = model_gguf.get(p + "rope.scaling.original_context_length")) gguf_rope_orig_ctx = v->num(); } catch (const std::exception& e) { std::fprintf(stderr, "strata generate: reading the model's geometry from %s: %s\n", diff --git a/tests/core/gguf_fixture.hpp b/tests/core/gguf_fixture.hpp index d3415c5e..c20fda35 100644 --- a/tests/core/gguf_fixture.hpp +++ b/tests/core/gguf_fixture.hpp @@ -45,6 +45,7 @@ inline Kv strs(const std::string& k, std::vector v) { r.sarr = std::move(v); return r; } +inline Kv str_array(const std::string& k, std::vector v) { return strs(k, std::move(v)); } struct Tensor { std::string name; diff --git a/tests/core/model_family_test.cpp b/tests/core/model_family_test.cpp new file mode 100644 index 00000000..479340d6 --- /dev/null +++ b/tests/core/model_family_test.cpp @@ -0,0 +1,292 @@ +// tests/core/model_family_test.cpp - the model families (NEW-MODELS-PLAN.md T0) on synthetic GGUFs: no model, no GPU. +// +// * the architecture guard accepts qwen4exp and qwen35moe and refuses anything else; the engine's guard refuses +// qwen35moe with "not ... yet" (no engine path for Qwen3.6 before T1); +// * geometry_from_gguf reads Qwen3.6-35B-A3B's real metadata values (hidden 2048, 40 + 1 MTP layers, 32 GDN V +// heads, conv 8192, no hyper-connections, no indexer) and Flash-Next's as exactly the compiled defaults; +// * the layout tables, on tiny files of either family: a complete file passes, a wrong shape, a missing tensor +// and (qwen35moe) a tensor the table does not name are refused, naming the tensor. +// +// `model_family_test --real SHARD`: the same view of a real model (headers only): family, geometry, the kernels' +// verdict and the layout check over every shard. +#include "gguf_fixture.hpp" + +#include "strata/core/family_layout.hpp" + +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace { +int g_fail = 0; +void check(bool ok, const std::string& what) { + std::printf(" %-90s %s\n", what.c_str(), ok ? "ok" : "FAIL"); + if (!ok) ++g_fail; +} + +struct TempDir { + fs::path path; + TempDir() { + path = fs::temp_directory_path() / + ("strata-model-family-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + fs::create_directories(path); + } + ~TempDir() { + std::error_code ignored; + fs::remove_all(path, ignored); + } +}; + +using fixture::Kv; +using fixture::Tensor; +const uint32_t F32 = 0; + +struct Dims { + uint64_t block_count, embd, heads, heads_kv, key_len, experts, used, ff, ff_sh, conv, state, groups, v_heads, + inner, interval, nextn, hc, hc_lr, idx_heads, idx_key; +}; +// Qwen3.6-35B-A3B (unsloth/Qwen3.6-35B-A3B-MTP-GGUF, every quant) and Qwen3.8-Flash-Next, as their files say +const Dims kQwen36 = {41, 2048, 16, 2, 256, 256, 8, 512, 512, 4, 128, 16, 32, 4096, 4, 1, 0, 0, 0, 0}; +const Dims kFlashNext = {48, 2560, 24, 2, 256, 512, 10, 640, 640, 4, 128, 16, 48, 6144, 4, 0, 4, 320, 4, 128}; +// tiny models of each family for the layout checks (every tensor F32, a few KB) +const Dims kTiny36 = {5, 64, 2, 1, 16, 4, 2, 32, 32, 4, 8, 2, 4, 32, 4, 1, 0, 0, 0, 0}; +const Dims kTinyFlash = {8, 64, 2, 1, 16, 4, 2, 32, 32, 4, 8, 2, 4, 32, 4, 0, 2, 8, 2, 8}; + +std::vector metadata(const char* arch, const Dims& d, uint64_t vocab) { + const std::string p = std::string(arch) + "."; + std::vector kv = {fixture::str("general.architecture", arch), + fixture::u32(p + "block_count", d.block_count), + fixture::u32(p + "embedding_length", d.embd), + fixture::u32(p + "attention.head_count", d.heads), + fixture::u32(p + "attention.head_count_kv", d.heads_kv), + fixture::u32(p + "attention.key_length", d.key_len), + fixture::u32(p + "attention.value_length", d.key_len), + fixture::u32(p + "expert_count", d.experts), + fixture::u32(p + "expert_used_count", d.used), + fixture::u32(p + "expert_feed_forward_length", d.ff), + fixture::u32(p + "expert_shared_feed_forward_length", d.ff_sh), + fixture::u32(p + "ssm.conv_kernel", d.conv), + fixture::u32(p + "ssm.state_size", d.state), + fixture::u32(p + "ssm.group_count", d.groups), + fixture::u32(p + "ssm.time_step_rank", d.v_heads), + fixture::u32(p + "ssm.inner_size", d.inner), + fixture::u32(p + "full_attention_interval", d.interval)}; + if (std::string(arch) == "qwen35moe") { + kv.push_back(fixture::u32(p + "nextn_predict_layers", d.nextn)); + } else { + kv.push_back(fixture::u32(p + "hyper_connection.count", d.hc)); + kv.push_back(fixture::u32(p + "hyper_connection.low_rank", d.hc_lr)); + kv.push_back(fixture::u32(p + "attention.indexer.head_count", d.idx_heads)); + kv.push_back(fixture::u32(p + "attention.indexer.key_length", d.idx_key)); + } + std::vector tokens; + for (uint64_t i = 0; i < vocab; ++i) tokens.push_back("t" + std::to_string(i)); + kv.push_back(fixture::str_array("tokenizer.ggml.tokens", tokens)); + return kv; +} + +/// The tensors the layout table of `g` names, as F32 fixtures. +std::vector tensors_of(const strata::core::ModelGeometry& g) { + std::vector ts; + uint8_t seed = 1; + auto add = [&](const std::string& name, const std::vector& shape) { + std::vector s(shape.begin(), shape.end()); + ts.push_back({name, s, F32, seed++}); + }; + for (const auto& w : strata::core::global_tensors(g)) add(w.name, w.shape); + for (int64_t l = 0; l < g.n_layers + g.n_mtp_layers; ++l) + for (const auto& w : strata::core::layer_tensors(g, l)) add("blk." + std::to_string(l) + "." + w.name, w.shape); + return ts; +} + +bool geometry_of(const fs::path& p, strata::core::ModelGeometry& g, int64_t& k, std::string& err) { + const strata::GgufFile f(p.string()); + return strata::core::geometry_from_gguf(f, g, k, err); +} + +std::string layout_error(const fs::path& dir, const char* arch, const Dims& d, uint64_t vocab, + void (*mutate)(std::vector&)) { + const fs::path meta = dir / "meta.gguf"; + fixture::write(meta, metadata(arch, d, vocab), {}); + strata::core::ModelGeometry g; + int64_t k = 0; + std::string err; + if (std::string(arch) == "qwen35moe") { + if (!geometry_of(meta, g, k, err)) return "geometry: " + err; + } else { + // the qwen4exp guard pins Flash-Next's own block count and widths, so the tiny model's geometry is set here + g.n_layers = (int64_t) d.block_count; + g.n_embd = (int64_t) d.embd; + g.n_head = (int64_t) d.heads; + g.n_head_kv = (int64_t) d.heads_kv; + g.head_dim = (int64_t) d.key_len; + g.n_expert = (int64_t) d.experts; + g.n_ff = (int64_t) d.ff; + g.n_ff_shexp = (int64_t) d.ff_sh; + g.ssm_d_conv = (int64_t) d.conv; + g.ssm_state_size = (int64_t) d.state; + g.ssm_k_heads = (int64_t) d.groups; + g.ssm_v_heads = (int64_t) d.v_heads; + g.ssm_value_dim = (int64_t) d.inner; + g.ssm_conv_channels = 2 * g.ssm_state_size * g.ssm_k_heads + g.ssm_value_dim; + g.hc = (int64_t) d.hc; + g.hc_lr = (int64_t) d.hc_lr; + g.idx_q_heads = (int64_t) d.idx_heads; + g.idx_key_dim = (int64_t) d.idx_key; + g.n_vocab = (int64_t) vocab; + } + std::vector ts = tensors_of(g); + if (mutate) mutate(ts); + const fs::path model = dir / (std::string(arch) + "-tiny.gguf"); + fixture::write(model, metadata(arch, d, vocab), ts); + const strata::GgufModel m({model.string()}); + size_t n = 0; + if (!strata::core::check_gguf_layout(m, g, err, &n)) return err; + return {}; +} + +int real_model(const std::string& any) { + try { + const strata::GgufModel m = strata::GgufModel::open(any); + const std::string arch = strata::check_architecture(m.meta()); + std::printf(" %zu shard(s); architecture guard: %s; engine guard: %s\n", m.size(), + arch.empty() ? "ok" : arch.c_str(), + strata::check_engine_architecture(m.meta()).empty() ? "runs" + : strata::check_engine_architecture(m.meta()).c_str()); + if (!arch.empty()) return 1; + strata::core::ModelGeometry g; + int64_t k = 0; + std::string err; + if (!strata::core::geometry_from_gguf(m.meta(), g, k, err)) { + std::printf(" geometry: %s\n", err.c_str()); + return 1; + } + std::printf(" family %s: layers %lld (+%lld MTP), hidden %lld, attention %lld/%lld x %lld every %lld, GDN K %lld" + " V %lld x %lld conv %lld (%lld), MoE %lld experts top-%lld FF %lld shared %lld, hc %lld, indexer" + " %lld, vocab %lld\n", + strata::model_family_title(g.family), (long long) g.n_layers, (long long) g.n_mtp_layers, + (long long) g.n_embd, (long long) g.n_head, (long long) g.n_head_kv, (long long) g.head_dim, + (long long) g.qsa_interval, (long long) g.ssm_k_heads, (long long) g.ssm_v_heads, + (long long) g.ssm_state_size, (long long) g.ssm_conv_channels, (long long) g.ssm_d_conv, + (long long) g.n_expert, (long long) k, (long long) g.n_ff, (long long) g.n_ff_shexp, + (long long) g.hc, (long long) g.idx_q_heads, (long long) g.n_vocab); + const std::string mm = strata::core::compiled_geometry_mismatch(g); + std::printf(" compiled kernels: %s\n", mm.empty() ? "match" : mm.c_str()); + size_t n = 0; + const bool ok = strata::core::check_gguf_layout(m, g, err, &n); + std::printf(" layout: %s (%zu tensors checked)\n", ok ? "ok" : err.c_str(), n); + return ok ? 0 : 1; + } catch (const std::exception& e) { + std::printf(" refused: %s\n", e.what()); + return 1; + } +} +} // namespace + +int main(int argc, char** argv) { + if (argc == 3 && std::string(argv[1]) == "--real") return real_model(argv[2]); + std::printf("model_family_test\n"); + TempDir d; + { + // the guards + const fs::path q36 = d.path / "q36.gguf", fn = d.path / "fn.gguf", other = d.path / "other.gguf"; + fixture::write(q36, metadata("qwen35moe", kQwen36, 8), {}); + fixture::write(fn, metadata("qwen4exp", kFlashNext, 8), {}); + fixture::write(other, {fixture::str("general.architecture", "llama")}, {}); + const strata::GgufFile a(q36.string()), b(fn.string()), c(other.string()); + check(strata::model_family(a) == strata::ModelFamily::Qwen35Moe && + strata::model_family(b) == strata::ModelFamily::Qwen4Exp && + strata::model_family(c) == strata::ModelFamily::Unknown, + "model_family: qwen35moe, qwen4exp, unknown"); + check(strata::check_architecture(a).empty(), "the architecture guard accepts qwen35moe"); + check(strata::check_architecture(b).empty(), "the architecture guard accepts qwen4exp"); + check(strata::check_architecture(c).find("'llama'") != std::string::npos, "and refuses llama, naming it"); + const std::string e = strata::check_engine_architecture(a); + check(e.find("Qwen3.6-35B-A3B") != std::string::npos && e.find("does not run it yet") != std::string::npos, + "the engine guard refuses Qwen3.6: recognised, not supported yet"); + check(strata::check_engine_architecture(b).empty(), "the engine guard runs qwen4exp"); + std::vector kv = metadata("qwen35moe", kQwen36, 8); + for (auto it = kv.begin(); it != kv.end(); ++it) + if (it->key == "qwen35moe.ssm.time_step_rank") { kv.erase(it); break; } + const fs::path miss = d.path / "miss.gguf"; + fixture::write(miss, kv, {}); + check(strata::check_architecture(strata::GgufFile(miss.string())).find("ssm.time_step_rank") != std::string::npos, + "a qwen35moe file without ssm.time_step_rank is refused, naming the key"); + } + { + // the geometry of the real models, from their metadata values + const fs::path q36 = d.path / "q36g.gguf", fn = d.path / "fng.gguf"; + fixture::write(q36, metadata("qwen35moe", kQwen36, 248320), {}); + fixture::write(fn, metadata("qwen4exp", kFlashNext, 248320), {}); + strata::core::ModelGeometry g; + int64_t k = 0; + std::string err; + const bool ok = geometry_of(q36, g, k, err); + check(ok, "Qwen3.6 geometry reads" + (ok ? std::string() : ": " + err)); + check(g.family == strata::ModelFamily::Qwen35Moe && g.n_layers == 40 && g.n_mtp_layers == 1 && g.n_embd == 2048, + "Qwen3.6: 40 trunk layers + 1 MTP block, hidden 2048"); + check(g.n_qsa_layers() == 10 && g.n_gdn_layers() == 30 && strata::core::layer_kind(g, 3) == + strata::core::LayerKind::Attention && strata::core::layer_kind(g, 40) == strata::core::LayerKind::Mtp, + "Qwen3.6: 10 attention / 30 GDN layers, layer 40 is the MTP block"); + check(g.ssm_k_heads == 16 && g.ssm_v_heads == 32 && g.ssm_conv_channels == 8192 && g.ssm_value_dim == 4096, + "Qwen3.6 GDN: 16 K groups, 32 V heads, conv 8192, inner 4096"); + check(g.n_head == 16 && g.n_head_kv == 2 && g.head_dim == 256 && !g.has_indexer() && !g.has_hyper_connections(), + "Qwen3.6 attention: 16 Q / 2 KV x 256, no indexer, no hyper-connections"); + check(g.n_expert == 256 && k == 8 && g.n_ff == 512 && g.n_ff_shexp == 512 && g.n_vocab == 248320, + "Qwen3.6 MoE: 256 experts top-8, FF 512, shared 512; vocab 248320"); + check(!strata::core::compiled_geometry_mismatch(g).empty(), "Qwen3.6 does not match the compiled kernels"); + strata::core::ModelGeometry f; + const bool okf = geometry_of(fn, f, k, err); + const strata::core::ModelGeometry c; + check(okf && strata::core::compiled_geometry_mismatch(f).empty() && k == 10 && f.n_expert == c.n_expert && + f.ssm_conv_channels == c.ssm_conv_channels && f.n_vocab == c.n_vocab && f.hc_dim() == c.hc_dim(), + "Flash-Next's metadata gives exactly the compiled geometry"); + Dims coder = kFlashNext; + coder.experts = 256; + const fs::path cp = d.path / "coder.gguf"; + fixture::write(cp, metadata("qwen4exp", coder, 8), {}); + check(geometry_of(cp, f, k, err) && f.n_expert == 256 && strata::core::compiled_geometry_mismatch(f).empty(), + "the Coder's 256 experts are a run-time size, not a kernel mismatch"); + Dims wrong = kQwen36; + wrong.inner = 4000; + const fs::path wp = d.path / "wrong.gguf"; + fixture::write(wp, metadata("qwen35moe", wrong, 8), {}); + check(!geometry_of(wp, f, k, err) && err.find("ssm.inner_size") != std::string::npos, + "an inconsistent ssm.inner_size is refused"); + } + { + // the layout tables + check(layout_error(d.path, "qwen35moe", kTiny36, 16, nullptr).empty(), + "a complete qwen35moe file passes its layout (incl. the nextn MTP block)"); + const std::string ef = layout_error(d.path, "qwen4exp", kTinyFlash, 16, nullptr); + check(ef.empty(), "a complete qwen4exp file passes its layout (hyper-connections, indexer)" + + (ef.empty() ? std::string() : ": " + ef)); + std::string e = layout_error(d.path, "qwen35moe", kTiny36, 16, [](std::vector& ts) { + for (auto& t : ts) + if (t.name == "blk.1.ssm_conv1d.weight") t.shape[1] += 1; + }); + check(e.find("blk.1.ssm_conv1d.weight") != std::string::npos && e.find("wants") != std::string::npos, + "a wrong shape is refused, naming the tensor and both shapes"); + e = layout_error(d.path, "qwen35moe", kTiny36, 16, [](std::vector& ts) { + for (auto it = ts.begin(); it != ts.end(); ++it) + if (it->name == "blk.4.nextn.eh_proj.weight") { ts.erase(it); break; } + }); + check(e == "missing blk.4.nextn.eh_proj.weight", "a missing MTP tensor is refused"); + e = layout_error(d.path, "qwen35moe", kTiny36, 16, [](std::vector& ts) { + ts.push_back({"blk.0.hc_attn_norm.weight", {64}, F32, 99}); + }); + check(e.find("blk.0.hc_attn_norm.weight") != std::string::npos && e.find("not in the") != std::string::npos, + "a tensor the qwen35moe table does not name is refused"); + e = layout_error(d.path, "qwen4exp", kTinyFlash, 16, [](std::vector& ts) { + for (auto it = ts.begin(); it != ts.end(); ++it) + if (it->name == "blk.3.indexer.k_proj.weight") { ts.erase(it); break; } + }); + check(e == "missing blk.3.indexer.k_proj.weight", "Flash-Next: a missing indexer tensor is refused (" + e + ")"); + } + std::printf(g_fail ? "FAILED (%d)\n" : "ALL PASSED\n", g_fail); + return g_fail ? 1 : 0; +} diff --git a/tools/qwen35/compare_dumps.py b/tools/qwen35/compare_dumps.py new file mode 100644 index 00000000..7b94a040 --- /dev/null +++ b/tools/qwen35/compare_dumps.py @@ -0,0 +1,67 @@ +"""tools/qwen35/compare_dumps.py - two runs of the Qwen3.6 parity dumps against each other (e.g. llama.cpp GPU vs +llama.cpp CPU: the noise floor the strata-q36ref comparison is judged against). + + python tools/qwen35/compare_dumps.py DIR_A KIND_A DIR_B KIND_B (KIND: llama or strata) +Per prompt: greedy tokens equal up to the answer's end (llama.cpp's first <|im_end|> in run A), the first divergence's +top-1/top-2 margins, and the layer outputs' median and max ||a-b||/||b|| over the positions before the divergence. +""" +from __future__ import annotations + +import sys +from pathlib import Path + +import numpy as np + +N_EMBD, N_LAYER, EOS = 2048, 40, 248046 + + +def gen_of(d: Path, tag: str, kind: str) -> list[int]: + f = d / (f"{tag}.strata.gen" if kind == "strata" else f"{tag}.llama.log") + for line in f.read_text(encoding="utf-8").splitlines(): + if line.startswith("gen:"): + return [int(x) for x in line.split(":", 1)[1].split()] + raise SystemExit(f"no gen line in {f}") + + +def prompt_len(d: Path, tag: str) -> int: + for line in (d / f"{tag}.llama.log").read_text(encoding="utf-8").splitlines(): + if line.startswith("prompt:"): + return len(line.split(":", 1)[1].split()) + raise SystemExit("no prompt line") + + +def main() -> int: + da, ka, db, kb = Path(sys.argv[1]), sys.argv[2], Path(sys.argv[3]), sys.argv[4] + tags = sorted({p.name.split(".")[0] for p in da.glob(f"p*.{ka}.layers")}) + rows = [] + for tag in tags: + ga, gb = gen_of(da, tag, ka), gen_of(db, tag, kb) + upto = min(len(ga), len(gb)) + if EOS in ga[:upto]: + upto = ga.index(EOS) + 1 + same = 0 + while same < upto and ga[same] == gb[same]: + same += 1 + la = np.fromfile(da / f"{tag}.{ka}.logits", dtype=np.float32).reshape(-1, 4) + lb = np.fromfile(db / f"{tag}.{kb}.logits", dtype=np.float32).reshape(-1, 4) + A = np.fromfile(da / f"{tag}.{ka}.layers", dtype=np.float32).reshape(-1, N_LAYER, N_EMBD) + B = np.fromfile(db / f"{tag}.{kb}.layers", dtype=np.float32).reshape(-1, N_LAYER, N_EMBD) + npos = min(len(A), len(B), prompt_len(da, tag) + same) + nb = np.linalg.norm(B[:npos], axis=2) + na = np.linalg.norm(A[:npos], axis=2) + err = np.where((nb > 0) & (na > 0), np.linalg.norm(A[:npos] - B[:npos], axis=2) / np.maximum(nb, 1e-30), np.nan) + div = "" + if same < upto: + div = (f"; step {same}: A {int(la[same, 0])} (margin {la[same, 1] - la[same, 3]:.3f}) vs B {int(lb[same, 0])} " + f"(margin {lb[same, 1] - lb[same, 3]:.3f})") + per_layer = np.nanmedian(err, axis=0) + rows.append((same == upto, np.nanmedian(err), np.nanmax(err))) + print(f"{tag}: {same}/{upto} equal; layer err median {np.nanmedian(err):.4f} max {np.nanmax(err):.4f}; " + f"median by layer 0/10/20/30/39: " + " ".join(f"{per_layer[i]:.4f}" for i in (0, 10, 20, 30, 39)) + div) + print(f"answers identical: {sum(r[0] for r in rows)} of {len(rows)}; layer err median of medians " + f"{np.median([r[1] for r in rows]):.4f}, worst max {max(r[2] for r in rows):.4f}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/qwen35/kl.py b/tools/qwen35/kl.py new file mode 100644 index 00000000..2ec18d57 --- /dev/null +++ b/tools/qwen35/kl.py @@ -0,0 +1,106 @@ +"""tools/qwen35/kl.py - teacher-forced KL for Qwen3.6-35B-A3B (NEW-MODELS-PLAN.md T1/T2): on one token sequence per +prompt (the prompt + llama.cpp GPU's greedy answer, from a parity.py run), the next-token distributions of +llama.cpp HIP (the reference P), llama.cpp CPU (the noise floor) and strata-q36ref. Reported: mean KL(P || Q) and +the top-1 agreement over all steps, per engine; the plan's gate is Strata's KL within 1.5x of the floor. + + python tools/qwen35/kl.py --ref BIN --dump BIN --model GGUF --parity DIR --out DIR [--lock "..."] [--cpu-lock "..."] +""" +from __future__ import annotations + +import argparse +import shlex +import subprocess +import sys +from pathlib import Path + +import numpy as np + +V = 248320 +EOS = 248046 # <|im_end|> + + +def ids(path: Path, key: str) -> list[int]: + for line in path.read_text(encoding="utf-8").splitlines(): + if line.startswith(key + ":"): + return [int(x) for x in line.split(":", 1)[1].split()] + raise SystemExit(f"no {key}: in {path}") + + +def run(cmd: list[str], lock: str, log: Path) -> None: + r = subprocess.run((shlex.split(lock) if lock else []) + cmd, capture_output=True, text=True, timeout=3600) + log.write_text(r.stdout + "\n--- stderr ---\n" + r.stderr, encoding="utf-8") + if r.returncode != 0: + raise SystemExit(f"{cmd[0]} failed (rc {r.returncode}), see {log}") + + +def log_softmax(x: np.ndarray) -> np.ndarray: + x = x.astype(np.float64) + m = x.max(axis=1, keepdims=True) + return x - m - np.log(np.exp(x - m).sum(axis=1, keepdims=True)) + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--ref", required=True) + ap.add_argument("--dump", required=True) + ap.add_argument("--model", required=True) + ap.add_argument("--parity", required=True, help="a parity.py output dir (its llama.cpp logs give the sequences)") + ap.add_argument("--out", required=True) + ap.add_argument("--lock", default="") + ap.add_argument("--cpu-lock", default="") + ap.add_argument("--cache", default="", help="where llama.cpp's logits are kept between runs (default --out)") + ap.add_argument("--ref-args", default="", help="extra strata-q36ref arguments (e.g. '--act f32')") + a = ap.parse_args() + out, par = Path(a.out), Path(a.parity) + out.mkdir(parents=True, exist_ok=True) + tags = sorted(p.name.split(".")[0] for p in par.glob("p*.llama.log")) + kl = {"cpu": [], "strata": []} + top1 = {"cpu": [], "strata": []} + kl_ans = {"cpu": [], "strata": []} + top1_ans = {"cpu": [], "strata": []} + for tag in tags: + prompt, gen = ids(par / f"{tag}.llama.log", "prompt"), ids(par / f"{tag}.llama.log", "gen") + force = ",".join(map(str, gen)) + toks = ",".join(map(str, prompt)) + cache = Path(a.cache) if a.cache else out + f = {k: (out if k == "strata" else cache) / f"{tag}.{k}.full" for k in ("gpu", "cpu", "strata")} + # llama.cpp's two runs depend only on the model and the sequence: kept in --out and reused (64 MB each) + if not f["gpu"].exists(): + run([a.dump, "--model", a.model, "--tokens", toks, "--force", force, "--ngl", "99", "--dump-full-logits", + str(f["gpu"])], a.lock, cache / f"{tag}.gpu.log") + if not f["cpu"].exists(): + run([a.dump, "--model", a.model, "--tokens", toks, "--force", force, "--ngl", "0", "--dump-full-logits", + str(f["cpu"])], a.cpu_lock, cache / f"{tag}.cpu.log") + run([a.ref, "--model", a.model, "--tokens", toks, "--force", force, "--dump-full-logits", str(f["strata"]), + *shlex.split(a.ref_args)], a.lock, out / f"{tag}.strata.log") + P = log_softmax(np.fromfile(f["gpu"], dtype=np.float32).reshape(-1, V)) + # the answer: the steps up to and including the first <|im_end|> of the forced sequence (past it the context is + # one no chat reaches, and its distributions are the noisiest); "all" keeps every step + ans = gen.index(EOS) + 1 if EOS in gen else len(P) + line = f"{tag}: {len(P)} steps ({ans} answer)" + per = {} + for k in ("cpu", "strata"): + Q = log_softmax(np.fromfile(f[k], dtype=np.float32).reshape(-1, V)) + n = min(len(P), len(Q)) + d = (np.exp(P[:n]) * (P[:n] - Q[:n])).sum(axis=1) + t1 = P[:n].argmax(axis=1) == Q[:n].argmax(axis=1) + kl[k].extend(d.tolist()) + top1[k].extend(t1.tolist()) + kl_ans[k].extend(d[:ans].tolist()) + top1_ans[k].extend(t1[:ans].tolist()) + per[k] = d + line += f"; {k}: KL {d.mean():.5f} (answer {d[:ans].mean():.5f}) top-1 {t1.mean():.3f}" + np.savez(out / f"{tag}.kl.npz", answer=ans, **per) + f["strata"].unlink(missing_ok=True) + print(line, flush=True) + for name, K, T in (("all steps", kl, top1), ("answers only", kl_ans, top1_ans)): + print(f"-- {name}") + for k in ("cpu", "strata"): + print(f"{k:6s} vs llama.cpp HIP: mean KL {np.mean(K[k]):.5f} (median {np.median(K[k]):.6f}, p99 " + f"{np.percentile(K[k], 99):.4f}), top-1 {np.mean(T[k]):.4f} over {len(K[k])} steps") + print(f"ratio strata / floor: {np.mean(K['strata']) / max(np.mean(K['cpu']), 1e-12):.2f}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/qwen35/parity.py b/tools/qwen35/parity.py new file mode 100644 index 00000000..640415f3 --- /dev/null +++ b/tools/qwen35/parity.py @@ -0,0 +1,112 @@ +"""tools/qwen35/parity.py - NEW-MODELS-PLAN.md T1's exit gate for Qwen3.6-35B-A3B: strata-q36ref against llama.cpp +(tools/qwen35/q36_llama_dump.cpp) on the same GGUF, the same box and the same token ids. + +For each prompt (parity_prompts.json, ChatML with thinking off): llama.cpp tokenizes it and runs it (the reference +ids, layer outputs and greedy tokens); strata-q36ref runs the same ids. Reported per prompt: the greedy tokens that +agree (of --n), the first divergence with both engines' top-1/top-2 logit margins (a near tie is a margin < 0.05), and +the per-layer hidden-state error max over positions of ||strata - llama|| / ||llama||. + + python tools/qwen35/parity.py --ref BIN --dump BIN --model GGUF --out DIR [--n 64] [--ngl 99] [--lock "flock ..."] +""" +from __future__ import annotations + +import argparse +import json +import shlex +import subprocess +import sys +from pathlib import Path + +import numpy as np + +HERE = Path(__file__).resolve().parent +TEMPLATE = "<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" +N_EMBD, N_LAYER = 2048, 40 +EOS = 248046 # <|im_end|> + + +def run(cmd: list[str], lock: str, log: Path) -> str: + full = shlex.split(lock) + cmd if lock else cmd + r = subprocess.run(full, capture_output=True, text=True, timeout=1800) + log.write_text(r.stdout + "\n--- stderr ---\n" + r.stderr, encoding="utf-8") + if r.returncode != 0: + raise SystemExit(f"{cmd[0]} failed (rc {r.returncode}), see {log}") + return r.stdout + + +def ids_of(out: str, key: str) -> list[int]: + for line in out.splitlines(): + if line.startswith(key + ":"): + return [int(x) for x in line.split(":", 1)[1].split()] + raise SystemExit(f"no '{key}:' line") + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--ref", required=True, help="strata-q36ref") + ap.add_argument("--dump", required=True, help="q36_llama_dump") + ap.add_argument("--model", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--n", type=int, default=64) + ap.add_argument("--ngl", type=int, default=99, help="llama.cpp's GPU layers (0 = its CPU backend)") + ap.add_argument("--lock", default="", help="a command prefix for the GPU runs (the box's flock)") + ap.add_argument("--prompts", default=str(HERE / "parity_prompts.json")) + ap.add_argument("--skip-ref", action="store_true", help="reuse strata-q36ref's outputs in --out") + ap.add_argument("--past-eos", action="store_true", help="compare all --n tokens, not only up to the answer's end") + a = ap.parse_args() + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + prompts = json.loads(Path(a.prompts).read_text(encoding="utf-8")) + summary = [] + for i, p in enumerate(prompts): + tag = f"p{i:02d}" + lo = run([a.dump, "--model", a.model, "--prompt", TEMPLATE.format(p=p), "--n", str(a.n), "--ngl", str(a.ngl), + "--dump-layers", str(out / f"{tag}.llama.layers"), "--dump-logits", str(out / f"{tag}.llama.logits")], + a.lock, out / f"{tag}.llama.log") + prompt_ids, lgen = ids_of(lo, "prompt"), ids_of(lo, "gen") + if not a.skip_ref: + so = run([a.ref, "--model", a.model, "--tokens", ",".join(map(str, prompt_ids)), "--n", str(a.n), + "--dump-layers", str(out / f"{tag}.strata.layers"), "--dump-logits", str(out / f"{tag}.strata.logits")], + a.lock, out / f"{tag}.strata.log") + (out / f"{tag}.strata.gen").write_text(so, encoding="utf-8") + sgen = ids_of((out / f"{tag}.strata.gen").read_text(encoding="utf-8"), "gen") + # the answer ends at llama.cpp's first <|im_end|> (included); past it both engines run on in a context no chat + # ever reaches, so the comparison stops there (--past-eos compares all --n tokens) + upto = min(len(sgen), len(lgen)) + if not a.past_eos and EOS in lgen[:upto]: + upto = lgen.index(EOS) + 1 + same = 0 + while same < upto and sgen[same] == lgen[same]: + same += 1 + sl = np.fromfile(out / f"{tag}.strata.logits", dtype=np.float32).reshape(-1, 4) + ll = np.fromfile(out / f"{tag}.llama.logits", dtype=np.float32).reshape(-1, 4) + div = None + if same < upto: + div = {"step": same, "strata": [int(sl[same, 0]), float(sl[same, 1] - sl[same, 3])], + "llama": [int(ll[same, 0]), float(ll[same, 1] - ll[same, 3])]} + # the layer outputs up to the divergence (after it the two engines read different tokens) + sL = np.fromfile(out / f"{tag}.strata.layers", dtype=np.float32).reshape(-1, N_LAYER, N_EMBD) + lL = np.fromfile(out / f"{tag}.llama.layers", dtype=np.float32).reshape(-1, N_LAYER, N_EMBD) + npos = min(len(sL), len(lL), len(prompt_ids) + same) + ln = np.linalg.norm(lL[:npos], axis=2) + err = np.linalg.norm(sL[:npos] - lL[:npos], axis=2) / np.maximum(ln, 1e-30) # [pos, layer] + # llama.cpp keeps only the output rows of the last layer of a prompt batch: rows it did not compute are 0 + err = np.where(ln > 0, err, np.nan) + per_layer = np.nanmax(err, axis=0) + rec = {"prompt": i, "tokens": len(prompt_ids), "same": same, "of": upto, + "divergence": div, "max_rel_err": float(np.nanmax(per_layer)), "worst_layer": int(np.nanargmax(per_layer)), + "median_rel_err": float(np.nanmedian(err)), "per_layer_max": [round(float(x), 5) for x in per_layer]} + summary.append(rec) + print(f"{tag}: {same}/{rec['of']} greedy tokens equal; layers max rel err {rec['max_rel_err']:.4f} (layer " + f"{rec['worst_layer']}), median {rec['median_rel_err']:.5f}" + (f"; diverges at {div}" if div else ""), + flush=True) + (out / "summary.json").write_text(json.dumps(summary, indent=1), encoding="utf-8") + full = sum(r["same"] == r["of"] for r in summary) + print(f"identical greedy answers (up to {a.n} tokens{'' if a.past_eos else ' or the end of the answer'}): {full} of " + f"{len(summary)} prompts; worst layer error " + f"{max(r['max_rel_err'] for r in summary):.4f}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/qwen35/parity_prompts.json b/tools/qwen35/parity_prompts.json new file mode 100644 index 00000000..75881bac --- /dev/null +++ b/tools/qwen35/parity_prompts.json @@ -0,0 +1,12 @@ +[ + "Write a short story about a lighthouse keeper who finds a message in a bottle.", + "Implement an LRU cache in Python with get and put in O(1), and add three unit tests.", + "What is 17 * 23 + 144 / 12? Show the steps.", + "Explain how a refrigerator works to a ten-year-old.", + "Translate into German: The train to Munich leaves at half past seven, platform four.", + "List five differences between TCP and UDP.", + "Summarize the plot of Romeo and Juliet in three sentences.", + "Write a JSON object describing a book with title, author, year and three tags.", + "If all bloops are razzies and all razzies are lazzies, are all bloops lazzies? Explain.", + "Write a haiku about autumn rain on a city street." +] diff --git a/tools/qwen35/q36_llama_dump.cpp b/tools/qwen35/q36_llama_dump.cpp new file mode 100644 index 00000000..cd8ee4ba --- /dev/null +++ b/tools/qwen35/q36_llama_dump.cpp @@ -0,0 +1,157 @@ +// tools/qwen35/q36_llama_dump.cpp - llama.cpp's side of the Qwen3.6 parity check (NEW-MODELS-PLAN.md T1): the same GGUF, +// the same token ids, llama.cpp's own graph. Prints the prompt's ids and the greedy ids, and dumps every processed +// position's layer outputs ("l_out-N", through the scheduler's eval callback) in strata-q36ref's format +// ([pos][layer][n_embd] f32) plus each greedy step's top-2 (id, logit). +// +// Built against a llama.cpp checkout (not part of Strata's build): +// g++ -O2 -std=c++17 q36_llama_dump.cpp -I/include -I/ggml/include -L/build/bin -lllama -lggml +// -lggml-base -Wl,-rpath,/build/bin -o q36_llama_dump +// Usage: q36_llama_dump --model GGUF (--prompt TEXT | --tokens ID,ID,...) [--n 64] [--ngl 99] [--dump-layers F] +// [--dump-logits F] [--force ID,ID,...] [--dump-full-logits F] +// --force feeds that continuation instead of the greedy ids (teacher forcing); --dump-full-logits writes every +// step's logits (f32, [step][vocab]). +// --prompt is tokenized with special tokens parsed and no BOS added (Qwen adds none). +#include "llama.h" +#include "ggml-backend.h" + +#include +#include +#include +#include +#include +#include + +namespace { +struct Capture { + int n_embd = 0, n_layer = 0, n_tok = 0; + std::map> layers; // layer -> [n_tok][n_embd] of the current batch +}; + +bool on_tensor(struct ggml_tensor* t, bool ask, void* user) { + auto* c = (Capture*) user; + const char* name = ggml_get_name(t); + if (std::strncmp(name, "l_out-", 6) != 0) return ask ? false : true; + if (ask) return true; + const int il = std::atoi(name + 6); + if (t->type != GGML_TYPE_F32 || t->ne[0] != c->n_embd) return true; + std::vector& v = c->layers[il]; + v.resize((size_t) ggml_nelements(t)); + ggml_backend_tensor_get(t, v.data(), 0, ggml_nbytes(t)); + return true; +} + +std::vector parse_ids(const std::string& s) { + std::vector v; + const char* p = s.c_str(); + while (*p) { + while (*p == ',' || *p == ' ') ++p; + if (!*p) break; + v.push_back(std::atoi(p)); + while (*p && *p != ',' && *p != ' ') ++p; + } + return v; +} +} // namespace + +int main(int argc, char** argv) { + std::string model, prompt, tokens, dump_layers, dump_logits, force, dump_full; + int n_gen = 64, ngl = 99; + for (int i = 1; i + 1 < argc; i += 2) { + const std::string a = argv[i], v = argv[i + 1]; + if (a == "--model") model = v; + else if (a == "--prompt") prompt = v; + else if (a == "--tokens") tokens = v; + else if (a == "--n") n_gen = std::atoi(v.c_str()); + else if (a == "--ngl") ngl = std::atoi(v.c_str()); + else if (a == "--dump-layers") dump_layers = v; + else if (a == "--dump-logits") dump_logits = v; + else if (a == "--force") force = v; + else if (a == "--dump-full-logits") dump_full = v; + else { std::fprintf(stderr, "unknown option %s\n", a.c_str()); return 2; } + } + // STRATA_DUMP_NGL: the GPU layers when the caller asks for the GPU (--ngl > 0) but the file does not fit (UD-Q4_K_XL + // on a 12 GB card); the other layers run on llama.cpp's CPU backend + if (const char* g = std::getenv("STRATA_DUMP_NGL"); g != nullptr && ngl > 0) ngl = std::atoi(g); + llama_backend_init(); + llama_model_params mp = llama_model_default_params(); + mp.n_gpu_layers = ngl; + llama_model* mdl = llama_model_load_from_file(model.c_str(), mp); + if (!mdl) { std::fprintf(stderr, "cannot load %s\n", model.c_str()); return 1; } + const llama_vocab* vocab = llama_model_get_vocab(mdl); + std::vector ids; + if (!tokens.empty()) { + for (int t : parse_ids(tokens)) ids.push_back(t); + } else { + ids.resize(prompt.size() + 16); + const int n = llama_tokenize(vocab, prompt.c_str(), (int) prompt.size(), ids.data(), (int) ids.size(), false, true); + if (n < 0) { std::fprintf(stderr, "tokenize failed\n"); return 1; } + ids.resize(n); + } + Capture cap; + cap.n_embd = llama_model_n_embd(mdl); + cap.n_layer = llama_model_n_layer(mdl); + llama_context_params cp = llama_context_default_params(); + // STRATA_DUMP_CTX: a smaller context / batch (the parity sequences are a few hundred tokens) for a file whose + // weights leave no VRAM for the 4096-token compute buffers (UD-Q6_K_XL on a 32 GB card) + const char* cx = std::getenv("STRATA_DUMP_CTX"); + const int nctx = cx ? std::atoi(cx) : 4096; + cp.n_ctx = nctx; + cp.n_batch = cp.n_ubatch = nctx; + cp.op_offload = ngl > 0; // --ngl 0 is the CPU backend: no prompt matmuls offloaded to a GPU either + cp.cb_eval = on_tensor; + cp.cb_eval_user_data = ∩ + llama_context* ctx = llama_init_from_model(mdl, cp); + if (!ctx) { std::fprintf(stderr, "cannot create the context\n"); return 1; } + FILE* fl = dump_layers.empty() ? nullptr : std::fopen(dump_layers.c_str(), "wb"); + FILE* fg = dump_logits.empty() ? nullptr : std::fopen(dump_logits.c_str(), "wb"); + FILE* ff = dump_full.empty() ? nullptr : std::fopen(dump_full.c_str(), "wb"); + const std::vector forced = parse_ids(force); + if (!forced.empty()) n_gen = (int) forced.size() + 1; + const int V = llama_vocab_n_tokens(vocab); + auto write_layers = [&](int n_tok) { + if (!fl) return; + // a layer may keep fewer rows than the batch (the last layer keeps only the output rows): those are the + // batch's LAST positions; the positions it did not compute are written as zeros + std::vector zero(cap.n_embd, 0.f); + for (int t = 0; t < n_tok; ++t) + for (int l = 0; l < cap.n_layer; ++l) { + auto it = cap.layers.find(l); + const int rows = it == cap.layers.end() ? 0 : (int) (it->second.size() / cap.n_embd); + const int r = t - (n_tok - rows); + const float* src = r >= 0 ? it->second.data() + (size_t) r * cap.n_embd : zero.data(); + std::fwrite(src, 4, cap.n_embd, fl); + } + cap.layers.clear(); + }; + std::printf("prompt:"); + for (int t : ids) std::printf(" %d", t); + std::printf("\n"); + std::vector gen; + llama_batch b = llama_batch_get_one(ids.data(), (int) ids.size()); + if (llama_decode(ctx, b) != 0) { std::fprintf(stderr, "decode failed\n"); return 1; } + write_layers((int) ids.size()); + for (int i = 0; i < n_gen; ++i) { + const float* lg = llama_get_logits_ith(ctx, -1); + int a = 0, c = -1; + for (int j = 1; j < V; ++j) if (lg[j] > lg[a]) a = j; + for (int j = 0; j < V; ++j) if (j != a && (c < 0 || lg[j] > lg[c])) c = j; + if (fg) { const float rec[4] = {(float) a, lg[a], (float) c, lg[c]}; std::fwrite(rec, 4, 4, fg); } + gen.push_back(a); + if (ff) std::fwrite(lg, 4, V, ff); + if (i + 1 == n_gen) break; + llama_token t = i < (int) forced.size() ? forced[i] : a; + llama_batch one = llama_batch_get_one(&t, 1); + if (llama_decode(ctx, one) != 0) { std::fprintf(stderr, "decode failed\n"); return 1; } + write_layers(1); + } + std::printf("gen:"); + for (int t : gen) std::printf(" %d", t); + std::printf("\n"); + if (fl) std::fclose(fl); + if (fg) std::fclose(fg); + if (ff) std::fclose(ff); + llama_free(ctx); + llama_model_free(mdl); + llama_backend_free(); + return 0; +} diff --git a/tools/strata_inspect.py b/tools/strata_inspect.py index 66cb727c..5d094d80 100644 --- a/tools/strata_inspect.py +++ b/tools/strata_inspect.py @@ -29,6 +29,7 @@ import quantscope as qs # noqa: E402 FINGERPRINTS = ROOT / "data" / "gguf_fingerprints.json" ARCH = "qwen4exp" # Qwen3.8-Flash-Next's general.architecture +PREVIEW_ARCHS = {"qwen35moe": "Qwen3.6-35B-A3B"} # model families Strata knows but does not run yet (T0) # the files setup installs: (family, model, ModelScope repository, file name prefix) - for --fingerprints KNOWN = [ @@ -88,10 +89,15 @@ def load_fingerprints(path: Path = FINGERPRINTS) -> dict: def verdict(fp: dict, table: dict) -> tuple[str, str]: - """(kind, sentence): kind is "known" (a file setup installs, under any name), "layout" (the same routed-expert + """(kind, sentence): kind is "known" (a file setup installs, under any name), "family" (another family Strata + runs on its own engine path: Qwen3.6), "layout" (the same routed-expert layout as one: a fine-tune made with the same recipe, untested), "no" (Strata cannot run it) or "untested" (naming the tensors whose quantization no file Strata runs has for them).""" known = {k: v for k, v in table.items() if not k.startswith("_")} + if fp["arch"] in PREVIEW_ARCHS: + return "family", (f"{PREVIEW_ARCHS[fp['arch']]} (architecture {fp['arch']!r}): Strata runs it on its own " + "engine path in the NVIDIA (CUDA) and AMD (HIP) builds, not yet on Intel Arc (SYCL); setup " + "installs it with --family qwen36") if fp["arch"] != ARCH: return "no", f"not Qwen3.8-Flash-Next (architecture {fp['arch']!r}): Strata runs only that model" exact = [k for k, v in known.items() if v["expert_bytes"] == fp["expert_bytes"] and v["bytes"] == fp["bytes"] diff --git a/tools/test_setup_qwen36.py b/tools/test_setup_qwen36.py new file mode 100644 index 00000000..7358a3d8 --- /dev/null +++ b/tools/test_setup_qwen36.py @@ -0,0 +1,197 @@ +"""Tests for setup.py's Qwen3.6-35B-A3B install (a family with its own engine path: OWN_PATH_FAMILIES): the pinned and +hashed files, the menu entry, steps 2-7 of install_own_path (size, context, the engine's --families check, the +download, the tokenizer, the config) and reading such a config back. Mocked engine, downloads and processes - +nothing is built, fetched or started. + + python -m unittest tools.test_setup_qwen36 +""" +from __future__ import annotations + +import argparse +import contextlib +import io +import json +import re +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +import setup # noqa: E402 + +SHA = re.compile(r"/resolve/[0-9a-f]{40}/") +REPO = "unsloth/Qwen3.6-35B-A3B-MTP-GGUF" + + +def args(**kw): + base = dict(family="qwen36", model=None, check=False, yes=True, vision=None, models_dir=None, gguf_dir=None, + context=None, rope_scaling=None, rope_scale=None, kv=None, resident_budget_gib=None, low_ram="auto", + vram_reserve_mib=None, host=None, api_key=None, browser=None, no_start=True, data_dir=None, gpu=None) + base.update(kw) + return argparse.Namespace(**base) + + +def run(fn, *a, **kw): + out = io.StringIO() + with contextlib.redirect_stdout(out): + try: + return fn(*a, **kw), out.getvalue() + except SystemExit as e: + return e.code, out.getvalue() + + +class Qwen36Entries(unittest.TestCase): + def test_pinned_and_hashed(self): + fam = setup.OWN_PATH_FAMILIES["qwen36"] + self.assertIs(setup.PREVIEW_FAMILIES, setup.OWN_PATH_FAMILIES) # the earlier name still works + self.assertEqual(setup.HF_REVISIONS[REPO], "5bc3e238d916f48a861bac2f8a1990a0e9b7e98d") + for key in ("hf", "mmproj_hf"): + self.assertRegex(fam[key], SHA) + self.assertIn(REPO, fam[key]) + self.assertEqual(fam["arch"], "qwen35moe") + self.assertEqual(list(fam["models"]), ["UD-Q4_K_XL", "UD-Q6_K_XL", "Q8_0"]) + for m in fam["models"]: + size, sha = fam["sha256"][fam["file"].format(q=m)] + self.assertGreater(size, 20e9) + self.assertRegex(sha, r"^[0-9a-f]{64}$") + self.assertEqual(fam["sha256"]["Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf"][0], 22853663008) + + def test_not_a_pack_family(self): + # FAMILIES are Flash-Next files with packs; Qwen3.6 is installed by install_own_path + self.assertNotIn("qwen36", setup.FAMILIES) + for m, d in setup.MODELS.items(): + self.assertNotIn("qwen36", d.get("families", ())) + + def test_size_recommendation(self): + fam = setup.OWN_PATH_FAMILIES["qwen36"] + self.assertEqual(setup.own_path_size(fam, 24.0), "UD-Q4_K_XL") # none fits: the smallest + self.assertEqual(setup.own_path_size(fam, 32.0), "UD-Q4_K_XL") + self.assertEqual(setup.own_path_size(fam, 46.0), "UD-Q6_K_XL") + self.assertEqual(setup.own_path_size(fam, 64.0), "Q8_0") + + def test_context_recommendation(self): + fam = setup.OWN_PATH_FAMILIES["qwen36"] + self.assertEqual(setup.own_path_context(fam, 12.0), 32768) + self.assertEqual(setup.own_path_context(fam, 16.0), 32768) + self.assertEqual(setup.own_path_context(fam, 24.0), 65536) + self.assertEqual(setup.own_path_context(fam, 32.0), 131072) + + +class InstallOwnPath(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.calls = [] + self.families = {"qwen4exp", "qwen35moe"} + eng = self.root / "engine" + self.cfg = {} + + def engine_step(a, gpu, hip, amd, cuda_tk, vision): + self.calls.append(("engine", vision)) + return self.root / "llama", eng, {"version": "0.1.44"}, ["/libs"], gpu, vision + + def write_cfg(path, cfg, source=None): + self.cfg = cfg + self.calls.append(("config", path.name)) + + patches = [mock.patch.object(setup, "download", lambda url, dst, what=None: self.calls.append(("get", url, dst))), + mock.patch.object(setup, "verify_sha256", lambda s, size, sha: self.calls.append(("sha", s.name))), + mock.patch.object(setup, "free_gb", lambda p: 500.0), + mock.patch.object(setup, "pip_install", lambda *a, **k: None), + mock.patch.object(setup, "engine_step", engine_step), + mock.patch.object(setup, "engine_families", lambda e: self.families), + mock.patch.object(setup, "run", lambda cmd, **k: self.calls.append(("run", cmd))), + mock.patch.object(setup, "data_folder", lambda d: (self.root / "data", [])), + mock.patch.object(setup, "write_setup_config", write_cfg), + mock.patch.object(setup, "write_run_script", lambda tag, p, port, o=True: self.root / f"run-{tag}.sh"), + mock.patch.object(setup, "recommend_pool_workers", lambda a: a), + mock.patch.object(setup, "ROOT", self.root)] + for p in patches: + p.start() + self.addCleanup(p.stop) + + def install(self, ram=64.0, vram=16.0, **kw): + gpu = {"index": 0, "count": 1, "vram_gb": vram, "name": "Test GPU"} + return run(setup.install_own_path, args(models_dir=str(self.root / "models"), **kw), "qwen36", gpu, False, [], + 13, [], 8080, ram, None) + + def test_installs_the_pinned_file_and_writes_the_config(self): + rc, out = self.install(model="UD-Q4_K_XL") + self.assertEqual(rc, 0, out) + get = [c for c in self.calls if c[0] == "get"] + self.assertEqual(len(get), 1) + gguf = self.root / "models" / "qwen36-UD-Q4_K_XL" / "Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf" + self.assertEqual(get[0][1], setup.hf(REPO) + gguf.name) + self.assertEqual(get[0][2], gguf) + self.assertIn(("sha", gguf.name), self.calls) + self.assertIn(("engine", "none"), self.calls) # no image encoder for this family yet + tok = [c for c in self.calls if c[0] == "run"] + self.assertTrue(tok and "strata_tokenizer.py" in str(tok[0][1])) + a = self.cfg["args"] + self.assertEqual(a[a.index("--native") + 1], str(gguf)) + self.assertEqual(a[a.index("--max-context") + 1], "32768") # 16 GB card + self.assertEqual(a[a.index("--mtp") + 1], "2") + self.assertNotIn("--pack", a) + self.assertNotIn("--expert-cache", a) + self.assertEqual(self.cfg["arch"], "qwen35moe") + self.assertEqual(self.cfg["model_name"], "qwen3.6-35b-a3b-ud-q4_k_xl") + self.assertEqual(Path(self.cfg["exe"]).parent, self.root / "engine") + self.assertIn(("config", "strata-qwen36-ud-q4_k_xl.json"), self.calls) + + def test_default_size_follows_the_ram(self): + rc, out = self.install(ram=64.0) + self.assertEqual(rc, 0, out) + self.assertIn("Recommended for 64 GB of RAM: Q8_0", out) + self.assertTrue(self.cfg["args"][self.cfg["args"].index("--native") + 1].endswith("Qwen3.6-35B-A3B-Q8_0.gguf")) + rc, out = self.install(ram=46.0) + self.assertTrue(self.cfg["args"][self.cfg["args"].index("--native") + 1].endswith("UD-Q6_K_XL.gguf")) + + def test_a_bigger_size_than_the_ram_is_asked_not_refused(self): + with mock.patch.object(setup, "confirm_risk", lambda *a, **k: None): + rc, out = self.install(ram=32.0, model="Q8_0") + self.assertEqual(rc, 0, out) + self.assertIn("installing Q8_0 with 32 GB of RAM, as you chose", out) + + def test_an_engine_without_the_family_is_refused_before_the_download(self): + self.families = {"qwen4exp"} + rc, out = self.install(model="UD-Q4_K_XL") + self.assertEqual(rc, 1) + self.assertIn("does not run Qwen3.6-35B-A3B yet", out) + self.assertEqual([c for c in self.calls if c[0] == "get"], []) + + def test_a_flash_next_size_is_refused(self): + rc, out = self.install(model="IQ3_XXS") + self.assertEqual(rc, 1) + self.assertIn("has no IQ3_XXS", out) + self.assertEqual(self.calls, []) + + def test_too_little_disk(self): + with mock.patch.object(setup, "free_gb", lambda p: 10.0): + rc, out = self.install(model="Q8_0") + self.assertEqual(rc, 1) + self.assertIn("not enough free disk space", out) + + def test_bigger_card_bigger_context_and_vision_said_off(self): + rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, vision="yes") + self.assertEqual(rc, 0, out) + a = self.cfg["args"] + self.assertEqual(a[a.index("--max-context") + 1], "131072") + self.assertIn("images are not available", out) + + def test_config_read_back(self): + self.install(model="UD-Q6_K_XL", context=65536) + p = self.root / "strata-qwen36-ud-q6_k_xl.json" + p.write_text(json.dumps(self.cfg), encoding="utf-8") + ch = setup.choices_from_config(p) + self.assertEqual((ch["family"], ch["model"], ch["context"]), ("qwen36", "UD-Q6_K_XL", 65536)) + self.assertTrue(setup.own_path_config(self.cfg)) + self.assertEqual(setup.calibration_targets([p], None, None), []) # the tuning is Flash-Next's + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_strata_inspect.py b/tools/test_strata_inspect.py index db375497..247e46de 100644 --- a/tools/test_strata_inspect.py +++ b/tools/test_strata_inspect.py @@ -42,6 +42,14 @@ class Verdict(unittest.TestCase): fp["arch"] = "qwen3moe" self.assertEqual(SI.verdict(fp, self.table)[0], "no") + def test_qwen36_runs_on_its_own_path(self): + fp = self.fp("qwen/Q2_0") + fp["arch"] = "qwen35moe" + kind, sentence = SI.verdict(fp, self.table) + self.assertEqual(kind, "family") + self.assertIn("Qwen3.6-35B-A3B", sentence) + self.assertIn("--family qwen36", sentence) + def test_expert_type_without_kernel(self): fp = self.fp("qwen/IQ3_S") fp["expert_bytes"] = {"IQ1_S": 30_000_000_000}