From 65a1111e3a19967a3afe022511382a0bb48d9d74 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 20:50:24 +0200 Subject: [PATCH 1/7] Split GGUF artifacts: every shard found (a missing one is an error), tensors from their owning shard, per-role expert files (native_experts.txt v4) Groundwork for Unsloth's UD-Q4_K_XL (4 shards: shard 1 metadata only, output/token_embd/PLE table in shard 2, layer 11's down in shard 2 and its gate/up in shard 3). Existing packs load unchanged. - include/strata/artifact/gguf_split.hpp: gguf_split_paths (from eddoursul/Strata 8029fa9) finds the shards from any shard's name; a missing shard is an error naming it. It replaces generate.cpp's model_shards(), which skipped a shard it could not open. - gguf_reader.hpp: GgufModel (8029fa9) looks a tensor up across the shards and refuses a name in two shards; the split keys are validated as #255 (gopinath87607) does for the head: shard 1 carries the architecture, later shards declare split.count / split.no / split.tensors.count consistently, and the directories add up to split.tensors.count. tensor_payload_bytes / in_bounds for payload checks. - NativeHead::load / NativeEmbed::load take the shard list: the architecture from the metadata shard, the tensor from the shard that holds it; the embedding also checks its payload is in the file. - generate: --native resolves all shards once (native_shards), the head from --native-head-gguf's family, the model keys from the metadata shard; --ple-gguf defaults to the shard that holds per_layer_token_embd.weight. - native_experts.txt: the shard column may be per role, `gate,up,down` (#255's comma form; empty = the --native shard). The reader accepts v2-v4 and refuses a higher version; an engine older than this one fails to open a "gate,up,down" file loudly. Fixes the parse's own aliasing hazard (parts.assign(3, parts[0])). - load_experts_gguf reads each role from its file, after check_experts_gguf proved every (file, offset) is that tensor, of the pack's type and dimensions, and inside its file. - Tests (synthetic, no model, no GPU): gguf_split_test (4 shards, missing shard, duplicate, split keys, count, truncation); expert_layout_test (copies of the Q2_0/IQ2_XS/IQ3_XXS/IQ3_S/Coder/Swift packs' native_experts.txt parse field for field as before; v4 column; v5 / 4 / 2 names refused; the arena from split synthetic shards at 2560/640 with Q4_K/Q5_1 and Q5_K/Q8_0, every byte compared, and wrong offset / file / type / shape / truncated / missing shard refused). --- .gitattributes | 3 + CMakeLists.txt | 12 + include/strata/artifact/gguf_reader.hpp | 104 +++++++ include/strata/artifact/gguf_split.hpp | 52 ++++ include/strata/core/expert_source.hpp | 18 +- include/strata/core/native_head.hpp | 7 +- include/strata/kernels/cpu/expert_layout.hpp | 15 +- src/core/expert_source.cpp | 106 ++++++-- src/core/native_head.cpp | 36 ++- src/kernels/cpu/expert_layout.cpp | 37 ++- src/program/generate.cpp | 60 +++-- tests/core/expert_layout_test.cpp | 269 +++++++++++++++++++ tests/core/gguf_fixture.hpp | 103 +++++++ tests/core/gguf_split_test.cpp | 186 +++++++++++++ tests/data/native_experts/coder-iq1_m.txt | 49 ++++ tests/data/native_experts/iq2_xs.txt | 49 ++++ tests/data/native_experts/iq3_s.txt | 49 ++++ tests/data/native_experts/iq3_xxs.txt | 49 ++++ tests/data/native_experts/q2_0.txt | 49 ++++ tests/data/native_experts/swift-iq2_xs.txt | 49 ++++ 20 files changed, 1235 insertions(+), 67 deletions(-) create mode 100644 include/strata/artifact/gguf_split.hpp create mode 100644 tests/core/expert_layout_test.cpp create mode 100644 tests/core/gguf_fixture.hpp create mode 100644 tests/core/gguf_split_test.cpp create mode 100644 tests/data/native_experts/coder-iq1_m.txt create mode 100644 tests/data/native_experts/iq2_xs.txt create mode 100644 tests/data/native_experts/iq3_s.txt create mode 100644 tests/data/native_experts/iq3_xxs.txt create mode 100644 tests/data/native_experts/q2_0.txt create mode 100644 tests/data/native_experts/swift-iq2_xs.txt diff --git a/.gitattributes b/.gitattributes index dc1b7ba2..466d97e8 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,3 +4,6 @@ bench/prompts/** -text # launchers keep their platform line endings wherever the repository is cloned *.sh text eol=lf *.bat text eol=crlf + +# copies of real packs' native_experts.txt, parsed byte for byte by tests/core/expert_layout_test.cpp +tests/data/native_experts/** -text diff --git a/CMakeLists.txt b/CMakeLists.txt index bc3c0b2b..ab2eef40 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -148,6 +148,10 @@ if(STRATA_BUILD_TESTS) add_executable(gguf_reader_test src/artifact/gguf_reader_test.cpp) target_link_libraries(gguf_reader_test PRIVATE strata_artifact) add_test(NAME gguf_reader_test COMMAND gguf_reader_test) + # a split model's shards and their joint view: missing shard, split keys, duplicates, truncation (synthetic) + 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) endif() # ---- strata_plan ---------------------------------------------------------- @@ -321,6 +325,14 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_test(NAME file_expert_source_test COMMAND file_expert_source_test) set_tests_properties(file_expert_source_test PROPERTIES TIMEOUT 60) endif() + if(STRATA_BUILD_TESTS AND STRATA_NATIVE_EXPERTS) + # native_experts.txt v2-v4 (the real packs' copies and the per-role shard column) and the arena filled from + # synthetic GGUF shards at the real expert dimensions + add_executable(expert_layout_test tests/core/expert_layout_test.cpp) + target_link_libraries(expert_layout_test PRIVATE strata_engine) + add_test(NAME expert_layout_test COMMAND expert_layout_test ${CMAKE_CURRENT_SOURCE_DIR}/tests/data/native_experts) + set_tests_properties(expert_layout_test PROPERTIES TIMEOUT 60) + endif() if(STRATA_BUILD_CONVERSATION_TESTS) add_executable(conversation_snapshot_test src/core/conversation_snapshot_test.cpp) target_link_libraries(conversation_snapshot_test PRIVATE strata_engine) diff --git a/include/strata/artifact/gguf_reader.hpp b/include/strata/artifact/gguf_reader.hpp index ee76f3c0..42e0665e 100644 --- a/include/strata/artifact/gguf_reader.hpp +++ b/include/strata/artifact/gguf_reader.hpp @@ -23,6 +23,8 @@ #include #include #include +#include +#include #include #include #include @@ -30,6 +32,8 @@ #include #include +#include "strata/artifact/gguf_split.hpp" + #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #ifndef NOMINMAX @@ -342,6 +346,8 @@ public: uint32_t version() const { return version_; } uint64_t data_start() const { return data_start_; } uint64_t file_size() const { return size_; } + uint64_t alignment() const { return alignment_; } + const std::string& path() const { return path_; } const TensorInfo* find(const std::string& name) const { for (const auto& t : tensors_) @@ -460,6 +466,104 @@ private: std::map meta_; }; +// Bytes of a tensor's payload from its shape and block geometry; 0 when the type is unknown, a row is not whole +// blocks, or the count overflows. +inline uint64_t tensor_payload_bytes(const TensorInfo& t) { + int be = 0, bb = 0; + if (t.shape.empty() || !block_geometry(t.type, be, bb) || t.shape[0] % (uint64_t) be) return 0; + uint64_t elements = 1; + for (uint64_t d : t.shape) { + if (d == 0 || elements > (std::numeric_limits::max)() / d) return 0; + elements *= d; + } + const uint64_t blocks = elements / (uint64_t) be; + if (blocks > (std::numeric_limits::max)() / (uint64_t) bb) return 0; + return blocks * (uint64_t) bb; +} + +// The shards of one model (strata::gguf_split_paths), opened together; tensors are looked up across all of them. +// From eddoursul/Strata 8029fa9, with the split-key validation of #255 (gopinath87607) made a property of the +// model rather than of one loader: a split GGUF carries the model's metadata (general.architecture and the +// qwen4exp keys) in its FIRST shard only, and the later shards just declare split.count / split.no / +// split.tensors.count. Unsloth's UD-Q4_K_XL is the extreme case: shard 1 holds the metadata and no tensor at +// all, and output.weight, token_embd.weight and the PLE table live in shard 2. So the architecture is checked +// on `meta()` and a tensor is read from the shard that holds it. +// +// Refused at construction: a later shard whose split keys disagree with shard 1's (another model's shard, or a +// shard renamed into the family), a split model whose tensor directories do not add up to split.tensors.count, +// and a tensor name present in two shards (GGUF has no index to say which one is meant). +class GgufModel { +public: + explicit GgufModel(const std::vector& paths) { + if (paths.empty()) throw std::runtime_error("GGUF: a model needs at least one shard"); + for (const auto& p : paths) shards_.push_back(std::make_unique(p)); + validate_split(); + for (size_t i = 0; i < shards_.size(); ++i) + for (const auto& t : shards_[i]->tensors()) { + const auto ins = index_.emplace(t.name, std::make_pair(i, &t)); + if (!ins.second) + throw std::runtime_error("GGUF: tensor " + t.name + " is in two shards (" + + shards_[ins.first->second.first]->path() + " and " + + shards_[i]->path() + ")"); + } + } + /// Opens every shard of the model that `any_shard` belongs to (throws when one is missing). + static GgufModel open(const std::string& any_shard) { return GgufModel(gguf_split_paths(any_shard)); } + + size_t size() const { return shards_.size(); } + const GgufFile& shard(size_t i) const { return *shards_[i]; } + /// The metadata shard: general.architecture and the model's keys. + const GgufFile& meta() const { return *shards_[0]; } + /// The tensor named `name` (its shard index in `*shard`), or nullptr. + const TensorInfo* find(const std::string& name, size_t* shard = nullptr) const { + const auto it = index_.find(name); + if (it == index_.end()) return nullptr; + if (shard) *shard = it->second.first; + return it->second.second; + } + /// Whether `t` (a tensor of shard `s`) has a known byte count that lies inside its file. + bool in_bounds(const TensorInfo& t, size_t s) const { + const GgufFile& g = *shards_[s]; + const uint64_t bytes = tensor_payload_bytes(t); + const uint64_t payload = g.file_size() - g.data_start(); + return bytes != 0 && t.offset <= payload && bytes <= payload - t.offset; + } + +private: + void validate_split() const { + const size_t n = shards_.size(); + const MetaValue* count0 = shards_[0]->get("split.count"); + if (n == 1) { + if (count0 && count0->u > 1) + throw std::runtime_error("GGUF: " + shards_[0]->path() + " is shard 1 of " + std::to_string(count0->u) + + ", but it was opened as a whole model"); + return; + } + if (!shards_[0]->get("general.architecture")) + throw std::runtime_error("GGUF: " + shards_[0]->path() + " has no general.architecture; the first shard " + "of a split model carries the metadata"); + const MetaValue* total = shards_[0]->get("split.tensors.count"); + uint64_t tensors = 0; + for (size_t i = 0; i < n; ++i) { + const GgufFile& g = *shards_[i]; + const MetaValue* count = g.get("split.count"); + const MetaValue* no = g.get("split.no"); + const MetaValue* tc = g.get("split.tensors.count"); + if (!count || !no || count->u != n || no->u != i || (total && (!tc || tc->u != total->u))) + throw std::runtime_error("GGUF: " + g.path() + " does not declare itself shard " + std::to_string(i + 1) + + " of " + std::to_string(n) + " of this model (split.count / split.no / " + "split.tensors.count)"); + tensors += g.tensors().size(); + } + if (total && tensors != total->u) + throw std::runtime_error("GGUF: the " + std::to_string(n) + " shards hold " + std::to_string(tensors) + + " tensors, but split.tensors.count is " + std::to_string(total->u)); + } + + std::vector> shards_; + std::map> index_; +}; + // ---- architecture guard (P1.S2). The engine is specialised to ONE model; anything else must be // refused with a precise error rather than silently mis-run. struct Qwen4ExpGuard { diff --git a/include/strata/artifact/gguf_split.hpp b/include/strata/artifact/gguf_split.hpp new file mode 100644 index 00000000..0f01001f --- /dev/null +++ b/include/strata/artifact/gguf_split.hpp @@ -0,0 +1,52 @@ +// include/strata/artifact/gguf_split.hpp - the shards of a split model. Separate from gguf_reader.hpp, which +// includes , so any translation unit can resolve a model's shards. +// +// From eddoursul/Strata 8029fa9 (gguf_split_paths), with one change of contract: upstream's model_shards() +// skipped a shard it could not open and returned the rest, so a download that was still running (or a shard +// deleted by hand) produced a model with some layers missing and an error much later, or none. A missing shard +// is now an error that names it. +#pragma once + +#include +#include +#include +#include +#include + +namespace strata { + +// Split models: `-00001-of-0000N.gguf` ... `-0000N-of-0000N.gguf`, as llama.cpp's gguf-split names +// them. Given ANY shard's path, the shards in split order (the metadata shard, 00001, first); a file without that +// suffix is a model of one shard. Only the five digits of the shard number are rewritten, so the directory and +// the stem are the caller's own spelling (a symlinked Hugging Face snapshot keeps its split names). Throws when +// a shard is missing. +inline std::vector gguf_split_paths(const std::string& any) { + static const char tag[] = "-of-"; + const size_t at = any.rfind(tag); + // "...-NNNNN-of-MMMMM.gguf": five digits before the tag, five after it, then the extension + if (at == std::string::npos || at < 6 || any[at - 6] != '-' || any.size() != at + 4 + 5 + 5 || + any.compare(at + 9, 5, ".gguf") != 0) + return {any}; + int no = 0, n = 0; + for (size_t i = 0; i < 5; ++i) { + const char a = any[at - 5 + i], b = any[at + 4 + i]; + if (a < '0' || a > '9' || b < '0' || b > '9') return {any}; + no = no * 10 + (a - '0'); + n = n * 10 + (b - '0'); + } + if (n < 1 || no < 1 || no > n) return {any}; + std::vector out; + for (int i = 1; i <= n; ++i) { + char num[8]; + std::snprintf(num, sizeof num, "%05d", i); + std::string p = any; + p.replace(at - 5, 5, num); + if (!std::ifstream(p, std::ios::binary)) + throw std::runtime_error("missing model shard " + p + " (shard " + std::to_string(i) + " of " + + std::to_string(n) + "; is the download complete?)"); + out.push_back(std::move(p)); + } + return out; +} + +} // namespace strata diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 372412d6..8af105aa 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -32,9 +32,14 @@ #include #include +namespace strata::kernels::cpu { +struct ExpertLayout; +} + namespace strata::core { class RemoteExperts; +struct LoadStats; namespace detail { @@ -450,8 +455,9 @@ public: /// rate, because those are the two numbers that say whether the arena is the one that was asked for. bool open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int threads, std::string& err, uint64_t max_pinned_bytes = 0, const std::string& shared_arena_file = {}); - /// Plan v0.3 P6: a native pack without experts.bin takes its experts from the model's shard 1. - void set_gguf(const std::string& shard1) { gguf_ = shard1; } + /// Plan v0.3 P6: a native pack without experts.bin takes its experts from the model's GGUF: `native` is the + /// --native shard, and native_experts.txt names the other shards beside it (per layer, or per role in v4). + void set_gguf(const std::string& native) { gguf_ = native; } void close(); bool mapped() const { return base_ != nullptr; } @@ -489,4 +495,12 @@ private: std::string gguf_; }; +/// Plan v0.3 P6: checks native_experts.txt's GGUF spans against the files, before anything is read: each layer's +/// gate/up/down at its recorded (file, offset) must be that tensor (`blk.L.ffn__exps.weight`), of the +/// layout's type and dimensions, and inside the file. `native` is the --native shard (see set_gguf). +bool check_experts_gguf(const std::string& native, const strata::kernels::cpu::ExpertLayout& lay, std::string& err); +/// Fills `dst` (lay.total bytes, the experts.bin layout) from the GGUF files, one role at a time. +LoadStats load_experts_gguf(const std::string& native, uint8_t* dst, const strata::kernels::cpu::ExpertLayout& lay, + int threads); + } // namespace strata::core diff --git a/include/strata/core/native_head.hpp b/include/strata/core/native_head.hpp index 22b4c8db..ff45dd6e 100644 --- a/include/strata/core/native_head.hpp +++ b/include/strata/core/native_head.hpp @@ -3,12 +3,15 @@ #include #include #include +#include namespace strata::core { /// Opt-in native output projection. Uploads unchanged GGUF blocks once at startup and owns its /// activation scratch. The normal canonical head remains available for numerical A/B comparisons. /// Plan v0.3 P6: any type the native MMVQ takes (Q5_K in the Q2_0 / IQ3_XXS files, IQ4_XS in IQ2_XS). +/// `load` takes the model's shards (strata::gguf_split_paths): the architecture is checked on the first, the +/// tensor is read from the shard that holds it. class NativeHead { public: NativeHead() = default; @@ -16,7 +19,7 @@ public: NativeHead(const NativeHead&) = delete; NativeHead& operator=(const NativeHead&) = delete; - bool load(const std::string& gguf, int64_t n_in, int64_t n_out, std::string& err); + bool load(const std::vector& shards, int64_t n_in, int64_t n_out, std::string& err); bool run(const float* mixed, float* logits, void* stream, std::string& err) const; uint64_t weight_bytes() const { return bytes_; } bool loaded() const { return weights_ != nullptr; } @@ -43,7 +46,7 @@ public: ~NativeEmbed(); NativeEmbed(const NativeEmbed&) = delete; NativeEmbed& operator=(const NativeEmbed&) = delete; - bool load(const std::string& gguf, int64_t n_embd, int64_t n_vocab, std::string& err); + bool load(const std::vector& shards, int64_t n_embd, int64_t n_vocab, std::string& err); /// Rows for device token ids. void gather_dev(const int32_t* tokens, int64_t n_tok, float* out, void* stream) const; /// One row for a host token id. diff --git a/include/strata/kernels/cpu/expert_layout.hpp b/include/strata/kernels/cpu/expert_layout.hpp index 126549ae..ccbf0f8a 100644 --- a/include/strata/kernels/cpu/expert_layout.hpp +++ b/include/strata/kernels/cpu/expert_layout.hpp @@ -20,12 +20,15 @@ struct ExpertLayout { int64_t n_layers = 0, n_expert = NE; std::vector fmt; ///< per layer (native packs) std::vector offset, bytes; ///< per layer: where its 512 blobs start, bytes per blob - /// Plan v0.3 P6: per layer, the absolute offsets of the gate / up / down tensors in the model's shard 1, so - /// the arena can be filled from the GGUF itself when the pack has no experts.bin (3 x n_layers, 0 = unknown). + /// Plan v0.3 P6: per layer, the absolute offsets of the gate / up / down tensors in their GGUF files, so the + /// arena can be filled from the GGUF itself when the pack has no experts.bin (3 x n_layers, 0 = unknown). std::vector gguf_off; - /// Per layer, the GGUF file (a name beside the --native shard) that holds its experts when the model's - /// shards split the layers (Swift's GGUFs: layers 13-47 in shard 2). Empty = the --native shard itself. + /// Per layer PER ROLE (3 x n_layers, `3 * layer + role`, matching `gguf_off`), the GGUF file - a name beside + /// the --native shard - that holds that role's tensor. Empty = the --native shard itself. Per role because a + /// shard boundary can fall inside a layer: Unsloth's UD-Q4_K_XL has layer 11's down in shard 2 and its gate + /// and up in shard 3 (native_experts.txt v4, the `gate,up,down` shard column). std::vector gguf_file; + int version = 0; ///< native_experts.txt's header version (0 = none given) uint64_t max_blob = BLOB; uint64_t total = 0; ///< experts.bin size @@ -49,6 +52,10 @@ void act_quant_any(const float* x, int n, ActQ& a); /// The process-wide layout (canonical Q2_0 until `expert_layout_load` finds a native pack). const ExpertLayout& expert_layout(); /// Reads `/native_experts.txt` when it exists (a native pack), else sets the canonical layout. +/// Versions up to kExpertLayoutVersion are read; a newer one is refused (a newer packer wrote it). bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err); +/// The newest native_experts.txt this engine reads. v4 = v3 plus the per-role shard column `gate,up,down`, +/// written only when some layer's roles are in different shards (every other pack stays v3, byte for byte). +inline constexpr int kExpertLayoutVersion = 4; } // namespace strata::kernels::cpu diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index bb550123..71a2ecc5 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -2,6 +2,7 @@ #include "strata/core/expert_source.hpp" #include "strata/core/remote_experts.hpp" #include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/artifact/gguf_reader.hpp" #include "strata/core/pinned.hpp" #include "strata/platform/memory.hpp" @@ -21,6 +22,8 @@ #include #include #include +#include +#include #include #include #include @@ -1400,9 +1403,75 @@ bool shared_arena_pack_hash(const std::string& pack_dir, const std::string& expe } // namespace -// Plan v0.3 P6: the arena from the model's shard 1. Each layer's gate, up and down tensors hold the 512 experts -// one after another; they are read in chunks and each expert's slice lands at its place in the blob -// [gate rows | up rows | down rows] - the layout tools/iq_pack.py would have written to experts.bin. +namespace { +/// The GGUF file that holds role `r` (0 gate, 1 up, 2 down) of layer `l`: a name beside the --native shard +/// (native_experts.txt v3 per layer, v4 per role), or the --native shard itself. +std::string expert_gguf_file(const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay, int64_t l, int r) { + const size_t i = (size_t) (3 * l + r); + if (lay.gguf_file.size() <= i || lay.gguf_file[i].empty()) return gguf; + const size_t cut = gguf.find_last_of("/\\"); + return (cut == std::string::npos ? std::string() : gguf.substr(0, cut + 1)) + lay.gguf_file[i]; +} +} // namespace + +bool check_experts_gguf(const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay, std::string& err) { + static const char* roles[3] = {"gate", "up", "down"}; + if (lay.gguf_off.size() != (size_t) (3 * lay.n_layers)) { + err = "native_experts.txt has no GGUF offsets (a pack older than v2): repack it with tools/iq_pack.py"; + return false; + } + try { + std::map> files; + for (int64_t l = 0; l < lay.n_layers; ++l) { + const auto& fm = lay.fmt[(size_t) l]; + const uint64_t blob = lay.bytes[(size_t) l]; + const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off}; + for (int r = 0; r < 3; ++r) { + const std::string path = expert_gguf_file(gguf, lay, l, r); + auto& f = files[path]; + if (!f) f = std::make_unique(path); + const std::string name = "blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight"; + const strata::TensorInfo* t = f->find(name); + const uint64_t want_type = (uint64_t) (r < 2 ? fm.gu_type : fm.d_type); + // GGUF order: dim 0 is the row (the input), dim 1 the rows, dim 2 the experts + const uint64_t cols = (uint64_t) (r < 2 ? fm.n_embd : fm.n_ff); + const uint64_t rows = (uint64_t) (r < 2 ? fm.n_ff : fm.n_embd); + const uint64_t bytes = per[r] * (uint64_t) lay.n_expert; + const uint64_t payload = f->file_size() - f->data_start(); + std::string why; + if (t == nullptr) why = "is not in it"; + else if (t->type != want_type) + why = std::string("is ") + t->type_name() + ", the pack says type " + std::to_string(want_type); + else if (t->shape.size() != 3 || t->shape[0] != cols || t->shape[1] != rows || + t->shape[2] != (uint64_t) lay.n_expert) + why = "is not [" + std::to_string(cols) + ", " + std::to_string(rows) + ", " + + std::to_string(lay.n_expert) + "]"; + else if (strata::tensor_payload_bytes(*t) != bytes) + why = "is not " + std::to_string(per[r]) + " B per expert"; + else if (f->data_start() + t->offset != lay.gguf_off[(size_t) (3 * l + r)]) + why = "starts at byte " + std::to_string(f->data_start() + t->offset) + ", the pack says " + + std::to_string(lay.gguf_off[(size_t) (3 * l + r)]); + else if (t->offset > payload || bytes > payload - t->offset) + why = "runs past the end of the file (a truncated shard?)"; + if (!why.empty()) { + err = "the pack's native_experts.txt does not match the model: " + name + " in " + path + " " + + why + " - repack with tools/iq_pack.py from this model's shards"; + return false; + } + } + } + return true; + } catch (const std::exception& e) { + err = std::string("native experts from the GGUF: ") + e.what(); + return false; + } +} + +// Plan v0.3 P6: the arena from the model's GGUF shards. Each layer's gate, up and down tensors hold the 512 +// experts one after another; they are read in chunks and each expert's slice lands at its place in the blob +// [gate rows | up rows | down rows] - the layout tools/iq_pack.py would have written to experts.bin. Each role +// is read from its own file (native_experts.txt v4: a shard boundary can fall inside a layer; per role as in +// #255, gopinath87607). The caller checks the spans first (check_experts_gguf). LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata::kernels::cpu::ExpertLayout& lay, int threads) { LoadStats st; @@ -1410,13 +1479,6 @@ LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata: const auto t0 = std::chrono::steady_clock::now(); std::atomic next{0}; std::atomic bad{false}; - // a layer's experts may sit in another shard of the model (native_experts.txt v3): a name beside `gguf` - const size_t cut = gguf.find_last_of("/\\"); - const std::string dir = cut == std::string::npos ? std::string() : gguf.substr(0, cut + 1); - auto file_of = [&](int64_t l) -> std::string { - if (lay.gguf_file.empty() || lay.gguf_file[(size_t) l].empty()) return gguf; - return dir + lay.gguf_file[(size_t) l]; - }; auto worker = [&]() { std::ifstream f; std::string open_name; @@ -1424,19 +1486,20 @@ LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata: for (;;) { const int64_t l = next.fetch_add(1); if (l >= lay.n_layers || bad) break; - const std::string name = file_of(l); - if (name != open_name) { - f.close(); - f.clear(); - f.open(name, std::ios::binary); - if (!f) { bad = true; return; } - open_name = name; - } const auto& fm = lay.fmt[(size_t) l]; const uint64_t blob = lay.bytes[(size_t) l]; const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off}; const uint64_t at[3] = {0, fm.up_off, fm.down_off}; for (int r = 0; r < 3; ++r) { + // the handle is kept while consecutive roles share a file (every layer of a v3 pack) + const std::string name = expert_gguf_file(gguf, lay, l, r); + if (name != open_name) { + f.close(); + f.clear(); + f.open(name, std::ios::binary); + if (!f) { bad = true; return; } + open_name = name; + } const uint64_t src = lay.gguf_off[(size_t) (3 * l + r)]; const uint64_t total = per[r] * (uint64_t) lay.n_expert; const uint64_t chunk = per[r] * 16; // 16 experts per read @@ -1489,7 +1552,12 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6 const bool from_gguf = !std::ifstream(path, std::ios::binary) && lay.native && !lay.gguf_off.empty() && !gguf_.empty(); // SIZE CHECK BEFORE THE ALLOCATION, not after. A wrong pack should name the two numbers rather than spend // 34 GB and a minute of loading first. - if (!from_gguf) { + if (from_gguf) { + // every (file, offset) of native_experts.txt must be the tensor it claims, of the pack's type and + // dimensions and inside its file - before the allocation, so a pack of another model or a truncated + // shard is a message rather than an arena of plausible wrong experts + if (!check_experts_gguf(gguf_, lay, err)) { err = "ArenaExpertSource: " + err; return false; } + } else { std::ifstream f(path, std::ios::binary | std::ios::ate); if (!f) { err = "ArenaExpertSource: cannot open " + path; return false; } const uint64_t got = (uint64_t) f.tellg(); diff --git a/src/core/native_head.cpp b/src/core/native_head.cpp index 2f58cfbd..5eed99d1 100644 --- a/src/core/native_head.cpp +++ b/src/core/native_head.cpp @@ -16,22 +16,21 @@ NativeHead::~NativeHead() { if (weights_) cudaFree(weights_); } -bool NativeHead::load(const std::string& path, int64_t n_in, int64_t n_out, std::string& err) { +bool NativeHead::load(const std::vector& shards, int64_t n_in, int64_t n_out, std::string& err) { if (loaded()) { err = "native head is already loaded"; return false; } if (n_in <= 0 || n_out <= 0 || n_in > INT_MAX || n_out > INT_MAX || n_in % 256) { err = "native head requires positive int32 dimensions and whole 256-value rows"; return false; } try { - strata::GgufFile gguf(path); - err = strata::check_architecture(gguf); + // 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()); if (!err.empty()) return false; - const strata::TensorInfo* tensor = nullptr; - for (const auto& candidate : gguf.tensors()) { - if (candidate.name != "output.weight") continue; - if (tensor) { err = "native head: duplicate output.weight"; return false; } - tensor = &candidate; - } + size_t at = 0; + const strata::TensorInfo* tensor = model.find("output.weight", &at); + const strata::GgufFile& gguf = model.shard(at); if (!tensor || !strata::kernels::native_mmvq_supported((int) tensor->type) || tensor->shape.size() != 2 || tensor->shape[0] != (uint64_t) n_in || tensor->shape[1] != (uint64_t) n_out) { err = "native head: expected a natively supported output.weight with the canonical head dimensions"; @@ -106,12 +105,14 @@ NativeEmbed::~NativeEmbed() { else if (dev_) cudaFree(const_cast(dev_)); // the VRAM fallback below } -bool NativeEmbed::load(const std::string& path, int64_t n_embd, int64_t n_vocab, std::string& err) { +bool NativeEmbed::load(const std::vector& shards, int64_t n_embd, int64_t n_vocab, std::string& err) { try { - strata::GgufFile gguf(path); - const strata::TensorInfo* t = nullptr; - for (const auto& c : gguf.tensors()) - if (c.name == "token_embd.weight") t = &c; + const strata::GgufModel model(shards); + err = strata::check_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); + const strata::GgufFile& gguf = model.shard(at); if (!t || t->shape.size() != 2 || t->shape[0] != (uint64_t) n_embd || t->shape[1] != (uint64_t) n_vocab || !strata::kernels::iq_supported((int) t->type) || n_embd % 256) { err = "native embedding: token_embd.weight is absent, of another shape, or of a type without a GPU " @@ -120,6 +121,13 @@ bool NativeEmbed::load(const std::string& path, int64_t n_embd, int64_t n_vocab, } row_ = strata::kernels::iq_row_bytes((int) t->type, n_embd); bytes_ = (uint64_t) row_ * (uint64_t) n_vocab; + // the table is copied out of the mapping below: a truncated shard must be an error, not a read past EOF + if (!model.in_bounds(*t, at) || strata::tensor_payload_bytes(*t) != bytes_) { + err = "native embedding: token_embd.weight's payload is truncated or not " + std::to_string(bytes_) + + " B (" + gguf.path() + ")"; + bytes_ = 0; + return false; + } if (cudaHostAlloc(&host_, bytes_, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess) { // Under WSL2 the driver's pinned/mapped host budget (~1 GiB) can be spent by the GPU contexts // themselves (three cards). The table is only gathered from, so keep it in the current device's VRAM diff --git a/src/kernels/cpu/expert_layout.cpp b/src/kernels/cpu/expert_layout.cpp index ec78774c..6d4475be 100644 --- a/src/kernels/cpu/expert_layout.cpp +++ b/src/kernels/cpu/expert_layout.cpp @@ -95,6 +95,18 @@ bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n while (std::getline(in, line)) { if (line.empty() || line[0] == '#') { if (!line.empty() && line[0] == '#') { + // "# strata native experts vN: ...". A version this engine does not know may mean columns it + // would misread, so it is refused rather than parsed as far as the known columns go. + static const char tag[] = "# strata native experts v"; + if (line.compare(0, sizeof tag - 1, tag) == 0) { + L.version = std::atoi(line.c_str() + sizeof tag - 1); + if (L.version > kExpertLayoutVersion) { + err = "native_experts.txt is v" + std::to_string(L.version) + "; this engine reads up to v" + + std::to_string(kExpertLayoutVersion) + " (the pack was written by a newer tools/" + "iq_pack.py: update the engine, or repack with this one)"; + return false; + } + } // v3 packs record their expert count in the header; a pruned model (GSQ-RCO Coder) ships // fewer experts than the canonical geometry the caller passes, which is a compile-time // default, so the header wins. @@ -124,8 +136,29 @@ bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n L.gguf_off[(size_t) (3 * l + 2)] = dox; std::string file; // v3: the shard that holds this layer (a file name beside --native) if (ss >> file) { - if (L.gguf_file.empty()) L.gguf_file.assign((size_t) n_layers, std::string()); - L.gguf_file[(size_t) l] = file; + if (L.gguf_file.empty()) L.gguf_file.assign((size_t) (3 * n_layers), std::string()); + // One name covers all three roles. When a shard boundary falls inside a layer the packer writes + // "gate,up,down" instead (v4), an empty field meaning the --native shard. A GGUF file name has no + // comma, so the split is unambiguous; an engine older than v4 fails to open such a "file" loudly. + // The comma form is from #255 (gopinath87607). + std::vector parts; + for (size_t from = 0;;) { + const size_t comma = file.find(',', from); + parts.push_back(file.substr(from, comma == std::string::npos ? comma : comma - from)); + if (comma == std::string::npos) break; + from = comma + 1; + } + if (parts.size() == 1) { + const std::string one = parts[0]; // not parts.assign(3, parts[0]): that aliases the element + parts.assign(3, one); // the assignment is about to overwrite + } + std::string extra; + if (parts.size() != 3 || (ss >> extra)) { + err = "native_experts.txt: layer " + std::to_string(l) + ": the shard column is one name or " + "gate,up,down, not: " + line; + return false; + } + for (size_t r = 0; r < 3; ++r) L.gguf_file[(size_t) (3 * l) + r] = parts[r]; } } L.fmt[(size_t) l] = f; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index a30746ff..94de0ea7 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -192,6 +192,9 @@ struct Options { bool cpu_oracle_q8_0 = false; // pinned x86 activation scales/codes at both expert stages std::string native_head_gguf; // native output.weight experiment; same model shard as the pack std::vector native_dense_gguf; // repeat for native GDN/QSA projection shards + /// Every shard of --native's model (strata::gguf_split_paths: the metadata shard first; a missing shard is an + /// error) and of --native-head-gguf's (the same list unless that names another model). + std::vector native_shards, native_head_shards; /// Plan v0.3 P1: the whole native arithmetic set as ONE switch (model shard 1). It enables exactly the /// combination recorded in bench/results/2026-09-23-attention-ple plus the native indexer, and never the /// <=256-token attention adapter. It becomes the default once P0 shows it is not slower. @@ -384,7 +387,8 @@ void usage() { " --pack DIR the pack directory (default pack/full)\n" " --tokens LIST the prompt as comma-separated token IDS (required)\n" " --tokens-file PATH pretokenized prompt, commas or whitespace (alternative to --tokens)\n" - " --ple-gguf PATH required PLE table (original second GGUF shard)\n" + " --ple-gguf PATH required PLE table (original second GGUF shard); with --native, the model's\n" + " shard that holds per_layer_token_embd.weight when not given\n" " --no-ple explicit diagnostic ablation of the PLE layer\n" " --ple-io direct|mmap|ram n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n" " reads, the table never enters RAM or the file cache; mmap: A/B arm;\n" @@ -528,23 +532,6 @@ void usage() { " does not fit. Same answers as --mmap-experts for the same placement.\n"); } -/// All shards of a split GGUF, from shard 1's path ("...-00001-of-00002.gguf"); just the path when it is not split. -std::vector model_shards(const std::string& first) { - const std::string tag = "-00001-of-"; - const size_t at = first.rfind(tag); - if (at == std::string::npos || first.size() < at + tag.size() + 10) return {first}; - const int total = std::atoi(first.substr(at + tag.size(), 5).c_str()); - std::vector out; - for (int i = 1; i <= total && i <= 99; ++i) { - char num[8]; - std::snprintf(num, sizeof num, "%05d", i); - std::string p = first; - p.replace(at + 1, 5, num); - if (std::ifstream(p, std::ios::binary)) out.push_back(p); - } - return out.empty() ? std::vector{first} : out; -} - bool parse_i64_list(const char* s, std::vector& out, std::string& err) { out.clear(); std::string text(s); @@ -1364,8 +1351,24 @@ int main(int argc, char** argv) { } strata::core::layer_set_shared_early(!o.shared_late); if (!o.native_preset.empty()) { + 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); + // --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) { + const strata::GgufModel model(o.native_shards); + size_t at = 0; + if (model.find("per_layer_token_embd.weight", &at) != nullptr) o.ple_gguf = o.native_shards[at]; + } + } catch (const std::exception& e) { + std::fprintf(stderr, "strata generate: --native %s: %s\n", o.native_preset.c_str(), e.what()); + return 2; + } if (o.no_ple || o.ple_gguf.empty()) { - std::fprintf(stderr, "strata generate: --native requires --ple-gguf (the PLE key is native too)\n"); + std::fprintf(stderr, "strata generate: --native requires --ple-gguf (the PLE key is native too), and no " + "shard of the model holds per_layer_token_embd.weight\n"); return 2; } o.stream_token = true; @@ -1377,7 +1380,7 @@ int main(int argc, char** argv) { if (o.native_dense_gguf.empty()) { // every shard of the model (-0000N-of-0000M.gguf beside --native), then the PLE shard: a split // may put any layer in any shard (Swift's GGUFs: layers 13-47 in shard 2, the PLE table in shard 1) - o.native_dense_gguf = model_shards(o.native_preset); + o.native_dense_gguf = o.native_shards; if (std::find(o.native_dense_gguf.begin(), o.native_dense_gguf.end(), o.ple_gguf) == o.native_dense_gguf.end()) o.native_dense_gguf.push_back(o.ple_gguf); } @@ -1480,6 +1483,15 @@ int main(int argc, char** argv) { "session, which a layer split does not have; run them without --layer-split\n"); return 2; } + if (!o.native_head_gguf.empty()) { + try { + o.native_head_shards = o.native_head_gguf == o.native_preset ? o.native_shards + : strata::gguf_split_paths(o.native_head_gguf); + } catch (const std::exception& e) { + std::fprintf(stderr, "strata generate: --native-head-gguf %s: %s\n", o.native_head_gguf.c_str(), e.what()); + return 2; + } + } if (o.native_ple_key && (o.native_dense_gguf.empty() || o.no_ple)) { std::fprintf(stderr, "strata generate: --native-ple-key requires PLE and --native-dense-gguf\n"); return 2; @@ -1570,7 +1582,7 @@ int main(int argc, char** argv) { // a pruned variant (GSQ-RCO Coder) ships fewer experts than the canonical 512x10; the model file // is the authority on its own MoE shape - everything else in the geometry is unchanged try { - strata::GgufFile model_gguf(o.native_preset); + strata::GgufFile model_gguf(o.native_shards.front()); // the metadata shard if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_count")) g.n_expert = (int64_t) v->u; if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_used_count")) K = (int64_t) v->u; if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.freq_base")) gguf_rope_base = v->num(); @@ -1665,7 +1677,7 @@ int main(int argc, char** argv) { return 2; } const strata::core::ModelGeometry g0; - if (!native_embed.load(o.native_preset, g0.n_embd, 248320, err)) { + if (!native_embed.load(o.native_shards, g0.n_embd, 248320, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } @@ -2192,7 +2204,7 @@ int main(int argc, char** argv) { const bool last = i + 1 == stages.size(); const strata::core::WeightRef* wo_s = st.wt.find("output.weight"); if (wo_s == nullptr || - (last && !o.native_head_gguf.empty() && !st.head.load(o.native_head_gguf, g.n_embd, wo_s->ne1, err))) { + (last && !o.native_head_gguf.empty() && !st.head.load(o.native_head_shards, g.n_embd, wo_s->ne1, err))) { std::fprintf(stderr, "strata generate: layer split, CUDA%d head: %s\n", st.dev, wo_s == nullptr ? "output.weight is missing" : err.c_str()); return 1; @@ -2321,7 +2333,7 @@ int main(int argc, char** argv) { const int64_t n_vocab = wo->ne1; strata::core::NativeHead native_head; if (!o.native_head_gguf.empty() && !multi_gpu) { // a layer split's head is on its last stage - if (!native_head.load(o.native_head_gguf, g.n_embd, n_vocab, err)) { + if (!native_head.load(o.native_head_shards, g.n_embd, n_vocab, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } diff --git a/tests/core/expert_layout_test.cpp b/tests/core/expert_layout_test.cpp new file mode 100644 index 00000000..d532d746 --- /dev/null +++ b/tests/core/expert_layout_test.cpp @@ -0,0 +1,269 @@ +// tests/core/expert_layout_test.cpp - native_experts.txt (v2/v3/v4) and the expert arena filled from GGUF shards, +// without a model or a GPU. +// +// 1. Copies of the real packs' native_experts.txt (tests/data/native_experts: Q2_0, IQ2_XS, IQ3_XXS, IQ3_S, +// Coder IQ1_M, Swift IQ2_XS; v2 and v3 headers) parse to the layout the pre-v4 reader produced: the test +// parses each line again with that reader's rules (one shard name for all three roles) and compares every +// field, and the totals with the header's. +// 2. The v4 shard column `gate,up,down` (an empty field = the --native shard); v5, four names, two names and a +// trailing column are refused. +// 3. check_experts_gguf + load_experts_gguf on a synthetic arena at the real dimensions 2560/640 with Unsloth's +// format pairs (Q4_K/Q5_1, Q5_K/Q8_0): layer 1's gate/up in another file than its down. Every byte of the +// arena is compared with the source tensors. Then the refusals: an offset that is not the tensor's, a +// truncated file, a role named in the wrong file, a type or a shape the pack does not say, a missing file. +#include "gguf_fixture.hpp" + +#include "strata/core/expert_source.hpp" +#include "strata/core/pinned.hpp" +#include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/cpu/native_expert.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; +using strata::kernels::cpu::ExpertLayout; + +namespace { +int g_fail = 0; +void check(bool ok, const std::string& what) { + std::printf(" %-84s %s\n", what.c_str(), ok ? "ok" : "FAIL"); + if (!ok) ++g_fail; +} + +struct TempDir { + fs::path path; + TempDir() { + path = fs::temp_directory_path() / + ("strata-expert-layout-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); + } +}; + +void write_text(const fs::path& p, const std::string& s) { std::ofstream(p, std::ios::binary) << s; } + +bool load(const fs::path& dir, int64_t n_layers, int64_t n_expert, std::string& err) { + err.clear(); + return strata::kernels::cpu::expert_layout_load(dir.string(), n_layers, n_expert, err); +} + +// ---- 1. the real packs' files +void real_packs(const fs::path& data) { + for (const char* pack : {"q2_0", "iq2_xs", "iq3_xxs", "iq3_s", "coder-iq1_m", "swift-iq2_xs"}) { + TempDir d; + fs::copy_file(data / (std::string(pack) + ".txt"), d.path / "native_experts.txt"); + std::string err; + const bool ok = load(d.path, 48, 512, err); + check(ok, std::string(pack) + ": loads" + (ok ? "" : ": " + err)); + if (!ok) continue; + const ExpertLayout& L = strata::kernels::cpu::expert_layout(); + // the pre-v4 reader's rules, applied to the same text + std::ifstream in(d.path / "native_experts.txt"); + std::string line; + long long hdr_n = -1, hdr_total = -1; + bool same = L.native && L.n_layers == 48 && L.gguf_off.size() == 3 * 48; + uint64_t max_blob = 0; + while (std::getline(in, line)) { + if (line.empty()) continue; + if (line[0] == '#') { + if (line.find("(n_expert ") == std::string::npos) continue; + std::istringstream h(line.substr(line.find("(n_expert ") + 10)); + char comma = 0; + std::string word; + h >> hdr_n >> comma >> word >> hdr_total; // "(n_expert N, total T; ..." + continue; + } + std::istringstream ss(line); + long long l = 0, gt = 0, dt = 0; + unsigned long long off = 0, blob = 0, o[3] = {0, 0, 0}; + std::string file; + ss >> l >> gt >> dt >> off >> blob >> o[0] >> o[1] >> o[2]; + ss >> file; + same = same && L.fmt[(size_t) l].gu_type == gt && L.fmt[(size_t) l].d_type == dt && + L.offset[(size_t) l] == off && L.bytes[(size_t) l] == blob; + for (int r = 0; r < 3; ++r) { + same = same && L.gguf_off[(size_t) (3 * l + r)] == o[r]; + const std::string got = L.gguf_file.empty() ? std::string() : L.gguf_file[(size_t) (3 * l + r)]; + same = same && got == file; + } + if (blob > max_blob) max_blob = blob; + } + same = same && L.n_expert == hdr_n && (long long) L.total == hdr_total && L.max_blob == max_blob; + check(same, std::string(pack) + ": every field as the pre-v4 reader, totals as the header (v" + + std::to_string(L.version) + ", n_expert " + std::to_string(L.n_expert) + ")"); + } +} + +// ---- 2. the v4 column and the refusals +std::string manifest(int version, const std::string& col1, int64_t blob, int n_expert = 2) { + std::string s = "# strata native experts v" + std::to_string(version) + + ": layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard | gate,up,down] " + "(n_expert " + std::to_string(n_expert) + ", total " + std::to_string(2 * blob * n_expert) + ")\n"; + s += "0 12 7 0 " + std::to_string(blob) + " 100 200 300\n"; + s += "1 12 7 " + std::to_string(blob * n_expert) + " " + std::to_string(blob) + " 400 500 600" + + (col1.empty() ? "" : " " + col1) + "\n"; + return s; +} + +void columns() { + strata::kernels::cpu::NativeFmt f; + std::string err; + if (!strata::kernels::cpu::native_fmt(12, 7, 2560, 640, f, err)) { + check(false, "Q4_K/Q5_1 native format: " + err); + return; + } + const int64_t blob = (int64_t) f.bytes; + TempDir d; + write_text(d.path / "native_experts.txt", manifest(4, "B.gguf,B.gguf,", blob)); + bool ok = load(d.path, 2, 512, err); + const ExpertLayout& L = strata::kernels::cpu::expert_layout(); + check(ok && L.version == 4 && L.gguf_file.size() == 6 && L.gguf_file[0].empty() && L.gguf_file[2].empty() && + L.gguf_file[3] == "B.gguf" && L.gguf_file[4] == "B.gguf" && L.gguf_file[5].empty() && + L.gguf_off[5] == 600, + "v4: `B.gguf,B.gguf,` = gate and up in B.gguf, down in the --native shard" + (ok ? "" : ": " + err)); + write_text(d.path / "native_experts.txt", manifest(3, "A.gguf", blob)); + ok = load(d.path, 2, 512, err); + check(ok && L.gguf_file[3] == "A.gguf" && L.gguf_file[4] == "A.gguf" && L.gguf_file[5] == "A.gguf", + "v3: one name covers the three roles"); + write_text(d.path / "native_experts.txt", manifest(5, "", blob)); + ok = load(d.path, 2, 512, err); + check(!ok && err.find("v5") != std::string::npos, "v5 is refused (\"" + err.substr(0, 40) + "...\")"); + write_text(d.path / "native_experts.txt", manifest(4, "a,b,c,d", blob)); + check(!load(d.path, 2, 512, err) && err.find("gate,up,down") != std::string::npos, "four names are refused"); + write_text(d.path / "native_experts.txt", manifest(4, "a,b", blob)); + check(!load(d.path, 2, 512, err), "two names are refused"); + write_text(d.path / "native_experts.txt", manifest(4, "a extra", blob)); + check(!load(d.path, 2, 512, err), "a column after the shard column is refused"); +} + +// ---- 3. the arena from synthetic shards +void arena() { + using fixture::Tensor; + constexpr int64_t H = 2560, FF = 640, NE = 2; + const uint32_t Q4_K = 12, Q5_1 = 7, Q5_K = 13, Q8_0 = 8, Q3_K = 11, IQ3_S = 21; + strata::kernels::cpu::NativeFmt f0, f1; + std::string err; + if (!strata::kernels::cpu::native_fmt(Q4_K, Q5_1, H, FF, f0, err) || + !strata::kernels::cpu::native_fmt(Q5_K, Q8_0, H, FF, f1, err)) { + check(false, "Q4_K/Q5_1 and Q5_K/Q8_0 native formats: " + err); + return; + } + TempDir d; + const fs::path A = d.path / "M-00002-of-00003.gguf", B = d.path / "M-00003-of-00003.gguf"; + // A: layer 0 (all roles) and layer 1's down; B: layer 1's gate and up + const std::vector ta = {{"blk.0.ffn_gate_exps.weight", {H, FF, NE}, Q4_K, 11}, + {"blk.0.ffn_up_exps.weight", {H, FF, NE}, Q4_K, 12}, + {"blk.0.ffn_down_exps.weight", {FF, H, NE}, Q5_1, 13}, + {"blk.1.ffn_down_exps.weight", {FF, H, NE}, Q8_0, 23}}; + const std::vector tb = {{"blk.1.ffn_gate_exps.weight", {H, FF, NE}, Q5_K, 21}, + {"blk.1.ffn_up_exps.weight", {H, FF, NE}, Q5_K, 22}}; + const auto wa = fixture::write(A, {}, ta); + const auto wb = fixture::write(B, {}, tb); + auto at = [](const fixture::Written& w, size_t i) { return std::to_string(w.data_start + w.offsets[i]); }; + const uint64_t total = (f0.bytes + f1.bytes) * NE; + auto text = [&](const std::string& down1, const std::string& col1) { + return "# strata native experts v4: layer gu_type d_type offset blob_bytes gate_off up_off down_off " + "[shard | gate,up,down] (n_expert 2, total " + std::to_string(total) + ")\n" + + "0 12 7 0 " + std::to_string(f0.bytes) + " " + at(wa, 0) + " " + at(wa, 1) + " " + at(wa, 2) + "\n" + + "1 13 8 " + std::to_string(f0.bytes * NE) + " " + std::to_string(f1.bytes) + " " + at(wb, 0) + " " + + at(wb, 1) + " " + down1 + " " + col1 + "\n"; + }; + const fs::path pack = d.path / "pack"; + fs::create_directories(pack); + write_text(pack / "native_experts.txt", text(at(wa, 3), B.filename().string() + "," + B.filename().string() + ",")); + bool ok = load(pack, 2, 512, err); + check(ok, "the v4 manifest of the split layer loads" + (ok ? "" : ": " + err)); + if (!ok) return; + const ExpertLayout& L = strata::kernels::cpu::expert_layout(); + ok = strata::core::check_experts_gguf(A.string(), L, err); + check(ok, "check_experts_gguf: every span is its tensor" + (ok ? "" : ": " + err)); + std::vector dst((size_t) L.total, 0xEE); + const strata::core::LoadStats st = strata::core::load_experts_gguf(A.string(), dst.data(), L, 3); + check(st.ok && st.bytes == L.total && L.total == total, "load_experts_gguf reads the whole arena (" + + std::to_string(L.total) + " B)"); + // every byte: expert e's slice of role r comes from byte e * per[r] of that role's tensor + bool exact = true; + for (int64_t l = 0; l < 2 && exact; ++l) { + const auto& fm = L.fmt[(size_t) l]; + const uint64_t per[3] = {fm.up_off, fm.up_off, fm.bytes - fm.down_off}; + const uint64_t off[3] = {0, fm.up_off, fm.down_off}; + const uint8_t seed[2][3] = {{11, 12, 13}, {21, 22, 23}}; + for (int64_t e = 0; e < NE && exact; ++e) + for (int r = 0; r < 3 && exact; ++r) { + const uint8_t* got = dst.data() + L.blob_offset(l, e) + off[r]; + for (uint64_t j = 0; j < per[r]; ++j) + if (got[j] != fixture::pattern(seed[l][r], (uint64_t) e * per[r] + j)) { exact = false; break; } + } + } + check(exact, "every blob is [gate | up | down] of its expert, layer 1 from both files"); + + auto refused = [&](const std::string& what, const std::string& needle) { + std::string e2; + const bool bad = load(pack, 2, 512, e2) && !strata::core::check_experts_gguf(A.string(), + strata::kernels::cpu::expert_layout(), e2); + check(bad && e2.find(needle) != std::string::npos, what + " (\"..." + needle + "...\")"); + }; + const std::string both = B.filename().string() + "," + B.filename().string() + ","; + write_text(pack / "native_experts.txt", text(std::to_string(std::stoull(at(wa, 3)) + 32), both)); + refused("an offset that is not the tensor's is refused", "starts at byte"); + write_text(pack / "native_experts.txt", text(at(wa, 3), "")); + refused("layer 1's gate named in the file that does not hold it is refused", "is not in it"); + write_text(pack / "native_experts.txt", text(at(wa, 3), both + ",x")); + std::string e3; + check(!load(pack, 2, 512, e3), "a malformed column is refused at load"); + write_text(pack / "native_experts.txt", text(at(wa, 3), "missing.gguf,missing.gguf,")); + refused("a shard that is not there is refused", "cannot open"); + fixture::write(B, {}, tb, /*cut=*/100); + write_text(pack / "native_experts.txt", text(at(wa, 3), both)); + refused("a truncated shard is refused before anything is read", "past the end"); + + // a type and a shape the pack does not say: Q3_K and IQ3_S are both 110 B per 256, so only the type differs + TempDir d2; + const fs::path C = d2.path / "C.gguf"; + const auto wc = fixture::write(C, {}, {{"blk.0.ffn_gate_exps.weight", {H, FF, NE}, IQ3_S, 31}, + {"blk.0.ffn_up_exps.weight", {H, FF, NE}, Q3_K, 32}, + {"blk.0.ffn_down_exps.weight", {FF, H, NE + 1}, Q5_1, 33}}); + strata::kernels::cpu::NativeFmt f2; + if (!strata::kernels::cpu::native_fmt(Q3_K, Q5_1, H, FF, f2, err)) { + check(false, "Q3_K/Q5_1 native format: " + err); + return; + } + fs::create_directories(d2.path / "pack"); + write_text(d2.path / "pack" / "native_experts.txt", + "# strata native experts v3: (n_expert 2, total " + std::to_string(f2.bytes * NE) + ")\n0 11 7 0 " + + std::to_string(f2.bytes) + " " + std::to_string(wc.data_start + wc.offsets[0]) + " " + + std::to_string(wc.data_start + wc.offsets[1]) + " " + std::to_string(wc.data_start + wc.offsets[2]) + "\n"); + ok = load(d2.path / "pack", 1, 512, err) && !strata::core::check_experts_gguf(C.string(), + strata::kernels::cpu::expert_layout(), err); + check(ok && err.find("is IQ3_S") != std::string::npos, "a gate of another type than the pack's is refused"); + // the same bytes with the pack's types, but a down tensor of three experts where the pack says two + fixture::write(C, {}, {{"blk.0.ffn_gate_exps.weight", {H, FF, NE}, Q3_K, 31}, + {"blk.0.ffn_up_exps.weight", {H, FF, NE}, Q3_K, 32}, + {"blk.0.ffn_down_exps.weight", {FF, H, NE + 1}, Q5_1, 33}}); + ok = load(d2.path / "pack", 1, 512, err) && !strata::core::check_experts_gguf(C.string(), + strata::kernels::cpu::expert_layout(), err); + check(ok && err.find("is not [640, 2560, 2]") != std::string::npos, "a down tensor of another shape is refused"); +} +} // namespace + +int main(int argc, char** argv) { + std::printf("expert_layout_test\n"); + if (argc < 2) { + std::printf("usage: expert_layout_test \n"); + return 2; + } + real_packs(argv[1]); + columns(); + arena(); + std::printf(g_fail ? "expert_layout_test: %d FAILED\n" : "expert_layout_test: all passed\n", g_fail); + return g_fail ? 1 : 0; +} diff --git a/tests/core/gguf_fixture.hpp b/tests/core/gguf_fixture.hpp new file mode 100644 index 00000000..677a5cd8 --- /dev/null +++ b/tests/core/gguf_fixture.hpp @@ -0,0 +1,103 @@ +// tests/core/gguf_fixture.hpp - synthetic GGUF v3 files for the loader tests (no gguf-py, no model, no GPU). +// +// A file is a header, metadata (strings and integers only), a tensor directory whose offsets are 32-byte aligned +// in the data section, and the tensors' payloads, each filled with a pattern the test can recognise. +#pragma once + +#include "strata/artifact/gguf_reader.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace fixture { + +struct Kv { + std::string key; + uint32_t type = 8; ///< GGUF value type: 8 string, 2 u16, 4 u32, 5 i32 + std::string s; + uint64_t u = 0; +}; +inline Kv str(const std::string& k, const std::string& v) { return Kv{k, 8, v, 0}; } +inline Kv u16(const std::string& k, uint64_t v) { return Kv{k, 2, {}, v}; } +inline Kv i32(const std::string& k, uint64_t v) { return Kv{k, 5, {}, v}; } +inline Kv u32(const std::string& k, uint64_t v) { return Kv{k, 4, {}, v}; } + +struct Tensor { + std::string name; + std::vector shape; ///< GGUF order: dim 0 varies fastest + uint32_t type = 0; + uint8_t seed = 1; ///< payload byte i is (seed * 131 + i * 7 + i / 4093) & 0xff +}; + +inline uint8_t pattern(uint8_t seed, uint64_t i) { return (uint8_t) ((seed * 131u + i * 7u + i / 4093u) & 0xffu); } + +/// The split keys llama.cpp's gguf-split writes (u16 split.no / split.count, i32 split.tensors.count). +inline std::vector split_keys(uint64_t no, uint64_t count, uint64_t tensors) { + return {u16("split.no", no), u16("split.count", count), i32("split.tensors.count", tensors)}; +} + +struct Written { + uint64_t data_start = 0; + std::vector offsets; ///< per tensor, from data_start + uint64_t size = 0; +}; + +/// Writes `path`; `cut` bytes are dropped from the end (a truncated download). +inline Written write(const std::filesystem::path& path, const std::vector& kv, const std::vector& ts, + uint64_t cut = 0) { + std::vector b; + auto put = [&](const void* p, size_t n) { b.insert(b.end(), (const uint8_t*) p, (const uint8_t*) p + n); }; + auto put32 = [&](uint32_t v) { put(&v, 4); }; + auto put64 = [&](uint64_t v) { put(&v, 8); }; + auto puts = [&](const std::string& s) { put64(s.size()); put(s.data(), s.size()); }; + put32(0x46554747u); + put32(3); + put64(ts.size()); + put64(kv.size()); + for (const auto& k : kv) { + puts(k.key); + put32(k.type); + if (k.type == 8) puts(k.s); + else if (k.type == 2) { const uint16_t v = (uint16_t) k.u; put(&v, 2); } + else if (k.type == 4 || k.type == 5) { const uint32_t v = (uint32_t) k.u; put(&v, 4); } + else throw std::runtime_error("fixture: unsupported metadata type"); + } + Written w; + std::vector bytes; + uint64_t at = 0; + for (const auto& t : ts) { + strata::TensorInfo info; + info.shape = t.shape; + info.type = t.type; + const uint64_t n = strata::tensor_payload_bytes(info); + if (n == 0) throw std::runtime_error("fixture: " + t.name + " has no whole-block byte count"); + puts(t.name); + put32((uint32_t) t.shape.size()); + for (uint64_t d : t.shape) put64(d); + put32(t.type); + put64(at); + w.offsets.push_back(at); + bytes.push_back(n); + at = (at + n + 31) / 32 * 32; + } + w.data_start = (b.size() + 31) / 32 * 32; + b.resize((size_t) w.data_start, 0); + for (size_t i = 0; i < ts.size(); ++i) { + b.resize((size_t) (w.data_start + w.offsets[i]), 0); + for (uint64_t j = 0; j < bytes[i]; ++j) b.push_back(pattern(ts[i].seed, j)); + } + if (cut > b.size()) cut = b.size(); + b.resize(b.size() - (size_t) cut); + w.size = b.size(); + std::ofstream f(path, std::ios::binary | std::ios::trunc); + f.write((const char*) b.data(), (std::streamsize) b.size()); + if (!f) throw std::runtime_error("fixture: cannot write " + path.string()); + return w; +} + +} // namespace fixture diff --git a/tests/core/gguf_split_test.cpp b/tests/core/gguf_split_test.cpp new file mode 100644 index 00000000..22b668b6 --- /dev/null +++ b/tests/core/gguf_split_test.cpp @@ -0,0 +1,186 @@ +// tests/core/gguf_split_test.cpp - a split model's shards (strata::gguf_split_paths) and their joint view +// (strata::GgufModel), on synthetic GGUFs: no model, no GPU. +// +// The layout is Unsloth's UD-Q4_K_XL in miniature: shard 1 holds the metadata and no tensor, shards 2-4 the +// tensors, and layer 11's down sits in shard 2 while its gate and up are in shard 3. Then the ways a real +// download goes wrong: a shard missing, a shard of another model (split keys that disagree), a tensor in two +// shards, a directory that does not add up to split.tensors.count, a truncated shard, and shard 1 opened alone. +#include "gguf_fixture.hpp" + +#include "strata/artifact/gguf_split.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(" %-78s %s\n", what.c_str(), ok ? "ok" : "FAIL"); + if (!ok) ++g_fail; +} + +struct TempDir { + fs::path path; + TempDir() { + path = fs::temp_directory_path() / + ("strata-gguf-split-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); + } +}; + +std::string shard_name(int i, int n) { + char b[64]; + std::snprintf(b, sizeof b, "Model-UD-Q4_K_XL-%05d-of-%05d.gguf", i, n); + return b; +} + +using fixture::Tensor; +const uint32_t F32 = 0, Q8_0 = 8; + +/// Writes the 4-shard model; `mutate(i, kv, tensors)` may change shard i (0-based) before it is written. +template std::vector write_model(const fs::path& dir, F mutate, uint64_t total = 7) { + std::vector paths; + for (int i = 0; i < 4; ++i) { + std::vector kv; + if (i == 0) kv.push_back(fixture::str("general.architecture", "qwen4exp")); + for (const auto& k : fixture::split_keys((uint64_t) i, 4, total)) kv.push_back(k); + std::vector ts; + if (i == 1) ts = {{"output.weight", {64, 4}, Q8_0, 1}, {"token_embd.weight", {64, 4}, Q8_0, 2}, + {"blk.11.ffn_down_exps.weight", {32, 32, 2}, F32, 3}}; + if (i == 2) ts = {{"blk.11.ffn_gate_exps.weight", {32, 32, 2}, F32, 4}, + {"blk.11.ffn_up_exps.weight", {32, 32, 2}, F32, 5}, {"blk.12.attn_q.weight", {32, 8}, F32, 6}}; + if (i == 3) ts = {{"output_norm.weight", {32}, F32, 7}}; + uint64_t cut = 0; + mutate(i, kv, ts, cut); + const fs::path p = dir / shard_name(i + 1, 4); + fixture::write(p, kv, ts, cut); + paths.push_back(p.string()); + } + return paths; +} +auto same = [](int, std::vector&, std::vector&, uint64_t&) {}; + +std::string error_of(const std::vector& paths) { + try { + strata::GgufModel m(paths); + } catch (const std::exception& e) { + return e.what(); + } + return {}; +} +} // namespace + +int main() { + std::printf("gguf_split_test\n"); + { + TempDir d; + const auto paths = write_model(d.path, same); + // any shard names the family; the list is in split order, metadata shard first + std::vector got; + try { got = strata::gguf_split_paths(paths[2]); } catch (...) {} + check(got == paths, "gguf_split_paths from shard 3: the 4 shards in order"); + try { got = strata::gguf_split_paths(paths[0]); } catch (...) { got.clear(); } + check(got == paths, "gguf_split_paths from shard 1: the same 4 shards"); + check(strata::gguf_split_paths((d.path / "plain.gguf").string()).size() == 1, + "a name without -NNNNN-of-MMMMM is a model of one file"); + std::string err; + try { + const strata::GgufModel m(paths); + size_t s_out = 9, s_gate = 9, s_down = 9, s_up = 9; + const strata::TensorInfo* out = m.find("output.weight", &s_out); + const strata::TensorInfo* gate = m.find("blk.11.ffn_gate_exps.weight", &s_gate); + const strata::TensorInfo* up = m.find("blk.11.ffn_up_exps.weight", &s_up); + const strata::TensorInfo* down = m.find("blk.11.ffn_down_exps.weight", &s_down); + check(m.size() == 4 && m.meta().get("general.architecture") && m.meta().tensors().empty(), + "shard 1: the metadata, no tensor"); + check(out && s_out == 1 && m.in_bounds(*out, s_out), "output.weight found in shard 2, in bounds"); + check(gate && up && down && s_gate == 2 && s_up == 2 && s_down == 1, + "layer 11 per role: gate/up in shard 3, down in shard 2"); + check(m.find("blk.99.ffn_gate_exps.weight") == nullptr, "an absent tensor is nullptr"); + check(strata::check_architecture(m.meta()).find("block_count") != std::string::npos, + "the architecture guard reads the metadata shard (and wants its keys)"); + } catch (const std::exception& e) { + err = e.what(); + } + check(err.empty(), "the 4-shard model opens" + (err.empty() ? std::string() : ": " + err)); + } + { + TempDir d; + const auto paths = write_model(d.path, same); + fs::remove(paths[3]); + std::string err; + try { strata::gguf_split_paths(paths[0]); } catch (const std::exception& e) { err = e.what(); } + check(err.find("missing model shard") != std::string::npos && err.find(shard_name(4, 4)) != std::string::npos, + "a missing shard is an error that names it"); + } + { + TempDir d; + const auto paths = write_model(d.path, [](int i, auto&, auto& ts, uint64_t&) { + if (i == 3) ts.push_back({"blk.11.ffn_up_exps.weight", {32, 32, 2}, F32, 9}); + }, 8); + const std::string err = error_of(paths); + check(err.find("in two shards") != std::string::npos && err.find(shard_name(3, 4)) != std::string::npos && + err.find(shard_name(4, 4)) != std::string::npos, + "a tensor in two shards is refused, naming both"); + } + { + TempDir d; + const auto paths = write_model(d.path, [](int i, auto& kv, auto&, uint64_t&) { + if (i == 2) kv = fixture::split_keys(1, 4, 7); // says it is shard 2 + }); + check(error_of(paths).find("does not declare itself shard 3 of 4") != std::string::npos, + "a shard whose split.no disagrees with its place is refused"); + } + { + TempDir d; + const auto paths = write_model(d.path, [](int i, auto& kv, auto&, uint64_t&) { + if (i == 3) kv = fixture::split_keys(3, 4, 9); // another model's split.tensors.count + }); + check(!error_of(paths).empty(), "a shard of another model (split.tensors.count differs) is refused"); + } + { + TempDir d; + const auto paths = write_model(d.path, [](int i, auto&, auto& ts, uint64_t&) { + if (i == 3) ts.clear(); // a directory short of split.tensors.count + }); + check(error_of(paths).find("split.tensors.count is 7") != std::string::npos, + "shards that do not add up to split.tensors.count are refused"); + } + { + TempDir d; + const auto paths = write_model(d.path, [](int i, auto& kv, auto&, uint64_t&) { + if (i == 0) kv.erase(kv.begin()); // no general.architecture in shard 1 + }); + check(error_of(paths).find("general.architecture") != std::string::npos, + "a split model whose first shard has no metadata is refused"); + check(error_of({paths[0]}).find("opened as a whole model") != std::string::npos, + "shard 1 of 4 opened as a whole model is refused"); + } + { + TempDir d; + const auto paths = write_model(d.path, [](int i, auto&, auto&, uint64_t& cut) { + if (i == 2) cut = 100; // the last tensor of shard 3 is cut short + }); + bool truncated = false, first_ok = false; + try { + const strata::GgufModel m(paths); + size_t s = 0; + const strata::TensorInfo* q = m.find("blk.12.attn_q.weight", &s); + const strata::TensorInfo* g = m.find("blk.11.ffn_gate_exps.weight"); + truncated = q && !m.in_bounds(*q, s); + first_ok = g && m.in_bounds(*g, 2); + } catch (...) {} + check(truncated && first_ok, "a truncated shard: its last tensor is out of bounds, the others are not"); + } + std::printf(g_fail ? "gguf_split_test: %d FAILED\n" : "gguf_split_test: all passed\n", g_fail); + return g_fail ? 1 : 0; +} diff --git a/tests/data/native_experts/coder-iq1_m.txt b/tests/data/native_experts/coder-iq1_m.txt new file mode 100644 index 00000000..bf0c408a --- /dev/null +++ b/tests/data/native_experts/coder-iq1_m.txt @@ -0,0 +1,49 @@ +# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] (n_expert 256, total 25146163200; absolute offsets in Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00001-of-00002.gguf, or in the named shard beside it) +0 18 20 0 2176000 1150562336 1313362976 913711136 +1 22 42 557056000 1510400 1664626592 1801161632 1545740192 +2 22 20 943718400 1971200 2308902688 2445488928 2072051488 +3 22 20 1448345600 1971200 2885763232 3022298272 2648912032 +4 22 20 1952972800 1971200 3458564256 3595572896 3221713056 +5 22 20 2457600000 1971200 4038269472 4174804512 3801418272 +6 22 20 2962227200 1971200 4613172128 4750180768 4376320928 +7 18 20 3466854400 2176000 5193708832 5356458272 4956857632 +8 22 42 4023910400 1510400 5696376096 5832911136 5577489696 +9 22 20 4410572800 1971200 6271347872 6407934112 6034496672 +10 22 42 4915200000 1510400 6732983328 6869569568 6614096928 +11 22 20 5301862400 1971200 7314285472 7450871712 7077434272 +12 18 42 5806489600 1715200 7761567136 7924790176 7642680736 +13 22 42 6245580800 1510400 8269195552 8405781792 8150309152 +14 18 20 6632243200 2176000 8850188448 9012937888 8613337248 +15 22 20 7189299200 1971200 9478952992 9615961632 9242101792 +16 18 20 7693926400 2176000 10047629856 10210430496 9810778656 +17 21 20 8250982400 2329600 10683191712 10865601952 10446340512 +18 18 20 8847360000 2176000 11353477408 11516482848 11116626208 +19 22 20 9404416000 1971200 11989461152 12126469792 11752609952 +20 18 42 9909043200 1715200 12445193376 12607942816 12326306976 +21 21 42 10348134400 1868800 12962739232 13145200672 12843852832 +22 18 20 10826547200 2176000 13631427488 13794650528 13394576288 +23 22 20 11383603200 1971200 14269635872 14406426912 14032784672 +24 22 20 11888230400 1971200 14842897696 14979432736 14606046496 +25 21 20 12392857600 2329600 15426184352 15608594592 15189333152 +26 22 20 12989235200 1971200 16097957408 16234966048 15861106208 +27 21 20 13493862400 2329600 16682121632 16864531872 16445270432 +28 21 20 14090240000 2329600 17346621856 17529505696 17109770656 +29 21 20 14686617600 2329600 18018868512 18201534752 17782017312 +30 18 42 15282995200 1715200 18571885728 18734635168 18452999328 +31 18 20 15722086400 2176000 19213849632 19376599072 18976998432 +32 22 20 16279142400 1971200 19837195296 19974203936 19600344096 +33 18 20 16783769600 2176000 20413173152 20575922592 20176321952 +34 22 20 17340825600 1971200 21040655648 21177241888 20803804448 +35 21 20 17845452800 2329600 21630446752 21812856992 21393595552 +36 22 42 18441830400 1510400 22173400736 22310409376 22054514336 +37 18 20 18828492800 2176000 22753323552 22916546592 22516472352 +38 18 20 19385548800 2176000 23383942048 23546742688 23147090848 +39 22 20 19942604800 1971200 24025905952 24162492192 23789054752 +40 21 20 20447232000 2329600 24598758176 24781424416 24361906976 +41 18 20 21043609600 2176000 25262981792 25425782432 25026130592 +42 18 20 21600665600 2176000 25890515488 26053738528 25653664288 +43 18 20 22157721600 2176000 26532901792 26696124832 26296050592 +44 21 20 22714777600 2329600 27151490976 27333952416 26914639776 +45 21 20 23311155200 2329600 27818796832 28001258272 27581945632 +46 18 20 23907532800 2176000 28488532128 28651332768 28251680928 +47 23 20 24464588800 2662400 29129699872 29354759712 28892029472 diff --git a/tests/data/native_experts/iq2_xs.txt b/tests/data/native_experts/iq2_xs.txt new file mode 100644 index 00000000..61c34b85 --- /dev/null +++ b/tests/data/native_experts/iq2_xs.txt @@ -0,0 +1,49 @@ +# strata native experts v2: layer gu_type d_type offset blob_bytes gate_off up_off down_off (n_expert 512, total 35454976000; the last three are absolute offsets in Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf) +0 22 42 0 1510400 957139232 1229167392 720288032 +1 16 42 773324800 1305600 1791743648 2011983008 1554892448 +2 22 42 1441792000 1510400 2589468704 2861663264 2352617504 +3 22 42 2215116800 1510400 3429617568 3701812128 3191947168 +4 16 42 2988441600 1305600 4258654112 4478419872 4021802912 +5 22 42 3656908800 1510400 4988400928 5260595488 4751549728 +6 22 42 4430233600 1510400 5824781984 6096976544 5588391584 +7 22 42 5203558400 1510400 6665627168 6938295328 6429236768 +8 29 42 5976883200 1177600 7496734752 7683732512 7259883552 +9 16 42 6579814400 1305600 8161931168 8381530528 7924260768 +10 16 42 7248281600 1305600 8893109024 9112874784 8656257824 +11 16 42 7916748800 1305600 9628172448 9847938208 9391782048 +12 22 42 8585216000 1510400 10354422432 10627090592 10117571232 +13 29 42 9358540800 1177600 11191917088 11378748448 10954246688 +14 16 42 9961472000 1305600 11856780704 12076546464 11619110304 +15 22 42 10629939200 1510400 12596884768 12868912928 12360033568 +16 22 42 11403264000 1510400 13428645152 13701313312 13190974752 +17 22 42 12176588800 1510400 14264363168 14536557728 14027511968 +18 16 42 12949913600 1305600 15100731424 15320330784 14863880224 +19 16 42 13618380800 1305600 15836089248 16055855008 15599238048 +20 22 42 14286848000 1510400 16562518432 16834712992 16324848032 +21 22 42 15060172800 1510400 17398108448 17670303008 17160438048 +22 22 42 15833497600 1510400 18230654624 18502849184 17994264224 +23 22 42 16606822400 1510400 19071581728 19343609888 18834730528 +24 22 42 17380147200 1510400 19906595872 20178790432 19669744672 +25 22 42 18153472000 1510400 20745913248 21017941408 20509062048 +26 22 42 18926796800 1510400 21580517664 21852712224 21343666464 +27 16 42 19700121600 1305600 22420899488 22641138848 22184048288 +28 22 42 20368588800 1510400 23146983072 23419011232 22910131872 +29 16 42 21141913600 1305600 23983658528 24203424288 23746807328 +30 16 42 21810380800 1305600 24713110944 24932876704 24476720544 +31 22 42 22478848000 1510400 25449180448 25721375008 25212329248 +32 22 42 23252172800 1510400 26279648032 26551842592 26042796832 +33 22 42 24025497600 1510400 27114892448 27387087008 26878041248 +34 22 42 24798822400 1510400 27955807264 28228001824 27718956064 +35 22 42 25572147200 1510400 28793160608 29065355168 28556309408 +36 22 42 26345472000 1510400 29623794592 29896462752 29386943392 +37 29 42 27118796800 1177600 30459512608 30646510368 30222661408 +38 22 42 27721728000 1510400 31125320864 31397515424 30888469664 +39 22 42 28495052800 1510400 31966247968 32238442528 31729396768 +40 22 42 29268377600 1510400 32794219552 33066414112 32557368352 +41 22 42 30041702400 1510400 33628823968 33901018528 33391972768 +42 22 42 30815027200 1510400 34464068384 34736736544 34227217184 +43 22 42 31588352000 1510400 35305090208 35577118368 35068239008 +44 22 42 32361676800 1510400 36135557792 36408225952 35898706592 +45 22 42 33135001600 1510400 36976946208 37249140768 36740095008 +46 22 42 33908326400 1510400 37813148064 38085342624 37576296864 +47 22 42 34681651200 1510400 38654454048 38926648608 38417602848 diff --git a/tests/data/native_experts/iq3_s.txt b/tests/data/native_experts/iq3_s.txt new file mode 100644 index 00000000..85164ba2 --- /dev/null +++ b/tests/data/native_experts/iq3_s.txt @@ -0,0 +1,49 @@ +# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] (n_expert 512, total 50292326400; absolute offsets in Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf, or in the named shard beside it) +0 18 20 0 2176000 1386491904 1711166464 913711104 +1 22 42 1114112000 1510400 2340958080 2613152640 2104106880 +2 22 20 1887436800 1971200 3491172096 3763417856 3018391296 +3 22 20 2896691200 1971200 4573970560 4846165120 4101189760 +4 22 20 3905945600 1971200 5652709504 5925377664 5179928704 +5 22 20 4915200000 1971200 6738352640 7010547200 6265571840 +6 22 20 5924454400 1971200 7819193216 8091861376 7346412416 +7 18 20 6933708800 2176000 8905667840 9230291200 8432887040 +8 22 42 8047820800 1510400 9848737024 10120931584 9611885824 +9 22 20 8821145600 1971200 10929646720 11201892480 10456865920 +10 22 42 9830400000 1510400 11779255296 12051501056 11542404096 +11 22 20 10603724800 1971200 12866495360 13138741120 12393714560 +12 18 42 11612979200 1715200 13701750144 14026847104 13464898944 +13 22 42 12491161600 1510400 14649780480 14922026240 14412929280 +14 18 20 13264486400 2176000 15736711296 16061334656 15263930496 +15 22 20 14378598400 1971200 16923842560 17196510720 16451061760 +16 18 20 15387852800 2176000 17998457344 18323131904 17525676544 +17 21 20 16501964800 2329600 19192385920 19556330880 18719605120 +18 18 20 17694720000 2176000 20460359936 20785239296 19987579136 +19 22 20 18808832000 1971200 21654710400 21927378560 21181929600 +20 18 42 19818086400 1715200 22498415744 22823039104 22261564544 +21 21 42 20696268800 1868800 23456363520 23820359680 23219512320 +22 18 20 21653094400 2176000 24722740096 25047837056 24249959296 +23 22 20 22767206400 1971200 25919315200 26191765760 25446534400 +24 22 20 23776460800 1971200 26998514944 27270709504 26525734144 +25 21 20 24785715200 2329600 28087739520 28451684480 27614958720 +26 22 20 25978470400 1971200 29357200896 29629869056 28884420096 +27 21 20 26987724800 2329600 30447303040 30811248000 29974522240 +28 21 20 28180480000 2329600 31709491584 32073910144 31236710784 +29 21 20 29373235200 2329600 32979426560 33343627520 32506645760 +30 18 42 30565990400 1715200 34012167296 34336790656 33775316096 +31 18 20 31444172800 2176000 35212497920 35537121280 34739717120 +32 22 20 32558284800 1971200 36394210304 36666878464 35921429504 +33 18 20 33567539200 2176000 37476126080 37800749440 37003345280 +34 22 20 34681651200 1971200 38661975296 38934221056 38189194496 +35 21 20 35690905600 2329600 39757704320 40121649280 39284923520 +36 22 42 36883660800 1510400 40780381824 41053049984 40543530624 +37 18 20 37656985600 2176000 41866242560 42191339520 41393461760 +38 18 20 38771097600 2176000 43055227776 43379902336 42582446976 +39 22 20 39885209600 1971200 44255558400 44527804160 43782777600 +40 21 20 40894464000 2329600 45334348544 45698549504 44861567744 +41 18 20 42087219200 2176000 46596260480 46920935040 46123479680 +42 18 20 43201331200 2176000 47782160896 48107257856 47309380096 +43 18 20 44315443200 2176000 48982913920 49308010880 48510133120 +44 21 20 45429555200 2329600 50159869824 50523865984 49687089024 +45 21 20 46622310400 2329600 51424864000 51788860160 50952083200 +46 18 20 47815065600 2176000 52692287616 53016962176 52219506816 +47 23 20 48929177600 2662400 53891822080 54341015040 53418222080 diff --git a/tests/data/native_experts/iq3_xxs.txt b/tests/data/native_experts/iq3_xxs.txt new file mode 100644 index 00000000..42f0ed50 --- /dev/null +++ b/tests/data/native_experts/iq3_xxs.txt @@ -0,0 +1,49 @@ +# strata native experts v2: layer gu_type d_type offset blob_bytes gate_off up_off down_off (n_expert 512, total 42912972800; the last three are absolute offsets in Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf) +0 17 20 0 1868800 1227833216 1473813376 755052416 +1 16 42 956825600 1305600 2016152832 2235918592 1779301632 +2 17 20 1625292800 1868800 3045972608 3292003968 2573191808 +3 16 42 2582118400 1305600 3839355392 4059172352 3602964992 +4 17 20 3250585600 1868800 4806683136 5052663296 4334363136 +5 17 42 4207411200 1408000 5596436352 5842416512 5359585152 +6 16 42 4928307200 1305600 6379748608 6599514368 6143358208 +7 16 42 5596774400 1305600 7121247872 7340847232 6884396672 +8 21 42 6265241600 1868800 7846857856 8210636416 7610006656 +9 17 42 7222067200 1408000 8873971712 9120003072 8637120512 +10 17 42 7942963200 1408000 9669920128 9915733888 9433068928 +11 16 42 8663859200 1305600 10465942272 10685759232 10229091072 +12 22 42 9332326400 1510400 11190582016 11462610176 10954191616 +13 16 42 10105651200 1305600 12031522432 12251121792 11795132032 +14 17 42 10774118400 1408000 12768096768 13014332928 12531706368 +15 22 42 11495014400 1510400 13563906432 13836152192 13327055232 +16 16 42 12268339200 1305600 14398521216 14618338176 14161670016 +17 22 42 12936806400 1510400 15134954752 15407149312 14898103552 +18 21 42 13710131200 1868800 15976688768 16340467328 15739837568 +19 17 42 14666956800 1408000 17010020352 17256000512 16773629952 +20 21 42 15387852800 1868800 17787815936 18151812096 17551425536 +21 22 42 16344678400 1510400 18811338112 19083532672 18574486912 +22 21 42 17118003200 1868800 19652089088 20016034048 19415237888 +23 21 42 18074828800 1868800 20682407552 21046352512 20445556352 +24 21 42 19031654400 1868800 21704611456 22068390016 21467760256 +25 17 42 19988480000 1408000 22734674432 22980654592 22497823232 +26 22 42 20709376000 1510400 23524471168 23796716928 23287619968 +27 16 42 21482700800 1305600 24379793152 24599558912 24142941952 +28 21 20 22151168000 2329600 25345879296 25709657856 24873098496 +29 22 20 23343923200 1971200 26610479232 26882673792 26137698432 +30 21 20 24353177600 2329600 27695226368 28059171328 27222445568 +31 16 20 25545932800 1766400 28974200192 29193965952 28501419392 +32 21 20 26450329600 2329600 29937050496 30301046656 29464269696 +33 21 42 27643084800 1868800 30959753472 31323698432 30722902272 +34 21 20 28599910400 2329600 32230185088 32594181248 31757404288 +35 18 20 29792665600 2176000 33501048832 33825672192 33028268032 +36 18 42 30906777600 1715200 34444591616 34769048576 34207740416 +37 21 20 31784960000 2329600 35626780032 35990776192 35153999232 +38 22 20 32977715200 1971200 36892498688 37164526848 36419717888 +39 17 20 33986969600 1868800 37987587712 38233567872 37514806912 +40 22 42 34943795200 1510400 38771773056 39043967616 38534921856 +41 18 42 35717120000 1715200 39610924032 39935598592 39374072832 +42 22 20 36595302400 1971200 40796033408 41068061568 40323252608 +43 21 20 37604556800 2329600 41891114752 42254893312 41418333952 +44 18 20 38797312000 2176000 43148423936 43472880896 42675643136 +45 18 42 39911424000 1715200 44098627712 44423724672 43861776512 +46 22 20 40789606400 1971200 45285101568 45557296128 44812320768 +47 18 20 41798860800 2176000 46363501952 46688125312 45890721152 diff --git a/tests/data/native_experts/q2_0.txt b/tests/data/native_experts/q2_0.txt new file mode 100644 index 00000000..7b2cbd4e --- /dev/null +++ b/tests/data/native_experts/q2_0.txt @@ -0,0 +1,49 @@ +# strata native experts v2: layer gu_type d_type offset blob_bytes gate_off up_off down_off (n_expert 512, total 33973862400; the last three are absolute offsets in Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf) +0 42 42 0 1382400 994197792 1233624352 757141792 +1 42 42 707788800 1382400 1766860448 2005877408 1530470048 +2 42 42 1415577600 1382400 2558049824 2797476384 2321198624 +3 42 42 2123366400 1382400 3325351328 3564368288 3088500128 +4 42 42 2831155200 1382400 4087571872 4326588832 3851181472 +5 42 42 3538944000 1382400 4853325088 5092342048 4616473888 +6 42 42 4246732800 1382400 5619500704 5858517664 5383110304 +7 42 42 4954521600 1382400 6384631328 6623648288 6148240928 +8 42 42 5662310400 1382400 7144855072 7383872032 6907799072 +9 42 42 6370099200 1382400 7903921568 8143348128 7667531168 +10 42 42 7077888000 1382400 8666152224 8905169184 8429301024 +11 42 42 7785676800 1382400 9441479328 9680905888 9205088928 +12 42 42 8493465600 1382400 10199355552 10438615712 9962965152 +13 42 42 9201254400 1382400 10964891168 11204368928 10728500768 +14 42 42 9909043200 1382400 11732659104 11971919264 11494988704 +15 42 42 10616832000 1382400 12510902048 12749919008 12273846048 +16 42 42 11324620800 1382400 13268829472 13508089632 13031978272 +17 42 42 12032409600 1382400 14035560608 14274577568 13798709408 +18 42 42 12740198400 1382400 14801313824 15040330784 14564462624 +19 42 42 13447987200 1382400 15573612448 15812629408 15336761248 +20 42 42 14155776000 1382400 16333413792 16572673952 16097023392 +21 42 42 14863564800 1382400 17099410208 17338427168 16862559008 +22 42 42 15571353600 1382400 17865654944 18104671904 17629264544 +23 42 42 16279142400 1382400 18638086688 18877564448 18401235488 +24 42 42 16986931200 1382400 19401894432 19641154592 19164838432 +25 42 42 17694720000 1382400 20168095648 20407112608 19931705248 +26 42 42 18402508800 1382400 20937573664 21176590624 20700722464 +27 42 42 19110297600 1382400 21715358368 21954618528 21478967968 +28 42 42 19818086400 1382400 22475620512 22715520672 22238769312 +29 42 42 20525875200 1382400 23242704928 23481721888 23005648928 +30 42 42 21233664000 1382400 24010902944 24250163104 23774512544 +31 42 42 21941452800 1382400 24790715168 25030192928 24553863968 +32 42 42 22649241600 1382400 25553857312 25792874272 25317006112 +33 42 42 23357030400 1382400 26319610528 26558870688 26083220128 +34 42 42 24064819200 1382400 27088512544 27327990304 26851661344 +35 42 42 24772608000 1382400 27864292768 28103309728 27627902368 +36 42 42 25480396800 1382400 28626756512 28866234272 28390366112 +37 42 42 26188185600 1382400 29397609248 29637035808 29160553248 +38 42 42 26895974400 1382400 30166895264 30406321824 29930044064 +39 42 42 27603763200 1382400 30946134048 31185394208 30709282848 +40 42 42 28311552000 1382400 31708403232 31947880992 31471552032 +41 42 42 29019340800 1382400 32478833568 32718093728 32241982368 +42 42 42 29727129600 1382400 33249046304 33488063264 33012195104 +43 42 42 30434918400 1382400 34028407968 34267424928 33791556768 +44 42 42 31142707200 1382400 34791498912 35030759072 34554647712 +45 42 42 31850496000 1382400 35567241248 35806501408 35330185248 +46 42 42 32558284800 1382400 36338232224 36577914784 36101381024 +47 42 42 33266073600 1382400 37117686048 37356946208 36880015648 diff --git a/tests/data/native_experts/swift-iq2_xs.txt b/tests/data/native_experts/swift-iq2_xs.txt new file mode 100644 index 00000000..0da3e8f9 --- /dev/null +++ b/tests/data/native_experts/swift-iq2_xs.txt @@ -0,0 +1,49 @@ +# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] (n_expert 512, total 35454976000; absolute offsets in Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf, or in the named shard beside it) +0 22 42 0 1510400 29757220608 30031875328 29520369408 +1 16 42 773324800 1305600 30594451584 30817317504 30357600384 +2 22 42 1441792000 1510400 31394803200 31669624320 31157952000 +3 22 42 2215116800 1510400 32237578624 32512399744 31999908224 +4 16 42 2988441600 1305600 33069241728 33291634048 32832390528 +5 22 42 3656908800 1510400 33801615104 34076436224 33564763904 +6 22 42 4430233600 1510400 34640622720 34915443840 34404232320 +7 22 42 5203558400 1510400 35484094464 35759389184 35247704064 +8 29 42 5976883200 1177600 36317828608 36507452928 36080977408 +9 16 42 6579814400 1305600 36985651584 37207877504 36747981184 +10 16 42 7248281600 1305600 37719456000 37941848320 37482604800 +11 16 42 7916748800 1305600 38457145984 38679538304 38220755584 +12 22 42 8585216000 1510400 39186022528 39461317248 38949171328 +13 29 42 9358540800 1177600 237726720 427184640 56320 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +14 16 42 9961472000 1305600 905216896 1127609216 667546496 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +15 22 42 10629939200 1510400 1647947520 1922602240 1411096320 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +16 22 42 11403264000 1510400 2482334464 2757629184 2244664064 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +17 22 42 12176588800 1510400 3320679040 3595500160 3083827840 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +18 16 42 12949913600 1305600 4159673856 4381899776 3922822656 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +19 16 42 13618380800 1305600 4897658240 5120050560 4660807040 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +20 22 42 14286848000 1510400 5626713984 5901535104 5389043584 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +21 22 42 15060172800 1510400 6464930560 6739751680 6227260160 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +22 22 42 15833497600 1510400 7300103296 7574924416 7063712896 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +23 22 42 16606822400 1510400 8143656960 8418311680 7906805760 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +24 22 42 17380147200 1510400 8981297664 9256118784 8744446464 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +25 22 42 18153472000 1510400 9823241600 10097896320 9586390400 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +26 22 42 18926796800 1510400 10660472576 10935293696 10423621376 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +27 16 42 19700121600 1305600 11503480960 11726346880 11266629760 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +28 22 42 20368588800 1510400 12232191104 12506845824 11995339904 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +29 16 42 21141913600 1305600 13071493120 13293885440 12834641920 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +30 16 42 21810380800 1305600 13803572096 14025964416 13567181696 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +31 22 42 22478848000 1510400 14542268160 14817089280 14305416960 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +32 22 42 23252172800 1510400 15375362304 15650183424 15138511104 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +33 22 42 24025497600 1510400 16213233280 16488054400 15976382080 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +34 22 42 24798822400 1510400 17056774656 17331595776 16819923456 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +35 22 42 25572147200 1510400 17896754560 18171575680 17659903360 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +36 22 42 26345472000 1510400 18730015104 19005309824 18493163904 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +37 29 42 27118796800 1177600 19568359680 19757984000 19331508480 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +38 22 42 27721728000 1510400 20236794496 20511615616 19999943296 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +39 22 42 28495052800 1510400 21080348160 21355169280 20843496960 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +40 22 42 29268377600 1510400 21910946304 22185767424 21674095104 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +41 22 42 30041702400 1510400 22748177280 23022998400 22511326080 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +42 22 42 30815027200 1510400 23586048256 23861342976 23349197056 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +43 22 42 31588352000 1510400 24429696640 24704351360 24192845440 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +44 22 42 32361676800 1510400 25262790784 25538085504 25025939584 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +45 22 42 33135001600 1510400 26106805760 26381626880 25869954560 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +46 22 42 33908326400 1510400 26945634176 27220455296 26708782976 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +47 22 42 34681651200 1510400 27789566720 28064387840 27552715520 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf From 21844a3ebf220b4d723b63a7d21763f88f9aa7a6 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 20:50:25 +0200 Subject: [PATCH 2/7] iq_pack: per-role shards and data_start (v4 only for a split layer), split keys checked, experts.bin reused only with its source sidecar, atomic publication - Each expert role is resolved in the shard that holds it and its offset is absolute in THAT shard (the first role's data_start was used for all three; #255, gopinath87607). A layer whose roles are in different shards gets the per-role column `gate,up,down` and the file becomes v4; every other pack keeps the v3 header and bytes (checked on Q2_0, IQ3_XXS, IQ3_S, Coder IQ1_M, Swift IQ2_XS: index.txt, native_experts.txt and dense.bin identical to main's packer). - The split keys are checked as the engine does (shard 1 has the metadata; split.count / split.no / split.tensors.count consistent). The expert table is computed and checked before any file of the pack changes. - experts.bin is written under a temporary name and gets experts.bin.src.json (the shards' names and sizes, the sha256 of native_experts.txt); it is reused only when that matches, never by size. An experts.bin of another source is refused without --experts-bin (the engine would read it). - dense.bin and index.txt are published together after the old completion marker (native_experts.txt) is removed, so a stop part-way never mixes files of two runs. - .absolute() stays (not .resolve()): symlinked HF snapshot names keep the split naming. - Tests: a synthetic 4-shard GGUF (shard 1 metadata only, layer 1 split per role; offsets per shard, experts.bin byte for byte), v3 kept when nothing is split, missing shard, duplicate tensor, a shard of another split, truncated shard, wrong type (pack untouched), interrupted pack (experts and index), stale same-size experts.bin. Idea of per-role names also in #247 (jagsan-cyber). --- tools/iq_pack.py | 212 +++++++++++++++++++++++++++++++----------- tools/test_iq_pack.py | 210 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 367 insertions(+), 55 deletions(-) diff --git a/tools/iq_pack.py b/tools/iq_pack.py index f0ff890b..74ef3239 100644 --- a/tools/iq_pack.py +++ b/tools/iq_pack.py @@ -6,9 +6,12 @@ The i-quant experts cannot be re-expressed in the Q2_0 pack form, so this pack keeps every quantized tensor in its GGUF form: - experts.bin per layer, 512 blobs of [gate rows | up rows | down rows], the raw GGUF slices. Blob - size is per layer (the files mix IQ1_M ... IQ3_S gate/up and Q2_0 / IQ4_NL down). - native_experts.txt one line per layer: layer gu_type d_type offset blob_bytes + experts.bin optional (--experts-bin): per layer, 512 blobs of [gate rows | up rows | down rows], the + raw GGUF slices. Blob size is per layer (the files mix IQ1_M ... IQ3_S gate/up and Q2_0 / + IQ4_NL down). experts.bin.src.json says which source it was cut from (the shards' names and + sizes, the hash of native_experts.txt); an experts.bin is reused only when that matches. + native_experts.txt one line per layer: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard]; + written last, so a pack without it is not finished index.txt the table the engine loads. Quantized dense tensors, token_embd and output are served natively from the GGUF by the engine (--native): their rows carry shape only. dense.bin standalone: the BF16/F16/F32 tensors exactly as the GGUF stores them (index kinds 4/5/2). @@ -17,10 +20,14 @@ its GGUF form: float here but quantized in the base pack (blk.1.ple_key). tokenizer/ exported from the GGUF (tools/strata_tokenizer.py), with the model's chat template. -Split files: every shard of the model is read (-0000N-of-0000M.gguf beside --gguf), so the layers may be -split anyhow (Swift 1.5's GGUFs put layers 13-47 in shard 2 and the PLE table in shard 1). A layer whose experts -are not in shard 1 names its shard in native_experts.txt (v3). Router tensors stored as F32 whose values are -exactly BF16 (Swift 1.5) are written as BF16, the form the engine's router takes; anything else is refused. +Split files: every shard of the model is read (-0000N-of-0000M.gguf beside --gguf; a missing shard is an +error), so the layers may be split anyhow (Swift 1.5's GGUFs put layers 13-47 in shard 2 and the PLE table in +shard 1). A layer whose experts are not in shard 1 names its shard in native_experts.txt (v3). A shard boundary +may even fall inside a layer (Unsloth's UD-Q4_K_XL: layer 11's down in shard 2, its gate and up in shard 3): that +layer's shard column is per role, `gate,up,down` (an empty field = the --gguf shard), and only then is the file +v4, so an older engine refuses it instead of misreading it. Every other pack stays v3, byte for byte. Router +tensors stored as F32 whose values are exactly BF16 (Swift 1.5) are written as BF16, the form the engine's router +takes; anything else is refused. For ordinary quants, --compat-bf16 dequantizes the small projections that the engine reads as BF16, using round-to-nearest-even. This introduces BF16 rounding; it does not reconstruct the original full-precision @@ -29,6 +36,7 @@ weights. Experts, native attention projections, token embeddings and the disk-ba from __future__ import annotations import argparse +import hashlib import json import os import pathlib @@ -93,9 +101,11 @@ class Model: if missing: raise FileNotFoundError("missing model shards (wait for the download): " + ", ".join(missing)) self.paths = paths + self.files = [G.GGUFFile(p) for p in paths] + self.sizes = [p.stat().st_size for p in paths] + check_split(self.files) self.where = {} - for p in paths: - g = G.GGUFFile(p) + for p, g in zip(paths, self.files): mm = np.memmap(p, dtype=np.uint8, mode="r") for t in g.tensors: size = t.expected_bytes() @@ -108,6 +118,34 @@ class Model: def bytes(self, name) -> np.ndarray: g, t, mm, _ = self.where[name] return tensor_bytes(mm, g, t) + + +def check_split(files) -> None: + """The split keys, as the engine checks them (strata::GgufModel): shard 1 carries the metadata, and every shard + declares split.count / split.no (and split.tensors.count) consistently - a shard of another model, or a shard + renamed into the family, is refused rather than mixed in.""" + n = len(files) + meta0 = files[0].metadata + if n == 1: + if int(meta0.get("split.count", 1)) > 1: + raise ValueError(f"{files[0].path.name} is shard 1 of {meta0['split.count']}, but its name has no " + "-00001-of-0000N.gguf to find the others by") + return + if "general.architecture" not in meta0: + raise ValueError(f"{files[0].path.name} has no general.architecture; the first shard of a split model " + "carries the metadata") + total = meta0.get("split.tensors.count") + for i, g in enumerate(files): + md = g.metadata + if md.get("split.count") != n or md.get("split.no") != i or \ + (total is not None and md.get("split.tensors.count") != total): + raise ValueError(f"{g.path.name} does not declare itself shard {i + 1} of {n} of this model " + "(split.count / split.no / split.tensors.count)") + if total is not None and sum(len(g.tensors) for g in files) != total: + raise ValueError(f"the {n} shards hold {sum(len(g.tensors) for g in files)} tensors, but " + f"split.tensors.count is {total}") + + ROLES = ("gate", "up", "down") N_EXPERT = 512 ALIGN = 64 @@ -145,7 +183,7 @@ def index_standalone(src, out, model: Model, compat_bf16: bool = False) -> int: rows, at = [], 0 served = 0 converted = [] - with open(out / "dense.bin", "wb") as fo: + with open(out / "dense.bin.tmp", "wb") as fo: for name, (g, t, mm, _) in model.where.items(): if is_expert(t.name) or t.name in NOT_IN_PACK: continue @@ -179,7 +217,13 @@ def index_standalone(src, out, model: Model, compat_bf16: bool = False) -> int: else: served += 1 rows.append([t.name, "0", "0", "0", "0", "0", "0", str(ne0), str(ne1), "8", "0", "32"] + ["0"] * 7) - write_index(out, rows, src, served, 0) + write_index(out, rows, src, served, 0, publish=False) + # published together, and the completion marker (native_experts.txt, written last by main) goes first: a stop + # from here on leaves a pack that setup and the engine see as unfinished, never a new dense.bin under an old + # index or the reverse + (out / "native_experts.txt").unlink(missing_ok=True) + (out / "dense.bin.tmp").replace(out / "dense.bin") + (out / "index.txt.tmp").replace(out / "index.txt") if compat_bf16: (out / "compat-bf16.json").write_text(json.dumps({ "source": str(src), "rounding": "nearest-even", "tensors": converted, @@ -189,16 +233,18 @@ def index_standalone(src, out, model: Model, compat_bf16: bool = False) -> int: return 0 -def write_index(out, rows, src, served, n_extra): +def write_index(out, rows, src, served, n_extra, publish=True): at = 0 for r in rows: r[5] = str(at) at += (int(r[6]) + ALIGN - 1) // ALIGN * ALIGN - with open(out / "index.txt", "w", encoding="utf-8", newline="\n") as fo: + with open(out / "index.txt.tmp", "w", encoding="utf-8", newline="\n") as fo: fo.write("# strata pack index v3 -- generated by tools/iq_pack.py (native experts) from %s\n" % src.name) fo.write("# align %d pool %d tensors %d\n" % (ALIGN, at, len(rows))) for r in rows: fo.write(" ".join(r) + "\n") + if publish: + (out / "index.txt.tmp").replace(out / "index.txt") print("index.txt: %d tensors, %d served natively, %d in extra.bin, arena %.2f GiB" % (len(rows), served, n_extra, at / 2**30)) @@ -253,6 +299,70 @@ def index_from_base(a, src, base, out, g, T, mm) -> int: return 0 +def expert_layout(model: Model, src: pathlib.Path): + """The pack's expert table: (layout rows, native_experts.txt text, n_expert, total bytes), or an error string. + Each role is resolved by name in whichever shard holds it, and its offset is absolute in THAT shard: two + shards do not start their data section at the same byte, so one role's data_start must not be used for + another's (per-role data_start as in #255, gopinath87607).""" + T = {n: w[1] for n, w in model.where.items()} + exps = [n for n in T if n.startswith("blk.") and n.endswith("_exps.weight")] + if not exps: + return "the model has no expert tensors (blk.N.ffn_{gate,up,down}_exps.weight)" + n_layers = 1 + max(int(n.split(".")[1]) for n in exps) + n_expert = int(T["blk.0.ffn_gate_inp.weight"].shape[1]) # router rows = experts kept (pruned models ship < 512) + if any(int(T["blk.%d.ffn_gate_inp.weight" % l].shape[1]) != n_expert for l in range(n_layers)): + return "the routers disagree on the expert count; a per-layer pruned model cannot be packed" + layout, lines, offset, n_split = [], [], 0, 0 + for l in range(n_layers): + names = ["blk.%d.ffn_%s_exps.weight" % (l, r) for r in ROLES] + if any(n not in T for n in names): + return "layer %d: missing %s" % (l, ", ".join(n for n in names if n not in T)) + ts = [T[n] for n in names] + if any(t.expected_bytes() is None or len(t.shape) != 3 or int(t.shape[2]) != n_expert for t in ts): + return "layer %d: an expert tensor is not [*, *, %d] of whole blocks" % (l, n_expert) + per = [t.expected_bytes() // n_expert for t in ts] + if per[0] != per[1] or ts[0].type_name != ts[1].type_name: + return "layer %d: gate and up differ in type" % l + blob = per[0] + per[1] + per[2] + layout.append((l, ts[0].type_id, ts[2].type_id, offset, blob, ts)) + ws = [model.where[n] for n in names] + files = ["" if w[3] == src else w[3].name for w in ws] + column = files[0] if len(set(files)) == 1 else ",".join(files) + n_split += len(set(files)) != 1 + line = "%d %d %d %d %d %d %d %d" % (l, ts[0].type_id, ts[2].type_id, offset, blob, + *[w[0].data_start + w[1].offset for w in ws]) + lines.append(line + ("" if not column else " " + column)) + offset += blob * n_expert + if n_split: + head = ("# strata native experts v4: layer gu_type d_type offset blob_bytes gate_off up_off down_off " + "[shard | gate,up,down] (n_expert %d, total %d; absolute offsets in %s, or in the named shard " + "beside it - per role where the column is gate,up,down)\n" % (n_expert, offset, src.name)) + print("%d layer(s) have their gate/up/down in different shards: native_experts.txt v4, per-role shard " + "column for %s" % (n_split, ", ".join(str(l) for l, *_ in layout if "," in lines[l]))) + else: + head = ("# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] " + "(n_expert %d, total %d; absolute offsets in %s, or in the named shard beside it)\n" + % (n_expert, offset, src.name)) + return layout, head + "".join(line + "\n" for line in lines), n_expert, offset + + +def experts_source(model: Model, text: str, total: int) -> dict: + """What experts.bin is cut from: the shards (names and sizes) and the hash of native_experts.txt (every + per-role file and offset, the formats and the blob sizes). A same-size experts.bin of another model or + another packing is not this one.""" + return {"schema": 1, + "shards": [{"name": p.name, "size": s} for p, s in zip(model.paths, model.sizes)], + "native_experts_sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(), + "bytes": total} + + +def read_json(path: pathlib.Path): + try: + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + + def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--gguf", required=True, help="the model's shard 1") @@ -267,7 +377,8 @@ def main() -> int: a = ap.parse_args() if a.compat_bf16 and a.base: ap.error("--compat-bf16 cannot reuse --base dense weights") - # HF snapshot files are symlinks to hash-named blobs. Keep the shard filename for discovery. + # HF snapshot files are symlinks to hash-named blobs. Keep the shard filename for discovery: .absolute(), not + # .resolve(), which would follow the link to the blob and lose the -0000N-of-0000M name. src = pathlib.Path(a.gguf).absolute() base = pathlib.Path(a.base).resolve() if a.base else None out = pathlib.Path(a.out) @@ -276,13 +387,30 @@ def main() -> int: g = G.GGUFFile(src) mm = np.memmap(src, dtype=np.uint8, mode="r") model = Model(src) - T = {n: w[1] for n, w in model.where.items()} if len(model.paths) > 1: print("model shards: " + ", ".join(p.name for p in model.paths)) + # ---- the expert table first: a model that cannot be packed is refused before any file of the pack changes + got = expert_layout(model, src) + if isinstance(got, str): + print(got) + return 1 + layout, text, n_expert, offset = got + path = out / "experts.bin" + sidecar = out / "experts.bin.src.json" + want = experts_source(model, text, offset) + reuse = path.exists() and path.stat().st_size == offset and read_json(sidecar) == want + if path.exists() and not reuse and not a.experts_bin: + if sidecar.exists(): + print("%s was cut from another source than this model (%s): the engine would read it instead of " + "the GGUF. Delete it, or rerun with --experts-bin to rewrite it." % (path, sidecar.name)) + return 1 + print("warning: %s has no %s, so nothing says it belongs to this model; the engine reads it instead of " + "the GGUF (rerun with --experts-bin to rewrite it)" % (path, sidecar.name)) if a.base: if any(w[3] != src for w in model.where.values() if not w[1].name in NOT_IN_PACK): print("--base needs a model whose tensors are all in shard 1") return 1 + (out / "native_experts.txt").unlink(missing_ok=True) rc = index_from_base(a, src, base, out, g, {t.name: t for t in g.tensors}, mm) else: rc = index_standalone(src, out, model, a.compat_bf16) @@ -292,49 +420,25 @@ def main() -> int: subprocess.run([sys.executable, str(HERE / "strata_tokenizer.py"), "--gguf", str(src), "--out", str(out)], check=True) # writes /tokenizer/ - # ---- the experts - n_layers = 1 + max(int(n.split(".")[1]) for n in T if n.startswith("blk.") and n.endswith("_exps.weight")) - n_expert = int(T["blk.0.ffn_gate_inp.weight"].shape[1]) # router rows = experts kept (pruned models ship < 512) - if any(int(T["blk.%d.ffn_gate_inp.weight" % l].shape[1]) != n_expert for l in range(n_layers)): - print("the routers disagree on the expert count; a per-layer pruned model cannot be packed") - return 1 - layout, offset = [], 0 - for l in range(n_layers): - ts = [T["blk.%d.ffn_%s_exps.weight" % (l, r)] for r in ROLES] - per = [t.expected_bytes() // n_expert for t in ts] - if per[0] != per[1] or ts[0].type_name != ts[1].type_name: - print("layer %d: gate and up differ in type" % l) - return 1 - blob = per[0] + per[1] + per[2] - layout.append((l, ts[0].type_id, ts[2].type_id, offset, blob, ts)) - offset += blob * n_expert - # written to a temporary name and renamed only when every layer is in: a stop part-way (a layer split across - # shards, #171) left a partial native_experts.txt that the next setup run took as a finished pack (#172) + # ---- the experts. native_experts.txt is written to a temporary name and renamed only when every layer is + # in: a stop part-way (a layer split across shards, #171) left a partial native_experts.txt that the next setup + # run took as a finished pack (#172). It is the pack's completion marker, so it is published last. tmp = out / "native_experts.txt.tmp" with open(tmp, "w", encoding="utf-8", newline="\n") as fo: - fo.write("# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] " - "(n_expert %d, total %d; absolute offsets in %s, or in the named shard beside it)\n" - % (n_expert, offset, src.name)) - for l, gt, dt, off, blob, ts in layout: - ws = [model.where[t.name] for t in ts] - if len({w[3] for w in ws}) != 1: - print("layer %d: its gate/up/down tensors are in different shards" % l) - fo.close() - tmp.unlink() - return 1 - gg, shard = ws[0][0], ws[0][3] - line = "%d %d %d %d %d %d %d %d" % (l, gt, dt, off, blob, *[gg.data_start + t.offset for t in ts]) - fo.write(line + ("" if shard == src else " " + shard.name) + "\n") + fo.write(text) tmp.replace(out / "native_experts.txt") if a.skip_experts or not a.experts_bin: - if (out / "experts.bin").exists() and not a.experts_bin: + if path.exists() and not a.experts_bin: print("note: %s/experts.bin exists; the engine reads it instead of the GGUF" % out) return 0 - path = out / "experts.bin" - if path.exists() and path.stat().st_size == offset: - print("experts.bin exists with the right size; not rewritten") + if reuse: + print("experts.bin was cut from this model's shards (%s); not rewritten" % sidecar.name) return 0 - with open(path, "wb") as fo: + # written under a temporary name and renamed when complete, then the sidecar: an interrupted write leaves no + # experts.bin, and an experts.bin without its sidecar is never reused + sidecar.unlink(missing_ok=True) + part = out / "experts.bin.tmp" + with open(part, "wb") as fo: for l, gt, dt, off, blob, ts in layout: parts = [model.bytes(t.name).reshape(n_expert, -1) for t in ts] chunk = np.concatenate(parts, axis=1) # (n_expert, blob): gate | up | down per expert @@ -343,7 +447,11 @@ def main() -> int: if l % 8 == 0: print(" layer %2d %-8s/%-7s blob %8d at %.2f GiB" % (l, ts[0].type_name, ts[2].type_name, blob, off / 2**30), flush=True) - print("experts.bin: %d layers, %.2f GiB" % (n_layers, offset / 2**30)) + part.replace(path) + side_tmp = out / "experts.bin.src.json.tmp" + side_tmp.write_text(json.dumps(want, indent=2) + "\n", encoding="utf-8") + side_tmp.replace(sidecar) + print("experts.bin: %d layers, %.2f GiB" % (len(layout), offset / 2**30)) return 0 diff --git a/tools/test_iq_pack.py b/tools/test_iq_pack.py index c7a5e876..6153409f 100644 --- a/tools/test_iq_pack.py +++ b/tools/test_iq_pack.py @@ -18,8 +18,15 @@ from gguf import GGUFWriter, GGMLQuantizationType as Q, quants import iq_pack -def write_gguf(path, tensors): +def write_gguf(path, tensors, split=None, arch=True): + """`split` = (no, count, tensors): llama.cpp's gguf-split keys (0-based split.no).""" writer = GGUFWriter(path, "qwen4exp") + if not arch: # a later shard of a split: no model metadata + writer.kv_data[0].pop("general.architecture", None) + if split is not None: + writer.add_uint16("split.no", split[0]) + writer.add_uint16("split.count", split[1]) + writer.add_int32("split.tensors.count", split[2]) for name, values, kind in tensors: writer.add_tensor(name, quants.quantize(values, kind), raw_dtype=kind) writer.write_header_to_file() @@ -121,9 +128,9 @@ class CompatibilityTests(unittest.TestCase): write_gguf(root / "blob1", [ ("blk.0.hc_attn_down.weight", np.ones((2, 32), np.float32), Q.Q8_0), ("blk.0.ffn_gate_inp.weight", np.ones((512, 32), np.float32), Q.BF16), - ]) + ], split=(0, 2, 5)) write_gguf(root / "blob2", [(f"blk.0.ffn_{r}_exps.weight", np.ones((512, 2, 32), np.float32), Q.Q8_0) - for r in ("gate", "up", "down")]) + for r in ("gate", "up", "down")], split=(1, 2, 5), arch=False) try: first.symlink_to(root / "blob1") except OSError: # Windows without Developer Mode or admin rights @@ -146,5 +153,202 @@ class CompatibilityTests(unittest.TestCase): iq_pack.Model(first) + +# ---- split artifacts: Unsloth's UD-Q4_K_XL in miniature. Shard 1 holds the metadata and no tensor; shard 2 the +# routers, layer 0 and layer 1's down; shard 3 layer 1's gate and up (a shard boundary inside a layer, like its +# layer 11); shard 4 one float tensor. 4 experts of 32 x 32, Q8_0 and F32. +N_EXPERT = 4 + + +def expert(seed, shape): + return np.random.default_rng(seed).standard_normal((N_EXPERT, *shape)).astype(np.float32) + + +def split_model(root, name="model", split_layer=True, dup=False, split_no=None, gate1=Q.Q8_0, seed=0): + """Writes the 4 shards; returns their paths.""" + gu, dn = (32, 32), (32, 32) + router = [(f"blk.{l}.ffn_gate_inp.weight", np.full((N_EXPERT, 32), 0.5, np.float32), Q.F32) for l in (0, 1)] + l0 = [(f"blk.0.ffn_{r}_exps.weight", expert(seed + 10 + i, gu if r != "down" else dn), Q.Q8_0) + for i, r in enumerate(("gate", "up", "down"))] + l1_gu = [("blk.1.ffn_gate_exps.weight", expert(seed + 20, gu), gate1), + ("blk.1.ffn_up_exps.weight", expert(seed + 21, gu), Q.Q8_0)] + l1_d = [("blk.1.ffn_down_exps.weight", expert(seed + 22, dn), Q.F32)] + shards = [[], router + l0 + (l1_d if split_layer else []), l1_gu + ([] if split_layer else l1_d), + [("output_norm.weight", np.ones(32, np.float32), Q.F32)]] + if dup: + shards[3].append(l1_gu[1]) + total = sum(len(s) for s in shards) + paths = [] + for i, tensors in enumerate(shards): + p = root / f"{name}-{i + 1:05d}-of-00004.gguf" + no = split_no.get(i, i) if split_no else i + write_gguf(p, tensors, split=(no, 4, total), arch=i == 0) + paths.append(p) + return paths + + +def run_pack(first, out, *extra): + (out / "tokenizer").mkdir(parents=True, exist_ok=True) + for n in ["vocab.json", "chat_template.jinja"]: + (out / "tokenizer" / n).touch() + buf = io.StringIO() + with patch.object(sys, "argv", ["iq_pack.py", "--gguf", str(first), "--out", str(out), *extra]): + with contextlib.redirect_stdout(buf): + rc = iq_pack.main() + return rc, buf.getvalue() + + +def expected_experts(model): + """experts.bin from first principles: per layer, per expert, gate | up | down slices.""" + parts = [] + for l in (0, 1): + ts = [model.bytes(f"blk.{l}.ffn_{r}_exps.weight").reshape(N_EXPERT, -1) for r in ("gate", "up", "down")] + parts.append(np.concatenate(ts, axis=1).tobytes()) + return b"".join(parts) + + +class SplitArtifactTests(unittest.TestCase): + def test_four_shards_and_a_layer_split_per_role(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + paths = split_model(root) + rc, log = run_pack(paths[0], root / "pack", "--experts-bin") + self.assertEqual(rc, 0, log) + text = (root / "pack" / "native_experts.txt").read_text() + head, line0, line1 = text.splitlines() + self.assertTrue(head.startswith("# strata native experts v4:"), head) + self.assertIn("(n_expert 4,", head) + s2, s3 = paths[1].name, paths[2].name + self.assertEqual(line0.split()[8:], [s2]) + self.assertEqual(line1.split()[8:], [f"{s3},{s3},{s2}"]) + # every role's offset is absolute in ITS shard: shard 3's data_start for gate/up, shard 2's for down + m = iq_pack.Model(paths[0]) + for line, l in ((line0, 0), (line1, 1)): + f = line.split() + for r, role in enumerate(("gate", "up", "down")): + g, t, _, _ = m.where[f"blk.{l}.ffn_{role}_exps.weight"] + self.assertEqual(int(f[5 + r]), g.data_start + t.offset) + self.assertNotEqual(m.where["blk.1.ffn_gate_exps.weight"][0].data_start, + m.where["blk.1.ffn_down_exps.weight"][0].data_start) + self.assertEqual((root / "pack" / "experts.bin").read_bytes(), expected_experts(m)) + side = json.loads((root / "pack" / "experts.bin.src.json").read_text()) + self.assertEqual([s["name"] for s in side["shards"]], [p.name for p in paths]) + self.assertFalse(list((root / "pack").glob("*.tmp"))) + # the index: routers as BF16, nothing of the experts + _, rows = iq_pack.read_index(root / "pack" / "index.txt") + self.assertNotIn("blk.1.ffn_gate_exps.weight", rows) + self.assertEqual(rows["blk.1.ffn_gate_inp.weight"][2], "4") + + def test_unsplit_layers_keep_the_v3_file(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + paths = split_model(root, split_layer=False) + rc, log = run_pack(paths[0], root / "pack") + self.assertEqual(rc, 0, log) + head, line0, line1 = (root / "pack" / "native_experts.txt").read_text().splitlines() + self.assertTrue(head.startswith("# strata native experts v3: layer gu_type d_type offset blob_bytes " + "gate_off up_off down_off [shard] (n_expert 4, total "), head) + self.assertEqual(line1.split()[8:], [paths[2].name]) + + def test_missing_shard(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + paths = split_model(Path(tmp)) + paths[3].unlink() + with self.assertRaisesRegex(FileNotFoundError, "missing model shards.*00004-of-00004"): + iq_pack.Model(paths[0]) + + def test_duplicate_tensor_across_shards(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + paths = split_model(Path(tmp), dup=True) + with self.assertRaisesRegex(ValueError, "duplicate tensor blk.1.ffn_up_exps.weight"): + iq_pack.Model(paths[0]) + + def test_shard_of_another_split(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + paths = split_model(Path(tmp), split_no={2: 1}) + with self.assertRaisesRegex(ValueError, "does not declare itself shard 3 of 4"): + iq_pack.Model(paths[0]) + + def test_truncated_shard(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + paths = split_model(Path(tmp)) + paths[2].write_bytes(paths[2].read_bytes()[:-64]) + with self.assertRaisesRegex(ValueError, "truncated tensor"): + iq_pack.Model(paths[0]) + + def test_wrong_type_or_shape_leaves_the_pack_alone(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + paths = split_model(root, gate1=Q.F32) # layer 1: gate F32, up Q8_0 + pack = root / "pack" + pack.mkdir() + (pack / "native_experts.txt").write_text("previous pack") + rc, log = run_pack(paths[0], pack) + self.assertEqual(rc, 1) + self.assertIn("layer 1: gate and up differ in type", log) + self.assertEqual((pack / "native_experts.txt").read_text(), "previous pack") + self.assertFalse((pack / "dense.bin").exists()) + + def test_interrupted_pack(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + paths = split_model(root) + pack = root / "pack" + real = np.concatenate + calls = [] + + def dies_on_layer_1(parts, axis): + calls.append(1) + if len(calls) == 2: + raise KeyboardInterrupt("stopped part-way") + return real(parts, axis=axis) + with patch.object(iq_pack.np, "concatenate", dies_on_layer_1): + with self.assertRaises(KeyboardInterrupt): + run_pack(paths[0], pack, "--experts-bin") + self.assertFalse((pack / "experts.bin").exists()) + self.assertFalse((pack / "experts.bin.src.json").exists()) + # the index stops part-way too: the old pack's files stay as they were + before = {n: (pack / n).read_bytes() for n in ("index.txt", "dense.bin", "native_experts.txt")} + with patch.object(iq_pack, "write_index", side_effect=KeyboardInterrupt("stopped")): + with self.assertRaises(KeyboardInterrupt): + run_pack(paths[0], pack) + self.assertEqual(before, {n: (pack / n).read_bytes() for n in before}) + rc, log = run_pack(paths[0], pack, "--experts-bin") + self.assertEqual(rc, 0, log) + self.assertEqual((pack / "experts.bin").read_bytes(), expected_experts(iq_pack.Model(paths[0]))) + + def test_stale_same_size_experts_bin(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + (root / "a").mkdir() + (root / "b").mkdir() + other = split_model(root / "a", name="other", seed=100) + paths = split_model(root / "b") + pack = root / "pack" + rc, log = run_pack(other[0], pack, "--experts-bin") # another model, the same geometry + self.assertEqual(rc, 0, log) + stale = (pack / "experts.bin").read_bytes() + want = expected_experts(iq_pack.Model(paths[0])) + self.assertEqual(len(stale), len(want)) + self.assertNotEqual(stale, want) + # without --experts-bin the engine would read it: refused, nothing rewritten + rc, log = run_pack(paths[0], pack) + self.assertEqual(rc, 1) + self.assertIn("another source", log) + self.assertEqual((pack / "experts.bin").read_bytes(), stale) + # with it: rewritten, not reused by its size + rc, log = run_pack(paths[0], pack, "--experts-bin") + self.assertEqual(rc, 0, log) + self.assertEqual((pack / "experts.bin").read_bytes(), want) + # and now reused + rc, log = run_pack(paths[0], pack, "--experts-bin") + self.assertIn("not rewritten", log) + # an experts.bin without its sidecar (an older packer) is rewritten too + (pack / "experts.bin.src.json").unlink() + (pack / "experts.bin").write_bytes(stale) + rc, log = run_pack(paths[0], pack, "--experts-bin") + self.assertEqual((pack / "experts.bin").read_bytes(), want) + + if __name__ == "__main__": unittest.main() From 24bba1743b55d61b759f61a828abe2ab4a06b9a7 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 20:55:30 +0200 Subject: [PATCH 3/7] iq_pack: each tensor in the form the engine reads (FORM), exact F32->BF16 by default, PLE conv F32 -> F16 by the loader, conversions.json; the engine refuses a wide conv1d - FORM (eddoursul/Strata's list of which tensor the engine reads as BF16, F16 or F32) decides the pack form; the conversion itself is upstream's bf16_bytes (gguf-py, finite check, round-to-nearest- even). By default only lossless conversions happen: F32 whose values are exactly BF16 (low 16 bits zero; before, only the routers) and F16/BF16 widened to F32. Rounding (inexact F32, Q8_0 hyper- connection / PLE value / output_hc, F16 -> BF16) still needs --compat-bf16. NaN/Inf are refused even where the low bits are zero. - A Q8_0 PLE key stays native (served from the GGUF, like Q2_0); other quantized keys take the BF16 path as before. (The engine's native PLE key learns Q8_0 in the formats change.) - blk.1.ple_conv1d stored F32 (Q8_0 / UD-Q4_K_XL files) goes into dense.bin as index kind 3 and the loader narrows it to F16 (#255, gopinath87607), with or without --compat-bf16; a value beyond F16's range is refused. generate refuses a pack whose conv1d is not F16 (#255's check, which also accepts the canonical Q2_0 pack's verbatim-F16 kind 0 - #255 as written refuses that pack). - conversions.json (schema 1): the source shards' names and sizes, and per converted tensor its shard, source/destination type, method, exact flag, largest absolute error and source sha256. compat-bf16.json is written as before. Refusals happen before anything is published. - Byte identity: index.txt, native_experts.txt and dense.bin of Q2_0, IQ3_XXS, IQ3_S, Coder IQ1_M and Swift IQ2_XS are identical to main's packer (Swift's 96 exact F32 routers are now listed in conversions.json). - Tests: exact F32->BF16 by default, inexact only with --compat-bf16 (error bound), NaN/+-Inf refused with and without the flag (previous pack untouched), conv1d kind 3 (bytes, record, F16 kept, overflow refused), Q8_0 projections need the flag and are recorded, Q8_0 key native. --- src/program/generate.cpp | 14 +++ tools/iq_pack.py | 239 ++++++++++++++++++++++++++++++--------- tools/test_iq_pack.py | 144 ++++++++++++++++++++++- 3 files changed, 336 insertions(+), 61 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 94de0ea7..98de832e 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1890,6 +1890,20 @@ int main(int argc, char** argv) { ss.ple.w.norm_key = (const float*) wnk->data; ss.ple.w.norm_query = (const float*) wnq->data; ss.ple.w.norm_conv = (const float*) wnc->data; + // The conv1d kernel reads F16, so this cast is a claim about the pack's storage. A checkpoint that keeps + // the tensor F32 (Q8_0, UD-Q4_K_XL) would hand the kernel the low halves of the f32 words - not an error, + // a plausible wrong layer-1 routing. tools/iq_pack.py narrows it (index kind 3); a pack that did not is + // refused here (#255, gopinath87607). F16 is index kind 5 or 3 (F16InF32) in a native pack and kind 0 + // (verbatim 2-byte F16) in the canonical Q2_0 pack; BF16 (kind 4) has the same size and is not F16. + const bool f16 = wc->kind == strata::core::WeightKind::F16InF32 || + (wc->kind == strata::core::WeightKind::Verbatim && wc->code_bits == 0); + if (!f16 || wc->bytes != (uint64_t) wc->elements * 2) { + std::fprintf(stderr, "strata generate: blk.1.ple_conv1d.weight is not stored as F16 (pack index kind %d, " + "%llu B for %lld values); the PLE conv1d kernel reads F16 - repack with " + "tools/iq_pack.py\n", + (int) wc->kind, (unsigned long long) wc->bytes, (long long) wc->elements); + return 1; + } ss.ple.w.conv1d_f16 = (const uint16_t*) wc->data; ss.ple.consts = strata::kernels::ple_artifact_consts(); if (o.ple_delay_us > 0) ple_table.set_injected_delay_us(o.ple_delay_us); diff --git a/tools/iq_pack.py b/tools/iq_pack.py index 74ef3239..43994075 100644 --- a/tools/iq_pack.py +++ b/tools/iq_pack.py @@ -14,7 +14,10 @@ its GGUF form: written last, so a pack without it is not finished index.txt the table the engine loads. Quantized dense tensors, token_embd and output are served natively from the GGUF by the engine (--native): their rows carry shape only. - dense.bin standalone: the BF16/F16/F32 tensors exactly as the GGUF stores them (index kinds 4/5/2). + dense.bin standalone: the BF16/F16/F32 tensors in the form the engine reads them (index kinds 4/5/2; + 3 = F32 narrowed to F16 by the loader) - as the GGUF stores them, or converted (FORM below). + conversions.json every tensor that was converted: shard, source/destination type, method, whether it was + exact, the largest absolute error, the source bytes' sha256 (schema 1). With --base: the base (Q2_0) pack's dense.bin, hard-linked - the float tensors are byte-identical in all three model files (checked) - plus extra.bin for tensors that are float here but quantized in the base pack (blk.1.ple_key). @@ -27,11 +30,12 @@ may even fall inside a layer (Unsloth's UD-Q4_K_XL: layer 11's down in shard 2, layer's shard column is per role, `gate,up,down` (an empty field = the --gguf shard), and only then is the file v4, so an older engine refuses it instead of misreading it. Every other pack stays v3, byte for byte. Router tensors stored as F32 whose values are exactly BF16 (Swift 1.5) are written as BF16, the form the engine's router -takes; anything else is refused. +takes (so are the other F32 tensors the engine reads as BF16, when exact); anything else is refused. For ordinary quants, --compat-bf16 dequantizes the small projections that the engine reads as BF16, using round-to-nearest-even. This introduces BF16 rounding; it does not reconstruct the original full-precision -weights. Experts, native attention projections, token embeddings and the disk-backed PLE table stay unchanged. +weights. Experts, native attention projections, token embeddings, a Q2_0/Q8_0 PLE key and the disk-backed PLE +table stay unchanged. """ from __future__ import annotations @@ -40,6 +44,7 @@ import hashlib import json import os import pathlib +import re import shutil import subprocess import sys @@ -54,25 +59,60 @@ FLOAT = {"BF16", "F32", "F16"} ROUTERS = ("ffn_gate_inp.weight", "ffn_gate_inp_shexp.weight") NOT_IN_PACK = {"per_layer_token_embd.weight"} # the 28.8 GB PLE table: read from its GGUF by the engine -# These small projections are read as BF16 by the residual, router, GDN, QSA and PLE kernels. -# GSQ-RCO files already store them that way. Ordinary GGUF quants (including OrcaRouter's IQ3_XXS) -# quantize them too; --compat-bf16 explicitly dequantizes and rounds ONLY these tensors. -BF16_PROJECTIONS = ( - "hc_attn_down.weight", "hc_attn_up.weight", "hc_attn_inject.weight", - "hc_ffn_down.weight", "hc_ffn_up.weight", "hc_ffn_inject.weight", - "ssm_alpha.weight", "ssm_beta.weight", "indexer.q_proj.weight", "indexer.k_proj.weight", - "ple_value.weight", *ROUTERS, -) -BF16_OUTPUT = {"output_hc_down.weight", "output_hc_up.weight"} +# The float form the engine reads each pack tensor in (name without `blk.N.`; from eddoursul/Strata's FORM table). +# The residual, router, GDN, QSA and PLE kernels read these small projections as BF16, the norms as F32 and the PLE +# conv as F16. GSQ-RCO files already store them that way; other files do not (Unsloth's UD-Q4_K_XL: the routers, +# SSM gates and injections F32, the hyper-connection projections and the PLE value Q8_0, the PLE conv F32), so a +# tensor stored otherwise is converted, and every conversion is recorded in conversions.json: +# F32 -> BF16 whose values are exactly BF16 (low 16 bits zero) exact, by default +# F32 with other values, F16 or a quantized type -> BF16 rounds (nearest-even): only with --compat-bf16 +# F32 -> F16 (ple_conv1d) index kind 3, narrowed by the loader (#255), +# by default - the kernel reads nothing else +# F16 / BF16 -> F32 exact widening, by default +# Tensors not named here are written as stored (floats) or served from the GGUF (quantized), as before. +FORM = { + "ffn_gate_inp.weight": "BF16", "ffn_gate_inp_shexp.weight": "BF16", + "hc_attn_down.weight": "BF16", "hc_attn_up.weight": "BF16", "hc_attn_inject.weight": "BF16", + "hc_ffn_down.weight": "BF16", "hc_ffn_up.weight": "BF16", "hc_ffn_inject.weight": "BF16", + "output_hc_down.weight": "BF16", "output_hc_up.weight": "BF16", + "indexer.k_proj.weight": "BF16", "indexer.q_proj.weight": "BF16", + "ssm_alpha.weight": "BF16", "ssm_beta.weight": "BF16", + "ple_key.weight": "BF16", "ple_value.weight": "BF16", "ple_conv1d.weight": "F16", + "attn_q_norm.weight": "F32", "attn_k_norm.weight": "F32", "hc_attn_norm.weight": "F32", + "hc_ffn_norm.weight": "F32", "output_hc_norm.weight": "F32", "indexer.q_norm.weight": "F32", + "indexer.k_norm.weight": "F32", "ple_norm_conv.weight": "F32", "ple_norm_key.weight": "F32", + "ple_norm_query.weight": "F32", "ssm_a": "F32", "ssm_conv1d.weight": "F32", "ssm_dt.bias": "F32", + "ssm_norm.weight": "F32", +} +# PLE key encodings left in the GGUF for the engine's native PLE key (Q2_0; Q8_0 in UD-Q4_K_XL). Other quantized +# keys take the BF16 path (--compat-bf16), as before. +NATIVE_PLE_KEY = {"Q2_0", "Q8_0"} +KIND = {"BF16": "4", "F16": "5", "F32": "2"} + + +def form_of(name: str): + return FORM.get(re.sub(r"^blk\.\d+\.", "", name)) def needs_bf16(name: str, type_name: str) -> bool: - if name in BF16_OUTPUT: - return True - if not name.startswith("blk."): + """Whether the engine reads `name` as BF16 from the pack (not natively from the GGUF).""" + if name == "blk.1.ple_key.weight" and type_name in NATIVE_PLE_KEY: return False - # The existing native PLE key supports Q2_0 only. Other key encodings use the BF16 path. - return name.endswith(BF16_PROJECTIONS) or (name == "blk.1.ple_key.weight" and type_name != "Q2_0") + return form_of(name) == "BF16" + + +def dequantize(raw: np.ndarray, type_name: str) -> np.ndarray: + """The tensor's values as float32 (float types exactly, quantized ones through gguf-py's dequantizer).""" + if type_name == "F32": + return raw.view(np.float32) + if type_name == "F16": + return raw.view(np.float16).astype(np.float32) + if type_name == "BF16": + return (raw.view(np.uint16).astype(np.uint32) << 16).view(np.float32) + from _paths import add_gguf_py + add_gguf_py() + from gguf import GGMLQuantizationType as Q, quants + return quants.dequantize(raw, Q[type_name]).astype(np.float32).reshape(-1) def bf16_bytes(raw: np.ndarray, type_name: str) -> bytes: @@ -86,6 +126,18 @@ def bf16_bytes(raw: np.ndarray, type_name: str) -> bytes: return quants.quantize(values, Q.BF16).tobytes() +def f16_values(values: np.ndarray, name: str) -> np.ndarray: + """values -> F16, nearest-even (numpy's conversion, which is the engine loader's f16_from_f32); refuses a value + that is not finite or overflows F16.""" + if not np.isfinite(values).all(): + raise ValueError(f"{name}: cannot convert non-finite weights to F16") + with np.errstate(over="ignore"): + h = values.astype(np.float16) + if not np.isfinite(h).all(): + raise ValueError(f"{name}: a value is beyond F16's range, which the engine reads it as") + return h + + class Model: """All shards of one model: name -> (GGUFFile, TensorInfo, memmap, shard path).""" @@ -171,59 +223,134 @@ def is_expert(name: str) -> bool: return name.startswith("blk.") and name.endswith(("_exps.weight",)) +def convert(name: str, type_name: str, raw: np.ndarray, compat_bf16: bool): + """The pack form of one tensor the engine reads from dense.bin: (kind, stored bytes, destination bytes, + record or None), or an error string. `record` describes a conversion for conversions.json.""" + form = form_of(name) + if form is None or form == type_name: + return KIND[type_name], raw.tobytes(), raw.nbytes, None + values = dequantize(raw, type_name) + rec = {"src_type": type_name, "dst_type": form} + if form == "BF16": + u = values.view(np.uint32) if type_name == "F32" else None + if u is not None and not np.count_nonzero(u & 0xFFFF): + if not np.isfinite(values).all(): + return f"{name} is F32 with non-finite values; refused rather than converted" + data = (u >> 16).astype("bf16 round-to-nearest-even (--compat-bf16)" % type_name.lower()) + rec.update(exact=bool(np.array_equal(got, values)), + max_abs_err=float(np.max(np.abs(got.astype(np.float64) - values))) if values.size else 0.0) + return "4", data, len(data), rec + if form == "F16": + if type_name != "F32" and not compat_bf16: + return f"{name} is {type_name}, but the engine reads F16; use --compat-bf16 (rounds to nearest-even)" + h = f16_values(values, name) + err = float(np.max(np.abs(h.astype(np.float64) - values))) if values.size else 0.0 + rec.update(exact=bool(np.array_equal(h.astype(np.float32), values)), max_abs_err=err) + if type_name == "F32": + # The F32 bytes go into dense.bin as index kind 3 and the loader narrows them to F16 (nearest-even), the + # form the PLE conv kernel reads (#255, gopinath87607): 4 B/elem in, 2 B/elem out. + rec.update(method="f32->f16 by the loader (index kind 3, round-to-nearest-even)") + return "3", raw.tobytes(), raw.nbytes // 2, rec + rec.update(method="%s->f16 round-to-nearest-even (--compat-bf16)" % type_name.lower()) + data = h.astype(" int: - """Every non-expert tensor of the model: floats into dense.bin as stored (exact-BF16 F32 routers as BF16), - quantized ones native-only.""" - if not compat_bf16: - for name, (_, t, _, _) in model.where.items(): - if needs_bf16(name, t.type_name) and t.type_name != "BF16" and not ( - t.type_name == "F32" and name.endswith(ROUTERS)): - print(f"{name} is {t.type_name}, but the engine requires BF16; use --compat-bf16") - return 1 + """Every non-expert tensor of the model: the floats the engine reads from the pack into dense.bin in the form it + reads them (FORM; converted when stored otherwise, see above), quantized ones served natively from the GGUF.""" + todo, problems = [], [] + for name, (g, t, mm, p) in model.where.items(): + if is_expert(t.name) or t.name in NOT_IN_PACK: + continue + if len(t.shape) > 2: + print("tensor %s has %d dimensions; the index holds two" % (t.name, len(t.shape))) + return 1 + # quantized: served from the GGUF unless the engine reads it from the pack (FORM), which takes + # --compat-bf16 to dequantize - except the native PLE key encodings + form = form_of(name) + native = t.type_name not in FLOAT and (form is None or ( + name == "blk.1.ple_key.weight" and t.type_name in NATIVE_PLE_KEY)) + if t.type_name not in FLOAT and not native and not compat_bf16: + problems.append(f"{name} is {t.type_name}, but the engine requires {form}; use --compat-bf16") + todo.append((name, g, t, mm, p, native)) + # refused before anything is written: the previous pack stays as it was + if problems: + for m in problems[:8]: + print(m) + if len(problems) > 8: + print("... and %d more" % (len(problems) - 8)) + return 1 rows, at = [], 0 served = 0 - converted = [] + converted, records = [], [] with open(out / "dense.bin.tmp", "wb") as fo: - for name, (g, t, mm, _) in model.where.items(): - if is_expert(t.name) or t.name in NOT_IN_PACK: - continue - if len(t.shape) > 2: - print("tensor %s has %d dimensions; the index holds two" % (t.name, len(t.shape))) - return 1 + for name, g, t, mm, p, native in todo: ne0 = int(t.shape[0]) ne1 = int(t.shape[1]) if len(t.shape) > 1 else 0 - convert = compat_bf16 and needs_bf16(t.name, t.type_name) and t.type_name != "BF16" - if t.type_name in FLOAT or convert: - raw = tensor_bytes(mm, g, t).tobytes() - if convert: - raw = bf16_bytes(np.frombuffer(raw, dtype=np.uint8), t.type_name) - kind = "4" - converted.append({"name": t.name, "source_type": t.type_name, "bytes": len(raw)}) - else: - kind = {"BF16": "4", "F16": "5", "F32": "2"}[t.type_name] - if not convert and t.type_name == "F32" and t.name.endswith(ROUTERS): - u = np.frombuffer(raw, dtype=np.uint32) - if np.count_nonzero(u & 0xFFFF): - print("router %s is F32 with values that are not BF16; the engine's router is BF16" % t.name) - return 1 - raw = (u >> 16).astype(np.uint16).tobytes() # the exact BF16 values - kind = "4" - rows.append([t.name, "0", kind, str(at), str(len(raw)), "0", str(len(raw)), str(ne0), str(ne1), - "0", "0", "1"] + ["0"] * 7) - fo.write(raw) - pad = (-len(raw)) % ALIGN - fo.write(b"\0" * pad) - at += len(raw) + pad - else: + if native: served += 1 rows.append([t.name, "0", "0", "0", "0", "0", "0", str(ne0), str(ne1), "8", "0", "32"] + ["0"] * 7) + continue + raw = tensor_bytes(mm, g, t) + try: + got = convert(name, t.type_name, raw, compat_bf16) + except ValueError as e: + got = str(e) + if isinstance(got, str): + print(got) + fo.close() + (out / "dense.bin.tmp").unlink(missing_ok=True) + return 1 + kind, data, dst_bytes, rec = got + if rec is not None: + rec = {"name": name, "shard": p.name, **rec, + "source_sha256": hashlib.sha256(raw.tobytes()).hexdigest()} + records.append(rec) + if "--compat-bf16" in rec["method"]: # the rounding the flag allowed + converted.append({"name": name, "source_type": t.type_name, "bytes": len(data)}) + rows.append([t.name, "0", kind, str(at), str(len(data)), "0", str(dst_bytes), str(ne0), str(ne1), + "0", "0", "1"] + ["0"] * 7) + fo.write(data) + pad = (-len(data)) % ALIGN + fo.write(b"\0" * pad) + at += len(data) + pad write_index(out, rows, src, served, 0, publish=False) + conv = out / "conversions.json.tmp" + conv.write_text(json.dumps({ + "schema": 1, "tool": "tools/iq_pack.py", "compat_bf16": compat_bf16, + "source_shards": [{"name": q.name, "size": s} for q, s in zip(model.paths, model.sizes)], + "tensors": records, + }, indent=1) + "\n", encoding="utf-8") # published together, and the completion marker (native_experts.txt, written last by main) goes first: a stop # from here on leaves a pack that setup and the engine see as unfinished, never a new dense.bin under an old # index or the reverse (out / "native_experts.txt").unlink(missing_ok=True) (out / "dense.bin.tmp").replace(out / "dense.bin") (out / "index.txt.tmp").replace(out / "index.txt") + conv.replace(out / "conversions.json") + if records: + exact = sum(1 for r in records if r["exact"]) + print("conversions.json: %d tensors converted to the engine's form (%d exact, %d rounded; max |err| %.3g)" + % (len(records), exact, len(records) - exact, max(r["max_abs_err"] for r in records))) + for r in records: + if r["dst_type"] == "F16": + print("narrowed to F16 by the loader: %s (%s, index kind 3)" % (r["name"], r["method"])) if compat_bf16: (out / "compat-bf16.json").write_text(json.dumps({ "source": str(src), "rounding": "nearest-even", "tensors": converted, diff --git a/tools/test_iq_pack.py b/tools/test_iq_pack.py index 6153409f..72339813 100644 --- a/tools/test_iq_pack.py +++ b/tools/test_iq_pack.py @@ -1,5 +1,6 @@ """Focused pack compatibility tests; run .venv/bin/python -m unittest discover -s tools -p test_iq_pack.py.""" import contextlib +import hashlib import io import json from pathlib import Path @@ -51,9 +52,10 @@ class CompatibilityTests(unittest.TestCase): source = root / "model.gguf" values = np.linspace(-1, 1, 256, dtype=np.float32).reshape(2, 128) router = np.full((2, 128), 0.10001, dtype=np.float32) - names = ["blk.0.hc_attn_down.weight", "output_hc_up.weight", "blk.1.ple_key.weight", + names = ["blk.0.hc_attn_down.weight", "output_hc_up.weight", "blk.0.ssm_alpha.weight", "blk.3.indexer.q_proj.weight", "blk.1.ple_value.weight"] write_gguf(source, [(n, values, Q.Q8_0) for n in names] + [ + ("blk.1.ple_key.weight", values, Q.Q8_0), ("blk.0.ffn_gate_inp.weight", router, Q.F32), ("blk.0.attn_qkv.weight", values, Q.Q8_0), ("per_layer_token_embd.weight", values, Q.Q8_0), @@ -77,12 +79,16 @@ class CompatibilityTests(unittest.TestCase): self.assertEqual(row[2], "4") offset, size = int(row[3]), int(row[4]) np.testing.assert_array_equal(np.frombuffer(dense[offset:offset + size], dtype=np.uint16), expected) - native = rows["blk.0.attn_qkv.weight"] - self.assertEqual(native[4], "0") - self.assertEqual(native[9], "8") + for name in ["blk.0.attn_qkv.weight", "blk.1.ple_key.weight"]: # a Q8_0 PLE key stays native + native = rows[name] + self.assertEqual(native[2], "0") + self.assertEqual(native[4], "0") + self.assertEqual(native[9], "8") self.assertNotIn("per_layer_token_embd.weight", rows) self.assertEqual(source.read_bytes(), before) - self.assertEqual(len(json.loads((root / "compat-bf16.json").read_text())["tensors"]), 7) + self.assertEqual(len(json.loads((root / "compat-bf16.json").read_text())["tensors"]), 6) + conv = json.loads((root / "conversions.json").read_text()) + self.assertEqual(sorted(r["name"] for r in conv["tensors"]), sorted(names + ["blk.0.ffn_gate_inp.weight"])) def test_default_still_refuses_inexact_f32_router(self): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: @@ -114,6 +120,8 @@ class CompatibilityTests(unittest.TestCase): def test_q2_ple_and_large_tensors_stay_native(self): self.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "Q2_0")) + self.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "Q8_0")) + self.assertTrue(iq_pack.needs_bf16("blk.1.ple_key.weight", "IQ3_XXS")) for name in ["blk.0.ffn_gate_exps.weight", "token_embd.weight", "output.weight", "per_layer_token_embd.weight", "blk.0.attn_qkv.weight"]: self.assertFalse(iq_pack.needs_bf16(name, "IQ3_XXS")) @@ -154,6 +162,132 @@ class CompatibilityTests(unittest.TestCase): +def bits(u32): + return np.array(u32, dtype=np.uint32).view(np.float32) + + +def pack_one(root, tensors, *flags): + """A one-file model of `tensors` packed into `root` (index only): (rc, printed, rows, dense, conversions).""" + source = root / "model.gguf" + write_gguf(source, tensors) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + rc = iq_pack.index_standalone(source, root, iq_pack.Model(source), *flags) + if rc: + return rc, buf.getvalue(), None, None, None + _, rows = iq_pack.read_index(root / "index.txt") + conv = json.loads((root / "conversions.json").read_text()) + return rc, buf.getvalue(), rows, (root / "dense.bin").read_bytes(), conv + + +def stored(rows, dense, name, dtype): + row = rows[name] + return np.frombuffer(dense[int(row[3]):int(row[3]) + int(row[4])], dtype=dtype) + + +class ConversionTests(unittest.TestCase): + """CS2: FORM decides the engine's form; exact F32->BF16 by default, rounding only with --compat-bf16, the PLE + conv F32 -> F16 by the loader (index kind 3), non-finite values refused, every conversion in conversions.json.""" + + def test_exact_f32_to_bf16_by_default(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + x = bits(np.arange(64, dtype=np.uint32).reshape(2, 32) << 16 | 0x3F000000) # BF16 values held as F32 + rc, log, rows, dense, conv = pack_one(Path(tmp), [("blk.0.hc_attn_inject.weight", x, Q.F32), + ("blk.0.ssm_beta.weight", x, Q.F32), + ("blk.0.ssm_norm.weight", x, Q.F32)]) + self.assertEqual(rc, 0, log) + for name in ["blk.0.hc_attn_inject.weight", "blk.0.ssm_beta.weight"]: + self.assertEqual(rows[name][2], "4") + np.testing.assert_array_equal(stored(rows, dense, name, "> 16).ravel()) + self.assertEqual(rows["blk.0.ssm_norm.weight"][2], "2") # F32 form: as stored + recs = {r["name"]: r for r in conv["tensors"]} + self.assertEqual(set(recs), {"blk.0.hc_attn_inject.weight", "blk.0.ssm_beta.weight"}) + r = recs["blk.0.ssm_beta.weight"] + self.assertEqual((r["src_type"], r["dst_type"], r["exact"], r["max_abs_err"], r["shard"]), + ("F32", "BF16", True, 0.0, "model.gguf")) + self.assertEqual(r["source_sha256"], hashlib.sha256(x.tobytes()).hexdigest()) + self.assertEqual(conv["schema"], 1) + self.assertEqual(conv["source_shards"], [{"name": "model.gguf", + "size": (Path(tmp) / "model.gguf").stat().st_size}]) + + def test_inexact_f32_rounds_only_with_compat(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + x = np.linspace(-1, 1, 64, dtype=np.float32).reshape(2, 32) + np.float32(1e-4) + rc, log, *_ = pack_one(Path(tmp), [("blk.0.hc_ffn_inject.weight", x, Q.F32)]) + self.assertEqual(rc, 1) + self.assertIn("not BF16", log) + rc, log, rows, dense, conv = pack_one(Path(tmp), [("blk.0.hc_ffn_inject.weight", x, Q.F32)], True) + self.assertEqual(rc, 0, log) + got = stored(rows, dense, "blk.0.hc_ffn_inject.weight", " Date: Wed, 30 Sep 2026 20:56:15 +0200 Subject: [PATCH 4/7] tests: --real modes for gguf_split_test and expert_layout_test (a real model's shards / a real pack's spans, headers only) `gguf_split_test --real SHARD` opens a real model's shards (GgufModel), checks the architecture on the metadata shard and prints where output / token_embd / the PLE table and key / layer 11's experts are. `expert_layout_test --real PACK NATIVE_SHARD` checks a real pack's native_experts.txt against its model (check_experts_gguf; no expert byte is read). Both pass on the Q2_0, IQ3_XXS (v2), IQ3_S, Coder IQ1_M and Swift IQ2_XS packs and models on the reference PC. --- tests/core/expert_layout_test.cpp | 15 +++++++++++++ tests/core/gguf_split_test.cpp | 36 ++++++++++++++++++++++++++++++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/tests/core/expert_layout_test.cpp b/tests/core/expert_layout_test.cpp index d532d746..f69e5c55 100644 --- a/tests/core/expert_layout_test.cpp +++ b/tests/core/expert_layout_test.cpp @@ -256,6 +256,21 @@ void arena() { } // namespace int main(int argc, char** argv) { + // `expert_layout_test --real PACK_DIR NATIVE_SHARD`: a real pack's native_experts.txt against its model's files + // (headers only - check_experts_gguf reads no expert byte) + if (argc == 4 && std::string(argv[1]) == "--real") { + std::string err; + if (!load(argv[2], 48, 512, err)) { std::printf("layout refused: %s\n", err.c_str()); return 1; } + const ExpertLayout& L = strata::kernels::cpu::expert_layout(); + const bool ok = strata::core::check_experts_gguf(argv[3], L, err); + size_t split = 0; + for (int64_t l = 0; l < L.n_layers && !L.gguf_file.empty(); ++l) + split += L.gguf_file[(size_t) (3 * l)] != L.gguf_file[(size_t) (3 * l + 2)]; + std::printf("%s: v%d, %lld layers x %lld experts, %.2f GiB, %zu layer(s) split per role: %s%s\n", argv[2], + L.version, (long long) L.n_layers, (long long) L.n_expert, (double) L.total / (1u << 30), split, + ok ? "every span is its tensor" : "REFUSED: ", ok ? "" : err.c_str()); + return ok ? 0 : 1; + } std::printf("expert_layout_test\n"); if (argc < 2) { std::printf("usage: expert_layout_test \n"); diff --git a/tests/core/gguf_split_test.cpp b/tests/core/gguf_split_test.cpp index 22b668b6..3f137ccb 100644 --- a/tests/core/gguf_split_test.cpp +++ b/tests/core/gguf_split_test.cpp @@ -79,7 +79,41 @@ std::string error_of(const std::vector& paths) { } } // namespace -int main() { +// `gguf_split_test --real SHARD`: the same view of a real model (headers only): its shards, the architecture +// check on the metadata shard, and where the tensors the engine reads by name live. +int real_model(const std::string& any) { + try { + const strata::GgufModel m = strata::GgufModel::open(any); + size_t tensors = 0; + for (size_t i = 0; i < m.size(); ++i) { + std::printf(" shard %zu: %s, %zu tensors, data at %llu\n", i + 1, m.shard(i).path().c_str(), + m.shard(i).tensors().size(), (unsigned long long) m.shard(i).data_start()); + tensors += m.shard(i).tensors().size(); + } + const std::string arch = strata::check_architecture(m.meta()); + std::printf(" %zu tensors; architecture check on the metadata shard: %s\n", tensors, + arch.empty() ? "ok" : arch.c_str()); + int bad = arch.empty() ? 0 : 1; + for (const char* name : {"output.weight", "token_embd.weight", "per_layer_token_embd.weight", + "blk.1.ple_key.weight", "blk.11.ffn_gate_exps.weight", "blk.11.ffn_up_exps.weight", + "blk.11.ffn_down_exps.weight"}) { + size_t s = 0; + const strata::TensorInfo* t = m.find(name, &s); + if (!t) { std::printf(" %-30s absent\n", name); continue; } + const bool ok = m.in_bounds(*t, s); + bad += !ok; + std::printf(" %-30s shard %zu, %s, %llu B, %s\n", name, s + 1, t->type_name(), + (unsigned long long) strata::tensor_payload_bytes(*t), ok ? "in bounds" : "OUT OF BOUNDS"); + } + return bad ? 1 : 0; + } catch (const std::exception& e) { + std::printf(" refused: %s\n", e.what()); + return 1; + } +} + +int main(int argc, char** argv) { + if (argc == 3 && std::string(argv[1]) == "--real") return real_model(argv[2]); std::printf("gguf_split_test\n"); { TempDir d; From ee7c802664c95be62c691014e9a1dabd1b67a23e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 22:02:59 +0200 Subject: [PATCH 5/7] iq_kernels: Q4_K / Q5_K / Q5_1 / Q8_0 native experts (Unsloth UD-Q4_K_XL), per-role format lists, native_expert_supported at startup, Q8_0 embedding and PLE key - Dots: llama.cpp's vec_dot_q4_K / q5_K / q8_0_q8_1 transcribed (VDR 2), via eddoursul/Strata 8029fa9 and #255 (gopinath87607, Q8_0), which agree. Q5_1's min term multiplies the sum of the QUANTIZED activations (ggml-cpu's convention, as the fork does), not llama.cpp CUDA's ds.y. - Dequantizers dq_q4_k / dq_q5_k / dq_q5_1 / dq_q8_0 (llama.cpp's formulas) for the prompt path's FP16 fallback, f32 dumps and the Q8_0 embedding; iq_row_bytes / is_iq know the four types; iq_dequant_gu_f16 now refuses an unknown type instead of leaving its output unwritten. - The grouped gate/up, down and iq_mmvq switches are generated from STRATA_GU_FMTS / STRATA_D_FMTS / STRATA_MMVQ_FMTS; the existing entries launch the same kernels as before. - native_expert_supported(gu, d, n_embd, n_ff): generate checks every layer of a native pack right after expert_layout_load and refuses an unsupported pair by name before anything is allocated (it used to exit from inside the first verify window). - Native PLE key: Q8_0 accepted (NativeDense, generate, ple.cu); native_mmvq already runs it. - native_expert_parity: --synthetic GU/DOWN (random ggml-quantized blobs at 2560/640; port of the fork's mode), GPU dequant f32/f16 and embedding rows vs ggml to_float bit for bit, split models via GgufModel, --q5_1-min. CTests: q4_K/q5_1, q4_K/q8_0, q5_K/q8_0, q8_0/q8_0, the Q5_1 min term, and q6_K refused. RTX 5070: GPU and CPU within 1.25-1.37e-2 of the float reference for all three real pairs; every dequantized value identical; Q5_1 GPU vs ggml-cpu 7.5e-5 (vs 1.95e-2 for the ds.y variant); IQ3_XXS/IQ4_NL and IQ2_XS/Q2_0 unchanged. - Not yet: #242's decode-once traits for the new types (they take the per-entry kernel; see phaseA-tests/s5_cs3_design.md), prompt MMQ for Q4_K/Q5_K/Q5_1, identity gates. --- CMakeLists.txt | 13 + include/strata/kernels/iq_kernels.hpp | 6 +- src/core/native_dense.cpp | 5 +- src/kernels/cuda/iq_kernels.cu | 334 ++++++++++++- src/kernels/cuda/ple.cu | 5 +- src/kernels/native_expert_parity.cpp | 686 ++++++++++++++++---------- src/program/generate.cpp | 18 +- 7 files changed, 788 insertions(+), 279 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ab2eef40..f2911175 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -862,6 +862,19 @@ if(STRATA_NATIVE_EXPERTS) add_executable(native_expert_parity src/kernels/native_expert_parity.cpp) target_include_directories(native_expert_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(native_expert_parity PRIVATE strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) + # Unsloth UD-Q4_K_XL's three expert pairs (and Q8_0 alone, its embedding) on synthetic ggml-quantized weights + # at 2560/640: GPU and CPU experts against the float reference, GPU dequantizers against to_float + foreach(_pair q4_K/q5_1 q4_K/q8_0 q5_K/q8_0 q8_0/q8_0) + string(REPLACE "/" "_" _name "${_pair}") + add_test(NAME native_expert_parity_${_name} COMMAND native_expert_parity --synthetic ${_pair}) + set_tests_properties(native_expert_parity_${_name} PROPERTIES TIMEOUT 120) + endforeach() + add_test(NAME native_expert_parity_q5_1_min COMMAND native_expert_parity --q5_1-min) + # a pair without GPU kernels (Q6_K gate/up) is refused by native_expert_supported, not run + add_test(NAME native_expert_parity_refuses_q6_K COMMAND native_expert_parity --synthetic q6_K/q8_0) + set_tests_properties(native_expert_parity_refuses_q6_K PROPERTIES WILL_FAIL TRUE) + endif() endif() endif() diff --git a/include/strata/kernels/iq_kernels.hpp b/include/strata/kernels/iq_kernels.hpp index 82730f1b..1beb9a14 100644 --- a/include/strata/kernels/iq_kernels.hpp +++ b/include/strata/kernels/iq_kernels.hpp @@ -1,5 +1,6 @@ // include/strata/kernels/iq_kernels.hpp - the i-quant formats (IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S, -// IQ4_NL) and Q2_0 on the GPU for the IQ2_XS / IQ3_XXS model files. +// IQ4_NL) and Q2_0 on the GPU for the IQ2_XS / IQ3_XXS model files, and Q4_K / Q5_K / Q5_1 / Q8_0 for Unsloth's +// UD-Q4_K_XL (gate/up Q4_K or Q5_K, down Q5_1 or Q8_0, a Q8_0 embedding). // // The block layouts, codebook grids and dot products are llama.cpp's (ggml-common.h, ggml-cuda/vecdotq.cuh, // ggml-cuda/dequantize.cuh; MIT, see third_party/ggml/LICENSE and VERSION.txt), so a weight means exactly what it @@ -43,6 +44,9 @@ struct NativeExpertLayout { size_t bytes = 0; // the whole blob }; NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff); +/// Whether `native_expert_grouped` has kernels for this gate/up and down type pair at these dimensions, and the +/// prompt path's dequantizer takes both (checked for every layer at startup, before anything is allocated). +bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept; /// Bytes of scratch `native_expert_grouped` needs for `cap_entries` entries. size_t native_expert_scratch_bytes(int64_t cap_entries, int64_t n_ff); diff --git a/src/core/native_dense.cpp b/src/core/native_dense.cpp index ba309989..6fa6896f 100644 --- a/src/core/native_dense.cpp +++ b/src/core/native_dense.cpp @@ -16,9 +16,10 @@ namespace { bool eligible(const strata::TensorInfo& tensor, bool include_ple_key) { const auto& name = tensor.name; if (name.rfind("blk.", 0) != 0) return false; - // Match the native PLE kernel: Q2_0, IQ3_XXS and IQ4_XS. Other keys retain the packed BF16 fallback. + // Match the native PLE kernel: Q2_0, IQ3_XXS, IQ4_XS and Q8_0 (UD-Q4_K_XL). Other keys retain the packed BF16 + // fallback. if (name == "blk.1.ple_key.weight") - return include_ple_key && (tensor.type == 42 || tensor.type == 18 || tensor.type == 23); + return include_ple_key && (tensor.type == 42 || tensor.type == 18 || tensor.type == 23 || tensor.type == 8); static const char* suffixes[] = {".attn_qkv.weight", ".attn_gate.weight", ".ssm_out.weight", ".attn_q.weight", ".attn_k.weight", ".attn_v.weight", ".attn_output.weight", ".ffn_gate_shexp.weight", ".ffn_up_shexp.weight", ".ffn_down_shexp.weight"}; diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index cb7ec009..61ace84a 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -291,6 +291,158 @@ __device__ __forceinline__ float vec_dot_iq4_xs_q8_1(const void* __restrict__ vb return d * sumi; } +// ---------------------------------------------------------------- Unsloth's UD-Q4_K_XL experts +// Q4_K / Q5_K gate/up and Q5_1 / Q8_0 down: llama.cpp's vec_dot_*_q8_1 (vecdotq.cuh, VDR 2 each), transcribed; the +// Q5_1 min term is the one departure (below). Via eddoursul/Strata 8029fa9 (iq_dot.cuh) and #255 (Q8_0, +// gopinath87607), which agree with llama.cpp and with each other. +constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q8_0 = 2; + +__device__ __forceinline__ float vec_dot_q4_K_q8_1_impl_vmmq(const int* __restrict__ v, const int* __restrict__ u, + const uint8_t* __restrict__ sc, const uint8_t* __restrict__ m, + const half2& dm4, const float* __restrict__ d8) { + float sumf_d = 0.0f; + float sumf_m = 0.0f; +#pragma unroll + for (int i = 0; i < QR4_K; ++i) { + const int v0i = (v[0] >> (4 * i)) & 0x0F0F0F0F; + const int v1i = (v[1] >> (4 * i)) & 0x0F0F0F0F; + const int dot1 = ggml_cuda_dp4a(v1i, u[2 * i + 1], ggml_cuda_dp4a(v0i, u[2 * i + 0], 0)); + const int dot2 = ggml_cuda_dp4a(0x01010101, u[2 * i + 1], ggml_cuda_dp4a(0x01010101, u[2 * i + 0], 0)); + sumf_d += d8[i] * (dot1 * sc[i]); + sumf_m += d8[i] * (dot2 * m[i]); // the min times the sum of the QUANTIZED activations + } + const float2 dm4f = __half22float2(dm4); + return dm4f.x * sumf_d - dm4f.y * sumf_m; +} +__device__ __forceinline__ float vec_dot_q5_K_q8_1_impl_vmmq(const int* __restrict__ vl, const int* __restrict__ vh, + const int* __restrict__ u, const uint8_t* __restrict__ sc, + const uint8_t* __restrict__ m, const half2& dm5, + const float* __restrict__ d8) { + float sumf_d = 0.0f; + float sumf_m = 0.0f; +#pragma unroll + for (int i = 0; i < QR5_K; ++i) { + const int vl0i = (vl[0] >> (4 * i)) & 0x0F0F0F0F; + const int vl1i = (vl[1] >> (4 * i)) & 0x0F0F0F0F; + const int vh0i = ((vh[0] >> i) << 4) & 0x10101010; + const int vh1i = ((vh[1] >> i) << 4) & 0x10101010; + const int v0i = vl0i | vh0i; + const int v1i = vl1i | vh1i; + const int dot1 = ggml_cuda_dp4a(v0i, u[2 * i + 0], ggml_cuda_dp4a(v1i, u[2 * i + 1], 0)); + const int dot2 = ggml_cuda_dp4a(0x01010101, u[2 * i + 0], ggml_cuda_dp4a(0x01010101, u[2 * i + 1], 0)); + sumf_d += d8[i] * (dot1 * sc[i]); + sumf_m += d8[i] * (dot2 * m[i]); + } + const float2 dm5f = __half22float2(dm5); + return dm5f.x * sumf_d - dm5f.y * sumf_m; +} +// the 6-bit scales and mins of the 32-value group pair bq8_offset / 2, branchless (llama.cpp; shared by Q4_K, Q5_K) +__device__ __forceinline__ void k_scale_min(const uint8_t* scales8, int bq8_offset, uint16_t aux[2]) { + const uint16_t* scales = (const uint16_t*) scales8; + const int j = bq8_offset / 2; + const int jm = j & 1; + const uint32_t s0 = scales[jm + 0]; + const uint32_t s2 = scales[jm + 2]; + const uint32_t s4 = scales[jm + 4]; + const uint32_t hi = (uint32_t) -(int32_t) (j >= 2); + aux[0] = (uint16_t) (((s0 & 0x3f3f) & ~hi) | ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi)); + aux[1] = (uint16_t) (((s2 & 0x3f3f) & ~hi) | ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi)); +} +__device__ __forceinline__ float vec_dot_q4_K_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_q4_K* bq4_K = (const block_q4_K*) vbq + kbx; + int v[2]; + int u[2 * QR4_K]; + float d8[QR4_K]; + const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2)); + const int* q4 = (const int*) (bq4_K->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4)); + v[0] = q4[0]; + v[1] = q4[4]; + uint16_t aux[2]; + k_scale_min(bq4_K->scales, bq8_offset, aux); + const uint8_t* sc = (const uint8_t*) aux; + const uint8_t* m = sc + 2; +#pragma unroll + for (int i = 0; i < QR4_K; ++i) { + const block_q8_1* bq8i = bq8_1 + bq8_offset + i; + d8[i] = __low2float(bq8i->ds); + const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4); + u[2 * i + 0] = q8[0]; + u[2 * i + 1] = q8[4]; + } + return vec_dot_q4_K_q8_1_impl_vmmq(v, u, sc, m, bq4_K->dm, d8); +} +__device__ __forceinline__ float vec_dot_q5_K_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_q5_K* bq5_K = (const block_q5_K*) vbq + kbx; + int vl[2]; + int vh[2]; + int u[2 * QR5_K]; + float d8[QR5_K]; + const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2)); + const int* ql = (const int*) (bq5_K->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4)); + const int* qh = (const int*) (bq5_K->qh + 4 * ((iqs / 2) % 4)); + vl[0] = ql[0]; + vl[1] = ql[4]; + vh[0] = qh[0] >> bq8_offset; + vh[1] = qh[4] >> bq8_offset; + uint16_t aux[2]; + k_scale_min(bq5_K->scales, bq8_offset, aux); + const uint8_t* sc = (const uint8_t*) aux; + const uint8_t* m = sc + 2; +#pragma unroll + for (int i = 0; i < QR5_K; ++i) { + const block_q8_1* bq8i = bq8_1 + bq8_offset + i; + d8[i] = __low2float(bq8i->ds); + const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4); + u[2 * i + 0] = q8[0]; + u[2 * i + 1] = q8[4]; + } + return vec_dot_q5_K_q8_1_impl_vmmq(vl, vh, u, sc, m, bq5_K->dm, d8); +} +// Q5_1: llama.cpp's integer chain, but the min term multiplies the sum of the QUANTIZED activations (dp4a with +// 0x01010101, times d8) instead of the q8_1 block's `ds.y`, which our quantizer (like llama.cpp's) fills with the sum +// of the ORIGINAL activations. That is ggml-cpu's convention (its q8_1 `s` is d * sum(q)) and the one the K-quant +// mins above use; the scaled and the min term then see the same activation (eddoursul/Strata measured 1.1-1.2% +// against 1.9% relative error per expert). Result: sumi * (d5 * d8) + sumu * (m5 * d8). +__device__ __forceinline__ float vec_dot_q5_1_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_q5_1* bq5_1 = (const block_q5_1*) vbq + kbx; + int sumi = 0, sumu = 0; +#pragma unroll + for (int i = 0; i < VDR_Q5_1; ++i) { + const int vl = get_int_b4(bq5_1->qs, iqs + i); + const int vh = get_int_b4(bq5_1->qh, 0) >> (4 * (iqs + i)); + const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI5_1); + int vi0 = (vl >> 0) & 0x0F0F0F0F; + vi0 |= (vh << 4) & 0x00000010; + vi0 |= (vh << 11) & 0x00001000; + vi0 |= (vh << 18) & 0x00100000; + vi0 |= (vh << 25) & 0x10000000; + sumi = ggml_cuda_dp4a(vi0, u0, sumi); + int vi1 = (vl >> 4) & 0x0F0F0F0F; + vi1 |= (vh >> 12) & 0x00000010; + vi1 |= (vh >> 5) & 0x00001000; + vi1 |= (vh << 2) & 0x00100000; + vi1 |= (vh << 9) & 0x10000000; + sumi = ggml_cuda_dp4a(vi1, u1, sumi); + sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu)); + } + const float2 dm5 = __half22float2(bq5_1->dm); + const float d8 = __low2float(bq8_1->ds); + return sumi * (dm5.x * d8) + sumu * (dm5.y * d8); +} +__device__ __forceinline__ float vec_dot_q8_0_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_q8_0* bq8_0 = (const block_q8_0*) vbq + kbx; + int sumi = 0; +#pragma unroll + for (int i = 0; i < VDR_Q8_0; ++i) + sumi = ggml_cuda_dp4a(get_int_b2(bq8_0->qs, iqs + i), get_int_b4(bq8_1->qs, iqs + i), sumi); + const float d8_0 = __half2float(bq8_0->d), d8_1 = __low2float(bq8_1->ds); + return d8_0 * d8_1 * ((float) sumi); +} + // ---------------------------------------------------------------- the formats // qk = values per block, ipb = dot calls per block (qi / vdr), step = the iqs stride between calls. template struct Fmt; @@ -312,6 +464,20 @@ template<> struct Fmt<29> { static constexpr int qk = 256, ipb = 8, step = 1; __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq1_m_q8_1(v, y, kbx, iqs); } }; template<> struct Fmt<42> { static constexpr int qk = 64, ipb = 2, step = 1; __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q2_0_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<12> { static constexpr int qk = 256, ipb = QI4_K / VDR_Q4_K, step = VDR_Q4_K; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_K_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<13> { static constexpr int qk = 256, ipb = QI5_K / VDR_Q5_K, step = VDR_Q5_K; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_K_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<7> { static constexpr int qk = 32, ipb = QI5_1 / VDR_Q5_1, step = VDR_Q5_1; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_1_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0, step = VDR_Q8_0; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q8_0_q8_1(v, y, kbx, iqs); } }; + +// The formats of each role, one list each so a type cannot be in one switch and missing from another. Every +// entry is a kernel template for each CUDA architecture of the build, hence two lists rather than one. +#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(8) +#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(8) +#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(8) __device__ __forceinline__ float warp_sum(float v) { #pragma unroll @@ -355,6 +521,11 @@ __global__ void __launch_bounds__(128) mmvq_kernel(const uint8_t* __restrict__ w // order on the same values, so a column of the kernels below is BITWISE equal to the same column of mmvq_kernel / // native_gu_kernel / native_down_kernel (iq_multi_parity checks it; STRATA_OLD_IQ_MMVQ=1 keeps the old kernels). template struct Split; +// Formats with a Split below take the decode-once kernels; the others (Q4_K, Q5_K, Q5_1, Q8_0: UD-Q4_K_XL) the +// per-entry ones, which call Fmt::dot per column exactly as before #242 (the launchers test kSplit at compile +// time, so the multi kernels are never instantiated for a type without a Split). +template inline constexpr bool kSplit = false; +template<> inline constexpr bool kSplit<16> = true; template<> struct Split<16> { // IQ2_XXS struct W { int g[8]; int ls; float dw; }; __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { @@ -399,6 +570,7 @@ struct SplitLs2 { return d * sumi; } }; +template<> inline constexpr bool kSplit<17> = true; template<> struct Split<17> : SplitLs2 { // IQ2_XS __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { const block_iq2_xs* bq2 = (const block_iq2_xs*) vbq + kbx; @@ -420,6 +592,7 @@ template<> struct Split<17> : SplitLs2 { // IQ2_XS return r; } }; +template<> inline constexpr bool kSplit<22> = true; template<> struct Split<22> : SplitLs2 { // IQ2_S __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { const block_iq2_s* bq2 = (const block_iq2_s*) vbq + kbx; @@ -443,6 +616,7 @@ template<> struct Split<22> : SplitLs2 { // IQ2_S return r; } }; +template<> inline constexpr bool kSplit<18> = true; template<> struct Split<18> { // IQ3_XXS struct W { int g[8]; int ls; float dw; }; __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { @@ -473,6 +647,7 @@ template<> struct Split<18> { // IQ3_XXS return d * sumi; } }; +template<> inline constexpr bool kSplit<21> = true; template<> struct Split<21> { // IQ3_S struct W { int g[8]; int ls; float dw; }; __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { @@ -505,6 +680,7 @@ template<> struct Split<21> { // IQ3_S return d * sumi; } }; +template<> inline constexpr bool kSplit<29> = true; template<> struct Split<29> { // IQ1_M struct W { int g[8]; float delta[4]; int sc0, sc1; float dw; }; __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { @@ -547,6 +723,7 @@ template<> struct Split<29> { // IQ1_M return d * ((sumi[0] + sumf[0]) * r.sc0 + (sumi[1] + sumf[1]) * r.sc1); } }; +template<> inline constexpr bool kSplit<20> = true; template<> struct Split<20> { // IQ4_NL struct W { int2 v[2]; float dw; }; __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { @@ -569,6 +746,7 @@ template<> struct Split<20> { // IQ4_NL return d * sumi; } }; +template<> inline constexpr bool kSplit<23> = true; template<> struct Split<23> { // IQ4_XS struct W { int2 v[4]; int ls; float dw; }; __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { @@ -594,6 +772,7 @@ template<> struct Split<23> { // IQ4_XS return d * sumi; } }; +template<> inline constexpr bool kSplit<42> = true; template<> struct Split<42> { // Q2_0 struct W { int qx[4], qy[4]; float d2; }; __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { @@ -962,6 +1141,84 @@ __device__ void dq_q2_0(const void* vx, int64_t ibs, dst_t* yy, int tid) { } } +// llama.cpp's dequantize_q4_K / dequantize_q5_K (dequantize.cuh; q5_K's 64 threads folded onto 32) and the 32-value +// blocks of Q5_1 / Q8_0, 8 of them per 256-value "superblock" (thread tid writes 8 values of block tid % 8). +__device__ __forceinline__ void get_scale_min_k4(int j, const uint8_t* q, uint8_t& d, uint8_t& 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 - 0] >> 6) << 4); + } +} +template +__device__ void dq_q4_k(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_q4_K* x = (const block_q4_K*) vx; + const int64_t il = tid / 8, ir = tid % 8, is = 2 * il; + const int n = 4; + dst_t* y = yy + 64 * il + n * ir; + const float dall = __low2half(x[ibs].dm); + const float dmin = __high2half(x[ibs].dm); + const uint8_t* q = x[ibs].qs + 32 * il + n * ir; + uint8_t sc, m; + get_scale_min_k4((int) is + 0, x[ibs].scales, sc, m); + const float d1 = dall * sc, m1 = dmin * m; + get_scale_min_k4((int) is + 1, x[ibs].scales, sc, m); + const float d2 = dall * sc, m2 = dmin * m; + for (int l = 0; l < n; ++l) { + y[l + 0] = cvt(d1 * (q[l] & 0xF) - m1); + y[l + 32] = cvt(d2 * (q[l] >> 4) - m2); + } +} +template +__device__ void dq_q5_k(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_q5_K* x = (const block_q5_K*) vx; + for (int tt = tid; tt < 64; tt += 32) { + const int il = tt / 16, ir = tt % 16, is = 2 * il; + dst_t* y = yy + 64 * il + 2 * ir; + const float dall = __low2half(x[ibs].dm); + const float dmin = __high2half(x[ibs].dm); + const uint8_t* ql = x[ibs].qs + 32 * il + 2 * ir; + const uint8_t* qh = x[ibs].qh + 2 * ir; + uint8_t sc, m; + get_scale_min_k4(is + 0, x[ibs].scales, sc, m); + const float d1 = dall * sc, m1 = dmin * m; + get_scale_min_k4(is + 1, x[ibs].scales, sc, m); + const float d2 = dall * sc, m2 = dmin * m; + uint8_t hm = (uint8_t) (1 << (2 * il)); + y[0] = cvt(d1 * ((ql[0] & 0xF) + (qh[0] & hm ? 16 : 0)) - m1); + y[1] = cvt(d1 * ((ql[1] & 0xF) + (qh[1] & hm ? 16 : 0)) - m1); + hm <<= 1; + y[32] = cvt(d2 * ((ql[0] >> 4) + (qh[0] & hm ? 16 : 0)) - m2); + y[33] = cvt(d2 * ((ql[1] >> 4) + (qh[1] & hm ? 16 : 0)) - m2); + } +} +template +__device__ void dq_q5_1(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_q5_1* x = (const block_q5_1*) vx + ibs * (QK_K / QK5_1); + const int ib = tid % 8, il = tid / 8; + const float2 dm = __half22float2(x[ib].dm); + uint32_t qh; + memcpy(&qh, x[ib].qh, sizeof(qh)); + dst_t* y = yy + 32 * ib; + for (int j = 0; j < 4; ++j) { + const int iqs = 4 * il + j; // llama.cpp's dequantize_q5_1 for value pairs iqs, iqs + 16 + const int xh_0 = ((qh >> (iqs + 0)) << 4) & 0x10; + const int xh_1 = ((qh >> (iqs + 12))) & 0x10; + y[iqs] = cvt((float) ((x[ib].qs[iqs] & 0xf) | xh_0) * dm.x + dm.y); + y[iqs + 16] = cvt((float) ((x[ib].qs[iqs] >> 4) | xh_1) * dm.x + dm.y); + } +} +template +__device__ void dq_q8_0(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_q8_0* x = (const block_q8_0*) vx + ibs * (QK_K / QK8_0); + const int ib = tid % 8, il = tid / 8; + const float d = __half2float(x[ib].d); + dst_t* y = yy + 32 * ib + 8 * il; + for (int j = 0; j < 8; ++j) y[j] = cvt((float) x[ib].qs[8 * il + j] * d); +} + +// Every type below must also be in is_iq(): the host entry points refuse the others, so the default is unreachable. template __device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs, dst_t* y, int tid) { switch (ty) { @@ -975,6 +1232,10 @@ __device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs, case 23: dq_iq4_xs(vx, ibs, y, tid); break; case 11: dq_q3_k(vx, ibs, y, tid); break; case 42: dq_q2_0(vx, ibs, y, tid); break; + case 12: dq_q4_k(vx, ibs, y, tid); break; + case 13: dq_q5_k(vx, ibs, y, tid); break; + case 7: dq_q5_1(vx, ibs, y, tid); break; + case 8: dq_q8_0(vx, ibs, y, tid); break; default: break; } } @@ -994,7 +1255,28 @@ __global__ void dequant_gu_kernel(int ty, const void* __restrict__ gate, const v dq_dispatch<__half>(ty, parity ? up : gate, i, y + ((2 * r + parity) * per_row + c) * QK_K, threadIdx.x); } -bool is_iq(int t) { return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11; } +// the types dq_dispatch dequantizes +bool is_iq(int t) { + return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11 || + t == 12 || t == 13 || t == 7 || t == 8; +} +// values per block of the types the grouped expert kernels take (0 = none) +int gu_qk(int t) { + switch (t) { +#define STRATA_QK(T) case T: return Fmt::qk; + STRATA_GU_FMTS(STRATA_QK) +#undef STRATA_QK + default: return 0; + } +} +int d_qk(int t) { + switch (t) { +#define STRATA_QK(T) case T: return Fmt::qk; + STRATA_D_FMTS(STRATA_QK) +#undef STRATA_QK + default: return 0; + } +} bool env_on(const char* name) { const char* v = std::getenv(name); @@ -1007,7 +1289,8 @@ template void launch_mmvq(const uint8_t* W, size_t rb, const block_q8_1* X, float* y, int n_in, int n_out, int ncols, cudaStream_t s) { const dim3 grid((unsigned) ((n_out + 3) / 4)), block(32, 4); - if (g_old_kernels) mmvq_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); + if constexpr (!kSplit) mmvq_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); + else if (g_old_kernels) mmvq_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); else if (ncols <= 1) mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); else if (ncols == 2) mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); else if (ncols <= 4) mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); @@ -1018,7 +1301,8 @@ template void launch_gu(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X, const NativeExpertLayout& L, float* gate, float* up) { - if (g_old_kernels) native_gu_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); + if constexpr (!kSplit) native_gu_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); + else if (g_old_kernels) native_gu_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_multi_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); } @@ -1026,7 +1310,8 @@ template void launch_down(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst, const block_q8_1* hq, const NativeExpertLayout& L, float* out) { - if (g_old_kernels) native_down_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + if constexpr (!kSplit) native_down_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + else if (g_old_kernels) native_down_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); else native_down_multi_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); } @@ -1049,6 +1334,10 @@ size_t iq_row_bytes(int t, int64_t n) noexcept { case 23: return (size_t) (n / 256) * sizeof(block_iq4_xs); case 11: return (size_t) (n / 256) * sizeof(block_q3_K); case 42: return (size_t) (n / 64) * sizeof(block_q2_0); + case 12: return (size_t) (n / 256) * sizeof(block_q4_K); + case 13: return (size_t) (n / 256) * sizeof(block_q5_K); + case 7: return (size_t) (n / 32) * sizeof(block_q5_1); + case 8: return (size_t) (n / 32) * sizeof(block_q8_0); default: return 0; } } @@ -1066,15 +1355,9 @@ void iq_mmvq(int t, const void* w, const void* x_q8_1, float* y, int n_in, int n const auto* W = (const uint8_t*) w; const auto* X = (const block_q8_1*) x_q8_1; switch (t) { - case 16: launch_mmvq<16>(W, rb, X, y, n_in, n_out, ncols, s); break; - case 17: launch_mmvq<17>(W, rb, X, y, n_in, n_out, ncols, s); break; - case 18: launch_mmvq<18>(W, rb, X, y, n_in, n_out, ncols, s); break; - case 20: launch_mmvq<20>(W, rb, X, y, n_in, n_out, ncols, s); break; - case 21: launch_mmvq<21>(W, rb, X, y, n_in, n_out, ncols, s); break; - case 22: launch_mmvq<22>(W, rb, X, y, n_in, n_out, ncols, s); break; - case 23: launch_mmvq<23>(W, rb, X, y, n_in, n_out, ncols, s); break; - case 29: launch_mmvq<29>(W, rb, X, y, n_in, n_out, ncols, s); break; - case 42: launch_mmvq<42>(W, rb, X, y, n_in, n_out, ncols, s); break; +#define STRATA_MMVQ(T) case T: launch_mmvq(W, rb, X, y, n_in, n_out, ncols, s); break; + STRATA_MMVQ_FMTS(STRATA_MMVQ) +#undef STRATA_MMVQ default: std::fprintf(stderr, "iq_mmvq: type %d is not supported\n", t); std::exit(1); } check("iq_mmvq"); @@ -1112,12 +1395,20 @@ void iq_dequant_f32(int t, const void* src, int64_t n, float* dst, void* stream) } void iq_dequant_gu_f16(int t, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst, void* stream) { + // checked like the other entry points: an unknown type used to leave `dst` unwritten, a wrong prompt and no error + if (n_embd % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_gu_f16: type %d / %lld\n", t, (long long) n_embd); std::exit(1); } const int64_t per_row = n_embd / 256; dequant_gu_kernel<<>>(t, gate, up, per_row, (__half*) dst); check("iq_dequant_gu_f16"); } +bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept { + const int qg = gu_qk(gu_type), qd = d_qk(d_type); + return qg > 0 && qd > 0 && is_iq(gu_type) && is_iq(d_type) && n_embd % qg == 0 && n_ff % qd == 0 && + n_embd % 256 == 0 && (n_ff * n_embd) % 256 == 0; +} + NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) { NativeExpertLayout L; L.gu_type = gu_type; @@ -1150,14 +1441,9 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long const auto* X = (const block_q8_1*) x_q8_1; const dim3 ggu((unsigned) ((2 * L.n_ff + GU_ROWS - 1) / GU_ROWS), (unsigned) cap_groups); switch (L.gu_type) { - case 16: launch_gu<16>(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; - case 17: launch_gu<17>(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; - case 18: launch_gu<18>(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; - case 21: launch_gu<21>(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; - case 22: launch_gu<22>(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; - case 23: launch_gu<23>(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; - case 29: launch_gu<29>(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; - case 42: launch_gu<42>(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; +#define STRATA_GU(T) case T: launch_gu(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; + STRATA_GU_FMTS(STRATA_GU) +#undef STRATA_GU default: std::fprintf(stderr, "native_expert_grouped: gate/up type %d\n", L.gu_type); std::exit(1); } check("native_expert_grouped/gu"); @@ -1166,9 +1452,9 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long quantize_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(h, hq, nh); const dim3 gd((unsigned) ((L.n_embd + 7) / 8), (unsigned) cap_groups); switch (L.d_type) { - case 20: launch_down<20>(gd, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break; - case 23: launch_down<23>(gd, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break; - case 42: launch_down<42>(gd, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break; +#define STRATA_DOWN(T) case T: launch_down(gd, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break; + STRATA_D_FMTS(STRATA_DOWN) +#undef STRATA_DOWN default: std::fprintf(stderr, "native_expert_grouped: down type %d\n", L.d_type); std::exit(1); } check("native_expert_grouped/down"); diff --git a/src/kernels/cuda/ple.cu b/src/kernels/cuda/ple.cu index 66bb4220..6585bbaa 100644 --- a/src/kernels/cuda/ple.cu +++ b/src/kernels/cuda/ple.cu @@ -229,8 +229,9 @@ void ple_block(const float* emb, const float* hidden, const float* hist_rows, co const bool native_key = w.key_native_data != nullptr && w.key_bf16 == nullptr; if (native_key && (!emb || !hidden || !hist_rows || !out.result || !scratch || !stream || !w.key_native_q8_1 || - (w.key_native_type != 42 && w.key_native_type != 18 && w.key_native_type != 23))) - throw std::invalid_argument("ple_block: native key requires Q2_0, IQ3_XXS or IQ4_XS weights, input/output, private scratch and explicit stream"); + (w.key_native_type != 42 && w.key_native_type != 18 && w.key_native_type != 23 && + w.key_native_type != 8))) + throw std::invalid_argument("ple_block: native key requires Q2_0, IQ3_XXS, IQ4_XS or Q8_0 weights, input/output, private scratch and explicit stream"); if (emb == nullptr || hidden == nullptr || hist_rows == nullptr || out.result == nullptr) return; const int n_embd = NG_N_EMBD, hc = NG_HC, hc_dim = NG_HC_DIM; static_assert(NG_N_EMBD == 2560 && NG_HC_DIM == 10240, "native PLE key geometry changed"); diff --git a/src/kernels/native_expert_parity.cpp b/src/kernels/native_expert_parity.cpp index 2faa9c2d..d6ede318 100644 --- a/src/kernels/native_expert_parity.cpp +++ b/src/kernels/native_expert_parity.cpp @@ -1,11 +1,15 @@ -// src/kernels/native_expert_parity.cpp - plan v0.3 P6: one native expert three ways, on real GGUF rows. +// src/kernels/native_expert_parity.cpp - plan v0.3 P6: one native expert three ways. // -// build/native_expert_parity [layer ...] +// build/native_expert_parity [layer ...] real rows (a split model's shards are found by name) +// build/native_expert_parity --synthetic GU/DOWN ... random weights quantized by ggml (e.g. q4_K/q5_1) +// build/native_expert_parity --q5_1-min the Q5_1 min term on crafted activations // // (a) float reference: ggml's own dequantizer (`to_float`) and a float SwiGLU expert, (b) the CPU path // (ggml-cpu vec_dot with its quantized activations), (c) the GPU path (`native_expert_grouped`, q8_1 // activations). (b) and (c) each differ from (a) by their activation rounding only (a few 1e-3 relative). (c) runs // twice, with the kernels that decode a weight part once for all entries and with the per-entry ones: bitwise equal. +// (d) the GPU dequantizers of the prompt path and the embedding against `to_float` (Q8_0: bit for bit). +// The synthetic mode and (d) follow eddoursul/Strata 8029fa9. #include "strata/artifact/gguf_reader.hpp" #include "strata/kernels/cpu/native_expert.hpp" #include "strata/kernels/cpu/expert.hpp" @@ -19,6 +23,8 @@ #include +#include +#include #include #include #include @@ -36,9 +42,393 @@ static double rel(const std::vector& a, const std::vector& b) { return n / (d + 1e-30); } + +namespace { +constexpr int NT = 3, E = 7; +constexpr int64_t H = 2560, FF = 640; + +// The three ways and the dequantizers for one expert blob; returns the number of failed checks. +int check_blob(const cpu::NativeFmt& f, const std::vector& blob, int seed, const std::string& label, + cudaStream_t s) { + int failures = 0; + // (a) the float reference + const auto* tg = ggml_get_type_traits((ggml_type) f.gu_type); + const auto* td = ggml_get_type_traits((ggml_type) f.d_type); + std::vector G((size_t) FF * H), U((size_t) FF * H), D((size_t) H * FF); + for (int64_t r = 0; r < FF; ++r) { + tg->to_float(blob.data() + r * f.gu_row, G.data() + r * H, H); + tg->to_float(blob.data() + f.up_off + r * f.gu_row, U.data() + r * H, H); + } + for (int64_t r = 0; r < H; ++r) td->to_float(blob.data() + f.down_off + r * f.d_row, D.data() + r * FF, FF); + std::mt19937 rng(11 + seed); + std::normal_distribution nd(0.f, 1.f); + std::vector x((size_t) NT * H); + for (auto& v : x) v = nd(rng); + std::vector ref((size_t) NT * H), got_c((size_t) NT * H), got_g((size_t) NT * H); + for (int k = 0; k < NT; ++k) { + std::vector h(FF); + for (int64_t r = 0; r < FF; ++r) { + double g = 0, u = 0; + for (int64_t i = 0; i < H; ++i) { g += (double) G[r * H + i] * x[k * H + i]; u += (double) U[r * H + i] * x[k * H + i]; } + h[r] = (float) (g / (1.0 + std::exp(-g)) * u); + } + for (int64_t r = 0; r < H; ++r) { + double o = 0; + for (int64_t i = 0; i < FF; ++i) o += (double) D[r * FF + i] * h[i]; + ref[k * H + r] = (float) o; + } + } + // (b) the CPU + { + std::vector> act(NT, std::vector(cpu::kNativeActBytes)); + std::vector> hq(NT, std::vector(cpu::kNativeHBytes)); + std::vector> ff(NT, std::vector(FF)); + const void* a[NT]; + float* ffp[NT]; + const void* hp[NT]; + float* op[NT]; + for (int k = 0; k < NT; ++k) { + cpu::native_quant_act(f, x.data() + k * H, act[k].data()); + a[k] = act[k].data(); + ffp[k] = ff[k].data(); + } + cpu::native_gu_rows(f, blob.data(), a, NT, ffp, 0, (int) FF); + if (cpu::iq512_supported(f.gu_type)) { + // ggml's own vec_dot, same Q8_K activations: the reference for both multi-token kernels + // (float-order differences only) + const auto* tc = ggml_get_type_traits_cpu((ggml_type) f.gu_type); + std::vector gref((size_t) NT * FF); + for (int k = 0; k < NT; ++k) + for (int64_t r = 0; r < FF; ++r) + tc->vec_dot((int) H, &gref[k * FF + r], 0, blob.data() + r * f.gu_row, 0, a[k], 0, 1); + double usg = 0.0; + { // ggml single-token throughput, the weights cache-resident (compute bound) + const int it = 50; + auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < it; ++i) + for (int64_t r = 0; r < FF; ++r) { + float gg, uu; + tc->vec_dot((int) H, &gg, 0, blob.data() + r * f.gu_row, 0, a[0], 0, 1); + tc->vec_dot((int) H, &uu, 0, blob.data() + f.up_off + r * f.gu_row, 0, a[0], 0, 1); + } + auto t1 = std::chrono::steady_clock::now(); + usg = std::chrono::duration(t1 - t0).count() / it; + } + // one multi-token kernel: parity against ggml's vec_dot, then one-token and NT-token throughput + auto check = [&](const char* tag, bool is512) { + std::vector g((size_t) NT * FF); + float* gp[NT]; + for (int k = 0; k < NT; ++k) gp[k] = g.data() + k * FF; + (is512 ? cpu::iq512_rows : cpu::iq256_rows)(f.gu_type, blob.data(), f.gu_row, (int) H, a, NT, gp, 0, (int) FF); + const double rg = rel(g, gref); + std::printf(" %s %s gate rows vs ggml vec_dot: rel %.2e\n", + ggml_type_name((ggml_type) f.gu_type), tag, rg); + if (rg > 1e-5) { // ggml's own vec_dot is the reference: above 1e-5 it is a real mismatch, + std::printf(" %s %s gate rows MISMATCH (rel %.2e > 1e-5)\n", + ggml_type_name((ggml_type) f.gu_type), tag, rg); // not rounding (measured 3e-8) + ++failures; + } + float* f1[1] = {ffp[0]}; + const int it = 50; + const auto gu = is512 ? cpu::iq512_gu_rows : cpu::iq256_gu_rows; + auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < it; ++i) gu(f.gu_type, blob.data(), f.gu_row, f.up_off, (int) H, a, 1, f1, 0, (int) FF); + auto t1 = std::chrono::steady_clock::now(); + for (int i = 0; i < it; ++i) gu(f.gu_type, blob.data(), f.gu_row, f.up_off, (int) H, a, NT, ffp, 0, (int) FF); + auto t2 = std::chrono::steady_clock::now(); + const double us1 = std::chrono::duration(t1 - t0).count() / it; + const double usn = std::chrono::duration(t2 - t1).count() / it; + std::printf(" gate+up one token one thread: %s %.0f us (%.2f GB/s), ggml %.0f us (%.2f GB/s)\n", + tag, us1, 2.0 * f.up_off / us1 / 1e3, usg, 2.0 * f.up_off / usg / 1e3); + std::printf(" gate+up %d tokens one thread: %s %.0f us vs ggml %d x %.0f us\n", NT, tag, usn, NT, usg); + }; + if (cpu::cpu_avx512_ok()) check("avx512", true); // guarded: the binary runs on AVX-2 CPUs too + check("avx2", false); + } + for (int k = 0; k < NT; ++k) { + cpu::native_quant_h(f, ff[k].data(), hq[k].data()); + hp[k] = hq[k].data(); + op[k] = got_c.data() + k * H; + } + cpu::native_down_rows(f, blob.data(), hp, NT, op, 0, (int) H); + { // #152: a token's rows must not depend on how many tokens share the call - each token alone (nt = 1) + // against its row of the NT-token call above, bit for bit, gate/up and down + size_t gu_diff = 0, dn_diff = 0; + std::vector one_ff(FF), one_out(H); + // the NT-token gate/up rows again: the throughput loops above overwrote ff with other kernels' rows + for (int k = 0; k < NT; ++k) ffp[k] = ff[k].data(); + cpu::native_gu_rows(f, blob.data(), a, NT, ffp, 0, (int) FF); + for (int k = 0; k < NT; ++k) { + const void* a1[1] = {a[k]}; + float* f1[1] = {one_ff.data()}; + cpu::native_gu_rows(f, blob.data(), a1, 1, f1, 0, (int) FF); + for (int64_t r = 0; r < FF; ++r) gu_diff += std::memcmp(&one_ff[r], &ff[k][r], 4) != 0; + const void* h1[1] = {hp[k]}; + float* o1[1] = {one_out.data()}; + cpu::native_down_rows(f, blob.data(), h1, 1, o1, 0, (int) H); + for (int64_t r = 0; r < H; ++r) dn_diff += std::memcmp(&one_out[r], &got_c[k * H + r], 4) != 0; + } + std::printf(" width invariance (1 vs %d tokens): gate/up %zu, down %zu rows differ\n", NT, + gu_diff, dn_diff); + if (gu_diff || dn_diff) ++failures; + } + if (f.d_type == 42) { + // (b2) the GGUF-layout Q2_0 kernel the pool uses for Q2_0 down projections - the AVX-512 one + // where the CPU has it, the AVX-2 one (q2_avx2.cpp) where it does not. Calling the AVX-512 + // kernel unconditionally faults on a Zen 2/3 CPU. + std::vector a2(NT); + const cpu::ActQ* ap[NT]; + std::vector alt((size_t) NT * H); + float* altp[NT]; + for (int k = 0; k < NT; ++k) { + cpu::act_quant_any(ff[k].data(), (int) FF, a2[k]); // gated: AVX-512 or AVX-2 per CPU + ap[k] = &a2[k]; + altp[k] = alt.data() + k * H; + } + cpu::q2_rows_any(blob.data() + f.down_off, f.d_row, (int) (FF / 64), ap, NT, altp, 0, (int) H); + std::printf(" q2_0 %s down vs ggml down: rel %.2e\n", + cpu::cpu_avx512_ok() ? "AVX-512" : "AVX-2", rel(alt, got_c)); + } + if (f.d_type == 20) { + // (b3) the IQ4_NL multi-token AVX-2 kernel the pool now uses for IQ4_NL down projections, + // against ggml-cpu's single-token vec_dot on the SAME Q8_0 activations (h), plus timing. + std::vector alt((size_t) NT * H), refd((size_t) NT * H); + float* altp[NT]; + for (int k = 0; k < NT; ++k) altp[k] = alt.data() + k * H; + cpu::iq4nl256_down_rows(blob.data() + f.down_off, f.d_row, (int) FF, hp, NT, altp, 0, (int) H); + const auto* tdc = ggml_get_type_traits_cpu((ggml_type) f.d_type); + for (int k = 0; k < NT; ++k) + for (int64_t r = 0; r < H; ++r) + tdc->vec_dot((int) FF, refd.data() + k * H + r, 0, + blob.data() + f.down_off + (size_t) r * f.d_row, 0, hp[k], 0, 1); + const double rdn = rel(alt, refd); + std::printf(" iq4_nl AVX-2 multi-token down vs ggml down: rel %.2e\n", rdn); + if (rdn > 1e-5) { // measured 1e-7; same reasoning as the gate/up rows above + std::printf(" iq4_nl down MISMATCH (rel %.2e > 1e-5)\n", rdn); + ++failures; + } + const int it = 50; + const auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < it; ++i) + cpu::iq4nl256_down_rows(blob.data() + f.down_off, f.d_row, (int) FF, hp, NT, altp, 0, (int) H); + const auto t1 = std::chrono::steady_clock::now(); + for (int i = 0; i < it; ++i) + for (int k = 0; k < NT; ++k) + for (int64_t r = 0; r < H; ++r) + tdc->vec_dot((int) FF, refd.data() + k * H + r, 0, + blob.data() + f.down_off + (size_t) r * f.d_row, 0, hp[k], 0, 1); + const auto t2 = std::chrono::steady_clock::now(); + const double usn = std::chrono::duration(t1 - t0).count() / it; + const double usg = std::chrono::duration(t2 - t1).count() / it; + std::printf(" down %d tokens one thread: avx2 %.0f us (%.2f GB/s) vs ggml %.0f us (%.2f GB/s)\n", + NT, usn, (double) (f.bytes - f.down_off) / usn / 1e3, usg, + (double) (f.bytes - f.down_off) / usg / 1e3); + } + } + // (c) the GPU: one group holding the NT entries + { + const auto L = strata::kernels::native_expert_layout(f.gu_type, f.d_type, H, FF); + void *dblob, *dx, *dxq, *dscr; + float* dout; + unsigned long long* dptr; + int32_t *dstart, *dn, *ddst, *dtok; + cudaMalloc(&dblob, blob.size()); + cudaMalloc(&dx, x.size() * 4); + cudaMalloc(&dxq, (size_t) NT * H / 32 * 36); + cudaMalloc(&dscr, strata::kernels::native_expert_scratch_bytes(NT, FF)); + cudaMalloc((void**) &dout, (size_t) NT * H * 4); + cudaMalloc((void**) &dptr, 8); + cudaMalloc((void**) &dstart, 8); + cudaMalloc((void**) &dn, 4); + cudaMalloc((void**) &ddst, NT * 4); + cudaMalloc((void**) &dtok, NT * 4); + cudaMemcpy(dblob, blob.data(), blob.size(), cudaMemcpyHostToDevice); + cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice); + const unsigned long long p = (unsigned long long) dblob; + const int32_t st[2] = {0, NT}, one = 1, idx[NT] = {0, 1, 2}; + cudaMemcpy(dptr, &p, 8, cudaMemcpyHostToDevice); + cudaMemcpy(dstart, st, 8, cudaMemcpyHostToDevice); + cudaMemcpy(dn, &one, 4, cudaMemcpyHostToDevice); + cudaMemcpy(ddst, idx, NT * 4, cudaMemcpyHostToDevice); + cudaMemcpy(dtok, idx, NT * 4, cudaMemcpyHostToDevice); + strata::kernels::quantize_q8_1_rows((const float*) dx, NT, H, dxq, s); + strata::kernels::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, 1, NT, dxq, dscr, dout, s); + cudaStreamSynchronize(s); + cudaMemcpy(got_g.data(), dout, got_g.size() * 4, cudaMemcpyDeviceToHost); + { // the kernels that decode a weight part once for the NT entries, bitwise vs the per-entry ones (#242; + // the formats without a decode-once split take the per-entry kernels either way) + std::vector old_g(got_g.size()); + const bool was = strata::kernels::iq_old_kernels(); + strata::kernels::iq_set_old_kernels(!was); + strata::kernels::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, 1, NT, dxq, dscr, dout, s); + strata::kernels::iq_set_old_kernels(was); + cudaStreamSynchronize(s); + cudaMemcpy(old_g.data(), dout, old_g.size() * 4, cudaMemcpyDeviceToHost); + const bool same = std::memcmp(old_g.data(), got_g.data(), got_g.size() * 4) == 0; + std::printf(" gpu decode-once vs per-entry kernels: %s\n", same ? "bitwise equal" : "MISMATCH"); + if (!same) ++failures; + } + { // (d) the GPU dequantizers (prompt path: iq_dequant_f32/_f16; embedding: iq_embed_rows) against to_float + float* dq = nullptr; + uint16_t* dh = nullptr; + int32_t* dtk = nullptr; + cudaMalloc((void**) &dq, (size_t) FF * H * 4); + cudaMalloc((void**) &dh, (size_t) FF * H * 2); + cudaMalloc((void**) &dtk, (size_t) FF * 4); + std::vector got_dq((size_t) FF * H); + std::vector got_h((size_t) FF * H); + std::vector tk((size_t) FF); + for (int64_t r = 0; r < FF; ++r) tk[(size_t) r] = (int32_t) (FF - 1 - r); // rows in reverse order + cudaMemcpy(dtk, tk.data(), tk.size() * 4, cudaMemcpyHostToDevice); + double dq_err = 0.0; + size_t differ = 0, h_differ = 0; + const struct { const uint8_t* src; int type; const std::vector* want; } mats[3] = { + {(const uint8_t*) dblob, f.gu_type, &G}, {(const uint8_t*) dblob + f.up_off, f.gu_type, &U}, + {(const uint8_t*) dblob + f.down_off, f.d_type, &D}}; + for (const auto& m : mats) { + strata::kernels::iq_dequant_f32(m.type, m.src, FF * H, dq, s); + strata::kernels::iq_dequant_f16(m.type, m.src, FF * H, dh, s); + cudaStreamSynchronize(s); + cudaMemcpy(got_dq.data(), dq, got_dq.size() * 4, cudaMemcpyDeviceToHost); + cudaMemcpy(got_h.data(), dh, got_h.size() * 2, cudaMemcpyDeviceToHost); + dq_err = (std::max)(dq_err, rel(got_dq, *m.want)); + for (size_t i = 0; i < got_dq.size(); ++i) { + differ += std::memcmp(&got_dq[i], &(*m.want)[i], 4) != 0; + h_differ += got_h[i] != ggml_fp32_to_fp16(got_dq[i]); + } + } + // the gate matrix as an embedding table of FF rows of H values + strata::kernels::iq_embed_rows(f.gu_type, dblob, f.gu_row, dtk, FF, H, dq, s); + cudaStreamSynchronize(s); + cudaMemcpy(got_dq.data(), dq, got_dq.size() * 4, cudaMemcpyDeviceToHost); + size_t emb_differ = 0; + for (int64_t r = 0; r < FF; ++r) + emb_differ += std::memcmp(got_dq.data() + r * H, G.data() + (FF - 1 - r) * H, (size_t) H * 4) != 0; + cudaFree(dq); cudaFree(dh); cudaFree(dtk); + std::printf(" GPU dequant vs ggml to_float: rel %.2e, %zu of %lld values differ in any bit; fp16 of " + "it: %zu differ; embedding rows: %zu of %lld differ\n", dq_err, differ, (long long) (3 * FF * H), + h_differ, emb_differ, (long long) FF); + // exact where there is one product (Q8_0), a rounding at most elsewhere (fused multiply-adds) + const bool exact = f.gu_type == 8 && f.d_type == 8; + if (!(dq_err < 1e-6) || h_differ || (exact && (differ || emb_differ))) ++failures; + } + cudaFree(dblob); cudaFree(dx); cudaFree(dxq); cudaFree(dscr); cudaFree(dout); cudaFree(dptr); + cudaFree(dstart); cudaFree(dn); cudaFree(ddst); cudaFree(dtok); + } + const double ec = rel(got_c, ref), eg = rel(got_g, ref), ecg = rel(got_c, got_g); + const bool ok = ec < 3e-2 && eg < 3e-2 && std::isfinite(ec) && std::isfinite(eg); + std::printf("%-9s %-8s/%-7s blob %8zu cpu rel %.2e gpu rel %.2e cpu-gpu %.2e %s\n", label.c_str(), + ggml_type_name((ggml_type) f.gu_type), ggml_type_name((ggml_type) f.d_type), f.bytes, ec, eg, ecg, + ok ? "ok" : "FAIL"); + return failures + (ok ? 0 : 1); +} + +int type_of(std::string name) { + for (auto& c : name) c = (char) std::tolower((unsigned char) c); + for (int t = 0; t < GGML_TYPE_COUNT; ++t) { + const char* n = ggml_type_name((ggml_type) t); + if (n == nullptr) continue; + std::string m(n); + for (auto& c : m) c = (char) std::tolower((unsigned char) c); + if (m == name) return t; + } + return -1; +} + +// Random weights (rows of different magnitudes) quantized by ggml into the blob layout. +std::vector synthetic_blob(const cpu::NativeFmt& f, int seed) { + std::vector blob(f.bytes); + std::mt19937 rng(seed); + std::normal_distribution nd(0.f, 1.f); + auto quant = [&](int type, int64_t rows, int64_t cols, uint8_t* dst) { + std::vector w((size_t) (rows * cols)); + for (int64_t r = 0; r < rows; ++r) { + const float scale = 0.02f * (0.5f + (float) (r % 7) / 7.0f); + for (int64_t c = 0; c < cols; ++c) w[(size_t) (r * cols + c)] = scale * nd(rng); + } + const std::vector imatrix((size_t) cols, 1.0f); + ggml_quantize_chunk((ggml_type) type, w.data(), dst, 0, rows, cols, + ggml_quantize_requires_imatrix((ggml_type) type) ? imatrix.data() : nullptr); + }; + quant(f.gu_type, FF, H, blob.data()); + quant(f.gu_type, FF, H, blob.data() + f.up_off); + quant(f.d_type, H, FF, blob.data() + f.down_off); + return blob; +} + +// The Q5_1 min term. Activations x = d * (q + 0.45) round to q, so each q8_1 block's sum of the ORIGINAL values +// (`ds.y`, what llama.cpp CUDA multiplies the min by) exceeds d * sum(q) by 0.45 * 32 * d. The GPU dot must take +// the quantized sum, as ggml-cpu's vec_dot does: equal to ggml-cpu on the same blocks with s = d * sum(q), and far +// from the ds.y variant. Weights with large mins make the difference visible. +int check_q5_1_min(cudaStream_t s) { + constexpr int n = 640, rows = 64; + ggml_cpu_init(); // the fp16 tables vec_dot uses (the other modes get this through native_fmt) + std::mt19937 rng(5); + std::uniform_int_distribution qd(-100, 100); + std::normal_distribution nd(0.f, 1.f); + std::vector w((size_t) rows * n), x(n); + for (auto& v : w) v = 0.3f + 0.05f * nd(rng); // positive weights: a large min per block + const float d = 0.01f; + for (auto& v : x) v = d * ((float) qd(rng) + 0.45f); + const size_t row_bytes = ggml_row_size(GGML_TYPE_Q5_1, n); + std::vector wq((size_t) rows * row_bytes); + ggml_quantize_chunk(GGML_TYPE_Q5_1, w.data(), wq.data(), 0, rows, n, nullptr); + // the GPU: its own q8_1 quantizer, then iq_mmvq on Q5_1 + void *dw, *dx, *dxq; + float* dy; + cudaMalloc(&dw, wq.size()); + cudaMalloc(&dx, n * 4); + cudaMalloc(&dxq, (size_t) n / 32 * 36); + cudaMalloc((void**) &dy, rows * 4); + cudaMemcpy(dw, wq.data(), wq.size(), cudaMemcpyHostToDevice); + cudaMemcpy(dx, x.data(), n * 4, cudaMemcpyHostToDevice); + strata::kernels::quantize_q8_1_rows((const float*) dx, 1, n, dxq, s); + strata::kernels::iq_mmvq(GGML_TYPE_Q5_1, dw, dxq, dy, n, rows, 1, s); + cudaStreamSynchronize(s); + std::vector gpu(rows); + std::vector xq((size_t) n / 32 * 36); + cudaMemcpy(gpu.data(), dy, rows * 4, cudaMemcpyDeviceToHost); + cudaMemcpy(xq.data(), dxq, xq.size(), cudaMemcpyDeviceToHost); + cudaFree(dw); cudaFree(dx); cudaFree(dxq); cudaFree(dy); + // ggml-cpu on the GPU's own blocks: once with s = d * sum(q) (the quantized sum), once with s = ds.y as stored + struct Q81 { ggml_fp16_t d, s; int8_t qs[32]; }; // ggml's block_q8_1: {d, s} halves, 32 codes + static_assert(sizeof(Q81) == 36, "block_q8_1 layout"); + auto* blocks = (Q81*) xq.data(); + std::vector qsum(blocks, blocks + n / 32); + double shift = 0.0; + for (auto& b : qsum) { + int sq = 0; + for (int i = 0; i < 32; ++i) sq += b.qs[i]; + const float dd = ggml_fp16_to_fp32(b.d); + shift = (std::max)(shift, (double) std::fabs(ggml_fp16_to_fp32(b.s) - dd * sq)); + b.s = ggml_fp32_to_fp16(dd * (float) sq); + } + const auto* tc = ggml_get_type_traits_cpu(GGML_TYPE_Q5_1); + std::vector want(rows), stored(rows); + for (int r = 0; r < rows; ++r) { + const uint8_t* row = wq.data() + (size_t) r * row_bytes; + tc->vec_dot(n, &want[r], 0, row, 0, qsum.data(), 0, 1); + tc->vec_dot(n, &stored[r], 0, row, 0, blocks, 0, 1); + } + const double e_q = rel(gpu, want), e_s = rel(gpu, stored); + // the quantized sum goes through fp16 in ggml-cpu's block (s is a half), so 1e-3 rather than bitwise + const bool ok = e_q < 1e-3 && e_s > 10 * e_q && shift > 0.0; + std::printf("q5_1 min row 0: GPU %.6g, ggml-cpu (quantized sum) %.6g, (stored sum) %.6g\n", gpu[0], want[0], + stored[0]); + std::printf("q5_1 min GPU vs ggml-cpu with s = d*sum(q): rel %.2e; vs s = sum(x) (llama.cpp CUDA's): rel %.2e " + "(largest per-block sum shift %.3g) %s\n", e_q, e_s, shift, ok ? "ok" : "FAIL"); + return ok ? 0 : 1; +} +} // namespace + int main(int argc, char** argv) { setvbuf(stdout, nullptr, _IONBF, 0); // keep the trail on a crash - if (argc < 2) { std::fprintf(stderr, "usage: native_expert_parity [layer ...]\n"); return 2; } + if (argc < 2) { + std::fprintf(stderr, "usage: native_expert_parity [layer ...]\n" + " native_expert_parity --synthetic GU/DOWN ... (ggml type names, e.g. q4_K/q5_1)\n" + " native_expert_parity --q5_1-min\n"); + return 2; + } // #152's width check tests the opt-in rule (the multi-token kernels from one token on) if (std::getenv("STRATA_IQ_MT_MIN") == nullptr) { #ifdef _WIN32 @@ -47,257 +437,55 @@ int main(int argc, char** argv) { setenv("STRATA_IQ_MT_MIN", "1", 1); #endif } - strata::GgufFile gguf(argv[1]); - std::vector layers; - for (int i = 2; i < argc; ++i) layers.push_back(std::atoi(argv[i])); - if (layers.empty()) layers = {0, 1, 2, 3, 20, 47}; - const int NT = 3, E = 7; - const int64_t H = 2560, FF = 640; int failures = 0; cudaStream_t s; cudaStreamCreate(&s); - for (int l : layers) { - const strata::TensorInfo* t[3] = {}; - const char* roles[3] = {"gate", "up", "down"}; - for (const auto& ti : gguf.tensors()) - for (int r = 0; r < 3; ++r) - if (ti.name == "blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight") t[r] = &ti; - if (!t[0] || !t[1] || !t[2]) { std::printf("layer %d: no expert tensors\n", l); ++failures; continue; } - cpu::NativeFmt f; - std::string err; - if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF, f, err)) { - std::printf("layer %d: %s\n", l, err.c_str()); ++failures; continue; + const std::string mode = argv[1]; + if (mode == "--q5_1-min") { + failures += check_q5_1_min(s); + } else if (mode == "--synthetic") { + for (int i = 2; i < argc; ++i) { + const std::string arg = argv[i]; + const size_t slash = arg.find('/'); + const int gu = slash == std::string::npos ? -1 : type_of(arg.substr(0, slash)); + const int dn = slash == std::string::npos ? -1 : type_of(arg.substr(slash + 1)); + cpu::NativeFmt f; + std::string err; + if (gu < 0 || dn < 0 || !cpu::native_fmt(gu, dn, H, FF, f, err) || + !strata::kernels::native_expert_supported(gu, dn, H, FF)) { + std::printf("%s: %s\n", arg.c_str(), err.empty() ? "not a pair the GPU expert kernels take" : err.c_str()); + ++failures; + continue; + } + failures += check_blob(f, synthetic_blob(f, i), i, "synthetic", s); } - std::vector blob(f.bytes); - std::memcpy(blob.data(), gguf.tensor_data(*t[0]) + (size_t) E * f.up_off, f.up_off); - std::memcpy(blob.data() + f.up_off, gguf.tensor_data(*t[1]) + (size_t) E * f.up_off, f.up_off); - std::memcpy(blob.data() + f.down_off, gguf.tensor_data(*t[2]) + (size_t) E * (f.bytes - f.down_off), - f.bytes - f.down_off); - // (a) the float reference - const auto* tg = ggml_get_type_traits((ggml_type) f.gu_type); - const auto* td = ggml_get_type_traits((ggml_type) f.d_type); - std::vector G((size_t) FF * H), U((size_t) FF * H), D((size_t) H * FF); - for (int64_t r = 0; r < FF; ++r) { - tg->to_float(blob.data() + r * f.gu_row, G.data() + r * H, H); - tg->to_float(blob.data() + f.up_off + r * f.gu_row, U.data() + r * H, H); + } else { + const strata::GgufModel model(strata::gguf_split_paths(argv[1])); + std::vector layers; + for (int i = 2; i < argc; ++i) layers.push_back(std::atoi(argv[i])); + if (layers.empty()) layers = {0, 1, 2, 3, 20, 47}; + for (int l : layers) { + const strata::TensorInfo* t[3] = {}; + const uint8_t* data[3] = {}; + const char* roles[3] = {"gate", "up", "down"}; + for (int r = 0; r < 3; ++r) { // each role from the shard that holds it + size_t at = 0; + t[r] = model.find("blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight", &at); + if (t[r]) data[r] = model.shard(at).tensor_data(*t[r]); + } + if (!t[0] || !t[1] || !t[2]) { std::printf("layer %d: no expert tensors\n", l); ++failures; continue; } + cpu::NativeFmt f; + std::string err; + if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF, f, err)) { + std::printf("layer %d: %s\n", l, err.c_str()); ++failures; continue; + } + std::vector blob(f.bytes); + std::memcpy(blob.data(), data[0] + (size_t) E * f.up_off, f.up_off); + std::memcpy(blob.data() + f.up_off, data[1] + (size_t) E * f.up_off, f.up_off); + std::memcpy(blob.data() + f.down_off, data[2] + (size_t) E * (f.bytes - f.down_off), + f.bytes - f.down_off); + failures += check_blob(f, blob, l, "layer " + std::to_string(l), s); } - for (int64_t r = 0; r < H; ++r) td->to_float(blob.data() + f.down_off + r * f.d_row, D.data() + r * FF, FF); - std::mt19937 rng(11 + l); - std::normal_distribution nd(0.f, 1.f); - std::vector x((size_t) NT * H); - for (auto& v : x) v = nd(rng); - std::vector ref((size_t) NT * H), got_c((size_t) NT * H), got_g((size_t) NT * H); - for (int k = 0; k < NT; ++k) { - std::vector h(FF); - for (int64_t r = 0; r < FF; ++r) { - double g = 0, u = 0; - for (int64_t i = 0; i < H; ++i) { g += (double) G[r * H + i] * x[k * H + i]; u += (double) U[r * H + i] * x[k * H + i]; } - h[r] = (float) (g / (1.0 + std::exp(-g)) * u); - } - for (int64_t r = 0; r < H; ++r) { - double o = 0; - for (int64_t i = 0; i < FF; ++i) o += (double) D[r * FF + i] * h[i]; - ref[k * H + r] = (float) o; - } - } - // (b) the CPU - { - std::vector> act(NT, std::vector(cpu::kNativeActBytes)); - std::vector> hq(NT, std::vector(cpu::kNativeHBytes)); - std::vector> ff(NT, std::vector(FF)); - const void* a[NT]; - float* ffp[NT]; - const void* hp[NT]; - float* op[NT]; - for (int k = 0; k < NT; ++k) { - cpu::native_quant_act(f, x.data() + k * H, act[k].data()); - a[k] = act[k].data(); - ffp[k] = ff[k].data(); - } - cpu::native_gu_rows(f, blob.data(), a, NT, ffp, 0, (int) FF); - if (cpu::iq512_supported(f.gu_type)) { - // ggml's own vec_dot, same Q8_K activations: the reference for both multi-token kernels - // (float-order differences only) - const auto* tc = ggml_get_type_traits_cpu((ggml_type) f.gu_type); - std::vector gref((size_t) NT * FF); - for (int k = 0; k < NT; ++k) - for (int64_t r = 0; r < FF; ++r) - tc->vec_dot((int) H, &gref[k * FF + r], 0, blob.data() + r * f.gu_row, 0, a[k], 0, 1); - double usg = 0.0; - { // ggml single-token throughput, the weights cache-resident (compute bound) - const int it = 50; - auto t0 = std::chrono::steady_clock::now(); - for (int i = 0; i < it; ++i) - for (int64_t r = 0; r < FF; ++r) { - float gg, uu; - tc->vec_dot((int) H, &gg, 0, blob.data() + r * f.gu_row, 0, a[0], 0, 1); - tc->vec_dot((int) H, &uu, 0, blob.data() + f.up_off + r * f.gu_row, 0, a[0], 0, 1); - } - auto t1 = std::chrono::steady_clock::now(); - usg = std::chrono::duration(t1 - t0).count() / it; - } - // one multi-token kernel: parity against ggml's vec_dot, then one-token and NT-token throughput - auto check = [&](const char* tag, bool is512) { - std::vector g((size_t) NT * FF); - float* gp[NT]; - for (int k = 0; k < NT; ++k) gp[k] = g.data() + k * FF; - (is512 ? cpu::iq512_rows : cpu::iq256_rows)(f.gu_type, blob.data(), f.gu_row, (int) H, a, NT, gp, 0, (int) FF); - const double rg = rel(g, gref); - std::printf(" %s %s gate rows vs ggml vec_dot: rel %.2e\n", - ggml_type_name((ggml_type) f.gu_type), tag, rg); - if (rg > 1e-5) { // ggml's own vec_dot is the reference: above 1e-5 it is a real mismatch, - std::printf(" %s %s gate rows MISMATCH (rel %.2e > 1e-5)\n", - ggml_type_name((ggml_type) f.gu_type), tag, rg); // not rounding (measured 3e-8) - ++failures; - } - float* f1[1] = {ffp[0]}; - const int it = 50; - const auto gu = is512 ? cpu::iq512_gu_rows : cpu::iq256_gu_rows; - auto t0 = std::chrono::steady_clock::now(); - for (int i = 0; i < it; ++i) gu(f.gu_type, blob.data(), f.gu_row, f.up_off, (int) H, a, 1, f1, 0, (int) FF); - auto t1 = std::chrono::steady_clock::now(); - for (int i = 0; i < it; ++i) gu(f.gu_type, blob.data(), f.gu_row, f.up_off, (int) H, a, NT, ffp, 0, (int) FF); - auto t2 = std::chrono::steady_clock::now(); - const double us1 = std::chrono::duration(t1 - t0).count() / it; - const double usn = std::chrono::duration(t2 - t1).count() / it; - std::printf(" gate+up one token one thread: %s %.0f us (%.2f GB/s), ggml %.0f us (%.2f GB/s)\n", - tag, us1, 2.0 * f.up_off / us1 / 1e3, usg, 2.0 * f.up_off / usg / 1e3); - std::printf(" gate+up %d tokens one thread: %s %.0f us vs ggml %d x %.0f us\n", NT, tag, usn, NT, usg); - }; - if (cpu::cpu_avx512_ok()) check("avx512", true); // guarded: the binary runs on AVX-2 CPUs too - check("avx2", false); - } - for (int k = 0; k < NT; ++k) { - cpu::native_quant_h(f, ff[k].data(), hq[k].data()); - hp[k] = hq[k].data(); - op[k] = got_c.data() + k * H; - } - cpu::native_down_rows(f, blob.data(), hp, NT, op, 0, (int) H); - { // #152: a token's rows must not depend on how many tokens share the call - each token alone (nt = 1) - // against its row of the NT-token call above, bit for bit, gate/up and down - size_t gu_diff = 0, dn_diff = 0; - std::vector one_ff(FF), one_out(H); - // the NT-token gate/up rows again: the throughput loops above overwrote ff with other kernels' rows - for (int k = 0; k < NT; ++k) ffp[k] = ff[k].data(); - cpu::native_gu_rows(f, blob.data(), a, NT, ffp, 0, (int) FF); - for (int k = 0; k < NT; ++k) { - const void* a1[1] = {a[k]}; - float* f1[1] = {one_ff.data()}; - cpu::native_gu_rows(f, blob.data(), a1, 1, f1, 0, (int) FF); - for (int64_t r = 0; r < FF; ++r) gu_diff += std::memcmp(&one_ff[r], &ff[k][r], 4) != 0; - const void* h1[1] = {hp[k]}; - float* o1[1] = {one_out.data()}; - cpu::native_down_rows(f, blob.data(), h1, 1, o1, 0, (int) H); - for (int64_t r = 0; r < H; ++r) dn_diff += std::memcmp(&one_out[r], &got_c[k * H + r], 4) != 0; - } - std::printf(" width invariance (1 vs %d tokens): gate/up %zu, down %zu rows differ\n", NT, - gu_diff, dn_diff); - if (gu_diff || dn_diff) ++failures; - } - if (f.d_type == 42) { - // (b2) the GGUF-layout Q2_0 kernel the pool uses for Q2_0 down projections - the AVX-512 one - // where the CPU has it, the AVX-2 one (q2_avx2.cpp) where it does not. Calling the AVX-512 - // kernel unconditionally faults on a Zen 2/3 CPU. - std::vector a2(NT); - const cpu::ActQ* ap[NT]; - std::vector alt((size_t) NT * H); - float* altp[NT]; - for (int k = 0; k < NT; ++k) { - cpu::act_quant_any(ff[k].data(), (int) FF, a2[k]); // gated: AVX-512 or AVX-2 per CPU - ap[k] = &a2[k]; - altp[k] = alt.data() + k * H; - } - cpu::q2_rows_any(blob.data() + f.down_off, f.d_row, (int) (FF / 64), ap, NT, altp, 0, (int) H); - std::printf(" q2_0 %s down vs ggml down: rel %.2e\n", - cpu::cpu_avx512_ok() ? "AVX-512" : "AVX-2", rel(alt, got_c)); - } - if (f.d_type == 20) { - // (b3) the IQ4_NL multi-token AVX-2 kernel the pool now uses for IQ4_NL down projections, - // against ggml-cpu's single-token vec_dot on the SAME Q8_0 activations (h), plus timing. - std::vector alt((size_t) NT * H), refd((size_t) NT * H); - float* altp[NT]; - for (int k = 0; k < NT; ++k) altp[k] = alt.data() + k * H; - cpu::iq4nl256_down_rows(blob.data() + f.down_off, f.d_row, (int) FF, hp, NT, altp, 0, (int) H); - const auto* tdc = ggml_get_type_traits_cpu((ggml_type) f.d_type); - for (int k = 0; k < NT; ++k) - for (int64_t r = 0; r < H; ++r) - tdc->vec_dot((int) FF, refd.data() + k * H + r, 0, - blob.data() + f.down_off + (size_t) r * f.d_row, 0, hp[k], 0, 1); - const double rdn = rel(alt, refd); - std::printf(" iq4_nl AVX-2 multi-token down vs ggml down: rel %.2e\n", rdn); - if (rdn > 1e-5) { // measured 1e-7; same reasoning as the gate/up rows above - std::printf(" iq4_nl down MISMATCH (rel %.2e > 1e-5)\n", rdn); - ++failures; - } - const int it = 50; - const auto t0 = std::chrono::steady_clock::now(); - for (int i = 0; i < it; ++i) - cpu::iq4nl256_down_rows(blob.data() + f.down_off, f.d_row, (int) FF, hp, NT, altp, 0, (int) H); - const auto t1 = std::chrono::steady_clock::now(); - for (int i = 0; i < it; ++i) - for (int k = 0; k < NT; ++k) - for (int64_t r = 0; r < H; ++r) - tdc->vec_dot((int) FF, refd.data() + k * H + r, 0, - blob.data() + f.down_off + (size_t) r * f.d_row, 0, hp[k], 0, 1); - const auto t2 = std::chrono::steady_clock::now(); - const double usn = std::chrono::duration(t1 - t0).count() / it; - const double usg = std::chrono::duration(t2 - t1).count() / it; - std::printf(" down %d tokens one thread: avx2 %.0f us (%.2f GB/s) vs ggml %.0f us (%.2f GB/s)\n", - NT, usn, (double) (f.bytes - f.down_off) / usn / 1e3, usg, - (double) (f.bytes - f.down_off) / usg / 1e3); - } - } - // (c) the GPU: one group holding the NT entries - { - const auto L = strata::kernels::native_expert_layout(f.gu_type, f.d_type, H, FF); - void *dblob, *dx, *dxq, *dscr; - float* dout; - unsigned long long* dptr; - int32_t *dstart, *dn, *ddst, *dtok; - cudaMalloc(&dblob, blob.size()); - cudaMalloc(&dx, x.size() * 4); - cudaMalloc(&dxq, (size_t) NT * H / 32 * 36); - cudaMalloc(&dscr, strata::kernels::native_expert_scratch_bytes(NT, FF)); - cudaMalloc((void**) &dout, (size_t) NT * H * 4); - cudaMalloc((void**) &dptr, 8); - cudaMalloc((void**) &dstart, 8); - cudaMalloc((void**) &dn, 4); - cudaMalloc((void**) &ddst, NT * 4); - cudaMalloc((void**) &dtok, NT * 4); - cudaMemcpy(dblob, blob.data(), blob.size(), cudaMemcpyHostToDevice); - cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice); - const unsigned long long p = (unsigned long long) dblob; - const int32_t st[2] = {0, NT}, one = 1, idx[NT] = {0, 1, 2}; - cudaMemcpy(dptr, &p, 8, cudaMemcpyHostToDevice); - cudaMemcpy(dstart, st, 8, cudaMemcpyHostToDevice); - cudaMemcpy(dn, &one, 4, cudaMemcpyHostToDevice); - cudaMemcpy(ddst, idx, NT * 4, cudaMemcpyHostToDevice); - cudaMemcpy(dtok, idx, NT * 4, cudaMemcpyHostToDevice); - strata::kernels::quantize_q8_1_rows((const float*) dx, NT, H, dxq, s); - strata::kernels::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, 1, NT, dxq, dscr, dout, s); - cudaStreamSynchronize(s); - cudaMemcpy(got_g.data(), dout, got_g.size() * 4, cudaMemcpyDeviceToHost); - { // the kernels that decode a weight part once for the NT entries, bitwise vs the per-entry ones - std::vector old_g(got_g.size()); - const bool was = strata::kernels::iq_old_kernels(); - strata::kernels::iq_set_old_kernels(!was); - strata::kernels::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, 1, NT, dxq, dscr, dout, s); - strata::kernels::iq_set_old_kernels(was); - cudaStreamSynchronize(s); - cudaMemcpy(old_g.data(), dout, old_g.size() * 4, cudaMemcpyDeviceToHost); - const bool same = std::memcmp(old_g.data(), got_g.data(), got_g.size() * 4) == 0; - std::printf(" gpu decode-once vs per-entry kernels: %s\n", same ? "bitwise equal" : "MISMATCH"); - if (!same) ++failures; - } - cudaFree(dblob); cudaFree(dx); cudaFree(dxq); cudaFree(dscr); cudaFree(dout); cudaFree(dptr); - cudaFree(dstart); cudaFree(dn); cudaFree(ddst); cudaFree(dtok); - } - const double ec = rel(got_c, ref), eg = rel(got_g, ref), ecg = rel(got_c, got_g); - const bool ok = ec < 3e-2 && eg < 3e-2 && std::isfinite(ec) && std::isfinite(eg); - std::printf("layer %2d %-8s/%-7s blob %8zu cpu rel %.2e gpu rel %.2e cpu-gpu %.2e %s\n", l, - ggml_type_name((ggml_type) f.gu_type), ggml_type_name((ggml_type) f.d_type), f.bytes, ec, eg, ecg, - ok ? "ok" : "FAIL"); - if (!ok) ++failures; } std::printf("native_expert_parity: %d failures\n", failures); return failures ? 1 : 0; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 98de832e..9b89f5f7 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -29,6 +29,7 @@ #include "strata/kernels/cpu/pool.hpp" #include "strata/kernels/cpu/expert_layout.hpp" #include "strata/kernels/ngram.hpp" +#include "strata/kernels/iq_kernels.hpp" #include "strata/kernels/s2_expert_grouped.hpp" #include "strata/kernels/sampler.hpp" #include "strata/kernels/verify_kernels.hpp" @@ -1520,6 +1521,20 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } + // Every layer's formats must have GPU expert kernels and a prompt-path dequantizer, checked here, before + // anything is allocated: an unsupported down type used to exit from inside the first verify window, and + // an unsupported dequant type left the prompt path's fp16 buffer unwritten. + const auto& lay = strata::kernels::cpu::expert_layout(); + for (int64_t l = 0; lay.native && l < (int64_t) lay.fmt.size(); ++l) { + const auto& f = lay.fmt[(size_t) l]; + if (!strata::kernels::native_expert_supported(f.gu_type, f.d_type, f.n_embd, f.n_ff)) { + std::fprintf(stderr, "strata generate: layer %lld's experts are %s/%s (ggml types %d/%d), which this " + "engine has no GPU kernels for\n", (long long) l, + strata::ggml_type_name((uint32_t) f.gu_type), strata::ggml_type_name((uint32_t) f.d_type), + f.gu_type, f.d_type); + return 1; + } + } } const bool native_pack = strata::kernels::cpu::expert_layout().native; // STRATA_EARLY_REMOTE_CONTEXTS=1: create EVERY secondary context here, like CUDA1's. Under WSL2 the driver's @@ -1878,7 +1893,8 @@ int main(int argc, char** argv) { ss.ple.w.key_scales = (const float*) ((const uint8_t*) wk->data + wk->codes_bytes); } if (o.native_ple_key && wk->quantized()) { - if (!wk->native_data || (wk->native_type != 42 && wk->native_type != 18 && wk->native_type != 23) || !wk->native_q8_1) { + if (!wk->native_data || (wk->native_type != 42 && wk->native_type != 18 && wk->native_type != 23 && + wk->native_type != 8) || !wk->native_q8_1) { std::fprintf(stderr, "strata generate: native PLE key is absent or incompatible\n"); return 1; } From 1e663cc70ee299b27978c3501329ddaf59f9f34e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 22:51:03 +0200 Subject: [PATCH 6/7] CS-T: native packs read their experts from the GGUF shards in place (--mmap-experts without experts.bin), --resident-budget-gib N, per-tier counters - FileExpertSource: a native pack without experts.bin, given the --native shard, maps every GGUF file native_experts.txt names (after check_experts_gguf) and assembles a blob [gate | up | down] from the three role slices when asked: into a small pool of buffers for blob() (a buffer is reused once its blob has not been asked for during 3 layers (begin_layer) or 256 assemblies), or straight into the caller's memory for copy_blob(). No 30-77 GB experts.bin on the disk. With experts.bin present nothing changes. - ExpertSource::transient / copy_blob: the prompt path's stager copies a transient blob itself (its queue holds a whole chunk's experts), everything else keeps using blob(). - --resident-budget-gib N (the resident mode with a budget): the experts the GPU cache does not hold are copied into RAM in expert-profile order while they fit N GiB (clamped to available RAM minus the headroom), the rest are read from the files; no lend region then. Without the flag the resident mode and --mmap-experts are unchanged. - Counters: blobs served from the RAM copy, from the files, and bytes read from the files; in the stats table ("expert tiers"), the serve log, and appended to DONE (RAM blobs, file blobs, file MB for the request), which serve/server.py puts into /metrics' request history (older DONE lines still parse). - expert_layout_test: the GGUF-in-place source gives the loaded arena's bytes through blob() and copy_blob(), an assembled blob stays put while in use, and experts.bin still wins when present. --- include/strata/core/expert_source.hpp | 71 +++++- serve/server.py | 5 +- src/core/expert_source.cpp | 305 +++++++++++++++++++++++++- src/prefill/prefill.cpp | 38 +++- src/program/generate.cpp | 54 ++++- tests/core/expert_layout_test.cpp | 53 +++++ 6 files changed, 493 insertions(+), 33 deletions(-) diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 8af105aa..6a1668bb 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -28,6 +28,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -120,6 +123,15 @@ public: /// checked with `pinned`). The arena answers per layer through its expert 0; the resident RAM mode's compact /// copy has no expert 0 when the GPU cache holds it, so it answers for the whole copy. virtual bool pcie_layer(int64_t layer) const { return device_alias(layer, 0) != nullptr; } + + /// CS-T: whether `blob(layer, expert)` would be assembled into a short-lived buffer (a native pack read from its + /// GGUF shards in place, where an expert's gate, up and down rows are three separate slices). Such a pointer + /// stays valid for the layer it was asked in and the next one or two; a consumer that keeps a blob longer (the + /// prompt path's stager queues a whole chunk) copies it with `copy_blob` instead. + virtual bool transient(int64_t layer, int64_t expert) const { (void) layer; (void) expert; return false; } + /// The blob's bytes into `dst` (blob_bytes(layer) of them). Safe from several threads for a source whose + /// `transient` can be true. + virtual bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst); }; /// Plan v0.3 P6: what the GPU computes in a verify window's layer, written by the pool (mapped host memory) right @@ -334,7 +346,16 @@ public: /// /// The size check is not a formality: a short file would fault at the END of a long sequence, and an /// over-long one means the pack is not the one the geometry came from. Refuses with the two numbers. + /// + /// CS-T: a native pack WITHOUT experts.bin, after `set_gguf`, maps the model's GGUF shards instead (every file + /// native_experts.txt names, after `check_experts_gguf`), and assembles a blob from its three role slices when + /// it is asked for: the SSD tier, read in place through the OS file cache, with no 30-77 GB experts.bin copy. + /// With experts.bin present nothing changes. bool open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err); + /// CS-T: the --native shard (native_experts.txt names the other files beside it); see `open`. + void set_gguf(const std::string& native) { gguf_ = native; } + /// Whether the experts are read from the GGUF shards in place (no experts.bin). + bool gguf_mode() const { return !role_ptr_.empty(); } /// Pin a compact host mirror of experts absent from a fully filled static GPU cache. The mmap remains open /// as a fallback for later cache reloads. This is opt-in because the complement may still be a large allocation. /// @@ -347,10 +368,15 @@ public: /// experts are kept in RAM too, from the last slot down, as far as `available RAM - headroom_bytes` allows /// (a lent slot's expert is streamed during the prompt and copied back after it). /// - the rest (the experts no slot holds) must fit that budget, or nothing is allocated and this returns false. + /// + /// CS-T, `budget_bytes` > 0 (`--resident-budget-gib`): only as many of those experts as fit `budget_bytes`, taken + /// in `rank` order (the expert profile: the hottest after the GPU cache's), are copied; the rest stay on the + /// mapped files (the SSD tier). No lend region then (a lent slot's expert is read from the files). bool pin_cache_complement( const ExpertCache& cache, std::string& err, bool pin = true, const std::vector>& additional_gpu_pairs = {}, int64_t lend_from_slot = -1, - uint64_t headroom_bytes = 8ull << 30); + uint64_t headroom_bytes = 8ull << 30, uint64_t budget_bytes = 0, + const std::vector>* rank = nullptr); void close(); bool mapped() const { return base_ != nullptr; } @@ -382,11 +408,19 @@ public: /// With the compact copy ready: blobs read from the mapped file since (what the plain mmap mode may read from /// the SSD). 0 in a steady resident mode; lend-region experts that did not fit the RAM count here. int64_t file_reads() const { return file_reads_.load(std::memory_order_relaxed); } + /// CS-T per-tier counters: blobs served from the RAM copy, and the bytes read from the mapped files (the blobs + /// `file_reads` counts, plus the prompt path's copies of them). + int64_t ram_reads() const { return ram_reads_.load(std::memory_order_relaxed); } + uint64_t file_read_bytes() const { return file_read_bytes_.load(std::memory_order_relaxed); } const uint8_t* blob(int64_t layer, int64_t expert) override; bool pinned(int64_t layer, int64_t expert) const override; const uint8_t* device_alias(int64_t layer, int64_t expert) const override; bool pcie_layer(int64_t layer) const override; + bool transient(int64_t layer, int64_t expert) const override; + bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst) override; + /// CS-T: advances the assembled blobs' age (see staged_blob). + void begin_layer(int64_t layer, const int32_t* ids, int64_t k) override; /// Blobs touched, for the driver to report. With `h = 0` this is `48 * k` per token and the number is only /// interesting once Phase 3 makes it not so. @@ -394,7 +428,42 @@ public: private: const uint8_t* mapped_blob(int64_t layer, int64_t expert) const; + /// The blob's bytes from the mapped file(s) - experts.bin, or the three GGUF role slices - into `dst`. + bool copy_from_files(int64_t layer, int64_t expert, uint8_t* dst) const; + bool open_gguf(std::string& err); + const uint8_t* staged_blob(int64_t layer, int64_t expert); static constexpr uint64_t kNoComplement = detail::kNoCacheComplement; + // ---- CS-T: the GGUF shards in place + std::string gguf_; + struct Map { + const uint8_t* base = nullptr; + uint64_t bytes = 0; +#if defined(_WIN32) + void* file = nullptr; + void* mapping = nullptr; +#else + int fd = -1; +#endif + }; + std::vector maps_; + std::vector role_ptr_; ///< 3 x n_layers: gate / up / down of the layer's expert 0 + std::vector role_bytes_; ///< 3 x n_layers: bytes per expert of that role + // the blobs assembled for `blob()`: a small pool of buffers, one per recent (layer, expert). A buffer is + // reused only once `kStageAge` layer changes have passed since its blob was last asked for, so a pointer holds + // through the layer it was asked in and the next ones (the pool computes a layer's misses before the next). + static constexpr uint64_t kStageAge = 3; + std::mutex stage_mu_; + std::vector> stage_buf_; + std::vector stage_key_; + std::vector stage_epoch_, stage_used_; + std::unordered_map stage_of_; + uint64_t stage_blob_ = 0; + uint64_t stage_seq_ = 0; + uint64_t epoch_ = 0; + int64_t last_layer_ = -1; + bool stage_grew_ = false; + std::atomic ram_reads_{0}; + std::atomic file_read_bytes_{0}; const uint8_t* base_ = nullptr; int64_t blobs_ = 0; int64_t n_layers_ = 0; diff --git a/serve/server.py b/serve/server.py index e03379e0..e363e3fa 100644 --- a/serve/server.py +++ b/serve/server.py @@ -284,6 +284,8 @@ class StrataEngine: self.last.update(drafts_accepted=int(f[6]), drafts_offered=int(f[7]), reused=int(f[8])) if len(f) >= 11: # decode hit rate fields self.last.update(hits=int(f[9]), lookups=int(f[10])) + if len(f) >= 14: # the expert tiers (engine 0.1.31+): RAM / file blobs, file MB + self.last.update(ram_blobs=int(f[11]), file_blobs=int(f[12]), file_mb=float(f[13])) @staticmethod def sampling_keys(sampling: dict) -> str: @@ -1063,7 +1065,8 @@ class Service: "prompt_ms": last.get("prompt_ms"), "decode_ms": last.get("decode_ms"), "decode_tok_s": round(last["generated"] / (last["decode_ms"] / 1000), 1) if n and last.get("generated") and last.get("decode_ms") else None, - "hit_rate": hit_rate}) + "hit_rate": hit_rate, "ram_blobs": last.get("ram_blobs"), + "file_blobs": last.get("file_blobs"), "file_mb": last.get("file_mb")}) t = self.totals t["requests"] += 1 t["prompt_tokens"] += len(ids) diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index 71a2ecc5..8d0ab32f 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -350,6 +350,16 @@ bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64 } } const std::string path = pack_dir + "/experts.bin"; + if (layout.native && !gguf_.empty() && !std::filesystem::exists(path)) { + // CS-T: no experts.bin - the model's GGUF shards, read in place + blobs_ = (int64_t) blob_count; + n_layers_ = n_layers; + n_expert_ = n_expert; + layer_offsets_ = std::move(layer_offsets); + layer_blob_bytes_ = std::move(layer_blob_bytes); + if (!open_gguf(err)) { close(); return false; } + return true; + } #if defined(_WIN32) // UTF-8 -> UTF-16: the pack may live under a path with non-ASCII characters, and `CreateFileA` would @@ -465,6 +475,37 @@ void FileExpertSource::close() { complement_ready_ = false; complement_locked_ = 0; complement_lent_slots_ = 0; + if (!maps_.empty()) { + for (Map& m : maps_) { +#if defined(_WIN32) + if (m.base != nullptr) UnmapViewOfFile((LPCVOID) m.base); + if (m.mapping != nullptr) CloseHandle((HANDLE) m.mapping); + if (m.file != nullptr) CloseHandle((HANDLE) m.file); +#else + if (m.base != nullptr) munmap((void*) m.base, (size_t) m.bytes); + if (m.fd >= 0) ::close(m.fd); +#endif + } + maps_.clear(); + base_ = nullptr; // one of the views above + } + role_ptr_.clear(); + role_bytes_.clear(); + { + std::lock_guard lk(stage_mu_); + stage_buf_.clear(); + stage_key_.clear(); + stage_epoch_.clear(); + stage_used_.clear(); + stage_of_.clear(); + stage_blob_ = 0; + stage_seq_ = 0; + epoch_ = 0; + last_layer_ = -1; + stage_grew_ = false; + } + ram_reads_.store(0); + file_read_bytes_.store(0); #if defined(_WIN32) if (base_ != nullptr) UnmapViewOfFile((LPCVOID) base_); if (mapping_ != nullptr) CloseHandle((HANDLE) mapping_); @@ -486,7 +527,199 @@ void FileExpertSource::close() { reads_ = 0; } + +bool ExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) { + const uint8_t* b = blob(layer, expert); + if (b == nullptr || dst == nullptr) return false; + std::memcpy(dst, b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(layer)); + return true; +} + +// ================================ CS-T: THE GGUF SHARDS IN PLACE ================================ +// +// A native pack without experts.bin: every file native_experts.txt names is mapped (MapViewOfFile / mmap, no +// flag - the same retention argument as experts.bin above), and an expert's blob [gate rows | up rows | down rows] +// is three slices of three tensors, possibly in two shards (UD-Q4_K_XL's layer 11). Nothing is read at open; a +// blob is assembled when it is asked for (`blob`, into a small pool of buffers) or copied where it is needed +// (`copy_blob`: the RAM copy, the prompt path's pinned stager buffers). +bool FileExpertSource::open_gguf(std::string& err) { + const auto& lay = strata::kernels::cpu::expert_layout(); + if (!check_experts_gguf(gguf_, lay, err)) { err = "FileExpertSource: " + err; return false; } + const size_t cut = gguf_.find_last_of("/\\"); + const std::string dir = cut == std::string::npos ? std::string() : gguf_.substr(0, cut + 1); + std::map index; + role_ptr_.assign((size_t) (3 * n_layers_), nullptr); + role_bytes_.assign((size_t) (3 * n_layers_), 0); + for (int64_t l = 0; l < n_layers_; ++l) { + const auto& fm = lay.fmt[(size_t) l]; + const uint64_t per[3] = {fm.up_off, fm.up_off, lay.bytes[(size_t) l] - fm.down_off}; + for (int r = 0; r < 3; ++r) { + const size_t i = (size_t) (3 * l + r); + const std::string path = lay.gguf_file.size() > i && !lay.gguf_file[i].empty() ? dir + lay.gguf_file[i] + : gguf_; + auto it = index.find(path); + if (it == index.end()) { + Map m; +#if defined(_WIN32) + const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0); + std::vector wpath((size_t) (wide > 0 ? wide : 1)); + if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide); + HANDLE f = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, nullptr); + LARGE_INTEGER sz{}; + if (f == INVALID_HANDLE_VALUE || !GetFileSizeEx(f, &sz)) { + if (f != INVALID_HANDLE_VALUE) CloseHandle(f); + err = "FileExpertSource: cannot open " + path; + return false; + } + HANDLE mh = CreateFileMappingW(f, nullptr, PAGE_READONLY, 0, 0, nullptr); + void* view = mh != nullptr ? MapViewOfFile(mh, FILE_MAP_READ, 0, 0, 0) : nullptr; + if (view == nullptr) { + if (mh != nullptr) CloseHandle(mh); + CloseHandle(f); + err = "FileExpertSource: cannot map " + path; + return false; + } + m.file = f; + m.mapping = mh; + m.bytes = (uint64_t) sz.QuadPart; + m.base = (const uint8_t*) view; +#else + const int fd = ::open(path.c_str(), O_RDONLY); + struct stat st{}; + if (fd < 0 || fstat(fd, &st) != 0 || st.st_size <= 0) { + if (fd >= 0) ::close(fd); + err = "FileExpertSource: cannot open " + path; + return false; + } + void* view = mmap(nullptr, (size_t) st.st_size, PROT_READ, MAP_SHARED, fd, 0); + if (view == MAP_FAILED) { ::close(fd); err = "FileExpertSource: cannot map " + path; return false; } + m.fd = fd; + m.bytes = (uint64_t) st.st_size; + m.base = (const uint8_t*) view; +#endif + maps_.push_back(m); + it = index.emplace(path, maps_.size() - 1).first; + } + const Map& m = maps_[it->second]; + const uint64_t at = lay.gguf_off[i], bytes = per[r] * (uint64_t) n_expert_; + if (at > m.bytes || bytes > m.bytes - at) { // check_experts_gguf proved it; the mapping must agree + err = "FileExpertSource: an expert span runs past the end of " + path; + return false; + } + role_ptr_[i] = m.base + (size_t) at; + role_bytes_[i] = per[r]; + } + } + base_ = maps_.front().base; // "opened"; mapped_blob answers nullptr in this mode + for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b); + return true; +} + +bool FileExpertSource::copy_from_files(int64_t layer, int64_t expert, uint8_t* dst) const { + if (dst == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false; + if (!role_ptr_.empty()) { + uint64_t at = 0; + for (int r = 0; r < 3; ++r) { + const size_t i = (size_t) (3 * layer + r); + const uint64_t per = role_bytes_[i]; + std::memcpy(dst + at, role_ptr_[i] + (size_t) ((uint64_t) expert * per), (size_t) per); + at += per; + } + return true; + } + const uint8_t* b = mapped_blob(layer, expert); + if (b == nullptr) return false; + std::memcpy(dst, b, (size_t) layer_blob_bytes_[(size_t) layer]); + return true; +} + +// A blob assembled from the three role slices. The buffer of a (layer, expert) is reused for another only once +// its blob has not been asked for during `kStageAge` layers (begin_layer) or 256 assemblies, whichever comes +// first: the pool computes a layer's misses before it starts the next, and a fill (the GPU cache at startup, an +// adaptive swap, a helper GPU) copies the blob right away. +const uint8_t* FileExpertSource::staged_blob(int64_t layer, int64_t expert) { + constexpr uint64_t kStageSeq = 256; + const int64_t key = layer * n_expert_ + expert; + std::lock_guard lk(stage_mu_); + const uint64_t seq = ++stage_seq_; + auto it = stage_of_.find(key); + if (it != stage_of_.end()) { + stage_epoch_[it->second] = epoch_; + stage_used_[it->second] = seq; + return stage_buf_[it->second].get(); + } + size_t v = stage_buf_.size(); + uint64_t oldest = std::numeric_limits::max(); + for (size_t i = 0; i < stage_buf_.size(); ++i) + if ((stage_epoch_[i] + kStageAge <= epoch_ || stage_used_[i] + kStageSeq <= seq) && stage_used_[i] < oldest) { + oldest = stage_used_[i]; + v = i; + } + if (v == stage_buf_.size()) { + stage_buf_.emplace_back(new (std::nothrow) uint8_t[(size_t) stage_blob_]); + if (!stage_buf_.back()) { stage_buf_.pop_back(); return nullptr; } + stage_key_.push_back(-1); + stage_epoch_.push_back(0); + stage_used_.push_back(0); + if (stage_buf_.size() == 512 && !stage_grew_) { + stage_grew_ = true; + std::fprintf(stderr, "FileExpertSource: %zu blobs assembled from the GGUF are in use at once (%.2f GiB)\n", + stage_buf_.size(), (double) stage_buf_.size() * (double) stage_blob_ / 1073741824.0); + } + } else { + stage_of_.erase(stage_key_[v]); + } + uint8_t* dst = stage_buf_[v].get(); + if (!copy_from_files(layer, expert, dst)) { stage_key_[v] = -1; return nullptr; } + file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed); + stage_key_[v] = key; + stage_epoch_[v] = epoch_; + stage_used_[v] = seq; + stage_of_[key] = v; + return dst; +} + +void FileExpertSource::begin_layer(int64_t layer, const int32_t* ids, int64_t k) { + (void) ids; + (void) k; + if (role_ptr_.empty()) return; + std::lock_guard lk(stage_mu_); + if (layer != last_layer_) { + ++epoch_; + last_layer_ = layer; + } +} + +bool FileExpertSource::transient(int64_t layer, int64_t expert) const { + if (role_ptr_.empty() || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false; + const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; + if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement) + return false; + return override_.empty() || override_[index] == nullptr; +} + +bool FileExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) { + if (base_ == nullptr || dst == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) + return false; + const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; + const uint64_t bytes = layer_blob_bytes_[(size_t) layer]; + if (complement_ready_) { + const uint8_t* held = + detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr); + if (held == nullptr && !override_.empty()) held = override_[index]; + if (held != nullptr) { + std::memcpy(dst, held, (size_t) bytes); + return true; + } + } + if (!copy_from_files(layer, expert, dst)) return false; + file_read_bytes_.fetch_add(bytes, std::memory_order_relaxed); + return true; +} + const uint8_t* FileExpertSource::mapped_blob(int64_t layer, int64_t expert) const { + if (!role_ptr_.empty()) return nullptr; // the GGUF in place: no contiguous blob in any file if (base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return nullptr; const size_t i = (size_t) layer; if (i >= layer_offsets_.size() || i >= layer_blob_bytes_.size()) return nullptr; @@ -503,7 +736,7 @@ const uint8_t* FileExpertSource::mapped_blob(int64_t layer, int64_t expert) cons bool FileExpertSource::pin_cache_complement( const ExpertCache& cache, std::string& err, bool pin, const std::vector>& additional_gpu_pairs, int64_t lend_from_slot, - uint64_t headroom_bytes) { + uint64_t headroom_bytes, uint64_t budget_bytes, const std::vector>* rank) { err.clear(); if (base_ == nullptr) { err = "FileExpertSource: open the mapped experts before pinning a complement"; return false; } if (complement_ready_) { err = "FileExpertSource: the cache complement is already pinned"; return false; } @@ -539,6 +772,43 @@ bool FileExpertSource::pin_cache_complement( uint64_t bytes = 0; if (!detail::make_cache_complement_plan(n_layers_, n_expert_, layer_blob_bytes_, primary_gpu_pairs, additional_gpu_pairs, offsets, bytes, err)) return false; + if (budget_bytes > 0) { + // CS-T: a RAM budget. The complement's experts in `rank` order (the expert profile, hottest first) while + // they fit, the rest left on the mapped files; clamped to what the RAM has room for. + uint64_t physical = 0; + if (!available_memory_bytes(physical)) { + err = "FileExpertSource: cannot determine available RAM for --resident-budget-gib"; + return false; + } + const uint64_t room = physical > headroom_bytes ? physical - headroom_bytes : 0; + if (budget_bytes > room) { + std::fprintf(stderr, "FileExpertSource: --resident-budget-gib %.2f is more than the RAM has room for " + "(%.2f GiB available minus %.0f GiB headroom): %.2f GiB\n", + (double) budget_bytes / 1073741824.0, (double) physical / 1073741824.0, + (double) headroom_bytes / 1073741824.0, (double) room / 1073741824.0); + budget_bytes = room; + } + std::vector ranked(offsets.size(), kNoComplement); + uint64_t at = 0; + int64_t held = 0; + if (rank != nullptr) + for (const auto& pr : *rank) { + if (pr.first < 0 || pr.second < 0 || pr.first >= n_layers_ || pr.second >= n_expert_) continue; + const size_t i = (size_t) pr.first * (size_t) n_expert_ + (size_t) pr.second; + if (offsets[i] == kNoComplement || ranked[i] != kNoComplement) continue; // on a GPU, or twice + const uint64_t b = layer_blob_bytes_[(size_t) pr.first]; + if (b > budget_bytes - at) continue; + ranked[i] = at; + at += b; + ++held; + } + std::fprintf(stderr, "FileExpertSource: RAM budget %.2f GiB: %lld of the %.2f GiB of experts the GPU cache does " + "not hold, by profile rank; the rest are read from the files\n", + (double) budget_bytes / 1073741824.0, (long long) held, (double) bytes / 1073741824.0); + offsets.swap(ranked); + bytes = at; + lend_from_slot = -1; + } const bool lend = lend_from_slot >= 0 && lend_from_slot < n_slots && additional_gpu_pairs.empty(); uint64_t budget = std::numeric_limits::max(); @@ -663,15 +933,15 @@ bool FileExpertSource::pin_cache_complement( const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; const uint64_t offset = offsets[index]; if (offset == kNoComplement) continue; - const uint8_t* source = mapped_blob(layer, expert); - if (source == nullptr || offset > bytes || blob_bytes > bytes - offset) { + if (offset > bytes || blob_bytes > bytes - offset || + !copy_from_files(layer, expert, (uint8_t*) host + (size_t) offset)) { fail("FileExpertSource: invalid blob bounds while building the cache complement"); return; } - std::memcpy((uint8_t*) host + (size_t) offset, source, (size_t) blob_bytes); copied.fetch_add(blob_bytes); } #if !defined(_WIN32) + if (role_ptr_.empty()) { // experts.bin; the GGUF in place leaves its pages to the OS const uint64_t layer_offset = layer_offsets_[(size_t) layer]; const uint64_t layer_bytes = blob_bytes * (uint64_t) n_expert_; const uint64_t layer_end = layer_offset + layer_bytes; @@ -689,6 +959,7 @@ bool FileExpertSource::pin_cache_complement( fail("FileExpertSource: posix_fadvise could not release expert layer " + std::to_string(layer)); return; } + } #endif const int64_t done = layers_done.fetch_add(1) + 1; if (done % 8 == 0 || done == n_layers_) @@ -712,7 +983,8 @@ bool FileExpertSource::pin_cache_complement( #if defined(_WIN32) // The mapped pages this process touched (the GPU cache's fill and this copy) leave its working set for the // standby list: VirtualUnlock on pages that are not locked does exactly that (it then reports ERROR_NOT_LOCKED). - (void) VirtualUnlock((LPVOID) base_, (SIZE_T) mapped_bytes_); + if (maps_.empty()) (void) VirtualUnlock((LPVOID) base_, (SIZE_T) mapped_bytes_); + for (const Map& m : maps_) (void) VirtualUnlock((LPVOID) m.base, (SIZE_T) m.bytes); #endif complement_arena_ = arena; @@ -814,15 +1086,28 @@ int64_t FileExpertSource::commit_exchanges() { const uint8_t* FileExpertSource::blob(int64_t layer, int64_t expert) { if (base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return nullptr; const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; - const uint8_t* mapped_fallback = mapped_blob(layer, expert); - const uint8_t* result = mapped_fallback; + const uint8_t* result = nullptr; + bool from_files = true; if (complement_ready_) { result = detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr); - if (result == nullptr) { - result = !override_.empty() && override_[index] != nullptr ? override_[index] : mapped_fallback; - if (result == mapped_fallback && result != nullptr) file_reads_.fetch_add(1, std::memory_order_relaxed); + if (result != nullptr) { + ram_reads_.fetch_add(1, std::memory_order_relaxed); + from_files = false; + } else if (!override_.empty() && override_[index] != nullptr) { + result = override_[index]; + from_files = false; } } + if (from_files) { + if (!role_ptr_.empty()) { + result = staged_blob(layer, expert); // counts its bytes + } else { + result = mapped_blob(layer, expert); + if (result != nullptr) + file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed); + } + if (complement_ready_ && result != nullptr) file_reads_.fetch_add(1, std::memory_order_relaxed); + } if (result != nullptr) ++reads_; return result; } diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 116094ad..28981d12 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -138,7 +138,9 @@ struct Stager { // D-5: the pinned ring's depth (STRATA_STAGER_RING, default 16) - how far the host copies can run ahead of the // DMAs of the unpinned experts' blobs int kRing = 16; - struct Job { const uint8_t* src; size_t bytes; }; + // `from` set: the blob is copied by the source itself (CS-T: a GGUF read in place assembles it from its three + // role slices; a pointer to it would not live as long as the queue) + struct Job { const uint8_t* src; size_t bytes; core::ExpertSource* from = nullptr; int32_t l = 0, e = 0; }; std::vector buf; std::vector pinned; std::vector> pageable; // the fallback when no more RAM can be pinned @@ -205,7 +207,12 @@ struct Stager { while (issued.load(std::memory_order_acquire) <= j - kRing) std::this_thread::yield(); cudaEventSynchronize(dma_done[b]); } - std::memcpy(buf[b], jobs[(size_t) j].src, jobs[(size_t) j].bytes); + const Job& jb = jobs[(size_t) j]; + if (jb.from == nullptr) std::memcpy(buf[b], jb.src, jb.bytes); + else if (!jb.from->copy_blob(jb.l, jb.e, buf[b])) { + std::fprintf(stderr, "prefill: the expert source could not copy expert %d of layer %d\n", jb.e, jb.l); + std::abort(); + } ready[(size_t) j].store(1, std::memory_order_release); active.fetch_sub(1, std::memory_order_acq_rel); } @@ -1095,12 +1102,18 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e seq_start[(size_t) l] = seq.size(); for (int32_t e = 0; e < m.g->n_expert; ++e) { if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue; - const uint8_t* b = m.src->blob(l, e); - if (!b) { err = "prefill: expert source has no blob"; return false; } int job = -1; - if (!m.src->pinned(l, e)) { + const uint8_t* b = nullptr; + if (m.src->transient(l, e)) { // CS-T: copied by the source into the stager's buffer job = (int) js.size(); - js.push_back({b, (size_t) lay0.blob_bytes(l)}); + js.push_back({nullptr, (size_t) lay0.blob_bytes(l), m.src, (int32_t) l, e}); + } else { + b = m.src->blob(l, e); + if (!b) { err = "prefill: expert source has no blob"; return false; } + if (!m.src->pinned(l, e)) { + job = (int) js.size(); + js.push_back({b, (size_t) lay0.blob_bytes(l)}); + } } seq.push_back({(int32_t) l, e, b, job}); } @@ -1585,9 +1598,13 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e const int32_t e = order[j]; if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue; if (m.src->pinned(l, e)) continue; + job_of[j] = (int) js.size(); + if (m.src->transient(l, e)) { // CS-T: copied by the source + js.push_back({nullptr, (size_t) lay.blob_bytes(l), m.src, (int32_t) l, e}); + continue; + } const uint8_t* b = m.src->blob(l, e); if (!b) { err = "prefill: expert source has no blob"; return false; } - job_of[j] = (int) js.size(); js.push_back({b, (size_t) lay.blob_bytes(l)}); } m.stager->start(std::move(js)); @@ -1600,9 +1617,10 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e const int sl = stage_next; stage_next = (stage_next + 1) % STAGE; const auto th = Clock::now(); - const uint8_t* b = m.src->blob(l, e); - if (!b) { err = "prefill: expert source has no blob"; return false; } - if (m.src->pinned(l, e)) { + const bool pinned = m.src->pinned(l, e); // pinned: never transient + const uint8_t* b = pinned ? m.src->blob(l, e) : nullptr; + if (pinned && !b) { err = "prefill: expert source has no blob"; return false; } + if (pinned) { // DMA straight from the page-locked arena: the copy stream only waits for the slot if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0); cudaMemcpyAsync(m.stage_dev[sl], b, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 9b89f5f7..6b927744 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -251,6 +251,10 @@ struct Options { bool resident_pin = false; uint64_t resident_headroom = 8ull << 30; bool resident_soft = false; + /// CS-T `--resident-budget-gib N`: the resident mode with a RAM budget - the N GiB of experts the GPU cache does + /// not hold that the expert profile ranks hottest are copied into RAM, the rest are read from the files in place + /// (the GGUF shards when the pack has no experts.bin). 0 = the whole complement (--resident-experts). + uint64_t resident_budget = 0; /// R4: slots of VRAM-resident experts. **0 = off, and off is the default.** /// **THE COMMENT THAT USED TO BE HERE WAS FALSE AND ROUND 328 MEASURED IT.** It said "the cache has no /// consumer yet - `moe_hit_grouped_s2` does not exist - so switching it on costs the fill traffic and @@ -1155,6 +1159,17 @@ int main(int argc, char** argv) { if (const char* v = std::getenv("STRATA_RESIDENT_HEADROOM_GIB"); v != nullptr && std::atof(v) >= 0.0) o.resident_headroom = (uint64_t) (std::atof(v) * 1073741824.0); } + else if (a == "--resident-budget-gib") { + const double gib = std::atof(next("--resident-budget-gib")); + if (!(gib > 0.0)) { std::fprintf(stderr, "strata generate: --resident-budget-gib needs N > 0\n"); return 2; } + o.resident_budget = (uint64_t) (gib * 1073741824.0); + o.mmap_experts = o.resident_cpu_experts = o.resident_pin = true; + o.resident_headroom = 4ull << 30; + if (const char* v = std::getenv("STRATA_RESIDENT_PIN"); v != nullptr && std::string(v) == "0") + o.resident_pin = false; + if (const char* v = std::getenv("STRATA_RESIDENT_HEADROOM_GIB"); v != nullptr && std::atof(v) >= 0.0) + o.resident_headroom = (uint64_t) (std::atof(v) * 1073741824.0); + } else if (a == "--stats") o.stats = true; else if (a == "--shared-late") o.shared_late = true; else if (a == "--keep-canonical") o.keep_canonical = true; @@ -2302,17 +2317,15 @@ int main(int argc, char** argv) { // built with `tools/iq_pack.py --experts-bin` (the per-layer blob sizes of its layout, PR #121). The low-RAM // mode: the experts come from the file through the OS cache instead of a pinned copy in RAM, for a PC whose // GPU holds most of them but whose RAM cannot hold them all. - if (native_pack && !std::filesystem::exists(std::filesystem::path(o.pack) / "experts.bin")) { - std::fprintf(stderr, "strata generate: --mmap-experts needs the pack's experts.bin; %s is a native (IQ) pack " - "built without it: python tools/iq_pack.py --gguf --out %s --experts-bin\n", - o.pack.c_str(), o.pack.c_str()); - return 2; - } + // CS-T: a native pack without experts.bin maps the model's GGUF shards instead (native_experts.txt's spans, + // checked against the files first) - no 30-77 GB copy of the experts on the disk + src.set_gguf(o.native_preset); if (!src.open(o.pack, g.n_layers, g.n_expert, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } - std::fprintf(stderr, "strata generate: experts via mmap (--mmap-experts; the A/B arm of R2.1)\n"); + std::fprintf(stderr, "strata generate: experts via mmap (--mmap-experts; %s)\n", + src.gguf_mode() ? "the GGUF shards in place, no experts.bin" : "the A/B arm of R2.1"); srcp = &src; } else { arena_src.set_gguf(o.native_preset); // plan v0.3 P6: a native pack may take its experts from shard 1 @@ -3453,7 +3466,8 @@ int main(int argc, char** argv) { const int64_t k = plan_lend(chunk); if (k > 0) lend_from = xcache.slots() - k; } - if (src.pin_cache_complement(xcache, err, o.resident_pin, {}, lend_from, o.resident_headroom)) { + if (src.pin_cache_complement(xcache, err, o.resident_pin, {}, lend_from, o.resident_headroom, + o.resident_budget, &profile)) { if (o.adapt_every > 0 && o.adapt_swaps > 0 && !src.reserve_exchanges(std::min(o.adapt_swaps, 96), err)) { std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str()); @@ -4766,6 +4780,9 @@ int main(int argc, char** argv) { double dt_run = 0, dt_commit = 0, dt_draft = 0; int64_t dec_windows = 0, dec_T = 0; const int64_t decode_hits0 = drive.d.cache_hits; + // CS-T: the RAM and file tiers of this request (the mmap source; 0 with the arena) + const int64_t ram0 = src.ram_reads(), files0 = src.file_reads(); + const uint64_t file_bytes0 = src.file_read_bytes(); const int64_t decode_look0 = drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused; if (cancelled) finish = "cancel"; while (!cancelled && produced_n < max_new) { @@ -5007,9 +5024,12 @@ int main(int argc, char** argv) { const int64_t req_hits = drive.d.cache_hits - decode_hits0; const int64_t req_look = (drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused) - decode_look0; // DONE [hits] [lookups] - std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld\n", (long long) produced_n, (long long) n, prompt_ms, - decode_ms, finish, (long long) draft_accepted, (long long) draft_offered, (long long) resume, - (long long) req_hits, (long long) req_look); + // [RAM blobs] [file blobs] [file MB] (CS-T tiers; appended, so an older server reads the rest) + std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f\n", (long long) produced_n, + (long long) n, prompt_ms, decode_ms, finish, (long long) draft_accepted, (long long) draft_offered, + (long long) resume, (long long) req_hits, (long long) req_look, + (long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0), + (double) (src.file_read_bytes() - file_bytes0) / 1e6); std::fflush(stdout); if (drive.routing != nullptr) std::fflush(drive.routing); // the routing trace survives a crash and is watchable mid-session const int64_t fresh = n - resume; @@ -5033,6 +5053,12 @@ int main(int argc, char** argv) { "VRAM tier, %lld blob reads from the file\n", (double) src.resident_bytes() / 1073741824.0, (long long) src.exchanges(), (long long) src.file_reads()); + // CS-T: the tiers, cumulative - GPU cache hits (the decode lookups above), RAM copy, files (SSD / OS cache) + if (srcp == &src) + std::fprintf(stderr, "strata serve: expert tiers: GPU %lld hits this request; since the start RAM %lld blobs, files %lld blobs " + "%.1f MB read%s\n", (long long) req_hits, (long long) src.ram_reads(), + (long long) src.file_reads(), (double) src.file_read_bytes() / 1e6, + src.gguf_mode() ? " (the GGUF in place)" : ""); // STRATA_SPLIT_TIMING: where each verify stage's host time went, cumulative per window since the start // (waiting for its GPU to ring a layer, the CPU pool and plan per layer, staging the window) if (static const bool st_timing = std::getenv("STRATA_SPLIT_TIMING") != nullptr; st_timing) @@ -5690,6 +5716,12 @@ int main(int argc, char** argv) { std::printf("%-24s %.2f GiB of experts in RAM, %lld exchanged with the VRAM tier, %lld blob reads from " "the file\n", "resident RAM", (double) src.resident_bytes() / 1073741824.0, (long long) src.exchanges(), (long long) src.file_reads()); + if (srcp == &src) // CS-T: the RAM and file tiers (the GPU cache's share is the hit rate above) + std::printf("%-24s RAM %lld blobs, files %lld blobs, %.1f MB read from the files (%.2f MB/round)%s\n", + "expert tiers", (long long) src.ram_reads(), (long long) src.file_reads(), + (double) src.file_read_bytes() / 1e6, + rounds > 0 ? (double) src.file_read_bytes() / 1e6 / rounds : 0.0, + src.gguf_mode() ? " (the GGUF in place)" : ""); if (rounds > 0 && drive.d.pcie_num > 0) std::printf("%-24s %.2f distinct experts per layer read over PCIe (share %d/256 of the misses)\n", "pcie experts", (double) (drive.d.pcie_experts - pcie0) / (double) (rounds * g.n_layers), diff --git a/tests/core/expert_layout_test.cpp b/tests/core/expert_layout_test.cpp index f69e5c55..a28ba2c7 100644 --- a/tests/core/expert_layout_test.cpp +++ b/tests/core/expert_layout_test.cpp @@ -18,7 +18,9 @@ #include "strata/kernels/cpu/expert_layout.hpp" #include "strata/kernels/cpu/native_expert.hpp" +#include #include +#include #include #include #include @@ -206,6 +208,57 @@ void arena() { } check(exact, "every blob is [gate | up | down] of its expert, layer 1 from both files"); + { // CS-T: the same blobs from FileExpertSource reading the shards in place (no experts.bin in the pack) + strata::core::FileExpertSource fs; + fs.set_gguf(A.string()); + std::string e1; + const bool opened = fs.open(pack.string(), 2, NE, e1); + check(opened && fs.gguf_mode(), "FileExpertSource opens the GGUF in place" + (opened ? "" : ": " + e1)); + if (opened) { + bool same = true, copies = true, transient = true; + std::vector buf((size_t) std::max(f0.bytes, f1.bytes)); + for (int64_t l = 0; l < 2; ++l) + for (int64_t e = 0; e < NE; ++e) { + fs.begin_layer(l, nullptr, 0); + const uint8_t* b = fs.blob(l, e); + const size_t n = (size_t) L.blob_bytes(l); + same = same && b != nullptr && std::memcmp(b, dst.data() + L.blob_offset(l, e), n) == 0; + copies = copies && fs.copy_blob(l, e, buf.data()) && + std::memcmp(buf.data(), dst.data() + L.blob_offset(l, e), n) == 0; + transient = transient && fs.transient(l, e); + } + check(same && copies && transient, "blob() and copy_blob() equal the loaded arena byte for byte (transient)"); + // a blob asked again in the same layer is the same buffer; its bytes hold through two more layers + fs.begin_layer(0, nullptr, 0); + const uint8_t* p = fs.blob(0, 1); + const uint8_t* q = fs.blob(0, 1); + fs.begin_layer(1, nullptr, 0); + (void) fs.blob(1, 0); + (void) fs.blob(1, 1); + fs.begin_layer(0, nullptr, 0); + (void) fs.blob(0, 0); + check(p == q && std::memcmp(p, dst.data() + L.blob_offset(0, 1), (size_t) L.blob_bytes(0)) == 0, + "an assembled blob stays put while it is in use"); + check(fs.file_read_bytes() > 0, "the file tier counts its bytes (" + std::to_string(fs.file_read_bytes()) + ")"); + } + fs.close(); + // with experts.bin present, the pack's file is mapped as before, whatever set_gguf says + { + std::ofstream eb(pack / "experts.bin", std::ios::binary); + eb.write((const char*) dst.data(), (std::streamsize) dst.size()); + } + strata::core::FileExpertSource fb; + fb.set_gguf(A.string()); + std::string e2; + const bool ob = fb.open(pack.string(), 2, NE, e2); + const uint8_t* b11 = ob ? fb.blob(1, 1) : nullptr; + check(ob && !fb.gguf_mode() && !fb.transient(1, 1) && b11 != nullptr && + std::memcmp(b11, dst.data() + L.blob_offset(1, 1), (size_t) L.blob_bytes(1)) == 0, + "with experts.bin the mapped file is used (unchanged behaviour)"); + fb.close(); + fs::remove(pack / "experts.bin"); + } + auto refused = [&](const std::string& what, const std::string& needle) { std::string e2; const bool bad = load(pack, 2, 512, e2) && !strata::core::check_experts_gguf(A.string(), From 003ec6214044202e419a2dd8aab59d848b92e1cd Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 1 Oct 2026 00:51:30 +0200 Subject: [PATCH 7/7] CS-T speed: the file tier fetched in parallel, PCIe planning without file reads, a partial pin of the RAM tier, bit-exact AVX2 multi-token kernels for Q4_K / Q5_1 / Q8_0 experts, decode-only tier stats Where the 288 ms/token at a 40 GiB budget went (UD-Q4_K_XL, --stats): of the 945 ms CPU pool call per verify round (3.46 tokens), 871 ms were the dispatch thread assembling missed experts from the mapped GGUF one after another (~391 blobs, 1.3 GB per round, ~1.5 GB/s: page faults from the SSD); the kernels were 42 ms gate/up and 30 ms down. At 24 GiB, 771 ms/round more went into the PCIe planning, which asked blob() - a file read with the GGUF in place - of every miss just to learn it was not pinned. - ExpertSource::prefetch: the dispatch hands the source the layer's missed experts before its jobs loop; FileExpertSource with the GGUF in place assembles them on STRATA_FETCH_THREADS threads (default 8) so the SSD sees a queue instead of one fault at a time. A no-op for every other source. Staging buffers being filled are never reused, and a blob asked while its fill runs waits for it. - The PCIe planning asks pinned() before blob(): the same decisions and bytes for every source. - --resident-budget-gib: when the driver refuses to page-lock the whole budget, the locked arena's hottest prefix (profile order) is registered with cudaHostRegister, as much as it takes (from the whole down in 2 GiB steps), so the GPU can read those misses over PCIe and the prompt path can DMA them; pinned() answers for that prefix only. STRATA_PARTIAL_PIN=0 is the A/B arm. - src/kernels/cpu/kq_avx2.cpp: ggml-cpu's AVX2 vec_dot for Q4_K x Q8_K, Q5_1 x Q8_1 and Q8_0 x Q8_0 with the token loop inside the block loop - the weight side decoded once per verify window, each token's integer chain and float operations exactly ggml's, so the results are ggml's to the bit for any group size (no #152 rule). native_gu_rows / native_down_rows use them for those types (only UD-Q4_K_XL has them); STRATA_NO_KQ256 is the A/B arm. native_expert_parity checks them bit for bit against vec_dot for 1..8 tokens and times 4 tokens. - Stats: the decode's file tier alone (blobs, MB, MB/round, reading ms/round and GB/s per thread) and the prompt path's copies separately. --- CMakeLists.txt | 4 +- include/strata/core/expert_source.hpp | 22 ++- include/strata/kernels/cpu/kq_avx2.hpp | 20 +++ src/core/expert_source.cpp | 174 ++++++++++++++++--- src/kernels/cpu/kq_avx2.cpp | 230 +++++++++++++++++++++++++ src/kernels/cpu/native_expert.cpp | 13 ++ src/kernels/native_expert_parity.cpp | 48 ++++++ src/program/generate.cpp | 21 ++- tests/core/expert_layout_test.cpp | 18 ++ 9 files changed, 522 insertions(+), 28 deletions(-) create mode 100644 include/strata/kernels/cpu/kq_avx2.hpp create mode 100644 src/kernels/cpu/kq_avx2.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index f2911175..1ed9887d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -781,15 +781,17 @@ if(STRATA_NATIVE_EXPERTS) # part of strata_kernels_cpu (the pool calls these and they call its CPU probe: one library, so GNU ld's # one-pass static linking has no cycle to resolve) target_sources(strata_kernels_cpu PRIVATE src/kernels/cpu/native_expert.cpp src/kernels/cpu/iq_avx512.cpp - src/kernels/cpu/iq_avx2.cpp) + src/kernels/cpu/iq_avx2.cpp src/kernels/cpu/kq_avx2.cpp) target_include_directories(strata_kernels_cpu PRIVATE third_party/ggml) if(MSVC) set_source_files_properties(src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512") set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") + set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") else() set_source_files_properties(src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma") set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") + set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") endif() target_link_libraries(strata_kernels_cpu PUBLIC ggml-cpu ggml-base) target_compile_definitions(strata_kernels_cpu PUBLIC STRATA_NATIVE_EXPERTS=1) diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 6a1668bb..485733b2 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -132,6 +133,9 @@ public: /// The blob's bytes into `dst` (blob_bytes(layer) of them). Safe from several threads for a source whose /// `transient` can be true. virtual bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst); + /// The `n` experts of `layer` the CPU is about to ask `blob` for, all at once: a source that reads a file may + /// fetch them in parallel. The bytes `blob` then returns are the same. Default: nothing. + virtual void prefetch(int64_t layer, const int64_t* experts, int64_t n) { (void) layer; (void) experts; (void) n; } }; /// Plan v0.3 P6: what the GPU computes in a verify window's layer, written by the pool (mapped host memory) right @@ -381,7 +385,7 @@ public: bool mapped() const { return base_ != nullptr; } int64_t blobs() const { return blobs_; } - uint64_t pinned_bytes() const { return complement_pinned_ ? complement_bytes_ : 0; } + uint64_t pinned_bytes() const { return complement_pinned_ ? complement_pin_limit_ : 0; } uint64_t resident_bytes() const { return complement_bytes_; } bool complement_pinned() const { return complement_pinned_; } bool complement_ready() const { return complement_ready_; } @@ -412,6 +416,12 @@ public: /// `file_reads` counts, plus the prompt path's copies of them). int64_t ram_reads() const { return ram_reads_.load(std::memory_order_relaxed); } uint64_t file_read_bytes() const { return file_read_bytes_.load(std::memory_order_relaxed); } + /// Of those, the bytes `blob` read (decode windows, adaptive swaps; the rest are the prompt path's copies), and + /// the time spent reading the files, summed over threads. + uint64_t file_blob_bytes() const { return file_blob_bytes_.load(std::memory_order_relaxed); } + double file_ms() const { return (double) file_us_.load(std::memory_order_relaxed) / 1000.0; } + /// Threads `prefetch` reads the GGUF with (STRATA_FETCH_THREADS, default 8). + void set_fetch_threads(int n) { fetch_threads_ = n < 1 ? 1 : n; } const uint8_t* blob(int64_t layer, int64_t expert) override; bool pinned(int64_t layer, int64_t expert) const override; @@ -421,6 +431,8 @@ public: bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst) override; /// CS-T: advances the assembled blobs' age (see staged_blob). void begin_layer(int64_t layer, const int32_t* ids, int64_t k) override; + /// CS-T: the GGUF in place assembles the missed experts on `fetch_threads_` threads. + void prefetch(int64_t layer, const int64_t* experts, int64_t n) override; /// Blobs touched, for the driver to report. With `h = 0` this is `48 * k` per token and the number is only /// interesting once Phase 3 makes it not so. @@ -432,6 +444,8 @@ private: bool copy_from_files(int64_t layer, int64_t expert, uint8_t* dst) const; bool open_gguf(std::string& err); const uint8_t* staged_blob(int64_t layer, int64_t expert); + bool claim_stage(int64_t key, size_t& v, bool& fill); + bool fill_stage(size_t v, int64_t layer, int64_t expert, uint8_t* dst); static constexpr uint64_t kNoComplement = detail::kNoCacheComplement; // ---- CS-T: the GGUF shards in place std::string gguf_; @@ -456,6 +470,10 @@ private: std::vector> stage_buf_; std::vector stage_key_; std::vector stage_epoch_, stage_used_; + std::vector stage_busy_; ///< being filled (outside stage_mu_): never a victim + std::condition_variable stage_cv_; + int fetch_threads_ = 8; + std::atomic file_blob_bytes_{0}, file_us_{0}; std::unordered_map stage_of_; uint64_t stage_blob_ = 0; uint64_t stage_seq_ = 0; @@ -476,6 +494,8 @@ private: uint64_t complement_bytes_ = 0; std::vector complement_offsets_; bool complement_pinned_ = false; + bool complement_partial_ = false; ///< CS-T: only the first complement_pin_limit_ bytes are registered + uint64_t complement_pin_limit_ = 0; bool complement_ready_ = false; uint64_t complement_locked_ = 0; ///< bytes held in the working set (pin refused) int64_t complement_lent_slots_ = 0; diff --git a/include/strata/kernels/cpu/kq_avx2.hpp b/include/strata/kernels/cpu/kq_avx2.hpp new file mode 100644 index 00000000..0b307404 --- /dev/null +++ b/include/strata/kernels/cpu/kq_avx2.hpp @@ -0,0 +1,20 @@ +// include/strata/kernels/cpu/kq_avx2.hpp - AVX-2 multi-token dot products for Unsloth UD-Q4_K_XL's expert formats +// (Q4_K gate/up against Q8_K activations; Q5_1 down against Q8_1, Q8_0 down against Q8_0), bit-exact against +// ggml-cpu's AVX2 vec_dot for every token. See src/kernels/cpu/kq_avx2.cpp. +#pragma once + +#include +#include + +namespace strata::kernels::cpu { + +/// Q4_K (12), Q5_1 (7), Q8_0 (8). +bool kq256_supported(int ggml_type) noexcept; +/// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]), rows [r0, r1); gate rows at blob, up rows at blob + up_off. +void kq256_gu_rows(int ggml_type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, + int nt, float* const* ff, int r0, int r1); +/// out[t][r] = w_r . a[t], rows [r0, r1). +void kq256_rows(int ggml_type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, + float* const* out, int r0, int r1); + +} // namespace strata::kernels::cpu diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index 8d0ab32f..e4fccea8 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -448,8 +448,9 @@ bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64 void FileExpertSource::close() { if (complement_arena_ != nullptr) { - if (complement_pinned_) (void) cudaFreeHost(complement_arena_); + if (complement_pinned_ && !complement_partial_) (void) cudaFreeHost(complement_arena_); else { + if (complement_partial_) (void) cudaHostUnregister(complement_arena_); if (complement_locked_ > 0) strata::platform::unlock_resident(complement_arena_, complement_locked_); std::free(complement_arena_); } @@ -472,6 +473,8 @@ void FileExpertSource::close() { complement_bytes_ = 0; complement_offsets_.clear(); complement_pinned_ = false; + complement_partial_ = false; + complement_pin_limit_ = 0; complement_ready_ = false; complement_locked_ = 0; complement_lent_slots_ = 0; @@ -497,6 +500,7 @@ void FileExpertSource::close() { stage_key_.clear(); stage_epoch_.clear(); stage_used_.clear(); + stage_busy_.clear(); stage_of_.clear(); stage_blob_ = 0; stage_seq_ = 0; @@ -506,6 +510,8 @@ void FileExpertSource::close() { } ram_reads_.store(0); file_read_bytes_.store(0); + file_blob_bytes_.store(0); + file_us_.store(0); #if defined(_WIN32) if (base_ != nullptr) UnmapViewOfFile((LPCVOID) base_); if (mapping_ != nullptr) CloseHandle((HANDLE) mapping_); @@ -636,32 +642,37 @@ bool FileExpertSource::copy_from_files(int64_t layer, int64_t expert, uint8_t* d // A blob assembled from the three role slices. The buffer of a (layer, expert) is reused for another only once // its blob has not been asked for during `kStageAge` layers (begin_layer) or 256 assemblies, whichever comes -// first: the pool computes a layer's misses before it starts the next, and a fill (the GPU cache at startup, an -// adaptive swap, a helper GPU) copies the blob right away. -const uint8_t* FileExpertSource::staged_blob(int64_t layer, int64_t expert) { +// first, and never while it is being filled: the pool computes a layer's misses before it starts the next, and a +// fill (the GPU cache at startup, an adaptive swap, a helper GPU) copies the blob right away. +// +// `claim_stage` finds or reserves the buffer of `key` (stage_mu_ held): true when the blob is already there (or +// being filled by another thread - the caller then waits), false when the caller must fill buffer `v`. +bool FileExpertSource::claim_stage(int64_t key, size_t& v, bool& fill) { constexpr uint64_t kStageSeq = 256; - const int64_t key = layer * n_expert_ + expert; - std::lock_guard lk(stage_mu_); const uint64_t seq = ++stage_seq_; auto it = stage_of_.find(key); + fill = false; if (it != stage_of_.end()) { - stage_epoch_[it->second] = epoch_; - stage_used_[it->second] = seq; - return stage_buf_[it->second].get(); + v = it->second; + stage_epoch_[v] = epoch_; + stage_used_[v] = seq; + return true; } - size_t v = stage_buf_.size(); + v = stage_buf_.size(); uint64_t oldest = std::numeric_limits::max(); for (size_t i = 0; i < stage_buf_.size(); ++i) - if ((stage_epoch_[i] + kStageAge <= epoch_ || stage_used_[i] + kStageSeq <= seq) && stage_used_[i] < oldest) { + if (!stage_busy_[i] && (stage_epoch_[i] + kStageAge <= epoch_ || stage_used_[i] + kStageSeq <= seq) && + stage_used_[i] < oldest) { oldest = stage_used_[i]; v = i; } if (v == stage_buf_.size()) { stage_buf_.emplace_back(new (std::nothrow) uint8_t[(size_t) stage_blob_]); - if (!stage_buf_.back()) { stage_buf_.pop_back(); return nullptr; } + if (!stage_buf_.back()) { stage_buf_.pop_back(); return false; } stage_key_.push_back(-1); stage_epoch_.push_back(0); stage_used_.push_back(0); + stage_busy_.push_back(0); if (stage_buf_.size() == 512 && !stage_grew_) { stage_grew_ = true; std::fprintf(stderr, "FileExpertSource: %zu blobs assembled from the GGUF are in use at once (%.2f GiB)\n", @@ -670,14 +681,87 @@ const uint8_t* FileExpertSource::staged_blob(int64_t layer, int64_t expert) { } else { stage_of_.erase(stage_key_[v]); } - uint8_t* dst = stage_buf_[v].get(); - if (!copy_from_files(layer, expert, dst)) { stage_key_[v] = -1; return nullptr; } - file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed); stage_key_[v] = key; stage_epoch_[v] = epoch_; stage_used_[v] = seq; + stage_busy_[v] = 1; stage_of_[key] = v; - return dst; + fill = true; + return false; +} + +// Fills buffer `v` (reserved by claim_stage) outside the lock, then publishes it. +bool FileExpertSource::fill_stage(size_t v, int64_t layer, int64_t expert, uint8_t* dst) { + const auto t0 = std::chrono::steady_clock::now(); + const bool ok = copy_from_files(layer, expert, dst); + const double us = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + file_us_.fetch_add((uint64_t) us, std::memory_order_relaxed); + if (ok) { + file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed); + file_blob_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed); + } + { + std::lock_guard lk(stage_mu_); + stage_busy_[v] = 0; + if (!ok) { + stage_of_.erase(stage_key_[v]); + stage_key_[v] = -1; + } + } + stage_cv_.notify_all(); + return ok; +} + +const uint8_t* FileExpertSource::staged_blob(int64_t layer, int64_t expert) { + const int64_t key = layer * n_expert_ + expert; + size_t v = 0; + bool fill = false; + uint8_t* dst = nullptr; + { + std::unique_lock lk(stage_mu_); + const bool have = claim_stage(key, v, fill); + if (!have && !fill) return nullptr; + dst = stage_buf_[v].get(); + if (have) { + // another thread (a prefetch, the adaptive tier) is filling it: wait for that + stage_cv_.wait(lk, [&] { return !stage_busy_[v] || stage_key_[v] != key; }); + if (stage_key_[v] != key) return nullptr; // its fill failed + return dst; + } + } + return fill_stage(v, layer, expert, dst) ? dst : nullptr; +} + +void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n) { + if (role_ptr_.empty() || n <= 0 || layer < 0 || layer >= n_layers_) return; + struct Fill { size_t v; int64_t e; uint8_t* dst; }; + std::vector todo; + { + std::lock_guard lk(stage_mu_); + for (int64_t i = 0; i < n; ++i) { + const int64_t e = experts[i]; + if (e < 0 || e >= n_expert_) continue; + const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e; + if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement) + continue; // in the RAM copy + if (!override_.empty() && override_[index] != nullptr) continue; + size_t v = 0; + bool fill = false; + if (!claim_stage(layer * n_expert_ + e, v, fill) && fill) todo.push_back({v, e, stage_buf_[v].get()}); + } + } + if (todo.empty()) return; + // the page faults of a mapped read are one outstanding request each: several threads keep the SSD's queue full + std::atomic next{0}; + auto work = [&] { + for (size_t i; (i = next.fetch_add(1)) < todo.size();) + (void) fill_stage(todo[i].v, layer, todo[i].e, todo[i].dst); + }; + const size_t nt = std::min(todo.size(), (size_t) fetch_threads_); + std::vector th; + for (size_t t = 1; t < nt; ++t) th.emplace_back(work); + work(); + for (auto& t : th) t.join(); } void FileExpertSource::begin_layer(int64_t layer, const int32_t* ids, int64_t k) { @@ -713,7 +797,10 @@ bool FileExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) { return true; } } + const auto t0 = std::chrono::steady_clock::now(); if (!copy_from_files(layer, expert, dst)) return false; + file_us_.fetch_add((uint64_t) std::chrono::duration(std::chrono::steady_clock::now() - t0).count(), + std::memory_order_relaxed); file_read_bytes_.fetch_add(bytes, std::memory_order_relaxed); return true; } @@ -852,11 +939,13 @@ bool FileExpertSource::pin_cache_complement( const uint8_t* device = nullptr; bool pinned_ok = false; uint64_t locked = 0; + uint64_t partial_pin = 0; ///< CS-T: a registered prefix of a locked arena std::string note; auto release = [&]() { if (arena == nullptr) return; if (pinned_ok) (void) cudaFreeHost(arena); else { + if (partial_pin > 0) (void) cudaHostUnregister(arena); if (locked > 0) strata::platform::unlock_resident(arena, locked); std::free(arena); } @@ -900,6 +989,37 @@ bool FileExpertSource::pin_cache_complement( const strata::platform::LockResult lr = strata::platform::lock_resident(arena, bytes); locked = lr.locked_bytes; note += (note.empty() ? "" : "; ") + lr.note; + // CS-T, a RAM budget: its bytes are in profile order, hottest first, so the driver is asked to + // register the largest prefix it takes (from the whole, down in 2 GiB steps). Those experts can be + // read by the GPU over PCIe (--pcie-frac) and copied by DMA; the rest stay locked-only. + static const bool partial_on = [] { + const char* v = std::getenv("STRATA_PARTIAL_PIN"); // 0: the A/B arm without it + return v == nullptr || std::atoi(v) != 0; + }(); + if (budget_bytes > 0 && partial_on) { + const uint64_t step = 2ull << 30; + for (uint64_t want = bytes; want >= step; want = want > step ? want - step : 0) { + const uint64_t w = want - want % (64ull << 10); + if (cudaHostRegister(arena, (size_t) w, cudaHostRegisterMapped | cudaHostRegisterPortable) == + cudaSuccess) { + void* alias = nullptr; + if (cudaHostGetDevicePointer(&alias, arena, 0) == cudaSuccess && alias != nullptr) { + device = (const uint8_t*) alias; + partial_pin = w; + } else { + (void) cudaGetLastError(); + (void) cudaHostUnregister(arena); + } + break; + } + (void) cudaGetLastError(); + if (want <= step) break; + } + char msg[160]; + std::snprintf(msg, sizeof msg, "%.2f GiB of it registered for the GPU (the hottest)", + (double) partial_pin / 1073741824.0); + note += std::string("; ") + msg; + } } } host = (const uint8_t*) arena; @@ -992,7 +1112,9 @@ bool FileExpertSource::pin_cache_complement( complement_device_ = device; complement_bytes_ = bytes; complement_offsets_ = std::move(offsets); - complement_pinned_ = pinned_ok && bytes > 0; + complement_pinned_ = (pinned_ok || partial_pin > 0) && bytes > 0; + complement_pin_limit_ = pinned_ok ? bytes : partial_pin; + complement_partial_ = !pinned_ok && partial_pin > 0; complement_locked_ = locked; complement_lent_slots_ = lend ? n_slots - keep_from : 0; complement_ready_ = true; @@ -1116,7 +1238,10 @@ bool FileExpertSource::pinned(int64_t layer, int64_t expert) const { if (!complement_ready_ || !complement_pinned_ || complement_host_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false; const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; - return index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement; + if (index >= complement_offsets_.size() || complement_offsets_[index] == kNoComplement) return false; + // a partial pin (CS-T): only the registered prefix + return !complement_partial_ || + complement_offsets_[index] + layer_blob_bytes_[(size_t) layer] <= complement_pin_limit_; } const uint8_t* FileExpertSource::device_alias(int64_t layer, int64_t expert) const { @@ -1332,8 +1457,8 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 : (size_t) slot * (size_t) d.cache_blob)); } else { if (miss_rank >= nmiss - m && fetches < P.staging_cap && fetches < 64) { - const uint8_t* src = d.src->blob(d.layers, e); - if (src != nullptr && d.src->pinned(d.layers, e)) { + const uint8_t* src = d.src->pinned(d.layers, e) ? d.src->blob(d.layers, e) : nullptr; + if (src != nullptr) { kd = 1; dma_src[fetches] = src; pcie_i0[fetches] = i0; @@ -1405,6 +1530,15 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 else for (int64_t t = 0; t < n_tok; ++t) act_quant_q8_1(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]); const auto c2 = std::chrono::steady_clock::now(); + { // CS-T: the experts the CPU computes, fetched together (the GGUF in place reads them on several threads) + static thread_local std::vector miss; + miss.clear(); + for (int64_t i = 0; i < n_tok * k; ++i) + if (kind[i] < 0 && ids[i] >= 0 && ids[i] < d.n_expert && + std::find(miss.begin(), miss.end(), (int64_t) ids[i]) == miss.end()) + miss.push_back(ids[i]); + d.src->prefetch(d.layers, miss.data(), (int64_t) miss.size()); + } int njobs = 0; for (int64_t t = 0; t < n_tok; ++t) for (int64_t j = 0; j < k; ++j) { diff --git a/src/kernels/cpu/kq_avx2.cpp b/src/kernels/cpu/kq_avx2.cpp new file mode 100644 index 00000000..8f08a2a8 --- /dev/null +++ b/src/kernels/cpu/kq_avx2.cpp @@ -0,0 +1,230 @@ +// src/kernels/cpu/kq_avx2.cpp - Unsloth UD-Q4_K_XL's expert rows (Q4_K gate/up, Q5_1 and Q8_0 down) for several +// tokens at once, BIT-EXACT against ggml-cpu's own dot products. +// +// ggml-cpu is built for AVX2 here (STRATA_PORTABLE: GGML_AVX2=ON, GGML_AVX512=OFF), so its vec_dot for these formats +// is the __AVX2__ branch of ggml-cpu/arch/x86/quants.c: ggml_vec_dot_q4_K_q8_K, ggml_vec_dot_q5_1_q8_1, +// ggml_vec_dot_q8_0_q8_0. The functions below are those branches with the loop over tokens moved inside the loop +// over blocks: everything that depends only on the weights (the 4-bit unpacking, the 6-bit scales and mins, the +// fifth bits, the absolute values of the Q8_0 weights, the fp16 scales) is done once per block, and every token then +// runs exactly ggml's integer chain and ggml's float operations in ggml's order - so each token's result is ggml's +// to the bit (native_expert_parity checks it), whatever the number of tokens. Unlike the i-quant kernels (#152) +// the group size therefore never changes an answer. +// +// The gain is the weight-side work and the weight bytes, read once per verify window instead of once per token. +#include "strata/kernels/cpu/kq_avx2.hpp" + +#define GGML_COMMON_DECL_CPP +#define GGML_COMMON_IMPL_CPP +#include "ggml-common.h" + +#include + +#include +#include + +namespace strata::kernels::cpu { +namespace { + +constexpr int MAXT = 8; // the verify window's tokens per group (kVerifyMaxT) + +inline float h2f(ggml_half h) { + uint16_t u; + std::memcpy(&u, &h, 2); + return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128((int) u))); +} +// the fp16 pair {d, dmin} / {d, m} / {d, s} a block starts with (a union in ggml-common.h's C++ declarations) +inline float half_at(const void* block, int i) { + ggml_half h; + std::memcpy(&h, (const uint8_t*) block + 2 * i, 2); + return h2f(h); +} + +// ---- ggml's helpers (ggml-cpu/arch/x86/quants.c, the AVX2 / non-VNNI forms), verbatim +inline float hsum_float_8(const __m256 x) { + __m128 res = _mm256_extractf128_ps(x, 1); + res = _mm_add_ps(res, _mm256_castps256_ps128(x)); + res = _mm_add_ps(res, _mm_movehl_ps(res, res)); + res = _mm_add_ss(res, _mm_movehdup_ps(res)); + return _mm_cvtss_f32(res); +} +inline __m256i bytes_from_bits_32(const uint8_t* x) { + uint32_t x32; + std::memcpy(&x32, x, sizeof(uint32_t)); + const __m256i shuf_mask = _mm256_set_epi64x(0x0303030303030303, 0x0202020202020202, 0x0101010101010101, + 0x0000000000000000); + __m256i bytes = _mm256_shuffle_epi8(_mm256_set1_epi32((int) x32), shuf_mask); + const __m256i bit_mask = _mm256_set1_epi64x(0x7fbfdfeff7fbfdfe); + bytes = _mm256_or_si256(bytes, bit_mask); + return _mm256_cmpeq_epi8(bytes, _mm256_set1_epi64x(-1)); +} +inline __m256i bytes_from_nibbles_32(const uint8_t* rsi) { + const __m128i tmp = _mm_loadu_si128((const __m128i*) rsi); + const __m256i bytes = _mm256_insertf128_si256(_mm256_castsi128_si256(tmp), _mm_srli_epi16(tmp, 4), 1); + const __m256i lowMask = _mm256_set1_epi8(0xF); + return _mm256_and_si256(lowMask, bytes); +} +inline __m256 sum_i16_pairs_float(const __m256i x) { + const __m256i ones = _mm256_set1_epi16(1); + return _mm256_cvtepi32_ps(_mm256_madd_epi16(ones, x)); +} +inline __m256 mul_sum_us8_pairs_float(const __m256i ax, const __m256i sy) { + return sum_i16_pairs_float(_mm256_maddubs_epi16(ax, sy)); +} +alignas(32) const uint8_t k_shuffle[256] = { + 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, + 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, + 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, + 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, + 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, + 10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11, + 12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13, + 14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15}; +inline __m256i get_scale_shuffle_k4(int i) { return _mm256_loadu_si256((const __m256i*) k_shuffle + i); } + +// ---- Q4_K x Q8_K (ggml_vec_dot_q4_K_q8_K, __AVX2__) +void q4k_dot(const block_q4_K* x, int nb, const void* const* act, int nt, float* res) { + static const uint32_t kmask1 = 0x3f3f3f3f, kmask2 = 0x0f0f0f0f, kmask3 = 0x03030303; + const __m256i m4 = _mm256_set1_epi8(0xF); + __m256 acc[MAXT]; + __m128 acc_m[MAXT]; + for (int t = 0; t < nt; ++t) { acc[t] = _mm256_setzero_ps(); acc_m[t] = _mm_setzero_ps(); } + for (int i = 0; i < nb; ++i) { + const float xd = half_at(&x[i], 0), xdmin = half_at(&x[i], 1); + uint32_t utmp[4]; + std::memcpy(utmp, x[i].scales, 12); + utmp[3] = ((utmp[2] >> 4) & kmask2) | (((utmp[1] >> 6) & kmask3) << 4); + const uint32_t uaux = utmp[1] & kmask1; + utmp[1] = (utmp[2] & kmask2) | (((utmp[0] >> 6) & kmask3) << 4); + utmp[2] = uaux; + utmp[0] &= kmask1; + const __m256i mins_and_scales = _mm256_cvtepu8_epi16(_mm_set_epi32((int) utmp[3], (int) utmp[2], + (int) utmp[1], (int) utmp[0])); + const __m128i mins = _mm256_extracti128_si256(mins_and_scales, 1); + const __m128i sc128 = _mm256_extracti128_si256(mins_and_scales, 0); + const __m256i scales = _mm256_insertf128_si256(_mm256_castsi128_si256(sc128), sc128, 1); + __m256i scale_l[4], scale_h[4], q4l[4], q4h[4]; + const uint8_t* q4 = x[i].qs; + for (int j = 0; j < QK_K / 64; ++j) { + scale_l[j] = _mm256_shuffle_epi8(scales, get_scale_shuffle_k4(2 * j + 0)); + scale_h[j] = _mm256_shuffle_epi8(scales, get_scale_shuffle_k4(2 * j + 1)); + const __m256i q4bits = _mm256_loadu_si256((const __m256i*) q4); + q4 += 32; + q4l[j] = _mm256_and_si256(q4bits, m4); + q4h[j] = _mm256_and_si256(_mm256_srli_epi16(q4bits, 4), m4); + } + for (int t = 0; t < nt; ++t) { + const block_q8_K* y = (const block_q8_K*) act[t] + i; + const float d = y->d * xd; + const float dmin = -y->d * xdmin; + const int8_t* q8 = y->qs; + const __m256i q8sums = _mm256_loadu_si256((const __m256i*) y->bsums); + const __m128i q8s = _mm_hadd_epi16(_mm256_extracti128_si256(q8sums, 0), _mm256_extracti128_si256(q8sums, 1)); + const __m128i prod = _mm_madd_epi16(mins, q8s); + acc_m[t] = _mm_fmadd_ps(_mm_set1_ps(dmin), _mm_cvtepi32_ps(prod), acc_m[t]); + __m256i sumi = _mm256_setzero_si256(); + for (int j = 0; j < QK_K / 64; ++j) { + const __m256i q8l = _mm256_loadu_si256((const __m256i*) q8); + q8 += 32; + __m256i p16l = _mm256_maddubs_epi16(q4l[j], q8l); + p16l = _mm256_madd_epi16(scale_l[j], p16l); + const __m256i q8h = _mm256_loadu_si256((const __m256i*) q8); + q8 += 32; + __m256i p16h = _mm256_maddubs_epi16(q4h[j], q8h); + p16h = _mm256_madd_epi16(scale_h[j], p16h); + sumi = _mm256_add_epi32(sumi, _mm256_add_epi32(p16l, p16h)); + } + acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(sumi), acc[t]); + } + } + for (int t = 0; t < nt; ++t) { + __m128 m = acc_m[t]; + m = _mm_add_ps(m, _mm_movehl_ps(m, m)); + m = _mm_add_ss(m, _mm_movehdup_ps(m)); + res[t] = hsum_float_8(acc[t]) + _mm_cvtss_f32(m); + } +} + +// ---- Q5_1 x Q8_1 (ggml_vec_dot_q5_1_q8_1, __AVX2__) +void q5_1_dot(const block_q5_1* x, int nb, const void* const* act, int nt, float* res) { + __m256 acc[MAXT]; + float summs[MAXT]; + for (int t = 0; t < nt; ++t) { acc[t] = _mm256_setzero_ps(); summs[t] = 0.0f; } + for (int ib = 0; ib < nb; ++ib) { + const __m256 dx = _mm256_set1_ps(half_at(&x[ib], 0)); + const float xm = half_at(&x[ib], 1); + __m256i qx = bytes_from_nibbles_32(x[ib].qs); + __m256i bxhi = bytes_from_bits_32(x[ib].qh); + bxhi = _mm256_and_si256(bxhi, _mm256_set1_epi8(0x10)); + qx = _mm256_or_si256(qx, bxhi); + for (int t = 0; t < nt; ++t) { + const block_q8_1* y = (const block_q8_1*) act[t] + ib; + summs[t] += xm * half_at(y, 1); + const __m256 dy = _mm256_set1_ps(half_at(y, 0)); + const __m256i qy = _mm256_loadu_si256((const __m256i*) y->qs); + const __m256 q = mul_sum_us8_pairs_float(qx, qy); + acc[t] = _mm256_fmadd_ps(q, _mm256_mul_ps(dx, dy), acc[t]); + } + } + for (int t = 0; t < nt; ++t) res[t] = hsum_float_8(acc[t]) + summs[t]; +} + +// ---- Q8_0 x Q8_0 (ggml_vec_dot_q8_0_q8_0, __AVX2__; mul_sum_i8_pairs_float without AVX-VNNI-INT8) +void q8_0_dot(const block_q8_0* x, int nb, const void* const* act, int nt, float* res) { + __m256 acc[MAXT]; + for (int t = 0; t < nt; ++t) acc[t] = _mm256_setzero_ps(); + for (int ib = 0; ib < nb; ++ib) { + const float xd = h2f(x[ib].d); + const __m256i qx = _mm256_loadu_si256((const __m256i*) x[ib].qs); + const __m256i ax = _mm256_sign_epi8(qx, qx); + for (int t = 0; t < nt; ++t) { + const block_q8_0* y = (const block_q8_0*) act[t] + ib; + const __m256 d = _mm256_set1_ps(xd * h2f(y->d)); + const __m256i qy = _mm256_loadu_si256((const __m256i*) y->qs); + const __m256i sy = _mm256_sign_epi8(qy, qx); + const __m256 q = mul_sum_us8_pairs_float(ax, sy); + acc[t] = _mm256_fmadd_ps(d, q, acc[t]); + } + } + for (int t = 0; t < nt; ++t) res[t] = hsum_float_8(acc[t]); +} + +void dot_rows(int type, const uint8_t* row, int n, const void* const* act, int nt, float* res) { + switch (type) { + case 12: q4k_dot((const block_q4_K*) row, n / QK_K, act, nt, res); break; + case 7: q5_1_dot((const block_q5_1*) row, n / QK5_1, act, nt, res); break; + case 8: q8_0_dot((const block_q8_0*) row, n / QK8_0, act, nt, res); break; + default: break; + } +} + +} // namespace + +bool kq256_supported(int type) noexcept { return type == 12 || type == 7 || type == 8; } + +void kq256_gu_rows(int type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt, + float* const* ff, int r0, int r1) { + for (int t0 = 0; t0 < nt; t0 += MAXT) { + const int m = nt - t0 < MAXT ? nt - t0 : MAXT; + float g[MAXT], u[MAXT]; + for (int r = r0; r < r1; ++r) { + dot_rows(type, blob + (size_t) r * gu_row, n, act + t0, m, g); + dot_rows(type, blob + up_off + (size_t) r * gu_row, n, act + t0, m, u); + // native_gu_rows' own SwiGLU expression: the same bits as the per-token ggml path + for (int t = 0; t < m; ++t) ff[t0 + t][r] = (g[t] / (1.f + std::exp(-g[t]))) * u[t]; + } + } +} + +void kq256_rows(int type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out, + int r0, int r1) { + for (int t0 = 0; t0 < nt; t0 += MAXT) { + const int m = nt - t0 < MAXT ? nt - t0 : MAXT; + float s[MAXT]; + for (int r = r0; r < r1; ++r) { + dot_rows(type, w + (size_t) r * row_bytes, n, act + t0, m, s); + for (int t = 0; t < m; ++t) out[t0 + t][r] = s[t]; + } + } +} + +} // namespace strata::kernels::cpu diff --git a/src/kernels/cpu/native_expert.cpp b/src/kernels/cpu/native_expert.cpp index d326b410..673d4ec9 100644 --- a/src/kernels/cpu/native_expert.cpp +++ b/src/kernels/cpu/native_expert.cpp @@ -5,6 +5,7 @@ #include "strata/kernels/cpu/expert.hpp" #include "strata/kernels/cpu/iq_avx512.hpp" #include "strata/kernels/cpu/iq_avx2.hpp" +#include "strata/kernels/cpu/kq_avx2.hpp" #include "strata/kernels/cpu/expert_layout.hpp" #include "ggml.h" @@ -89,6 +90,13 @@ void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const* // can depend on how many drafts a verify window held. STRATA_IQ_MT_MIN=1 (opt-in, 0.1.30) uses the multi-token // kernels for every group: output independent of the drafting, at a measured -1..-3% decode on IQ3_S (AVX-512). static const int mt_min = [] { const char* e = std::getenv("STRATA_IQ_MT_MIN"); return e ? std::atoi(e) : 2; }(); + // Unsloth UD-Q4_K_XL's Q4_K gate/up: the multi-token kernel is bit-exact against ggml's per-token dot, so it + // runs for every group size (no #152 rule). STRATA_NO_KQ256 falls back to ggml's vec_dot. + static const bool kq = std::getenv("STRATA_NO_KQ256") == nullptr; + if (kq && f.gu_type == 12) { + kq256_gu_rows(f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act, nt, ff, r0, r1); + return; + } if (nt >= mt_min && iq512_supported(f.gu_type)) { if (avx512) { iq512_gu_rows(f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act, nt, ff, r0, r1); @@ -119,6 +127,11 @@ void native_down_rows(const NativeFmt& f, const uint8_t* blob, const void* const // block instead of once per token; ggml-cpu's dot is single-token. STRATA_NO_IQ4NL falls back to it. static const bool iq4nl_mt = std::getenv("STRATA_NO_IQ4NL") == nullptr; static const int mt_min = [] { const char* e = std::getenv("STRATA_IQ_MT_MIN"); return e ? std::atoi(e) : 2; }(); + static const bool kq = std::getenv("STRATA_NO_KQ256") == nullptr; + if (kq && (f.d_type == 7 || f.d_type == 8)) { // Q5_1 / Q8_0 down: bit-exact, every group size + kq256_rows(f.d_type, blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1); + return; + } if (nt >= mt_min && f.d_type == 20 && iq4nl_mt) { // #152: the same rule as the gate/up rows iq4nl256_down_rows(blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1); return; diff --git a/src/kernels/native_expert_parity.cpp b/src/kernels/native_expert_parity.cpp index d6ede318..2425062e 100644 --- a/src/kernels/native_expert_parity.cpp +++ b/src/kernels/native_expert_parity.cpp @@ -15,6 +15,7 @@ #include "strata/kernels/cpu/expert.hpp" #include "strata/kernels/cpu/iq_avx512.hpp" #include "strata/kernels/cpu/iq_avx2.hpp" +#include "strata/kernels/cpu/kq_avx2.hpp" #include "strata/kernels/cpu/expert_layout.hpp" #include "ggml-cpu.h" #include "strata/kernels/iq_kernels.hpp" @@ -172,6 +173,53 @@ int check_blob(const cpu::NativeFmt& f, const std::vector& blob, int se gu_diff, dn_diff); if (gu_diff || dn_diff) ++failures; } + // UD-Q4_K_XL's formats: the multi-token AVX2 kernels (kq_avx2.cpp) against ggml-cpu's vec_dot per token, + // BIT FOR BIT, for 1..8 tokens; then the time of 4 tokens (a verify window) both ways + for (int role = 0; role < 2; ++role) { + const int type = role == 0 ? f.gu_type : f.d_type; + if (!cpu::kq256_supported(type) || (role == 0 && type != 12)) continue; + const int n = role == 0 ? (int) H : (int) FF, rows = role == 0 ? (int) FF : (int) H; + const size_t rb = role == 0 ? f.gu_row : f.d_row; + const uint8_t* w = blob.data() + (role == 0 ? 0 : f.down_off); + const auto* tc = ggml_get_type_traits_cpu((ggml_type) type); + const ggml_type at = tc->vec_dot_type; + std::vector> acts(8, std::vector(ggml_row_size(at, n))); + std::mt19937 arng(77 + seed); + std::normal_distribution and_(0.f, 1.f); + std::vector xs((size_t) n); + const void* ap[8]; + for (int t = 0; t < 8; ++t) { + for (auto& v : xs) v = and_(arng); + ggml_get_type_traits_cpu(at)->from_float(xs.data(), acts[t].data(), n); + ap[t] = acts[t].data(); + } + std::vector ref((size_t) 8 * rows), got((size_t) 8 * rows); + for (int t = 0; t < 8; ++t) + for (int r = 0; r < rows; ++r) tc->vec_dot(n, &ref[(size_t) t * rows + r], 0, w + (size_t) r * rb, 0, ap[t], 0, 1); + size_t differ = 0; + for (int nt = 1; nt <= 8; ++nt) { + float* op[8]; + for (int t = 0; t < nt; ++t) op[t] = got.data() + (size_t) t * rows; + cpu::kq256_rows(type, w, rb, n, ap, nt, op, 0, rows); + for (int t = 0; t < nt; ++t) + differ += std::memcmp(op[t], ref.data() + (size_t) t * rows, (size_t) rows * 4) != 0; + } + const int it = 30; + float* op4[4] = {got.data(), got.data() + rows, got.data() + 2 * rows, got.data() + 3 * rows}; + auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < it; ++i) cpu::kq256_rows(type, w, rb, n, ap, 4, op4, 0, rows); + auto t1 = std::chrono::steady_clock::now(); + for (int i = 0; i < it; ++i) + for (int r = 0; r < rows; ++r) + for (int t = 0; t < 4; ++t) tc->vec_dot(n, op4[t] + r, 0, w + (size_t) r * rb, 0, ap[t], 0, 1); + auto t2 = std::chrono::steady_clock::now(); + const double us_k = std::chrono::duration(t1 - t0).count() / it; + const double us_g = std::chrono::duration(t2 - t1).count() / it; + std::printf(" %s %s rows, AVX2 multi-token vs ggml vec_dot: %zu of 36 token-sets differ in any bit; " + "4 tokens one thread %.0f us vs ggml %.0f us (%.2fx)\n", ggml_type_name((ggml_type) type), + role == 0 ? "gate" : "down", differ, us_k, us_g, us_g / us_k); + if (differ) ++failures; + } if (f.d_type == 42) { // (b2) the GGUF-layout Q2_0 kernel the pool uses for Q2_0 down projections - the AVX-512 one // where the CPU has it, the AVX-2 one (q2_avx2.cpp) where it does not. Calling the AVX-512 diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 6b927744..0f522522 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -2320,6 +2320,8 @@ int main(int argc, char** argv) { // CS-T: a native pack without experts.bin maps the model's GGUF shards instead (native_experts.txt's spans, // checked against the files first) - no 30-77 GB copy of the experts on the disk src.set_gguf(o.native_preset); + if (const char* v = std::getenv("STRATA_FETCH_THREADS"); v != nullptr && std::atoi(v) > 0) + src.set_fetch_threads(std::atoi(v)); if (!src.open(o.pack, g.n_layers, g.n_expert, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; @@ -5477,6 +5479,10 @@ int main(int argc, char** argv) { if (drive.d.pcie_num < 0) drive.d.pcie_num = 0; if (drive.d.pcie_num > 256) drive.d.pcie_num = 256; const int64_t pcie0 = drive.d.pcie_experts; + // CS-T: the file tier since the decode began (the prompt path's copies are before this) + const int64_t files0 = src.file_reads(), ram0 = src.ram_reads(); + const uint64_t fbytes0 = src.file_blob_bytes(), fall0 = src.file_read_bytes(); + const double fms0 = src.file_ms(); if (o.adapt_every > 0 && o.adapt_swaps > 0) drive.d.usage.assign((size_t) (g.n_layers * g.n_expert), 0.0f); int64_t swaps_total = 0; double ms_adapt = 0; @@ -5716,12 +5722,15 @@ int main(int argc, char** argv) { std::printf("%-24s %.2f GiB of experts in RAM, %lld exchanged with the VRAM tier, %lld blob reads from " "the file\n", "resident RAM", (double) src.resident_bytes() / 1073741824.0, (long long) src.exchanges(), (long long) src.file_reads()); - if (srcp == &src) // CS-T: the RAM and file tiers (the GPU cache's share is the hit rate above) - std::printf("%-24s RAM %lld blobs, files %lld blobs, %.1f MB read from the files (%.2f MB/round)%s\n", - "expert tiers", (long long) src.ram_reads(), (long long) src.file_reads(), - (double) src.file_read_bytes() / 1e6, - rounds > 0 ? (double) src.file_read_bytes() / 1e6 / rounds : 0.0, - src.gguf_mode() ? " (the GGUF in place)" : ""); + if (srcp == &src) { // CS-T: the RAM and file tiers (the GPU cache's share is the hit rate above) + const double fms = src.file_ms() - fms0, fmb = (double) (src.file_blob_bytes() - fbytes0) / 1e6; + std::printf("%-24s decode: RAM %lld blobs, files %lld blobs, %.1f MB read from the files (%.2f MB/round, " + "%.1f ms/round of reading, %.2f GB/s per reading thread)%s; prompt copies %.1f MB\n", + "expert tiers", (long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0), + fmb, rounds > 0 ? fmb / rounds : 0.0, rounds > 0 ? fms / rounds : 0.0, + fms > 0 ? fmb / fms : 0.0, src.gguf_mode() ? " (the GGUF in place)" : "", + (double) (fall0 - fbytes0) / 1e6); + } if (rounds > 0 && drive.d.pcie_num > 0) std::printf("%-24s %.2f distinct experts per layer read over PCIe (share %d/256 of the misses)\n", "pcie experts", (double) (drive.d.pcie_experts - pcie0) / (double) (rounds * g.n_layers), diff --git a/tests/core/expert_layout_test.cpp b/tests/core/expert_layout_test.cpp index a28ba2c7..35d1accf 100644 --- a/tests/core/expert_layout_test.cpp +++ b/tests/core/expert_layout_test.cpp @@ -240,6 +240,24 @@ void arena() { check(p == q && std::memcmp(p, dst.data() + L.blob_offset(0, 1), (size_t) L.blob_bytes(0)) == 0, "an assembled blob stays put while it is in use"); check(fs.file_read_bytes() > 0, "the file tier counts its bytes (" + std::to_string(fs.file_read_bytes()) + ")"); + // prefetch: a layer's experts fetched together on several threads, then the same bytes from blob() + bool pre = true; + for (int round = 0; round < 3; ++round) + for (int64_t l = 0; l < 2; ++l) { + fs.begin_layer(l, nullptr, 0); + fs.begin_layer(l == 0 ? 1 : 0, nullptr, 0); // age the buffers so the prefetch refills them + fs.begin_layer(l, nullptr, 0); + const int64_t both[2] = {1, 0}; + fs.set_fetch_threads(2); + fs.prefetch(l, both, 2); + for (int64_t e = 0; e < NE; ++e) { + const uint8_t* b = fs.blob(l, e); + pre = pre && b != nullptr && + std::memcmp(b, dst.data() + L.blob_offset(l, e), (size_t) L.blob_bytes(l)) == 0; + } + } + check(pre && fs.file_blob_bytes() > 0 && fs.file_ms() >= 0.0, + "prefetch on 2 threads, then blob(): the same bytes"); } fs.close(); // with experts.bin present, the pack's file is mapped as before, whatever set_gguf says