From c00942d2c2c5ca9cd16efba1231d873406b1d3fe Mon Sep 17 00:00:00 2001 From: Robert Karl Date: Sun, 11 Oct 2026 08:43:10 -0700 Subject: [PATCH] Restore the development tooling the port needs from the import commit ref/load.py, the pack, profile, MTP, tokenizer and fixture tools with their tests, and the tests/ sources the root CMakeLists already wires under STRATA_BUILD_TESTS. Development only: the shipped binary still needs no Python. Taken unchanged from 12a7825 (Strata 6f32ec0); the HIP tests, the installer tests and the conversation-cache tests stay out. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_017tPVMg2wGSNR1KANEiUtwr --- ref/load.py | 212 +++++++ tests/core/expert_cache_per_layer_test.cpp | 44 ++ tests/core/expert_cache_segmented_test.cpp | 99 ++++ tests/core/expert_layout_test.cpp | 355 ++++++++++++ tests/core/expert_profile_save_test.cpp | 80 +++ tests/core/file_expert_source_test.cpp | 360 ++++++++++++ tests/core/gguf_fixture.hpp | 103 ++++ tests/core/gguf_split_test.cpp | 220 +++++++ tests/core/native_dense_ple_key_test.cpp | 169 ++++++ tests/cuda/prefill_fused_iq_test.cpp | 633 +++++++++++++++++++++ tests/cuda/prefill_fused_moe_test.cpp | 420 ++++++++++++++ tests/cuda/prefill_mmq_kquant_test.cpp | 168 ++++++ 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 ++ tests/platform/direct_file_async.cpp | 60 ++ tools/_paths.py | 28 + tools/draft_vocab.py | 146 +++++ tools/gguf_reader.py | 142 +++++ tools/gguf_writer.py | 234 ++++++++ tools/iq_fixture.py | 137 +++++ tools/iq_pack.py | 602 ++++++++++++++++++++ tools/make_profile.py | 119 ++++ tools/mtp_fetch.py | 308 ++++++++++ tools/mtp_pack.py | 193 +++++++ tools/mtp_rt.py | 111 ++++ tools/pack_index.py | 260 +++++++++ tools/pack_layer.py | 123 ++++ tools/strata_pack.py | 423 ++++++++++++++ tools/strata_tokenizer.py | 331 +++++++++++ tools/test_draft_vocab.py | 47 ++ tools/test_iq_pack.py | 528 +++++++++++++++++ tools/test_make_profile.py | 104 ++++ tools/test_mtp_fetch.py | 201 +++++++ 37 files changed, 7254 insertions(+) create mode 100644 ref/load.py create mode 100644 tests/core/expert_cache_per_layer_test.cpp create mode 100644 tests/core/expert_cache_segmented_test.cpp create mode 100644 tests/core/expert_layout_test.cpp create mode 100644 tests/core/expert_profile_save_test.cpp create mode 100644 tests/core/file_expert_source_test.cpp create mode 100644 tests/core/gguf_fixture.hpp create mode 100644 tests/core/gguf_split_test.cpp create mode 100644 tests/core/native_dense_ple_key_test.cpp create mode 100644 tests/cuda/prefill_fused_iq_test.cpp create mode 100644 tests/cuda/prefill_fused_moe_test.cpp create mode 100644 tests/cuda/prefill_mmq_kquant_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 create mode 100644 tests/platform/direct_file_async.cpp create mode 100644 tools/_paths.py create mode 100644 tools/draft_vocab.py create mode 100644 tools/gguf_reader.py create mode 100644 tools/gguf_writer.py create mode 100644 tools/iq_fixture.py create mode 100644 tools/iq_pack.py create mode 100644 tools/make_profile.py create mode 100644 tools/mtp_fetch.py create mode 100644 tools/mtp_pack.py create mode 100644 tools/mtp_rt.py create mode 100644 tools/pack_index.py create mode 100644 tools/pack_layer.py create mode 100644 tools/strata_pack.py create mode 100644 tools/strata_tokenizer.py create mode 100644 tools/test_draft_vocab.py create mode 100644 tools/test_iq_pack.py create mode 100644 tools/test_make_profile.py create mode 100644 tools/test_mtp_fetch.py diff --git a/ref/load.py b/ref/load.py new file mode 100644 index 0000000..0e4575a --- /dev/null +++ b/ref/load.py @@ -0,0 +1,212 @@ +"""ref/load.py - P1.S4: GGUF -> FP32 tensors on demand, with LAZY per-expert dequantization. + +The plan is explicit: "experts are dequantized lazily per (layer, expert) - do not materialize 120B +parameters". That is the whole design constraint here, and it is what `expert()` below exists for: the +routed-expert tensors are fused `[in, out, experts]`, and touching one expert must not touch the other +511. + +Dequantization itself is NOT reimplemented. `gguf-py` handles the twelve standard encodings and is +already the reference this project validates its C++ against; `Q2_0` (type 42) is the one gguf-py +cannot represent at all, so it is served by this project's own decoder. That split is deliberate: it +means a bug in `tools/gguf_writer.dequantize_q2_0` cannot hide behind gguf-py and vice versa. + + from ref.load import Gguf + g = Gguf("path.gguf") + w = g.tensor("blk.0.attn_gate.weight") # (out, in) fp32, whole tensor + e = g.expert("blk.0.ffn_gate_exps.weight", 7) # (out, in) fp32, ONE expert only +""" +from __future__ import annotations + +import pathlib +import re +import sys + +import numpy as np + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "tools")) +from gguf_reader import GGUFFile # noqa: E402 +from gguf_writer import dequantize_q2_0 # noqa: E402 + +# gguf-py names differ from our reader's names in a few places; map only what differs. +_GGUF_PY_NAME = {"Q4_0": "Q4_0", "Q8_0": "Q8_0", "Q4_K": "Q4_K", "Q5_K": "Q5_K", "Q6_K": "Q6_K", + "Q3_K": "Q3_K", "IQ4_NL": "IQ4_NL", "IQ4_XS": "IQ4_XS", "Q5_0": "Q5_0"} + +# (elements per block, bytes per block) - mirrors block_geometry() in src/artifact/gguf_reader.cpp +GEOM = {"F32": (1, 4), "F16": (1, 2), "BF16": (1, 2), + "Q4_0": (32, 18), "Q5_0": (32, 22), "Q8_0": (32, 34), "IQ4_NL": (32, 18), + "Q3_K": (256, 110), "Q4_K": (256, 144), "Q5_K": (256, 176), "Q6_K": (256, 210), + "IQ4_XS": (256, 136), "Q2_0": (64, 18)} + + +def _dequant_flat(type_name: str, raw: np.ndarray) -> np.ndarray: + """One dequantization dispatch, shared by tensor()/expert()/rows(). + + Q2_0 is this project's own decoder because gguf-py's enum cannot represent type 42 at all; + everything else goes through gguf-py, which is already the reference this project validates its + C++ against. Keeping one dispatch means a type added in one path cannot be forgotten in another. + """ + if type_name == "Q2_0": + return dequantize_q2_0(raw.tobytes()) + if type_name == "BF16": + return _bf16_to_f32(raw) + if type_name == "F32": + return raw.view(np.float32) + if type_name == "F16": + return raw.view(np.float16).astype(np.float32) + from gguf import quants, GGMLQuantizationType as Q + return quants.dequantize(raw, Q[_GGUF_PY_NAME[type_name]]).astype(np.float32) + + +def _bf16_to_f32(raw: np.ndarray) -> np.ndarray: + return (raw.view(np.uint16).astype(np.uint32) << 16).view(np.float32) + + +def _discover_shards(path) -> list[pathlib.Path]: + """Resolve a GGUF argument to its shard list. + + The real artifact is TWO files and the split is not incidental: shard 2 holds exactly one tensor, + `per_layer_token_embd.weight` (26.82 GiB). A reader that opens one file can therefore load the + whole model EXCEPT the PLE table and will not fail until a forward pass reaches layer 1 - so + shard discovery is not a convenience, it is a correctness requirement for the real model. + + Accepts a directory (all `*.gguf` in it), any single shard (siblings found by the + `-NNNNN-of-MMMMM` suffix), or an explicit list. + """ + if isinstance(path, (list, tuple)): + return [pathlib.Path(p) for p in path] + p = pathlib.Path(path) + if p.is_dir(): + # A directory is ambiguous in practice: the project root holds BOTH the model shards (in a + # subdirectory) and an unrelated `mmproj-*.gguf`. Globbing `*.gguf` there silently loaded + # the multimodal projector instead of the model. So prefer an explicit shard set, accept a + # single unambiguous file, and REFUSE to guess otherwise. + shards = sorted(p.glob("*-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9].gguf")) + if shards: + totals = {re.match(r"^.*-(\d{5})-of-(\d{5})\.gguf$", s.name).group(2) for s in shards} + if len(totals) != 1: + raise ValueError(f"{p}: shard files from more than one split: {sorted(totals)}") + return shards + found = sorted(p.glob("*.gguf")) + if len(found) == 1: + return found + if not found: + raise FileNotFoundError(f"no .gguf files in {p}") + raise ValueError( + f"{p}: {len(found)} .gguf files and none is a shard set, so which is the model is " + f"ambiguous: {[f.name for f in found]}. Pass one file explicitly.") + m = re.match(r"^(.*)-(\d{5})-of-(\d{5})\.gguf$", p.name) + if m: + stem, _, total = m.groups() + sibs = sorted(p.parent.glob(f"{stem}-*-of-{total}.gguf")) + if len(sibs) != int(total): + raise FileNotFoundError( + f"{p.name}: expected {total} shards, found {len(sibs)} in {p.parent}") + return sibs + return [p] + + +class Gguf: + """Read-only, demand-paged view of a (possibly multi-shard) GGUF. + + Nothing is dequantized until asked for. `g` is the FIRST shard's `GGUFFile`, so metadata and the + tensor directory are reachable as before; reads route to whichever shard owns the tensor. + """ + + def __init__(self, path): + self.paths = _discover_shards(path) + self.path = self.paths[0] + self.shards: list[tuple[GGUFFile, object]] = [] + self._by_name: dict[str, tuple[int, object]] = {} + for i, sp in enumerate(self.paths): + gf = GGUFFile(sp) + self.shards.append((gf, sp.open("rb"))) + for t in gf.tensors: + if t.name in self._by_name: + raise ValueError(f"{sp.name}: duplicate tensor {t.name} across shards") + self._by_name[t.name] = (i, t) + self.g = self.shards[0][0] # metadata / directory / alignment live in shard 1 + + # ---- raw bytes + def _raw(self, name: str, nbytes: int, byte_offset: int = 0) -> bytes: + i, t = self._by_name[name] + gf, fh = self.shards[i] + fh.seek(gf.data_start + t.offset + byte_offset) + return fh.read(nbytes) + + def info(self, name: str): + return self._by_name[name][1] + + def row_bytes(self, t) -> int: + el, by = GEOM[t.type_name] + return t.shape[0] // el * by + + # ---- full tensors + def tensor(self, name: str) -> np.ndarray: + """Dequantize a whole tensor to FP32, shape as GGUF order reversed to (out, in[, experts]).""" + t = self.info(name) + el, by = GEOM[t.type_name] + if t.elements % el: + raise ValueError(f"{name}: {t.elements} not a multiple of block {el}") + raw = np.frombuffer(self._raw(name, t.elements // el * by), dtype=np.uint8) + flat = _dequant_flat(t.type_name, raw) + # GGUF dim 0 varies fastest; numpy's last axis does, so reverse and transpose to (out, in). + return flat.reshape(tuple(reversed(t.shape))) + + # ---- the lazy row path + def rows(self, name: str, idx) -> np.ndarray: + """Gather specific ROWS of a 2-D tensor without decoding the rest of it. + + This exists for `per_layer_token_embd.weight`, which is `[160, 320001536]` IQ4_NL = **26.82 + GiB** - 43% of the artifact, the entire second shard - and is read 16 rows per token by one + layer (see round 98's finding). Calling `tensor()` on it would dequantize 320 million rows to + FP32, about 205 GB, to use 2.5 KB of them. + + A row is contiguous in GGUF (ne0 varies fastest), so one row is `row_bytes` at + `row * row_bytes`. The type's block size must divide the row width; for this table it does + (160 = 5 x 32 for IQ4_NL). + """ + t = self.info(name) + if len(t.shape) != 2: + raise ValueError(f"{name}: rows() needs a 2-D tensor, got shape {t.shape}") + el, by = GEOM[t.type_name] + width = t.shape[0] + if width % el: + raise ValueError(f"{name}: row width {width} is not a multiple of block {el}") + rb = self.row_bytes(t) + idx = np.asarray(idx, dtype=np.int64).ravel() + if idx.size and (idx.min() < 0 or idx.max() >= t.shape[1]): + raise ValueError(f"{name}: row index out of range (0..{t.shape[1] - 1})") + out = np.empty((idx.size, width), dtype=np.float32) + for k, r in enumerate(idx): + raw = np.frombuffer(self._raw(name, rb, int(r) * rb), dtype=np.uint8) + out[k] = _dequant_flat(t.type_name, raw) + return out + + # ---- the lazy path + def expert(self, name: str, expert_id: int) -> np.ndarray: + """One expert out of a fused `[in, out, experts]` tensor, WITHOUT touching the others. + + In GGUF order the expert index is the LAST axis, so expert e's matrix occupies a contiguous + run of `in*out` elements at offset e*in*out. Only that run is read and decoded - which is the + plan's "do not materialize 120B parameters" requirement, and the reason the engine can run at + all on a machine where the expert set is 34 GB. + """ + t = self.info(name) + if len(t.shape) != 3: + raise ValueError(f"{name}: not a fused expert tensor (shape {t.shape})") + in_f, out_f, n_exp = t.shape + if not 0 <= expert_id < n_exp: + raise ValueError(f"{name}: expert {expert_id} out of range (0..{n_exp - 1})") + el, by = GEOM[t.type_name] + per_expert = in_f * out_f + if per_expert % el: + raise ValueError(f"{name}: per-expert element count {per_expert} not a multiple of {el}") + # byte offset of expert e: whole experts before it, in blocks + start = expert_id * (per_expert // el) * by + raw = np.frombuffer(self._raw(name, per_expert // el * by, start), dtype=np.uint8) + flat = _dequant_flat(t.type_name, raw) + return flat.reshape((out_f, in_f)) + + def close(self) -> None: + for _, fh in self.shards: + fh.close() diff --git a/tests/core/expert_cache_per_layer_test.cpp b/tests/core/expert_cache_per_layer_test.cpp new file mode 100644 index 0000000..26bfdd4 --- /dev/null +++ b/tests/core/expert_cache_per_layer_test.cpp @@ -0,0 +1,44 @@ +// #369: per-layer admission on a sized cache (open_sized, every native pack) - each layer admits into its own slot +// range, as on the uniform cache, so no two layers write the same slot. Needs a CUDA device (exits 77 without one). +#include "strata/core/expert_cache.hpp" + +#include + +#include +#include +#include + +int main() { + int n = 0; + if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { + std::puts("no CUDA device: skipped"); + return 77; + } + std::string err; + for (int sized = 0; sized < 2; ++sized) { + strata::core::ExpertCache cache; + const bool ok = sized ? cache.open_sized(std::vector(6, 1024), 3, 4, err) + : cache.open(6, 3, 4, 1024, err); + if (!ok) { + std::fprintf(stderr, "open: %s\n", err.c_str()); + return 1; + } + cache.set_per_layer_admission(true); + for (int64_t layer = 0; layer < 3; ++layer) { + int64_t lo = 0, hi = 0; + cache.layer_slot_range(layer, lo, hi); + for (int64_t e = 0; e < 3; ++e) { + const int32_t slot = cache.admit(layer, e); + const bool want_room = lo + e < hi; + if (want_room ? slot != (int32_t) (lo + e) : slot != strata::core::kNotResident) { + std::fprintf(stderr, "%s cache: layer %lld expert %lld got slot %d (range %lld..%lld)\n", + sized ? "sized" : "uniform", (long long) layer, (long long) e, slot, (long long) lo, + (long long) hi - 1); + return 1; + } + } + } + } + std::puts("expert cache per-layer admission: uniform and sized caches passed"); + return 0; +} diff --git a/tests/core/expert_cache_segmented_test.cpp b/tests/core/expert_cache_segmented_test.cpp new file mode 100644 index 0000000..cabf24a --- /dev/null +++ b/tests/core/expert_cache_segmented_test.cpp @@ -0,0 +1,99 @@ +// #533: the segmented expert cache (--vram-elastic). A shrink gives the last segments' VRAM back to the driver and +// keeps every slot left exactly as it was (same address, same bytes); a grow maps them again at the same addresses. +// Uniform and sized slots. Needs a CUDA device with virtual memory management (exits 77 without one). +#include "strata/core/expert_cache.hpp" + +#include + +#include +#include +#include + +namespace { +int fail(const char* what, const std::string& err = "") { + std::fprintf(stderr, "FAIL %s %s\n", what, err.c_str()); + return 1; +} + +size_t free_vram() { + size_t f = 0, t = 0; + cudaMemGetInfo(&f, &t); + return f; +} + +// slot i holds the byte (i * 7 + 1) everywhere +bool fill(strata::core::ExpertCache& c, int64_t from, int64_t to, int64_t blob) { + std::vector b((size_t) blob); + for (int64_t i = from; i < to; ++i) { + std::fill(b.begin(), b.end(), (uint8_t) (i * 7 + 1)); + if (cudaMemcpy(c.device_slot((int32_t) i), b.data(), (size_t) blob, cudaMemcpyHostToDevice) != cudaSuccess) + return false; + } + return true; +} + +bool check(const strata::core::ExpertCache& c, int64_t to, int64_t blob) { + std::vector b((size_t) blob); + for (int64_t i = 0; i < to; ++i) { + if (cudaMemcpy(b.data(), c.device_slot((int32_t) i), (size_t) blob, cudaMemcpyDeviceToHost) != cudaSuccess) + return false; + for (const uint8_t x : b) + if (x != (uint8_t) (i * 7 + 1)) return false; + } + return true; +} +} // namespace + +int main() { + int n = 0; + if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { + std::puts("no CUDA device: skipped"); + return 77; + } + constexpr int64_t kBlob = 1 << 20, kSlots = 96, kSeg = 8ll << 20; + for (int sized = 0; sized < 2; ++sized) { + strata::core::ExpertCache c; + c.set_segment_bytes(kSeg); + std::string err; + const bool ok = sized ? c.open_sized(std::vector(kSlots, kBlob), 4, 64, err) + : c.open(kSlots, 4, 64, kBlob, err); + if (!ok) { + if (err.find("virtual memory management") != std::string::npos) { + std::printf("%s: skipped\n", err.c_str()); + return 77; + } + return fail("open", err); + } + if (!c.segmented() || c.slots() != kSlots || c.mapped_bytes() < kSlots * kBlob) return fail("open sizes"); + uint8_t* const first = c.device_slot(0); + if (!fill(c, 0, kSlots, kBlob)) return fail("fill"); + const size_t before = free_vram(); + // keep 30 MiB: rounded up to whole 8 MiB segments = 32 MiB = 32 slots + if (!c.shrink(30ll << 20, err)) return fail("shrink", err); + if (c.slots() != 32 || c.mapped_bytes() != 32ll << 20 || c.bytes() != 32ll << 20) + return fail("shrunk sizes"); + if (c.full_slots() != kSlots || c.full_bytes() != kSlots * kBlob) return fail("full sizes"); + const size_t freed = free_vram() - before; + if (freed + (8u << 20) < (size_t) (64ll << 20)) { // ~64 MiB back to the driver (WDDM rounds a little) + std::fprintf(stderr, "freed %zu bytes\n", freed); + return fail("VRAM not given back"); + } + if (c.device_slot(0) != first || !check(c, 32, kBlob)) return fail("slots kept after the shrink"); + // grow to 70 MiB: whole segments only, 64 MiB = 64 slots + if (!c.grow(70ll << 20, err) || c.slots() != 64) return fail("grow part", err); + if (!c.grow(1ll << 40, err) || c.slots() != kSlots || c.mapped_bytes() < kSlots * kBlob) + return fail("grow all", err); + if (c.device_slot(0) != first || !check(c, 32, kBlob)) return fail("slots kept after the grow"); + if (!fill(c, 32, kSlots, kBlob) || !check(c, kSlots, kBlob)) return fail("the grown slots"); + if (c.slots_within(0) != 0 || c.slots_within(kBlob * 3 + 5) != 3 || c.bytes_of(5) != 5 * kBlob) + return fail("slots_within / bytes_of"); + c.close(); + if (c.valid() || c.slots() != 0) return fail("close"); + } + // the default (no segment size): one allocation, shrink refused + strata::core::ExpertCache d; + std::string err; + if (!d.open(8, 2, 4, kBlob, err) || d.segmented() || d.shrink(0, err)) return fail("unsegmented", err); + std::puts("expert cache segments: shrink gives VRAM back and keeps the slots, grow maps them again"); + return 0; +} diff --git a/tests/core/expert_layout_test.cpp b/tests/core/expert_layout_test.cpp new file mode 100644 index 0000000..35d1acc --- /dev/null +++ b/tests/core/expert_layout_test.cpp @@ -0,0 +1,355 @@ +// 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 +#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"); + + { // 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()) + ")"); + // 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 + { + 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(), + 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) { + // `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"); + 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/expert_profile_save_test.cpp b/tests/core/expert_profile_save_test.cpp new file mode 100644 index 0000000..6b61070 --- /dev/null +++ b/tests/core/expert_profile_save_test.cpp @@ -0,0 +1,80 @@ +// #477: --expert-profile-save's profile - rank_learned_profile's order (resident first, then the counted routing, then +// the profile the engine started from) and write_expert_profile's file, byte for byte tools/make_profile.py's format, +// read back by read_expert_profile. CPU only: no device is touched. +#include "strata/core/expert_cache.hpp" + +#include +#include +#include +#include +#include +#include + +namespace { +int fails = 0; +void check(bool ok, const char* what) { + if (!ok) { + std::fprintf(stderr, "FAIL: %s\n", what); + ++fails; + } +} +} // namespace + +int main() { + using Pair = std::pair; + const int64_t L = 3, E = 4; // 12 pairs, index = layer * 4 + expert + std::vector resident(12, 0); + resident[5] = 1; // (1, 1) + resident[2] = 1; // (0, 2) + std::vector heat(12, 0.0); + heat[2] = 1.0; + heat[5] = 7.0; + heat[11] = 9.0; // (2, 3): the hottest, but not resident + heat[0] = 3.0; + const std::vector prior = {{2, 0}, {1, 3}, {0, 1}}; // a profile that ranks three pairs + const std::vector r = strata::core::rank_learned_profile(L, E, resident, heat, prior); + check(r.size() == 12, "every pair is ranked"); + const std::vector head = {{1, 1}, {0, 2}, {2, 3}, {0, 0}, {2, 0}, {1, 3}, {0, 1}, {0, 3}}; + for (size_t i = 0; i < head.size() && i < r.size(); ++i) + check(r[i] == head[i], "resident by heat, then the rest by heat, then the prior, then the index"); + // no counts at all: the resident ones, then the prior's order + const std::vector r0 = strata::core::rank_learned_profile(L, E, resident, {}, prior); + check(r0.size() == 12 && r0[0] == Pair(0, 2) && r0[1] == Pair(1, 1) && r0[2] == Pair(2, 0) && + r0[3] == Pair(1, 3) && r0[4] == Pair(0, 1) && r0[5] == Pair(0, 0), "without heat: resident, then prior"); + + const std::filesystem::path dir = std::filesystem::temp_directory_path() / "strata_profile_save_test"; + std::filesystem::create_directories(dir); + const std::string path = (dir / "learned.bin").string(); + std::string err; + check(strata::core::write_expert_profile(path, L, E, r, err), "written"); + check(!std::filesystem::exists(path + ".tmp"), "no temporary file left"); + // the bytes make_profile.write_profile would write for the same ranking + std::vector want(4); + std::memcpy(want.data(), "STRP", 4); + auto u32 = [&](uint32_t v) { for (int b = 0; b < 4; ++b) want.push_back((uint8_t) (v >> (8 * b))); }; + auto u16 = [&](uint32_t v) { want.push_back((uint8_t) v); want.push_back((uint8_t) (v >> 8)); }; + for (uint32_t v : {1u, 3u, 4u, 12u, 12u}) u32(v); + for (const Pair& p : r) { u16((uint32_t) p.first); u16((uint32_t) p.second); } + std::vector table(12, -1); + for (size_t i = 0; i < r.size(); ++i) table[(size_t) (r[i].first * E + r[i].second)] = (int32_t) i; + for (int32_t v : table) u32((uint32_t) v); + std::vector got(want.size() + 1); + if (std::FILE* f = std::fopen(path.c_str(), "rb")) { + got.resize(std::fread(got.data(), 1, got.size(), f)); + std::fclose(f); + } + check(got == want, "the file is make_profile.py's format, byte for byte"); + std::vector back; + int64_t slots = 0; + check(strata::core::read_expert_profile(path, L, E, back, slots, err) && back == r && slots == 12, + "read back by the loader"); + // a second save replaces the first (the rename over an existing file) + check(strata::core::write_expert_profile(path, L, E, r0, err), "written again"); + check(strata::core::read_expert_profile(path, L, E, back, slots, err) && back == r0, "replaced"); + check(!strata::core::write_expert_profile(path, L, E, {{3, 0}}, err), "a pair out of range is refused"); + check(strata::core::read_expert_profile(path, L, E, back, slots, err) && back == r0, + "a refused save keeps the file"); + std::filesystem::remove_all(dir); + if (fails == 0) std::puts("expert_profile_save_test: OK"); + return fails == 0 ? 0 : 1; +} diff --git a/tests/core/file_expert_source_test.cpp b/tests/core/file_expert_source_test.cpp new file mode 100644 index 0000000..104507d --- /dev/null +++ b/tests/core/file_expert_source_test.cpp @@ -0,0 +1,360 @@ +#include "strata/core/expert_source.hpp" +#include "strata/kernels/cpu/expert.hpp" +#include "strata/kernels/cpu/expert_layout.hpp" + +#if defined(STRATA_NATIVE_EXPERTS) +#include "strata/kernels/cpu/native_expert.hpp" +#include "ggml.h" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace { + +void require(bool ok, const std::string& message) { + if (!ok) throw std::runtime_error(message); +} + +struct TempDirectory { + fs::path path; + + TempDirectory() { + const auto stamp = std::chrono::steady_clock::now().time_since_epoch().count(); + path = fs::temp_directory_path() / ("strata-file-source-test-" + std::to_string(stamp)); + fs::create_directories(path); + } + + ~TempDirectory() { + std::error_code ignored; + fs::remove_all(path, ignored); + } +}; + +void create_pack(const fs::path& dir, uint64_t bytes, const std::vector>& markers = {}) { + const fs::path file = dir / "experts.bin"; + { + std::ofstream out(file, std::ios::binary | std::ios::trunc); + require((bool) out, "could not create synthetic experts.bin"); + if (bytes > 0) { + out.seekp((std::streamoff) (bytes - 1)); + out.put('\0'); + } + require((bool) out, "could not size synthetic experts.bin"); + } + for (const auto& [offset, marker] : markers) { + require(offset < bytes, "synthetic marker lies beyond experts.bin"); + std::fstream file_out(file, std::ios::binary | std::ios::in | std::ios::out); + require((bool) file_out, "could not open synthetic experts.bin for markers"); + file_out.seekp((std::streamoff) offset); + file_out.put(marker); + require((bool) file_out, "could not write synthetic expert marker"); + } +} + +void check_file_size_rejection(strata::core::FileExpertSource& source, const fs::path& dir, int64_t layers, + int64_t experts, uint64_t expected_bytes) { + std::string err; + source.close(); + fs::resize_file(dir / "experts.bin", expected_bytes - 1); + require(!source.open(dir.string(), layers, experts, err), "a truncated expert file was accepted"); + require(!source.mapped() && !err.empty(), "truncated-file rejection left the source mapped or unreported"); + + fs::resize_file(dir / "experts.bin", expected_bytes + 1); + err.clear(); + require(!source.open(dir.string(), layers, experts, err), "an oversized expert file was accepted"); + require(!source.mapped() && !err.empty(), "oversized-file rejection left the source mapped or unreported"); +} + +void test_canonical_layout() { + using namespace strata::core; + using namespace strata::kernels::cpu; + constexpr int64_t layers = 2; + constexpr int64_t experts = 3; + const uint64_t layer_bytes = (uint64_t) experts * BLOB; + const uint64_t total = (uint64_t) layers * layer_bytes; + TempDirectory dir; + + std::string err; + const bool layout_ok = expert_layout_load(dir.path.string(), layers, experts, err); + require(layout_ok, "could not load canonical layout: " + err); + create_pack(dir.path, total, {{0, 'a'}, {(uint64_t) BLOB, 'b'}, {layer_bytes, 'c'}, + {layer_bytes + (uint64_t) BLOB, 'd'}}); + + FileExpertSource source; + bool opened = source.open(dir.path.string(), layers, experts, err); + require(opened, "could not map canonical pack: " + err); + require(source.blobs() == layers * experts, "canonical blob count is wrong"); + const uint8_t* first = source.blob(0, 0); + const uint8_t* second = source.blob(0, 1); + const uint8_t* next_layer = source.blob(1, 0); + require(first && second && next_layer, "valid canonical blob lookup failed"); + require(second - first == (ptrdiff_t) BLOB && next_layer - first == (ptrdiff_t) layer_bytes, + "canonical expert or layer stride is wrong"); + require(first[0] == 'a' && second[0] == 'b' && next_layer[0] == 'c', + "canonical blob lookup returned bytes from the wrong expert"); + require(source.blob(-1, 0) == nullptr && source.blob(0, -1) == nullptr && + source.blob(layers, 0) == nullptr && source.blob(0, experts) == nullptr, + "canonical bounds check accepted an invalid layer or expert"); + require(source.reads() == 3, "invalid canonical lookups changed the read count"); + + check_file_size_rejection(source, dir.path, layers, experts, total); + create_pack(dir.path, total, {{layer_bytes, 'c'}}); + err.clear(); + opened = source.open(dir.path.string(), layers, experts, err); + require(opened, "source failed to reopen after size errors: " + err); + const uint8_t* reopened = source.blob(1, 0); + require(reopened && source.reads() == 1 && reopened[0] == 'c', "reopened canonical source kept stale state"); + source.close(); +} + +#if defined(STRATA_NATIVE_EXPERTS) +void test_native_variable_layout() { + using namespace strata::core; + using namespace strata::kernels::cpu; + constexpr int64_t layers = 2; + constexpr int64_t experts = 3; + constexpr int64_t embedding = 2560; + constexpr int64_t feed_forward = 640; + TempDirectory dir; + + NativeFmt first_fmt, second_fmt; + std::string err; + const bool first_ok = native_fmt(GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ4_NL, embedding, feed_forward, first_fmt, err); + require(first_ok, "IQ3_XXS/IQ4_NL synthetic format is unavailable: " + err); + err.clear(); + const bool second_ok = native_fmt(GGML_TYPE_IQ2_XS, GGML_TYPE_IQ4_NL, embedding, feed_forward, second_fmt, err); + require(second_ok, "IQ2_XS/IQ4_NL synthetic format is unavailable: " + err); + require(first_fmt.bytes != second_fmt.bytes, "chosen native formats do not exercise variable layer sizes"); + + const uint64_t layer0_bytes = (uint64_t) first_fmt.bytes * experts; + const uint64_t total = layer0_bytes + (uint64_t) second_fmt.bytes * experts; + { + std::ofstream metadata(dir.path / "native_experts.txt"); + require((bool) metadata, "could not create synthetic native_experts.txt"); + metadata << "0 " << GGML_TYPE_IQ3_XXS << ' ' << GGML_TYPE_IQ4_NL << " 0 " << first_fmt.bytes << '\n'; + metadata << "1 " << GGML_TYPE_IQ2_XS << ' ' << GGML_TYPE_IQ4_NL << ' ' << layer0_bytes << ' ' + << second_fmt.bytes << '\n'; + require((bool) metadata, "could not write synthetic native_experts.txt"); + } + create_pack(dir.path, total, {{0, 'a'}, {(uint64_t) first_fmt.bytes, 'b'}, + {layer0_bytes, 'c'}, {layer0_bytes + (uint64_t) second_fmt.bytes, 'd'}}); + + const bool layout_ok = expert_layout_load(dir.path.string(), layers, experts, err); + require(layout_ok, "could not load synthetic native layout: " + err); + FileExpertSource source; + bool opened = source.open(dir.path.string(), layers, experts, err); + require(opened, "could not map native pack: " + err); + require(source.blobs() == layers * experts, "native blob count is wrong"); + const uint8_t* first = source.blob(0, 0); + const uint8_t* second = source.blob(0, 1); + const uint8_t* next_layer = source.blob(1, 0); + const uint8_t* next_layer_second = source.blob(1, 1); + require(first && second && next_layer && next_layer_second, "valid native blob lookup failed"); + require(second - first == (ptrdiff_t) first_fmt.bytes && next_layer - first == (ptrdiff_t) layer0_bytes && + next_layer_second - next_layer == (ptrdiff_t) second_fmt.bytes, + "native per-layer expert stride is wrong"); + require(first[0] == 'a' && second[0] == 'b' && next_layer[0] == 'c' && next_layer_second[0] == 'd', + "native blob lookup returned bytes from the wrong expert"); + require(source.blob(-1, 0) == nullptr && source.blob(0, -1) == nullptr && + source.blob(layers, 0) == nullptr && source.blob(0, experts) == nullptr, + "native bounds check accepted an invalid layer or expert"); + require(source.reads() == 4, "invalid native lookups changed the read count"); + + check_file_size_rejection(source, dir.path, layers, experts, total); + create_pack(dir.path, total, {{layer0_bytes, 'c'}}); + err.clear(); + opened = source.open(dir.path.string(), layers, experts, err); + require(opened, "source failed to reopen after size errors: " + err); + const uint8_t* reopened = source.blob(1, 0); + require(reopened && source.reads() == 1 && reopened[0] == 'c', "reopened native source kept stale state"); + source.close(); +} +#endif + +void test_complement_plan() { + using namespace strata::core::detail; + std::vector offsets; + uint64_t bytes = 0; + std::string error; + require(make_cache_complement_plan(2, 3, {3, 5}, {{0, 1}, {1, 2}}, {}, offsets, bytes, error), error); + require(bytes == 16 && offsets == std::vector{0, kNoCacheComplement, 3, 6, 11, kNoCacheComplement}, + "wrong compact offsets for variable native layer sizes"); + const uint8_t resident[16] = {}, mapped[5] = {}; + require(cache_complement_blob_or_fallback(1, offsets, resident, mapped) == mapped, + "GPU-resident expert lost mmap fallback"); + require(cache_complement_blob_or_fallback(4, offsets, resident, mapped) == resident + 11, + "CPU miss did not use resident complement"); + require(!make_cache_complement_plan(2, 3, {3, 5}, {{0, 1}, {0, 1}}, {}, offsets, bytes, error) + && offsets.empty() && bytes == 0, "duplicate pair accepted"); + require(!make_cache_complement_plan(2, 3, {3, 5}, {{0, 1}}, {{0, 1}}, offsets, bytes, error), + "overlapping tiers accepted"); + require(!make_cache_complement_plan(2, 3, {3, 5}, {{2, 0}}, {}, offsets, bytes, error), + "out-of-range pair accepted"); + require(!make_cache_complement_plan(2, 3, {0, 5}, {}, {}, offsets, bytes, error), "zero-size layer accepted"); +} + +void test_resident_lend_region() { + using namespace strata::core::detail; + // four slots (sizes 5, 3, 3, 5); the experts no slot holds take 10 bytes + const std::vector slots{5, 3, 3, 5}; + require(choose_resident_keep_from(slots, 10, 9, 1) == -1, "a base larger than the budget was accepted"); + require(choose_resident_keep_from(slots, 10, 10, 1) == 4, "no room: the lend region must stay on the file"); + require(choose_resident_keep_from(slots, 10, 15, 1) == 3, "the last slot fits and must be kept first"); + require(choose_resident_keep_from(slots, 10, 17, 1) == 3, "a slot that does not fit ends the lend region's walk"); + require(choose_resident_keep_from(slots, 10, 18, 1) == 2, "two slots fit"); + require(choose_resident_keep_from(slots, 10, 100, 1) == 1, "the walk must stop at the lend region's first slot"); + require(choose_resident_keep_from(slots, 10, 100, -1) == 4, "no lend region kept slots in RAM"); + require(choose_resident_keep_from(slots, 10, 100, 9) == 4, "an out-of-range lend region kept slots in RAM"); + require(choose_resident_keep_from({}, 0, 0, 0) == 0, "an empty cache"); +} + +void test_resident_exchange() { + using namespace strata::core; + using namespace strata::core::detail; + // 2 layers x 3 experts; the GPU holds (0,1) and (1,2): the compact copy holds the other four + std::vector offsets; + uint64_t bytes = 0; + std::string error; + require(make_cache_complement_plan(2, 3, {3, 5}, {{0, 1}, {1, 2}}, {}, offsets, bytes, error), error); + const std::vector before = offsets; + // (1,0) moves into the GPU, (1,2) leaves it: (1,2) takes (1,0)'s bytes' place + require(exchange_cache_complement(offsets, 3, 5), "a valid exchange was refused"); + require(offsets[5] == before[3] && offsets[3] == kNoCacheComplement, "the exchange did not move the place"); + for (size_t i : {0u, 1u, 2u, 4u}) require(offsets[i] == before[i], "an exchange touched another expert"); + // the copy's size and its set of places are unchanged + std::vector a, b; + for (uint64_t o : before) if (o != kNoCacheComplement) a.push_back(o); + for (uint64_t o : offsets) if (o != kNoCacheComplement) b.push_back(o); + std::sort(a.begin(), a.end()); + std::sort(b.begin(), b.end()); + require(a == b, "an exchange changed the compact copy's places"); + const std::vector after = offsets; + require(!exchange_cache_complement(offsets, 3, 0), "an `in` the copy does not hold was accepted"); + require(!exchange_cache_complement(offsets, 0, 2), "an `out` the copy holds already was accepted"); + require(!exchange_cache_complement(offsets, 0, 0), "a self-exchange was accepted"); + require(!exchange_cache_complement(offsets, 0, 6), "an out-of-range `out` was accepted"); + require(offsets == after, "a refused exchange changed the offsets"); + // and back: the copy is again what the plan makes for the original placement + require(exchange_cache_complement(offsets, 5, 3), "the reverse exchange was refused"); + require(offsets == before, "exchanging back did not restore the plan"); +} + +void test_cgroup_memory_budget() { + using namespace strata::core::detail; + constexpr uint64_t GiB = 1ull << 30; + uint64_t bytes = 0; + + CgroupMemoryStat clean_cache{40 * GiB, 32 * GiB, 0, 0, true}; + require(cgroup_available_bytes(56 * GiB, clean_cache, bytes), "valid cgroup memory.stat was rejected"); + require(bytes == 48 * GiB, "clean inactive file cache was not credited against the cgroup cap"); + + CgroupMemoryStat dirty_cache{40 * GiB, 32 * GiB, 4 * GiB, 2 * GiB, true}; + require(cgroup_available_bytes(56 * GiB, dirty_cache, bytes), "valid dirty-cache counters were rejected"); + require(bytes == 42 * GiB, "dirty/writeback pages were incorrectly counted as reclaimable"); + + CgroupMemoryStat oversized_inactive{10 * GiB, 20 * GiB, 0, 0, true}; + require(cgroup_available_bytes(12 * GiB, oversized_inactive, bytes), + "valid oversized inactive-file counter was rejected"); + require(bytes == 12 * GiB, "inactive-file accounting exceeded charged current usage"); + + const uint64_t max = std::numeric_limits::max(); + CgroupMemoryStat large_counters{max, max, max - 1, max, true}; + require(cgroup_available_bytes(max, large_counters, bytes), + "large memory.stat counters were rejected"); + require(bytes == 0, "dirty/writeback subtraction overflowed or escaped the usage cap"); + + CgroupMemoryStat usage_over_limit{60 * GiB, 0, 0, 0, true}; + require(cgroup_available_bytes(56 * GiB, usage_over_limit, bytes), + "valid over-limit memory counters were rejected"); + require(bytes == 0, "over-limit cgroup usage produced a positive budget"); + + CgroupMemoryStat missing_stat{}; + bytes = 123; + require(!cgroup_available_bytes(56 * GiB, missing_stat, bytes) && bytes == 0, + "missing memory.stat counters did not fail closed"); +} + +// #633: the host RAM probe with fake /proc and cgroup trees: v2 (a limit, "max", a missing or malformed limit), v1 +// (a limit, unlimited), and no cgroup line at all. Elsewhere than Linux it reads the machine's RAM. +void test_host_memory() { + using namespace strata::core::detail; + constexpr uint64_t GiB = 1ull << 30; + HostMemory m; +#if defined(__linux__) + TempDirectory t; + auto put = [&](const fs::path& rel, const std::string& text) { + fs::create_directories((t.path / rel).parent_path()); + std::ofstream(t.path / rel) << text; + }; + put("meminfo", "MemTotal: 134217728 kB\nMemAvailable: 104857600 kB\n"); // 100 GiB available + const std::string mi = (t.path / "meminfo").string(), cg = (t.path / "cgroup").string(), + root = (t.path / "fs").string(); + auto probe = [&](const std::string& self) { + put("cgroup", self); + return host_available_memory(m, mi, cg, root); + }; + // no cgroup line at all: MemAvailable alone (before #633: "cannot determine") + require(probe("") && m.available == 100 * GiB && m.cgroup_limit == ~0ull, "no cgroup: MemAvailable alone"); + // v2, a 48 GiB limit with 16 GiB charged, 4 GiB of it clean cache + put("fs/cgroup.controllers", "memory\n"); + put("fs/box/memory.max", std::to_string(48 * GiB) + "\n"); + put("fs/box/memory.current", std::to_string(16 * GiB) + "\n"); + put("fs/box/memory.stat", "inactive_file " + std::to_string(4 * GiB) + "\nfile_dirty 0\nfile_writeback 0\n"); + require(probe("0::/box\n") && m.available == 36 * GiB && m.cgroup_limit == 48 * GiB, "v2 limit"); + put("fs/box/memory.max", "max\n"); + require(probe("0::/box\n") && m.available == 100 * GiB && m.cgroup_limit == ~0ull, "v2 max"); + put("fs/box/memory.max", "48G\n"); + require(!probe("0::/box\n"), "v2 malformed limit accepted"); + fs::remove(t.path / "fs/box/memory.max"); + require(!probe("0::/box\n"), "v2 group without memory.max accepted"); + // v1: the memory controller's group (a hybrid line list), a 32 GiB limit with 10 GiB used + put("fs/memory/docker/abc/memory.limit_in_bytes", std::to_string(32 * GiB) + "\n"); + put("fs/memory/docker/abc/memory.usage_in_bytes", std::to_string(10 * GiB) + "\n"); + put("fs/memory/memory.limit_in_bytes", "9223372036854771712\n"); // the root: unlimited + put("fs/memory/memory.usage_in_bytes", std::to_string(50 * GiB) + "\n"); + require(probe("12:cpu,cpuacct:/docker/abc\n4:memory:/docker/abc\n1:name=systemd:/docker/abc\n") && + m.available == 22 * GiB && m.cgroup_limit == 32 * GiB, "v1 limit"); + put("fs/memory/docker/abc/memory.limit_in_bytes", "9223372036854771712\n"); + require(probe("4:memory:/docker/abc\n") && m.available == 100 * GiB && m.cgroup_limit == ~0ull, "v1 unlimited"); + // a v1 group not visible here (another namespace): MemAvailable alone + require(probe("4:memory:/elsewhere\n") && m.available == 100 * GiB, "v1 group not mounted"); +#else + require(host_available_memory(m) && m.available > 0 && m.cgroup_limit == ~0ull, "this PC's RAM"); + (void) GiB; +#endif +} + +} // namespace + +int main() { + try { + test_complement_plan(); + test_resident_lend_region(); + test_resident_exchange(); + test_cgroup_memory_budget(); + test_host_memory(); + test_canonical_layout(); +#if defined(STRATA_NATIVE_EXPERTS) + test_native_variable_layout(); +#endif + std::cout << "file_expert_source_test: PASS\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "file_expert_source_test: " << error.what() << '\n'; + return 1; + } +} diff --git a/tests/core/gguf_fixture.hpp b/tests/core/gguf_fixture.hpp new file mode 100644 index 0000000..677a5cd --- /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 0000000..3f137cc --- /dev/null +++ b/tests/core/gguf_split_test.cpp @@ -0,0 +1,220 @@ +// 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 + +// `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; + 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/core/native_dense_ple_key_test.cpp b/tests/core/native_dense_ple_key_test.cpp new file mode 100644 index 0000000..e69d838 --- /dev/null +++ b/tests/core/native_dense_ple_key_test.cpp @@ -0,0 +1,169 @@ +// tests/core/native_dense_ple_key_test.cpp - #326: a native pack whose PLE key row is BF16 (iq_pack --compat-bf16 of +// OrcaRouter's IQ3_XXS key) loads with that row in the arena, and NativeDense does not upload the GGUF key over it. +// +// 1. BF16 key row + IQ3_XXS GGUF key: served_names lists the key, keep_unquantized_ple_key takes it out of the +// skip set, the arena holds the BF16 bytes, and NativeDense::load attaches no native key (0.1.25-0.1.31 refused +// the load with "incompatible matrix blk.1.ple_key.weight"). The other matrix still gets its native upload. +// 2. A quantized key row (the Q2_0 / UD-Q4_K_XL packs: a shape-only row) + a Q8_0 GGUF key: unchanged - the key +// stays skipped and is served natively. +// 3. index_code_bits on a missing row and a missing index. +// Synthetic files at small dimensions; needs a CUDA device for the arena (exits 77 without one). +#include "gguf_fixture.hpp" + +#include "strata/core/native_dense.hpp" +#include "strata/core/weights.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; +using strata::core::NativeDense; +using strata::core::WeightTable; + +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-ple-key-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); + } +}; + +const char* KEY = "blk.1.ple_key.weight"; +const char* QKV = "blk.0.attn_qkv.weight"; +constexpr uint64_t NE0 = 256, NE1 = 4; + +std::vector arch_keys() { + return {fixture::str("general.architecture", "qwen4exp"), fixture::u32("qwen4exp.block_count", 48), + fixture::u32("qwen4exp.embedding_length", 2560), fixture::u32("qwen4exp.expert_count", 512), + fixture::u32("qwen4exp.expert_used_count", 10), fixture::u32("qwen4exp.attention.head_count", 24), + fixture::u32("qwen4exp.attention.head_count_kv", 2)}; +} + +// A shape-only quantized row (what iq_pack writes for a tensor the GGUF serves) and, with `bf16_key`, the key as a +// raw BF16 row (index kind 4) in dense.bin. +void write_pack(const fs::path& dir, bool bf16_key) { + fs::create_directories(dir); + const uint64_t key_bytes = NE0 * NE1 * 2; + std::string idx = "# align 256 pool " + std::to_string(bf16_key ? 2048 + 256 : 256) + " tensors 2\n"; + idx += std::string(QKV) + " 0 0 0 0 0 0 256 4 8 0 32 0 0 0 0 0 0 0\n"; + if (bf16_key) + idx += std::string(KEY) + " 0 4 0 " + std::to_string(key_bytes) + " 256 " + std::to_string(key_bytes) + + " 256 4 0 0 1 0 0 0 0 0 0 0\n"; + else + idx += std::string(KEY) + " 0 0 0 0 256 0 256 4 8 0 32 0 0 0 0 0 0 0\n"; + std::ofstream(dir / "index.txt", std::ios::binary) << idx; + std::vector bytes(bf16_key ? key_bytes : 16); + for (size_t i = 0; i < bytes.size(); ++i) bytes[i] = (char) fixture::pattern(9, i); + std::ofstream(dir / "dense.bin", std::ios::binary).write(bytes.data(), (std::streamsize) bytes.size()); +} + +struct Loaded { + bool ok = false; + std::string err; + std::set skip; + WeightTable wt; + NativeDense dense; + void* arena = nullptr; + ~Loaded() { if (arena) cudaFree(arena); } +}; + +// generate.cpp's order: served_names, keep_unquantized_ple_key (native packs), pool_bytes, load, NativeDense::load. +void load(const fs::path& pack, const std::string& shard, Loaded& l) { + const std::vector shards{shard}; + if (!NativeDense::served_names(shards, true, l.skip, l.err)) return; + if (!NativeDense::keep_unquantized_ple_key(pack.string(), l.skip, l.err)) return; + uint64_t pool = 0; + if (!WeightTable::pool_bytes(pack.string(), pool, l.err, &l.skip)) return; + if (cudaMalloc(&l.arena, pool ? pool : 256) != cudaSuccess) { l.err = "cudaMalloc"; return; } + if (!l.wt.load(pack.string(), l.arena, pool ? pool : 256, l.err, &l.skip)) return; + l.ok = l.dense.load(shards, l.wt, l.err, true); +} +} // namespace + +int main() { + int devices = 0; + if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) { + std::printf("native_dense_ple_key_test: no CUDA device, skipped\n"); + return 77; + } + TempDir tmp; + + std::printf("1. BF16 key row (--compat-bf16), IQ3_XXS GGUF key\n"); + { + const fs::path pack = tmp.path / "orca"; + write_pack(pack, true); + const std::string shard = (tmp.path / "orca.gguf").string(); + fixture::write(shard, arch_keys(), {{QKV, {NE0, NE1}, 8, 1}, {KEY, {NE0, NE1}, 18, 2}}); + int bits = 99; + std::string err; + check(WeightTable::index_code_bits(pack.string(), KEY, bits, err) && bits == 0, "index_code_bits: key row is 0"); + check(WeightTable::index_code_bits(pack.string(), QKV, bits, err) && bits == 8, "index_code_bits: qkv row is 8"); + Loaded l; + load(pack, shard, l); + check(l.ok, "the pack loads (was: incompatible matrix) " + l.err); + check(!l.skip.count(KEY) && l.skip.count(QKV), "the key is not skipped, qkv is"); + const auto* k = l.wt.find(KEY); + check(k && k->resident && k->data && !k->quantized(), "the key is resident and BF16"); + check(k && !k->native_data, "no native key attached"); + if (k && k->data) { + std::vector back(NE0 * NE1 * 2); + cudaMemcpy(back.data(), k->data, back.size(), cudaMemcpyDeviceToHost); + bool same = true; + for (size_t i = 0; i < back.size(); ++i) same = same && back[i] == fixture::pattern(9, i); + check(same, "the arena holds the pack's BF16 bytes"); + } + const auto* q = l.wt.find(QKV); + check(q && q->native_data && q->native_type == 8, "qkv still served natively (Q8_0)"); + check(l.dense.tensor_count() == 1, "one native matrix"); + } + + std::printf("2. quantized key row (Q2_0 / UD-Q4_K_XL packs), Q8_0 GGUF key: unchanged\n"); + { + const fs::path pack = tmp.path / "q8"; + write_pack(pack, false); + const std::string shard = (tmp.path / "q8.gguf").string(); + fixture::write(shard, arch_keys(), {{QKV, {NE0, NE1}, 8, 1}, {KEY, {NE0, NE1}, 8, 2}}); + Loaded l; + load(pack, shard, l); + check(l.ok, "the pack loads " + l.err); + check(l.skip.count(KEY) == 1, "the key stays skipped"); + const auto* k = l.wt.find(KEY); + check(k && !k->resident && k->native_data && k->native_type == 8, "the key is served natively"); + check(l.dense.tensor_count() == 2, "two native matrices"); + } + + std::printf("3. index_code_bits edge cases\n"); + { + int bits = 0; + std::string err; + check(WeightTable::index_code_bits((tmp.path / "orca").string(), "blk.9.nothing.weight", bits, err) && + bits == -1, "a missing row is -1"); + check(!WeightTable::index_code_bits((tmp.path / "none").string(), KEY, bits, err) && !err.empty(), + "a missing index is an error"); + std::set skip{QKV}; + check(NativeDense::keep_unquantized_ple_key((tmp.path / "none").string(), skip, err) && skip.size() == 1, + "no key in the skip set: the index is not read"); + } + + std::printf(g_fail ? "native_dense_ple_key_test: %d FAILED\n" : "native_dense_ple_key_test: all passed\n", g_fail); + return g_fail ? 1 : 0; +} diff --git a/tests/cuda/prefill_fused_iq_test.cpp b/tests/cuda/prefill_fused_iq_test.cpp new file mode 100644 index 0000000..d436a60 --- /dev/null +++ b/tests/cuda/prefill_fused_iq_test.cpp @@ -0,0 +1,633 @@ +// prefill_fused_iq_test - #136: the fused int8 expert kernels for the native packs (moe_fused_iq.hpp, STRATA_PF_FUSED=1) +// on random native expert blobs ([gate rows | up rows | down rows], GGUF blocks) and random routing, per format pair, +// against +// - a double-precision reference: the weights dequantized by ggml's own to_float, times the FP32 activations +// (gate/up, SwiGLU, down), and +// - the MMQ path in prefill.cpp's sequence (gather_native into 16-expert groups, q8_1 of the slots' activations, +// gate/up, SwiGLU, q8_1 of H, down). +// Both round the activations and H to int8 per 32 values, differently, so this is not a bitwise test: the fused +// path's error against the reference has to be comparable to MMQ's own (at most 1.5x its RMS and 2x its worst row). +// The pairs cover every format the kernels take: gate/up IQ2_XXS IQ2_XS IQ2_S IQ3_XXS IQ3_S IQ4_XS, down Q2_0 IQ4_NL. +// Part 1 (reference), per pair: 256 tokens over 64 experts, skewed routing - experts with 0 rows, with one, with +// several 64-row tiles - an all-zero token, per-expert blobs at unrelated (2-byte aligned) addresses, three launches of +// different expert ranges. Part 2 (timing): one layer at the engine's chunks (2048, 3584, 8192 tokens; 512 experts, +// top 10) on both paths and on MMQ's products alone (no gathers), for the IQ2_XS, IQ3_XXS and IQ3_S packs' most +// common layers, with the grouping checked and a sample of rows against the reference. --no-ref, --no-timing, +// --only=NAME, --chunks=A,B. Exit 77 without a CUDA device of sm_80 or newer. +#include "strata/prefill/moe_fused_iq.hpp" +#include "strata/prefill/moe_mmq.hpp" + +#include "ggml.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace mmq = strata::prefill::mmq; +namespace fused = strata::prefill::fused; + +constexpr int N = 2560, FF = 640, K = 10, GROUP = 16; + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e)); +} + +struct Dev { + void* p = nullptr; + explicit Dev(size_t n) { ck(cudaMalloc(&p, n), "cudaMalloc"); } + ~Dev() { cudaFree(p); } + Dev(const Dev&) = delete; + Dev& operator=(const Dev&) = delete; + template T* as() const { return (T*) p; } +}; + +struct Pair { + ggml_type gu, d; + const char* name; +}; + +struct Geo { + size_t gu_row, d_row, up_off, down_off, bytes; + explicit Geo(const Pair& p) { + gu_row = ggml_row_size(p.gu, N); + d_row = ggml_row_size(p.d, FF); + up_off = gu_row * FF; + down_off = 2 * up_off; + bytes = down_off + d_row * N; + } + fused::NativeGeom native(const Pair& p) const { + fused::NativeGeom g; + g.gu_type = (int) p.gu; g.d_type = (int) p.d; g.gu_row = gu_row; g.d_row = d_row; g.up_off = up_off; + g.down_off = down_off; + return g; + } +}; + +// random blocks with a sane fp16 scale `d` at each block's start (every format here begins with it): scales chosen so +// that the weights' typical size is that of a 2-3 bit expert (a few hundredths) +void fill_matrix(uint8_t* m, ggml_type t, int64_t rows, int64_t cols, std::mt19937& rng) { + const size_t bs = ggml_type_size(t), nb = (size_t) rows * (size_t) (cols / ggml_blck_size(t)); + std::uniform_int_distribution byte(0, 255); + const float lo = t == GGML_TYPE_IQ3_S ? 0.0004f : t == GGML_TYPE_IQ4_XS ? 0.00005f + : t == GGML_TYPE_IQ4_NL ? 0.0002f : t == GGML_TYPE_Q2_0 ? 0.004f : 0.0008f; + std::uniform_real_distribution sc(lo, 6.0f * lo); + for (size_t i = 0; i < nb * bs; ++i) m[i] = (uint8_t) byte(rng); + for (size_t b = 0; b < nb; ++b) { + const ggml_fp16_t h = ggml_fp32_to_fp16(sc(rng)); + std::memcpy(m + b * bs, &h, 2); + } +} +std::vector make_blob(const Pair& p, const Geo& g, std::mt19937& rng) { + std::vector b(g.bytes); + fill_matrix(b.data(), p.gu, 2 * FF, N, rng); + fill_matrix(b.data() + g.down_off, p.d, N, FF, rng); + return b; +} + +// ggml's dequantized weights: gate [640][2560], up [640][2560], down [2560][640] +void dequant(const Pair& p, const Geo& g, const std::vector& b, std::vector& gu, std::vector& dn) { + const auto* tg = ggml_get_type_traits(p.gu); + const auto* td = ggml_get_type_traits(p.d); + gu.resize((size_t) 2 * FF * N); + dn.resize((size_t) N * FF); + for (int r = 0; r < 2 * FF; ++r) tg->to_float(b.data() + (size_t) r * g.gu_row, gu.data() + (size_t) r * N, N); + for (int r = 0; r < N; ++r) td->to_float(b.data() + g.down_off + (size_t) r * g.d_row, dn.data() + (size_t) r * FF, FF); +} + +// activations: N(0, 1) with a few large values (the hidden state has outliers); token `zero` all zero +std::vector make_x(int T, std::mt19937& rng, int zero) { + std::vector x((size_t) T * N); + std::normal_distribution nd(0.0f, 1.0f); + std::uniform_int_distribution pick(0, 199); + for (float& v : x) v = nd(rng) * (pick(rng) == 0 ? 12.0f : 1.0f); + if (zero >= 0) std::fill(x.begin() + (size_t) zero * N, x.begin() + (size_t) (zero + 1) * N, 0.0f); + return x; +} + +// K distinct experts per token; `hot` > 0 skews the first choices towards the lowest ids +std::vector make_ids(int T, int E, std::mt19937& rng, int hot, int unused) { + std::vector ids((size_t) T * K); + std::uniform_int_distribution any(0, E - 1 - unused); + for (int t = 0; t < T; ++t) + for (int k = 0; k < K; ++k) { + int e; + bool dup; + do { + e = (hot > 0 && k < 3 && (int) (rng() % 4) != 0) ? (int) (rng() % (unsigned) hot) : any(rng); + dup = false; + for (int j = 0; j < k; ++j) dup |= ids[(size_t) t * K + j] == e; + } while (dup); + ids[(size_t) t * K + k] = e; + } + return ids; +} + +struct Routing { + std::vector cnt, off, src; // per expert; sorted row -> token (rows in pair order within an expert) + std::vector row_of; // pair -> sorted row +}; +Routing sort_rows(const std::vector& ids, int E) { + Routing r; + r.cnt.assign((size_t) E, 0); + for (int32_t e : ids) ++r.cnt[(size_t) e]; + r.off.assign((size_t) E + 1, 0); + for (int e = 0; e < E; ++e) r.off[(size_t) e + 1] = r.off[(size_t) e] + r.cnt[(size_t) e]; + std::vector fill(r.off.begin(), r.off.end() - 1); + r.src.resize(ids.size()); + r.row_of.resize(ids.size()); + for (size_t i = 0; i < ids.size(); ++i) { + const int32_t p = fill[(size_t) ids[i]]++; + r.row_of[i] = p; + r.src[(size_t) p] = (int32_t) (i / K); + } + return r; +} + +// MMQ, as prefill.cpp runs a native layer: per group of 16 routed experts a gather, gate/up, SwiGLU (gate rows, then +// up rows), q8_1 of H, down. Returns Dm [rows][N] in sorted-row order. +struct MmqBufs { + Dev xq, gu, h, hq, dm, ident, bounds, grp_gu, grp_d; + MmqBufs(const Pair& p, int64_t rows, int E) + : xq(mmq::q8_bytes(rows, N)), gu((size_t) rows * 1280 * 4), h((size_t) rows * FF * 4), + hq(mmq::q8_bytes(rows, FF)), dm((size_t) rows * N * 4), ident((size_t) rows * 4), + bounds((size_t) (2 * (E + E / GROUP + 2)) * 4), grp_gu(GROUP * mmq::matrix_bytes(p.gu, 1280, N) + 4096), + grp_d(GROUP * mmq::matrix_bytes(p.d, N, FF) + 4096) {} +}; +// `direct`: no gathers - the products read the blobs where they are (they must lie at a fixed stride, every expert +// with rows: the timing part's layout), the cost of MMQ's own kernels alone +void run_mmq(const Pair& p, const Geo& geo, mmq::Context& ctx, MmqBufs& b, const Routing& r, const float* x_dev, + const int32_t* src_dev, const std::vector& blob, int64_t rows, cudaStream_t s, + bool direct = false, size_t stride = 0) { + const size_t gub = mmq::matrix_bytes(p.gu, 1280, N), db = mmq::matrix_bytes(p.d, N, FF); + const int E = (int) r.cnt.size(); + std::vector order; + for (int e = 0; e < E; ++e) if (r.cnt[(size_t) e] > 0) order.push_back(e); + const size_t n = order.size(), ng = (n + GROUP - 1) / GROUP; + std::vector bh(n + 1 + ng * (GROUP + 1)); + for (size_t j = 0; j < n; ++j) bh[j] = r.off[(size_t) order[j]]; + bh[n] = (int32_t) rows; + for (size_t g = 0; g < ng; ++g) + for (size_t i = 0; i <= GROUP; ++i) + bh[n + 1 + g * (GROUP + 1) + i] = bh[std::min(n, g * GROUP + i)] - bh[g * GROUP]; + ck(cudaMemcpyAsync(b.bounds.p, bh.data(), bh.size() * 4, cudaMemcpyHostToDevice, s), "bounds"); + mmq::iota(b.ident.as(), rows, s); + mmq::quantize(x_dev, src_dev, b.xq.p, (int) p.gu, N, N, rows, s); + for (size_t j = 0; j < n; ++j) { + const size_t q = j % GROUP; + const uint8_t* bl = blob[(size_t) order[j]]; + if (!direct) + mmq::gather_native(bl, bl + geo.up_off, gub / 2, bl + geo.down_off, db, b.grp_gu.as() + q * gub, + b.grp_d.as() + q * db, s); + if (q + 1 < GROUP && j + 1 < n) continue; + const size_t j0 = j - q, g = j0 / GROUP; + const int ngx = (int) (q + 1); + const int64_t r0 = bh[j0], nr = bh[j + 1] - r0; + int64_t maxr = 0; + for (size_t i = j0; i <= j; ++i) maxr = std::max(maxr, r.cnt[(size_t) order[i]]); + if (!direct) { + ck(cudaMemsetAsync(b.grp_gu.as() + (size_t) ngx * gub, 0, 4096, s), "tail"); + ck(cudaMemsetAsync(b.grp_d.as() + (size_t) ngx * db, 0, 4096, s), "tail"); + } + const uint8_t* b0 = blob[(size_t) order[j0]]; + mmq::Product gu; + gu.w = direct ? (const void*) b0 : b.grp_gu.p; gu.type = (int) p.gu; gu.w_rows = 1280; gu.w_cols = N; + gu.expert_bytes = direct ? stride : gub; + gu.n = ngx; gu.xq = b.xq.p; gu.bounds = b.bounds.as() + j0; gu.ids = b.ident.as(); + gu.total_rows = rows; gu.max_rows = maxr; gu.dst = b.gu.as(); gu.ld_dst = 1280; + ctx.run(gu, s); + mmq::swiglu(b.gu.as() + r0 * 1280, b.h.as() + r0 * FF, nr, FF, false, s); + mmq::quantize(b.h.as() + r0 * FF, nullptr, b.hq.p, (int) p.d, FF, FF, nr, s); + mmq::Product dn; + dn.w = direct ? (const void*) (b0 + geo.down_off) : b.grp_d.p; dn.type = (int) p.d; dn.w_rows = N; dn.w_cols = FF; + dn.expert_bytes = direct ? stride : db; + dn.n = ngx; dn.xq = b.hq.p; dn.bounds = b.bounds.as() + n + 1 + g * (GROUP + 1); + dn.ids = b.ident.as(); dn.total_rows = nr; dn.max_rows = maxr; dn.dst = b.dm.as() + r0 * N; + dn.ld_dst = N; + ctx.run(dn, s); + } +} + +// the fused path: quantize, group on the device, then launches over expert ranges `cuts` (e.g. {0, 20, 64}) +struct FusedBufs { + Dev xa, ha, dm, scratch, slot, src, ids; + FusedBufs(int T, int64_t rows, int E) + : xa(fused::act_bytes(T, N)), ha(fused::act_bytes(rows, FF)), dm((size_t) rows * N * 4), + scratch(fused::group_bytes(rows, E)), slot((size_t) rows * 4), src((size_t) rows * 4), + ids((size_t) rows * 4) {} +}; +void run_fused(const Pair& p, const Geo& geo, FusedBufs& b, const float* x_dev, int T, int E, + const std::vector& cuts, const std::vector& blob, cudaStream_t s) { + const int64_t rows = (int64_t) T * K; + const fused::NativeGeom ng = geo.native(p); + fused::quantize_act_native(x_dev, T, N, b.xa.p, s); + fused::group(b.ids.as(), rows, K, E, b.scratch.p, b.slot.as(), b.src.as(), s); + for (size_t c = 0; c + 1 < cuts.size(); ++c) { + for (int e0 = cuts[c]; e0 < cuts[c + 1]; e0 += fused::kMaxBatch) { + fused::Batch bt; + bt.e0 = e0; + bt.e1 = std::min(cuts[c + 1], e0 + fused::kMaxBatch); + for (int e = bt.e0; e < bt.e1; ++e) bt.blob[e - bt.e0] = blob[(size_t) e]; + fused::experts_native(bt, ng, E, rows, b.scratch.p, b.xa.p, b.src.as(), b.ha.p, b.dm.as(), s); + } + } +} + +struct Err { + double rms = 0, worst = 0; // RMS error / RMS of the reference; the worst row's max |error| / its max |ref| +}; +// y_a[row_a(i)] against y_b[row_b(i)] for every pair i (rows of N values) +template +Err compare(const std::vector& a, RA row_a, const std::vector& b, RB row_b, size_t pairs) { + double e2 = 0, r2 = 0; + Err out; + for (size_t i = 0; i < pairs; ++i) { + const float* ya = a.data() + (size_t) row_a(i) * N; + const float* yb = b.data() + (size_t) row_b(i) * N; + double me = 0, mr = 0; + for (int o = 0; o < N; ++o) { + if (!std::isfinite(ya[o])) throw std::runtime_error("a non-finite output"); + const double d = (double) ya[o] - yb[o]; + e2 += d * d; + r2 += (double) yb[o] * yb[o]; + me = std::max(me, std::fabs(d)); + mr = std::max(mr, (double) std::fabs(yb[o])); + } + if (mr > 0) out.worst = std::max(out.worst, me / mr); + else if (me > 0) out.worst = 1e30; // a zero row must stay exactly zero + } + out.rms = r2 > 0 ? std::sqrt(e2 / r2) : 0; + return out; +} + +std::vector download(const Dev& d, size_t n) { + std::vector h(n); + ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download"); + return h; +} +std::vector download_i(const Dev& d, size_t n) { + std::vector h(n); + ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download"); + return h; +} + +// part 1: against the double-precision reference +void reference_part(const Pair& p, cudaStream_t s) { + constexpr int T = 256, E = 64, ZERO = 77; + const Geo geo(p); + std::mt19937 rng(136 + (unsigned) p.gu * 7 + (unsigned) p.d); + std::vector> host((size_t) E); + std::vector> dev; + std::vector blob((size_t) E); + for (int e = 0; e < E; ++e) { + host[(size_t) e] = make_blob(p, geo, rng); + dev.push_back(std::make_unique(geo.bytes + 4096 * (size_t) (e % 3) + 64)); // unrelated addresses + uint8_t* q = dev.back()->as() + 256 * (size_t) (e % 3) + 2 * (size_t) (e % 2); // 2-byte aligned + ck(cudaMemcpy(q, host[(size_t) e].data(), geo.bytes, cudaMemcpyHostToDevice), "blob"); + blob[(size_t) e] = q; + } + const std::vector x = make_x(T, rng, ZERO); + const std::vector ids = make_ids(T, E, rng, 2, 4); // experts 0, 1 hot (several tiles), 60-63 unused + const int64_t rows = (int64_t) T * K; + const Routing r = sort_rows(ids, E); + std::printf("%s - reference part: %d tokens, %d experts, rows per expert: max %d, experts without rows %d\n", p.name, + T, E, *std::max_element(r.cnt.begin(), r.cnt.end()), (int) std::count(r.cnt.begin(), r.cnt.end(), 0)); + + Dev x_dev(x.size() * 4), src_dev((size_t) rows * 4); + ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); + ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src"); + // (the uploads above are on the legacy stream and the work below on a non-blocking one: a cudaMemcpy from pageable + // memory may return before its DMA lands - on Windows it can wait in the queue until the next synchronous call) + ck(cudaDeviceSynchronize(), "uploads"); + mmq::Context ctx; + MmqBufs mb(p, rows, E); + run_mmq(p, geo, ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s); + FusedBufs fb(T, rows, E); + ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids"); + ck(cudaMemset(fb.dm.p, 0xff, (size_t) rows * N * 4), "sentinel"); // an unwritten row is NaN + ck(cudaDeviceSynchronize(), "uploads"); + run_fused(p, geo, fb, x_dev.as(), T, E, {0, 1, 20, E}, blob, s); + ck(cudaStreamSynchronize(s), "sync"); + const std::vector y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N); + const std::vector slot = download_i(fb.slot, (size_t) rows), fsrc = download_i(fb.src, (size_t) rows); + for (int64_t i = 0; i < rows; ++i) + if (fsrc[(size_t) slot[(size_t) i]] != (int32_t) (i / K)) throw std::runtime_error("group: slot/src disagree"); + + // the reference, an expert at a time on all cores + std::vector ref((size_t) rows * N); + std::vector th; + const int nth = std::max(1, std::min(16, (int) std::thread::hardware_concurrency())); + for (int w = 0; w < nth; ++w) + th.emplace_back([&, w] { + std::vector gu, dn, h(FF); + for (int e = w; e < E; e += nth) { + if (r.cnt[(size_t) e] == 0) continue; + dequant(p, geo, host[(size_t) e], gu, dn); + for (int64_t i = 0; i < rows; ++i) { + if (ids[(size_t) i] != e) continue; + const float* xr = x.data() + (size_t) (i / K) * N; + for (int f = 0; f < FF; ++f) { + double gt = 0, up = 0; + const float *wg = gu.data() + (size_t) f * N, *wu = gu.data() + (size_t) (FF + f) * N; + for (int k = 0; k < N; ++k) { gt += (double) wg[k] * xr[k]; up += (double) wu[k] * xr[k]; } + h[(size_t) f] = (float) (gt / (1.0 + std::exp(-gt)) * up); + } + for (int o = 0; o < N; ++o) { + double a = 0; + const float* wd = dn.data() + (size_t) o * FF; + for (int f = 0; f < FF; ++f) a += (double) wd[f] * h[(size_t) f]; + ref[(size_t) i * N + o] = (float) a; + } + } + } + }); + for (auto& t : th) t.join(); + + auto pair = [](size_t i) { return (int64_t) i; }; + auto mrow = [&](size_t i) { return (int64_t) r.row_of[i]; }; + auto frow = [&](size_t i) { return (int64_t) slot[i]; }; + const Err em = compare(y_mmq, mrow, ref, pair, (size_t) rows); + const Err ef = compare(y_f, frow, ref, pair, (size_t) rows); + const Err efm = compare(y_f, frow, y_mmq, mrow, (size_t) rows); + std::printf(" MMQ vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n", em.rms, em.worst); + std::printf(" fused vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n", ef.rms, ef.worst); + std::printf(" fused vs MMQ : rel RMS %.3e worst row max rel %.3e\n", efm.rms, efm.worst); + double zmax = 0; + for (int k = 0; k < K; ++k) + for (int o = 0; o < N; ++o) + zmax = std::max(zmax, (double) std::fabs(y_f[(size_t) slot[(size_t) (ZERO * K + k)] * N + o])); + if (zmax != 0) throw std::runtime_error(std::string(p.name) + ": the all-zero token's outputs are not zero"); + if (ef.rms > 1.5 * em.rms || ef.worst > 2.0 * em.worst) + throw std::runtime_error(std::string(p.name) + ": the fused path's error is not comparable to MMQ's"); +} + +// part 2: one layer at a real chunk, timed +void timing_part(const Pair& p, int T, cudaStream_t s) { + constexpr int E = 512; + const Geo geo(p); + std::mt19937 rng(1360); + const int64_t rows = (int64_t) T * K; + // 512 distinct blobs - the products read each once per tile, as the engine does + // at a stride of whole blocks of both formats (MMQ's expert stride counts blocks), + MMQ's read past the end + size_t unit = ggml_type_size(p.gu); + while (unit % ggml_type_size(p.d) != 0 || unit % 16 != 0) unit += ggml_type_size(p.gu); + const size_t stride = (geo.bytes + unit - 1) / unit * unit; + Dev blobs((size_t) E * stride + 4096); + ck(cudaMemset(blobs.p, 0, (size_t) E * stride + 4096), "zero"); + { + std::vector b = make_blob(p, geo, rng); + for (int e = 0; e < E; ++e) { + b[4 + (size_t) (e % 16)] ^= (uint8_t) e; // not all equal (inside the first block, not its scale) + ck(cudaMemcpy(blobs.as() + (size_t) e * stride, b.data(), geo.bytes, cudaMemcpyHostToDevice), + "blob"); + } + } + std::vector blob((size_t) E); + for (int e = 0; e < E; ++e) blob[(size_t) e] = blobs.as() + (size_t) e * stride; + const std::vector x = make_x(T, rng, -1); + const std::vector ids = make_ids(T, E, rng, 0, 0); + const Routing r = sort_rows(ids, E); + Dev x_dev(x.size() * 4), src_dev((size_t) rows * 4); + ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); + ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src"); + mmq::Context ctx; + MmqBufs mb(p, rows, E); + FusedBufs fb(T, rows, E); + ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids"); + ck(cudaDeviceSynchronize(), "uploads"); // (see reference_part) + cudaEvent_t a, b; + ck(cudaEventCreate(&a), "event"); + ck(cudaEventCreate(&b), "event"); + auto once = [&](auto&& f) { + ck(cudaEventRecord(a, s), "record"); + f(); + ck(cudaEventRecord(b, s), "record"); + ck(cudaEventSynchronize(b), "sync"); + float t = 0; + ck(cudaEventElapsedTime(&t, a, b), "elapsed"); + return t; + }; + auto mmq_run = [&] { run_mmq(p, geo, ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s); }; + auto fused_run = [&] { run_fused(p, geo, fb, x_dev.as(), T, E, {0, E}, blob, s); }; + const bool all_routed = std::count(r.cnt.begin(), r.cnt.end(), 0) == 0; + auto direct_run = [&] { + run_mmq(p, geo, ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s, true, stride); + }; + if (std::getenv("S20_IDSDIAG")) { // which step overwrites the routing ids on the device + auto check = [&](const char* after) { + ck(cudaStreamSynchronize(s), "sync"); + const std::vector d = download_i(fb.ids, (size_t) rows); + int64_t bad = 0; + for (size_t i = 0; i < (size_t) rows; ++i) bad += d[i] != ids[i]; + std::printf(" ids on the device after %s: %lld of %lld differ (fb.ids %p, mb.dm %p..%p, fb.dm %p..%p)\n", + after, (long long) bad, (long long) rows, fb.ids.p, mb.dm.p, + (void*) (mb.dm.as() + (size_t) rows * N * 4), fb.dm.p, + (void*) (fb.dm.as() + (size_t) rows * N * 4)); + }; + check("the upload"); + mmq_run(); + check("an MMQ run"); + fused_run(); + check("a fused run"); + if (all_routed) { + direct_run(); + check("an MMQ run without gathers"); + } + } + // ~1 s of both first (the clocks ramp up), then alternating rounds; the medians + const bool no_mmq = std::getenv("S20_NOMMQ") != nullptr; // (debug: the fused runs alone) + for (float spent = 0; spent < 1000.0f;) spent += (no_mmq ? 0.0f : once(mmq_run)) + once(fused_run); + std::vector tm, tf, td; + for (int rep = 0; rep < 8; ++rep) { + tm.push_back(no_mmq ? 1.0f : once(mmq_run)); + tf.push_back(once(fused_run)); + if (all_routed && !no_mmq) td.push_back(once(direct_run)); + } + if (td.empty()) td.push_back(0.0f); + std::sort(tm.begin(), tm.end()); + std::sort(tf.begin(), tf.end()); + std::sort(td.begin(), td.end()); + const float t_mmq = tm[tm.size() / 2], t_f = tf[tf.size() / 2]; + if (all_routed) + std::printf(" (MMQ's products alone, no gathers: %.3f ms - fused %.2fx)\n", td[td.size() / 2], + td[td.size() / 2] / t_f); + std::vector tf2; // back to back + for (int rep = 0; rep < 8; ++rep) tf2.push_back(once(fused_run)); + std::sort(tf2.begin(), tf2.end()); + std::printf(" (fused back to back: median %.3f ms, min %.3f; alternating min %.3f; MMQ min %.3f)\n", tf2[4], + tf2[0], tf[0], tm[0]); + const std::vector y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N); + const std::vector slot = download_i(fb.slot, (size_t) rows); + const Err efm = compare(y_f, [&](size_t i) { return (int64_t) slot[i]; }, y_mmq, + [&](size_t i) { return (int64_t) r.row_of[i]; }, (size_t) rows); + std::printf("%s - timing part: %d tokens x top %d over %d experts, one layer: MMQ path %.3f ms, fused %.3f ms " + "(%.2fx); fused vs MMQ rel RMS %.3e worst row %.3e\n", + p.name, T, K, E, t_mmq, t_f, t_mmq / t_f, efm.rms, efm.worst); + { // the grouping: every pair in its expert's rows (the near-identical blobs here would hide a wrong expert) + const std::vector fsrc = download_i(fb.src, (size_t) rows); + int64_t bad = 0, bad_src = 0; + for (size_t i = 0; i < (size_t) rows; ++i) { + const int e = ids[i]; + bad += slot[i] < r.off[(size_t) e] || slot[i] >= r.off[(size_t) e + 1]; + bad_src += fsrc[(size_t) slot[i]] != (int32_t) (i / K); + } + if (bad || bad_src) { + std::vector tbl((size_t) 4 * E + 2); + ck(cudaMemcpy(tbl.data(), fb.scratch.p, tbl.size() * 4, cudaMemcpyDeviceToHost), "tables"); + int64_t bad_cnt = 0, bad_off = 0, bad_ids = 0; + const std::vector d_ids = download_i(fb.ids, (size_t) rows); + for (size_t i = 0; i < (size_t) rows; ++i) bad_ids += d_ids[i] != ids[i]; + std::printf(" the routing ids on the device: %lld of %lld differ (first %d %d %d)\n", (long long) bad_ids, + (long long) rows, d_ids[0], d_ids[1], d_ids[2]); + const int32_t smin = *std::min_element(slot.begin(), slot.end()), smax = *std::max_element(slot.begin(), slot.end()); + std::printf(" slots %d..%d; off[0..3] %d %d %d %d off[E] %d; fill[0..3] %d %d %d %d; ts[0..3] %d %d %d %d " + "ts[E] %d\n", smin, smax, tbl[E], tbl[E + 1], tbl[E + 2], tbl[E + 3], tbl[2 * E], tbl[2 * E + 1], + tbl[2 * E + 2], tbl[2 * E + 3], tbl[2 * E + 4], tbl[3 * E + 1], tbl[3 * E + 2], tbl[3 * E + 3], + tbl[3 * E + 4], tbl[4 * E + 1]); + // the group again on these ids, synchronously + fused::group(fb.ids.as(), rows, K, E, fb.scratch.p, fb.slot.as(), fb.src.as(), s); + ck(cudaStreamSynchronize(s), "sync"); + std::vector t2((size_t) 4 * E + 2); + ck(cudaMemcpy(t2.data(), fb.scratch.p, t2.size() * 4, cudaMemcpyDeviceToHost), "tables"); + std::printf(" group() again, synchronized: cnt[0..3] %d %d %d %d off[E] %d\n", t2[0], t2[1], t2[2], t2[3], + t2[(size_t) 2 * E]); + for (int e = 0; e < E; ++e) { + bad_cnt += tbl[(size_t) e] != r.cnt[(size_t) e]; + bad_off += tbl[(size_t) E + e] != r.off[(size_t) e]; + } + std::printf(" GROUPING WRONG: %lld pairs outside their expert's rows, %lld src mismatches; tables: %lld counts " + "and %lld offsets differ from the host's (cnt[0..3] %d %d %d %d vs %d %d %d %d)\n", + (long long) bad, (long long) bad_src, (long long) bad_cnt, (long long) bad_off, tbl[0], tbl[1], + tbl[2], tbl[3], r.cnt[0], r.cnt[1], r.cnt[2], r.cnt[3]); + throw std::runtime_error(std::string(p.name) + ": the grouping is wrong"); + } + } + if (std::getenv("S20_ROWDIAG")) { // the pairs whose rows differ most: expert, its rows, the row's place + const std::vector fsrc = download_i(fb.src, (size_t) rows); + std::vector> worst; + for (size_t i = 0; i < (size_t) rows; ++i) { + const float* a = y_f.data() + (size_t) slot[i] * N; + const float* m = y_mmq.data() + (size_t) r.row_of[i] * N; + double me = 0, mr = 0; + for (int o = 0; o < N; ++o) { me = std::max(me, (double) std::fabs(a[o] - m[o])); mr = std::max(mr, (double) std::fabs(m[o])); } + worst.push_back({mr > 0 ? me / mr : me, i}); + } + std::sort(worst.rbegin(), worst.rend()); + for (int k = 0; k < 12; ++k) { + const size_t i = worst[(size_t) k].second; + const int e = ids[i]; + // the expert's rows start at its first fused row: the smallest slot of its pairs + int32_t first = INT32_MAX; + for (size_t j = 0; j < (size_t) rows; ++j) if (ids[j] == e) first = std::min(first, slot[j]); + std::printf(" pair %zu token %zu expert %d (%d rows) fused row %d (+%d in the expert) max rel %.3e\n", i, + i / K, e, r.cnt[(size_t) e], slot[i], slot[i] - first, worst[(size_t) k].first); + } + (void) fsrc; + } + // both against the double-precision reference on a sample of 96 pairs + { + std::vector pick; + for (size_t i = 0; i < 96; ++i) pick.push_back((i * 2654435761u) % (size_t) rows); + std::vector ref(pick.size() * N), ym(pick.size() * N), yf(pick.size() * N); + std::vector hb(geo.bytes); + std::vector gu, dn, h(FF); + for (size_t j = 0; j < pick.size(); ++j) { + const size_t i = pick[j]; + const int e = ids[i]; + ck(cudaMemcpy(hb.data(), blob[(size_t) e], geo.bytes, cudaMemcpyDeviceToHost), "blob back"); + dequant(p, geo, hb, gu, dn); + const float* xr = x.data() + (i / K) * N; + for (int f = 0; f < FF; ++f) { + double gt = 0, up = 0; + const float *wg = gu.data() + (size_t) f * N, *wu = gu.data() + (size_t) (FF + f) * N; + for (int k = 0; k < N; ++k) { gt += (double) wg[k] * xr[k]; up += (double) wu[k] * xr[k]; } + h[(size_t) f] = (float) (gt / (1.0 + std::exp(-gt)) * up); + } + for (int o = 0; o < N; ++o) { + double a = 0; + const float* wd = dn.data() + (size_t) o * FF; + for (int f = 0; f < FF; ++f) a += (double) wd[f] * h[(size_t) f]; + ref[j * N + o] = (float) a; + } + std::copy_n(y_mmq.begin() + (ptrdiff_t) ((size_t) r.row_of[i] * N), N, ym.begin() + (ptrdiff_t) (j * N)); + std::copy_n(y_f.begin() + (ptrdiff_t) ((size_t) slot[i] * N), N, yf.begin() + (ptrdiff_t) (j * N)); + } + auto id = [](size_t j) { return (int64_t) j; }; + const Err em = compare(ym, id, ref, id, pick.size()), ef = compare(yf, id, ref, id, pick.size()); + std::printf(" sample of %zu pairs vs FP32 reference: MMQ rel RMS %.3e worst %.3e, fused rel RMS %.3e worst " + "%.3e\n", pick.size(), em.rms, em.worst, ef.rms, ef.worst); + if (ef.rms > 1.5 * em.rms || ef.worst > 2.0 * em.worst) + throw std::runtime_error(std::string(p.name) + ": the fused path's error is not comparable to MMQ's (timing)"); + } + cudaEventDestroy(a); + cudaEventDestroy(b); + if (efm.rms > 0.05) throw std::runtime_error(std::string(p.name) + ": the paths disagree at the real shape"); +} +} // namespace + +int main(int argc, char** argv) { + try { +#ifdef _WIN32 + _putenv_s("STRATA_PF_FUSED", "1"); +#else + setenv("STRATA_PF_FUSED", "1", 1); +#endif + int n = 0; + if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { std::printf("no CUDA device: skipped\n"); return 77; } + if (!fused::available()) { std::printf("the fused kernels need sm_80 or newer: skipped\n"); return 77; } + if (!mmq::built()) { std::printf("no MMQ in this build\n"); return 1; } + const std::vector pairs = { + {GGML_TYPE_IQ2_S, GGML_TYPE_Q2_0, "IQ2_S / Q2_0"}, {GGML_TYPE_IQ2_XXS, GGML_TYPE_Q2_0, "IQ2_XXS / Q2_0"}, + {GGML_TYPE_IQ2_XS, GGML_TYPE_IQ4_NL, "IQ2_XS / IQ4_NL"}, {GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ4_NL, "IQ3_XXS / IQ4_NL"}, + {GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL, "IQ3_S / IQ4_NL"}, {GGML_TYPE_IQ4_XS, GGML_TYPE_Q2_0, "IQ4_XS / Q2_0"}}; + const char* only = nullptr; // --only=NAME: the pairs whose name contains NAME + for (int i = 1; i < argc; ++i) + if (std::strncmp(argv[i], "--only=", 7) == 0) only = argv[i] + 7; + bool timing = true, ref = true; // --no-timing, --no-ref: skip a part + std::vector chunks = {2048, 3584, 8192}; // --chunks=A,B: the timing part's chunk sizes + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--no-timing") == 0) timing = false; + if (std::strcmp(argv[i], "--no-ref") == 0) ref = false; + if (std::strncmp(argv[i], "--chunks=", 9) == 0) { + chunks.clear(); + for (const char* c = argv[i] + 9; *c;) { + chunks.push_back(std::atoi(c)); + while (*c && *c != ',') ++c; + if (*c == ',') ++c; + } + } + } + cudaStream_t s = nullptr; + ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream"); + for (const Pair& p : pairs) { + if (only && std::string(p.name).find(only) == std::string::npos) continue; + if (!fused::native_supported((int) p.gu, (int) p.d)) + throw std::runtime_error(std::string(p.name) + ": not covered by the native kernels"); + if (ref) reference_part(p, s); + } + if (timing) { + // the IQ2_XS pack's layers (34 of 48 IQ2_S / Q2_0, 11 IQ2_XXS / Q2_0), the IQ3_S pack's most common, IQ3_XXS's + for (const Pair& p : {pairs[0], pairs[1], pairs[4], pairs[3]}) { + if (only && std::string(p.name).find(only) == std::string::npos) continue; + for (int T : chunks) timing_part(p, T, s); + } + } + ck(cudaStreamDestroy(s), "destroy"); + std::printf("prefill fused MoE (native formats) parity passed\n"); + return 0; + } catch (const std::exception& e) { + std::fprintf(stderr, "prefill fused MoE (native formats) parity failed: %s\n", e.what()); + return 1; + } +} diff --git a/tests/cuda/prefill_fused_moe_test.cpp b/tests/cuda/prefill_fused_moe_test.cpp new file mode 100644 index 0000000..991b663 --- /dev/null +++ b/tests/cuda/prefill_fused_moe_test.cpp @@ -0,0 +1,420 @@ +// prefill_fused_moe_test - #136: the fused int8 expert kernels of the prompt path (moe_fused.hpp, STRATA_PF_FUSED=1) +// on random Strata Q2_0 expert blobs and random routing, against +// - a double-precision reference: the dequantized weights times the FP32 activations (gate/up, SwiGLU, down), and +// - the MMQ path in prefill.cpp's sequence (gather_strata_q2 into 16-expert groups, q8_1 of the slots' activations, +// gate/up, SwiGLU, q8_1 of H, down). +// Both round the activations and H to int8 per 32 values, differently, so this is not a bitwise test: the fused +// path's error against the reference has to be comparable to MMQ's own (at most 1.5x its RMS and 2x its worst row). +// Part 1 (reference): 256 tokens over 64 experts, skewed routing - experts with 0 rows, with one, with several 64-row +// tiles - an all-zero token, per-expert blobs at unrelated addresses, three launches of different expert ranges. +// Part 2 (timing): one layer at a real chunk (2048 tokens, 512 experts, top 10) on both paths, with their agreement. +// Exit 77 without a CUDA device of sm_80 or newer. +#include "strata/prefill/moe_fused.hpp" +#include "strata/prefill/moe_mmq.hpp" + +#include "ggml.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace mmq = strata::prefill::mmq; +namespace fused = strata::prefill::fused; + +constexpr int N = 2560, FF = 640, K = 10, GROUP = 16, Q2 = 42; // GGML_TYPE_Q2_0 +constexpr size_t BLOB = 1382400, O_D_CODES = (size_t) 1280 * 640, O_GU_SC = O_D_CODES + (size_t) 2560 * 160, + O_D_SC = O_GU_SC + (size_t) 1280 * 40 * 2; + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e)); +} + +struct Dev { + void* p = nullptr; + explicit Dev(size_t n) { ck(cudaMalloc(&p, n), "cudaMalloc"); } + ~Dev() { cudaFree(p); } + Dev(const Dev&) = delete; + Dev& operator=(const Dev&) = delete; + template T* as() const { return (T*) p; } +}; + +// a Strata Q2_0 blob: random codes, scales in [0.004, 0.03] (a 2-bit expert's range) +std::vector make_blob(std::mt19937& rng) { + std::vector b(BLOB); + std::uniform_int_distribution byte(0, 255); + std::uniform_real_distribution sc(0.004f, 0.03f); + for (size_t i = 0; i < O_GU_SC; ++i) b[i] = (uint8_t) byte(rng); + for (size_t i = O_GU_SC; i < BLOB; i += 2) { + const ggml_fp16_t h = ggml_fp32_to_fp16(sc(rng)); + std::memcpy(&b[i], &h, 2); + } + return b; +} + +// the blob's weights as floats: gate/up [1280][2560] (interleaved rows), down [2560][640] +void dequant(const std::vector& b, std::vector& gu, std::vector& dn) { + auto row = [&](size_t codes, size_t ld, size_t scales, int nb, int r, float* out) { + for (int k = 0; k < nb * 64; ++k) { + ggml_fp16_t h; + std::memcpy(&h, &b[scales + ((size_t) r * nb + k / 64) * 2], 2); + const int q = (b[codes + (size_t) r * ld + k / 4] >> (2 * (k % 4))) & 3; + out[k] = ggml_fp16_to_fp32(h) * (float) (q - 1); + } + }; + gu.resize((size_t) 1280 * N); + dn.resize((size_t) N * FF); + for (int r = 0; r < 1280; ++r) row(0, 640, O_GU_SC, 40, r, gu.data() + (size_t) r * N); + for (int r = 0; r < N; ++r) row(O_D_CODES, 160, O_D_SC, 10, r, dn.data() + (size_t) r * FF); +} + +// activations: N(0, 1) with a few large values (the hidden state has outliers); token `zero` all zero +std::vector make_x(int T, std::mt19937& rng, int zero) { + std::vector x((size_t) T * N); + std::normal_distribution nd(0.0f, 1.0f); + std::uniform_int_distribution pick(0, 199); + for (float& v : x) v = nd(rng) * (pick(rng) == 0 ? 12.0f : 1.0f); + if (zero >= 0) std::fill(x.begin() + (size_t) zero * N, x.begin() + (size_t) (zero + 1) * N, 0.0f); + return x; +} + +// K distinct experts per token; `hot` > 0 skews the first choices towards the lowest ids +std::vector make_ids(int T, int E, std::mt19937& rng, int hot, int unused) { + std::vector ids((size_t) T * K); + std::uniform_int_distribution any(0, E - 1 - unused); + for (int t = 0; t < T; ++t) + for (int k = 0; k < K; ++k) { + int e; + bool dup; + do { + e = (hot > 0 && k < 3 && (int) (rng() % 4) != 0) ? (int) (rng() % (unsigned) hot) : any(rng); + dup = false; + for (int j = 0; j < k; ++j) dup |= ids[(size_t) t * K + j] == e; + } while (dup); + ids[(size_t) t * K + k] = e; + } + return ids; +} + +struct Routing { + std::vector cnt, off, src; // per expert; sorted row -> token (rows in pair order within an expert) + std::vector row_of; // pair -> sorted row +}; +Routing sort_rows(const std::vector& ids, int E) { + Routing r; + r.cnt.assign((size_t) E, 0); + for (int32_t e : ids) ++r.cnt[(size_t) e]; + r.off.assign((size_t) E + 1, 0); + for (int e = 0; e < E; ++e) r.off[(size_t) e + 1] = r.off[(size_t) e] + r.cnt[(size_t) e]; + std::vector fill(r.off.begin(), r.off.end() - 1); + r.src.resize(ids.size()); + r.row_of.resize(ids.size()); + for (size_t i = 0; i < ids.size(); ++i) { + const int32_t p = fill[(size_t) ids[i]]++; + r.row_of[i] = p; + r.src[(size_t) p] = (int32_t) (i / K); + } + return r; +} + +// MMQ, as prefill.cpp runs it: per group of 16 routed experts a gather, gate/up, SwiGLU, q8_1 of H, down. Returns +// Dm [rows][N] in sorted-row order. +struct MmqBufs { + Dev xq, gu, h, hq, dm, ident, bounds, grp_gu, grp_d; + MmqBufs(int64_t rows, int E) + : xq(mmq::q8_bytes(rows, N)), gu((size_t) rows * 1280 * 4), h((size_t) rows * FF * 4), + hq(mmq::q8_bytes(rows, FF)), + dm((size_t) rows * N * 4), ident((size_t) rows * 4), bounds((size_t) (2 * (E + E / GROUP + 2)) * 4), + grp_gu(GROUP * mmq::matrix_bytes(Q2, 1280, N) + 4096), grp_d(GROUP * mmq::matrix_bytes(Q2, N, FF) + 4096) {} +}; +void run_mmq(mmq::Context& ctx, MmqBufs& b, const Routing& r, const float* x_dev, const int32_t* src_dev, + const std::vector& blob, int64_t rows, cudaStream_t s) { + const size_t gub = mmq::matrix_bytes(Q2, 1280, N), db = mmq::matrix_bytes(Q2, N, FF); + const int E = (int) r.cnt.size(); + std::vector order; + for (int e = 0; e < E; ++e) if (r.cnt[(size_t) e] > 0) order.push_back(e); + const size_t n = order.size(), ng = (n + GROUP - 1) / GROUP; + std::vector bh(n + 1 + ng * (GROUP + 1)); + for (size_t j = 0; j < n; ++j) bh[j] = r.off[(size_t) order[j]]; + bh[n] = (int32_t) rows; + for (size_t g = 0; g < ng; ++g) + for (size_t i = 0; i <= GROUP; ++i) + bh[n + 1 + g * (GROUP + 1) + i] = bh[std::min(n, g * GROUP + i)] - bh[g * GROUP]; + ck(cudaMemcpyAsync(b.bounds.p, bh.data(), bh.size() * 4, cudaMemcpyHostToDevice, s), "bounds"); + mmq::iota(b.ident.as(), rows, s); + mmq::quantize(x_dev, src_dev, b.xq.p, Q2, N, N, rows, s); + for (size_t j = 0; j < n; ++j) { + const size_t q = j % GROUP; + mmq::gather_strata_q2(blob[(size_t) order[j]], b.grp_gu.as() + q * gub, b.grp_d.as() + q * db, + s); + if (q + 1 < GROUP && j + 1 < n) continue; + const size_t j0 = j - q, g = j0 / GROUP; + const int ngx = (int) (q + 1); + const int64_t r0 = bh[j0], nr = bh[j + 1] - r0; + int64_t maxr = 0; + for (size_t i = j0; i <= j; ++i) maxr = std::max(maxr, r.cnt[(size_t) order[i]]); + ck(cudaMemsetAsync(b.grp_gu.as() + (size_t) ngx * gub, 0, 4096, s), "tail"); + ck(cudaMemsetAsync(b.grp_d.as() + (size_t) ngx * db, 0, 4096, s), "tail"); + mmq::Product gu; + gu.w = b.grp_gu.p; gu.type = Q2; gu.w_rows = 1280; gu.w_cols = N; gu.expert_bytes = gub; + gu.n = ngx; gu.xq = b.xq.p; gu.bounds = b.bounds.as() + j0; gu.ids = b.ident.as(); + gu.total_rows = rows; gu.max_rows = maxr; gu.dst = b.gu.as(); gu.ld_dst = 1280; + ctx.run(gu, s); + mmq::swiglu(b.gu.as() + r0 * 1280, b.h.as() + r0 * FF, nr, FF, true, s); + mmq::quantize(b.h.as() + r0 * FF, nullptr, b.hq.p, Q2, FF, FF, nr, s); + mmq::Product dn; + dn.w = b.grp_d.p; dn.type = Q2; dn.w_rows = N; dn.w_cols = FF; dn.expert_bytes = db; + dn.n = ngx; dn.xq = b.hq.p; dn.bounds = b.bounds.as() + n + 1 + g * (GROUP + 1); + dn.ids = b.ident.as(); dn.total_rows = nr; dn.max_rows = maxr; dn.dst = b.dm.as() + r0 * N; + dn.ld_dst = N; + ctx.run(dn, s); + } +} + +// the fused path: quantize, group on the device, then launches over expert ranges `cuts` (e.g. {0, 20, 64}) +struct FusedBufs { + Dev xa, ha, dm, scratch, slot, src, ids; + FusedBufs(int T, int64_t rows, int E) + : xa(fused::act_bytes(T, N)), ha(fused::act_bytes(rows, FF)), dm((size_t) rows * N * 4), + scratch(fused::group_bytes(rows, E)), slot((size_t) rows * 4), src((size_t) rows * 4), + ids((size_t) rows * 4) {} +}; +void run_fused(FusedBufs& b, const float* x_dev, int T, int E, const std::vector& cuts, + const std::vector& blob, cudaStream_t s) { + const int64_t rows = (int64_t) T * K; + fused::quantize_act(x_dev, T, N, b.xa.p, s); + fused::group(b.ids.as(), rows, K, E, b.scratch.p, b.slot.as(), b.src.as(), s); + for (size_t c = 0; c + 1 < cuts.size(); ++c) { + for (int e0 = cuts[c]; e0 < cuts[c + 1]; e0 += fused::kMaxBatch) { + fused::Batch bt; + bt.e0 = e0; + bt.e1 = std::min(cuts[c + 1], e0 + fused::kMaxBatch); + for (int e = bt.e0; e < bt.e1; ++e) bt.blob[e - bt.e0] = blob[(size_t) e]; + fused::experts(bt, E, rows, b.scratch.p, b.xa.p, b.src.as(), b.ha.p, b.dm.as(), s); + } + } +} + +struct Err { + double rms = 0, worst = 0; // RMS error / RMS of the reference; the worst row's max |error| / its max |ref| +}; +// y_a[row_a(i)] against y_b[row_b(i)] for every pair i (rows of N values) +template +Err compare(const std::vector& a, RA row_a, const std::vector& b, RB row_b, size_t pairs) { + double e2 = 0, r2 = 0; + Err out; + for (size_t i = 0; i < pairs; ++i) { + const float* ya = a.data() + (size_t) row_a(i) * N; + const float* yb = b.data() + (size_t) row_b(i) * N; + double me = 0, mr = 0; + for (int o = 0; o < N; ++o) { + if (!std::isfinite(ya[o])) throw std::runtime_error("a non-finite output"); + const double d = (double) ya[o] - yb[o]; + e2 += d * d; + r2 += (double) yb[o] * yb[o]; + me = std::max(me, std::fabs(d)); + mr = std::max(mr, (double) std::fabs(yb[o])); + } + if (mr > 0) out.worst = std::max(out.worst, me / mr); + else if (me > 0) out.worst = 1e30; // a zero row must stay exactly zero + } + out.rms = r2 > 0 ? std::sqrt(e2 / r2) : 0; + return out; +} + +std::vector download(const Dev& d, size_t n) { + std::vector h(n); + ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download"); + return h; +} +std::vector download_i(const Dev& d, size_t n) { + std::vector h(n); + ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download"); + return h; +} + +// part 1: against the double-precision reference +void reference_part(cudaStream_t s) { + constexpr int T = 256, E = 64, ZERO = 77; + std::mt19937 rng(136); + std::vector> host((size_t) E); + std::vector> dev; + std::vector blob((size_t) E); + for (int e = 0; e < E; ++e) { + host[(size_t) e] = make_blob(rng); + dev.push_back(std::make_unique(BLOB + 4096 * (size_t) (e % 3))); // unrelated addresses + uint8_t* p = dev.back()->as() + 256 * (size_t) (e % 3); // 16-byte aligned, not 512 + ck(cudaMemcpy(p, host[(size_t) e].data(), BLOB, cudaMemcpyHostToDevice), "blob"); + blob[(size_t) e] = p; + } + const std::vector x = make_x(T, rng, ZERO); + const std::vector ids = make_ids(T, E, rng, 2, 4); // experts 0, 1 hot (several tiles), 60-63 unused + const int64_t rows = (int64_t) T * K; + const Routing r = sort_rows(ids, E); + std::printf("reference part: %d tokens, %d experts, rows per expert: max %d, experts without rows %d\n", T, E, + *std::max_element(r.cnt.begin(), r.cnt.end()), (int) std::count(r.cnt.begin(), r.cnt.end(), 0)); + + Dev x_dev(x.size() * 4), src_dev((size_t) rows * 4); + ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); + ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src"); + mmq::Context ctx; + MmqBufs mb(rows, E); + // the uploads (legacy stream) must land before the non-blocking stream reads them (S20 found the kernels could run + // on all-zero routing otherwise - every pair on one expert: fast and wrong) + ck(cudaDeviceSynchronize(), "uploads"); + run_mmq(ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s); + FusedBufs fb(T, rows, E); + ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids"); + ck(cudaMemset(fb.dm.p, 0xff, (size_t) rows * N * 4), "sentinel"); // an unwritten row is NaN + ck(cudaDeviceSynchronize(), "uploads"); + run_fused(fb, x_dev.as(), T, E, {0, 1, 20, E}, blob, s); + ck(cudaStreamSynchronize(s), "sync"); + const std::vector y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N); + const std::vector slot = download_i(fb.slot, (size_t) rows), fsrc = download_i(fb.src, (size_t) rows); + for (int64_t i = 0; i < rows; ++i) + if (fsrc[(size_t) slot[(size_t) i]] != (int32_t) (i / K)) throw std::runtime_error("group: slot/src disagree"); + + // the reference, an expert at a time on all cores + std::vector ref((size_t) rows * N); + std::vector th; + const int nth = std::max(1, std::min(16, (int) std::thread::hardware_concurrency())); + for (int w = 0; w < nth; ++w) + th.emplace_back([&, w] { + std::vector gu, dn, h(FF); + for (int e = w; e < E; e += nth) { + if (r.cnt[(size_t) e] == 0) continue; + dequant(host[(size_t) e], gu, dn); + for (int64_t i = 0; i < rows; ++i) { + if (ids[(size_t) i] != e) continue; + const float* xr = x.data() + (size_t) (i / K) * N; + for (int f = 0; f < FF; ++f) { + double gt = 0, up = 0; + const float *wg = gu.data() + (size_t) (2 * f) * N, *wu = wg + N; + for (int k = 0; k < N; ++k) { gt += (double) wg[k] * xr[k]; up += (double) wu[k] * xr[k]; } + h[(size_t) f] = (float) (gt / (1.0 + std::exp(-gt)) * up); + } + for (int o = 0; o < N; ++o) { + double a = 0; + const float* wd = dn.data() + (size_t) o * FF; + for (int f = 0; f < FF; ++f) a += (double) wd[f] * h[(size_t) f]; + ref[(size_t) i * N + o] = (float) a; + } + } + } + }); + for (auto& t : th) t.join(); + + auto pair = [](size_t i) { return (int64_t) i; }; + auto mrow = [&](size_t i) { return (int64_t) r.row_of[i]; }; + auto frow = [&](size_t i) { return (int64_t) slot[i]; }; + const Err em = compare(y_mmq, mrow, ref, pair, (size_t) rows); + const Err ef = compare(y_f, frow, ref, pair, (size_t) rows); + const Err efm = compare(y_f, frow, y_mmq, mrow, (size_t) rows); + std::printf(" MMQ vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n", em.rms, em.worst); + std::printf(" fused vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n", ef.rms, ef.worst); + std::printf(" fused vs MMQ : rel RMS %.3e worst row max rel %.3e\n", efm.rms, efm.worst); + double zmax = 0; + for (int k = 0; k < K; ++k) + for (int o = 0; o < N; ++o) + zmax = std::max(zmax, (double) std::fabs(y_f[(size_t) slot[(size_t) (ZERO * K + k)] * N + o])); + if (zmax != 0) throw std::runtime_error("the all-zero token's outputs are not zero"); + if (ef.rms > 1.5 * em.rms || ef.worst > 2.0 * em.worst) + throw std::runtime_error("the fused path's error is not comparable to MMQ's"); +} + +// part 2: one layer at a real chunk, timed +void timing_part(cudaStream_t s) { + constexpr int T = 2048, E = 512; + std::mt19937 rng(1360); + const int64_t rows = (int64_t) T * K; + // 512 distinct blobs (708 MB) - the products read each once per tile, as the engine does + Dev blobs((size_t) E * BLOB); + { + std::vector b = make_blob(rng); + for (int e = 0; e < E; ++e) { + b[(size_t) e * 7919 % O_GU_SC] ^= (uint8_t) e; // not all equal + ck(cudaMemcpy(blobs.as() + (size_t) e * BLOB, b.data(), BLOB, cudaMemcpyHostToDevice), "blob"); + } + } + std::vector blob((size_t) E); + for (int e = 0; e < E; ++e) blob[(size_t) e] = blobs.as() + (size_t) e * BLOB; + const std::vector x = make_x(T, rng, -1); + const std::vector ids = make_ids(T, E, rng, 0, 0); + const Routing r = sort_rows(ids, E); + Dev x_dev(x.size() * 4), src_dev((size_t) rows * 4); + ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); + ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src"); + mmq::Context ctx; + MmqBufs mb(rows, E); + FusedBufs fb(T, rows, E); + ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids"); + ck(cudaDeviceSynchronize(), "uploads"); // the legacy-stream uploads before the timed non-blocking stream + cudaEvent_t a, b; + ck(cudaEventCreate(&a), "event"); + ck(cudaEventCreate(&b), "event"); + auto time = [&](auto&& f) { + std::vector ms; + for (int rep = 0; rep < 6; ++rep) { + ck(cudaEventRecord(a, s), "record"); + f(); + ck(cudaEventRecord(b, s), "record"); + ck(cudaEventSynchronize(b), "sync"); + float t = 0; + ck(cudaEventElapsedTime(&t, a, b), "elapsed"); + if (rep > 0) ms.push_back(t); // the first is the warm-up + } + std::sort(ms.begin(), ms.end()); + return ms[ms.size() / 2]; + }; + // the engine's batches: up to 128 experts per launch (the streamed ring decides; 4 launches here) + const float t_mmq = time([&] { run_mmq(ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s); }); + const float t_f = time([&] { run_fused(fb, x_dev.as(), T, E, {0, E}, blob, s); }); + const float t_f1 = time([&] { // one launch per 16 experts, MMQ's group size + std::vector cuts; + for (int e = 0; e <= E; e += 16) cuts.push_back(e); + run_fused(fb, x_dev.as(), T, E, cuts, blob, s); + }); + const std::vector y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N); + const std::vector slot = download_i(fb.slot, (size_t) rows); + const Err efm = compare(y_f, [&](size_t i) { return (int64_t) slot[i]; }, y_mmq, + [&](size_t i) { return (int64_t) r.row_of[i]; }, (size_t) rows); + std::printf("timing part: %d tokens x top %d over %d experts (%.1f rows per expert), one layer:\n", T, K, E, + (double) rows / E); + std::printf(" MMQ path (gathers, q8_1, products, SwiGLU, 32 groups): %.3f ms\n", t_mmq); + std::printf(" fused path (quantize, group, 4 launches of 128): %.3f ms (%.2fx)\n", t_f, t_mmq / t_f); + std::printf(" fused path, launches of 16 experts: %.3f ms\n", t_f1); + std::printf(" fused vs MMQ: rel RMS %.3e worst row max rel %.3e\n", efm.rms, efm.worst); + cudaEventDestroy(a); + cudaEventDestroy(b); + if (efm.rms > 0.05) throw std::runtime_error("the paths disagree at the real shape"); +} +} // namespace + +int main(int argc, char** argv) { + try { + int n = 0; + if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { std::printf("no CUDA device: skipped\n"); return 77; } + if (!fused::available()) { std::printf("the fused kernels need sm_80 or newer: skipped\n"); return 77; } + if (!mmq::built()) { std::printf("no MMQ in this build\n"); return 1; } + cudaStream_t s = nullptr; + ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream"); + reference_part(s); + if (!(argc > 1 && std::strcmp(argv[1], "--no-timing") == 0)) timing_part(s); + ck(cudaStreamDestroy(s), "destroy"); + std::printf("prefill fused MoE parity passed\n"); + return 0; + } catch (const std::exception& e) { + std::fprintf(stderr, "prefill fused MoE parity failed: %s\n", e.what()); + return 1; + } +} diff --git a/tests/cuda/prefill_mmq_kquant_test.cpp b/tests/cuda/prefill_mmq_kquant_test.cpp new file mode 100644 index 0000000..01e6eff --- /dev/null +++ b/tests/cuda/prefill_mmq_kquant_test.cpp @@ -0,0 +1,168 @@ +// prefill_mmq_kquant_test - the prompt path's MMQ products for the expert formats of Unsloth's UD-Q4_K_XL (Q4_K and +// Q5_K gate/up at 1280 x 2560, Q5_1 and Q8_0 down at 2560 x 640), on synthetic weights quantized by ggml's own +// reference quantizers, against a double-precision product of ggml's dequantized weights. MMQ rounds the activations +// to q8_1 by design, so this is a screen for layout, stride, expert-bound and row-id errors (the bounds of +// tests/hip/prefill_mmq_parity.cpp), not a bit-exactness test. Several experts per product, permuted rows, an +// all-zero row; the formats the build does not cover (Q6_K) must say so. +#include "strata/prefill/moe_mmq.hpp" + +#include "ggml.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace mmq = strata::prefill::mmq; + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e)); +} + +struct Dev { + void* p = nullptr; + explicit Dev(size_t n) { ck(cudaMalloc(&p, n), "cudaMalloc"); } + ~Dev() { cudaFree(p); } + Dev(const Dev&) = delete; + Dev& operator=(const Dev&) = delete; +}; + +std::vector make_matrix(ggml_type t, int64_t rows, int64_t cols, int expert, int trial) { + const auto* tr = ggml_get_type_traits(t); + if (tr == nullptr || tr->from_float_ref == nullptr) throw std::runtime_error("no reference quantizer"); + const size_t rb = ggml_row_size(t, cols); + std::vector out((size_t) rows * rb); + std::vector row((size_t) cols); + for (int64_t r = 0; r < rows; ++r) { + for (int64_t k = 0; k < cols; ++k) { + const int code = (int) ((k * 37 + r * 19 + expert * 23 + trial * 11) % 101) - 50; + row[(size_t) k] = 0.025f * std::sin(0.013f * (float) (k + 1) + 0.17f * (float) r + 0.31f * (float) expert) + + 0.0015f * (float) code; + } + tr->from_float_ref(row.data(), out.data() + (size_t) r * rb, cols); + } + return out; +} + +std::vector make_x(int rows, int64_t cols, int trial) { + std::vector x((size_t) rows * (size_t) cols); + for (int r = 0; r < rows; ++r) + for (int64_t k = 0; k < cols; ++k) + x[(size_t) r * (size_t) cols + (size_t) k] = + 0.45f * std::sin(0.009f * (float) (k + 1) + 0.23f * (float) r + 0.07f * (float) trial) + + 0.17f * std::cos(0.021f * (float) (k + 3) - 0.19f * (float) r) + + 0.002f * (float) (((k * 7 + r * 13 + trial * 5) % 19) - 9); + std::fill(x.end() - cols, x.end(), 0.0f); // an all-zero row: exactly zero out + return x; +} + +std::vector perm(int n, int shift, bool reverse) { + std::vector p((size_t) n); + for (int i = 0; i < n; ++i) p[(size_t) i] = (int32_t) (((reverse ? n - 1 - i : i) + shift) % n); + return p; +} + +// one grouped product: experts side by side at one stride (a zeroed tail after them, as prefill.cpp stages them) +void product(mmq::Context& ctx, cudaStream_t s, const char* name, ggml_type t, int64_t out_rows, int64_t cols, + const std::vector& counts, int trial) { + if (!mmq::supported((int) t)) throw std::runtime_error(std::string(name) + ": not covered by this build"); + const int n = (int) counts.size(), rows = std::accumulate(counts.begin(), counts.end(), 0); + std::vector bounds((size_t) n + 1, 0); + for (int e = 0; e < n; ++e) bounds[(size_t) e + 1] = bounds[(size_t) e] + counts[(size_t) e]; + const auto src = perm(rows, trial + 1, false), dst = perm(rows, trial + 2, true); + const std::vector x = make_x(rows, cols, trial); + const size_t eb = mmq::matrix_bytes((int) t, out_rows, cols); + if (eb != (size_t) out_rows * ggml_row_size(t, cols)) throw std::runtime_error(std::string(name) + ": matrix_bytes"); + std::vector> ws; + std::vector w((size_t) n * eb + 4096, 0); + for (int e = 0; e < n; ++e) { + ws.push_back(make_matrix(t, out_rows, cols, e, trial)); + std::copy(ws.back().begin(), ws.back().end(), w.begin() + (ptrdiff_t) ((size_t) e * eb)); + } + Dev dx(x.size() * 4), dsrc((size_t) rows * 4), ddst((size_t) rows * 4), db(bounds.size() * 4), dw(w.size()), + dxq(mmq::q8_bytes(rows, cols)), dy((size_t) rows * (size_t) out_rows * 4); + ck(cudaMemcpy(dx.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); + ck(cudaMemcpy(dsrc.p, src.data(), src.size() * 4, cudaMemcpyHostToDevice), "src"); + ck(cudaMemcpy(ddst.p, dst.data(), dst.size() * 4, cudaMemcpyHostToDevice), "dst"); + ck(cudaMemcpy(db.p, bounds.data(), bounds.size() * 4, cudaMemcpyHostToDevice), "bounds"); + ck(cudaMemcpy(dw.p, w.data(), w.size(), cudaMemcpyHostToDevice), "w"); + ck(cudaMemset(dy.p, 0xff, (size_t) rows * (size_t) out_rows * 4), "sentinel"); + mmq::quantize((const float*) dx.p, (const int32_t*) dsrc.p, dxq.p, (int) t, cols, cols, rows, s); + mmq::Product p; + p.w = dw.p; p.type = (int) t; p.w_rows = out_rows; p.w_cols = cols; p.expert_bytes = eb; p.n = n; + p.xq = dxq.p; p.bounds = (const int32_t*) db.p; p.ids = (const int32_t*) ddst.p; p.total_rows = rows; + p.max_rows = *std::max_element(counts.begin(), counts.end()); p.dst = (float*) dy.p; p.ld_dst = out_rows; + ctx.run(p, s); + ck(cudaGetLastError(), "launch"); + ck(cudaStreamSynchronize(s), "sync"); + std::vector got((size_t) rows * (size_t) out_rows); + ck(cudaMemcpy(got.data(), dy.p, got.size() * 4, cudaMemcpyDeviceToHost), "y"); + + const auto* tr = ggml_get_type_traits(t); + std::vector ref(got.size(), 0.0f), wd((size_t) out_rows * (size_t) cols); + for (int e = 0; e < n; ++e) { + const size_t rb = ggml_row_size(t, cols); + for (int64_t o = 0; o < out_rows; ++o) + tr->to_float(ws[(size_t) e].data() + (size_t) o * rb, wd.data() + (size_t) o * (size_t) cols, cols); + for (int r = bounds[(size_t) e]; r < bounds[(size_t) e + 1]; ++r) { + const float* xr = x.data() + (size_t) src[(size_t) r] * (size_t) cols; + for (int64_t o = 0; o < out_rows; ++o) { + double acc = 0; + const float* wr = wd.data() + (size_t) o * (size_t) cols; + for (int64_t k = 0; k < cols; ++k) acc += (double) wr[k] * xr[k]; + ref[(size_t) dst[(size_t) r] * (size_t) out_rows + (size_t) o] = (float) acc; + } + } + } + double err2 = 0, ref2 = 0, max_abs = 0, zero_max = 0; + for (size_t i = 0; i < got.size(); ++i) { + if (!std::isfinite(got[i])) throw std::runtime_error(std::string(name) + ": unwritten or non-finite output"); + const double d = (double) got[i] - ref[i]; + err2 += d * d; ref2 += (double) ref[i] * ref[i]; max_abs = std::max(max_abs, std::fabs(d)); + } + for (int r = 0; r < rows; ++r) + if (src[(size_t) r] == rows - 1) // the zero row + for (int64_t o = 0; o < out_rows; ++o) + zero_max = std::max(zero_max, (double) std::fabs(got[(size_t) dst[(size_t) r] * (size_t) out_rows + (size_t) o])); + const double rms = std::sqrt(ref2 / (double) ref.size()), rel = std::sqrt(err2 / (double) ref.size()) / rms; + std::printf("%-22s rows %2d experts %d ref_rms %.4g rel_l2 %.5f max/rms %.4f zero row %.3g\n", name, rows, n, rms, + rel, max_abs / rms, zero_max); + if (rel > 0.04 || max_abs / rms > 0.35 || zero_max > std::max(1e-5, 1e-4 * rms)) + throw std::runtime_error(std::string(name) + ": outside the screen"); +} +} // namespace + +int main() { + try { + if (!mmq::built()) { std::printf("no MMQ in this build\n"); return 1; } + if (mmq::supported(GGML_TYPE_Q6_K)) throw std::runtime_error("Q6_K should not be covered"); + cudaStream_t s = nullptr; + ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream"); + { + mmq::Context ctx; + const std::vector> batches{{1, 3, 3}, {4, 1, 2}, {2, 3}, {17}}; + int trial = 0; + for (const auto& counts : batches) { + const std::string tag = "-" + std::to_string(trial); + product(ctx, s, ("Q4_K gate/up" + tag).c_str(), GGML_TYPE_Q4_K, 1280, 2560, counts, trial); + product(ctx, s, ("Q5_K gate/up" + tag).c_str(), GGML_TYPE_Q5_K, 1280, 2560, counts, trial + 5); + product(ctx, s, ("Q5_1 down" + tag).c_str(), GGML_TYPE_Q5_1, 2560, 640, counts, trial + 9); + product(ctx, s, ("Q8_0 down" + tag).c_str(), GGML_TYPE_Q8_0, 2560, 640, counts, trial + 13); + ++trial; + } + } + ck(cudaStreamDestroy(s), "destroy"); + std::printf("prefill MMQ K-quant screen passed\n"); + return 0; + } catch (const std::exception& e) { + std::fprintf(stderr, "prefill MMQ K-quant screen failed: %s\n", e.what()); + return 1; + } +} 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 0000000..bf0c408 --- /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 0000000..61c34b8 --- /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 0000000..85164ba --- /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 0000000..42f0ed5 --- /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 0000000..7b2cbd4 --- /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 0000000..0da3e8f --- /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 diff --git a/tests/platform/direct_file_async.cpp b/tests/platform/direct_file_async.cpp new file mode 100644 index 0000000..f046b31 --- /dev/null +++ b/tests/platform/direct_file_async.cpp @@ -0,0 +1,60 @@ +#include "strata/platform/direct_file.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +using strata::platform::DirectFile; +using strata::platform::Completion; +static void check(bool ok, const char* why) { if (!ok) throw std::runtime_error(why); } +int main() { + char name[] = "/tmp/strata-direct-test-XXXXXX"; + int fd = mkstemp(name); + if (fd < 0) return 1; + close(fd); + void* memory = DirectFile::alloc_aligned(4096 * 18); + try { + check(memory != nullptr, "buffer allocation"); + { std::ofstream f(name, std::ios::binary); std::string bytes(4096 * 16 + 17, 'x'); f.write(bytes.data(), bytes.size()); } + DirectFile f; + std::string error; + setenv("STRATA_IO_THREADS", "4", 1); // the pool's size (out-of-range values are clamped to 1..64) + check(f.open(name, error), error.c_str()); + check(!f.submit(1, memory, 4096, 0, error), "unaligned request accepted"); + for (unsigned i = 0; i < 17; ++i) + check(f.submit(i * 4096, static_cast(memory) + i * 4096, 4096, i, error), error.c_str()); + std::vector seen(17); + unsigned count = 0; + while (count < 17) { + Completion c[17]; int n = f.wait(c, 17, 5000); + check(n > 0, "completion timeout"); + for (int i = 0; i < n; ++i) { + check(c[i].tag < 17 && !seen[c[i].tag], "wrong or repeated completion"); + seen[c[i].tag] = true; ++count; + check(c[i].ok && c[i].bytes == (c[i].tag == 16 ? 17u : 4096u), "incorrect full/EOF completion"); + check(static_cast(memory)[c[i].tag * 4096] == 'x', "read data mismatch"); + } + } + std::jthread waker([&] { f.wake(); }); + Completion c; check(f.wait(&c, 1, 5000) == 1 && c.tag == DirectFile::WAKE_TAG, "wake lost"); + waker.join(); + check(f.submit(0, memory, 4096, 99, error), error.c_str()); + f.close(); // Must drain outstanding buffer writes before returning. + std::memset(memory, 0, 4096); + check(f.open(name, error), error.c_str()); + check(f.wait(&c, 1, 0) == 0, "stale completion on reopen"); + check(f.submit(0, memory, 4096, 100, error), error.c_str()); + check(f.wait(&c, 1, 5000) == 1 && c.ok && c.tag == 100, "reopened read failed"); + f.close(); + DirectFile::free_aligned(memory); unlink(name); + std::cout << "direct_file_async: passed queued reads, short EOF, wake, close drain, reopen\n"; + return 0; + } catch (const std::exception& e) { + DirectFile::free_aligned(memory); unlink(name); + std::cerr << e.what() << '\n'; return 1; + } +} diff --git a/tools/_paths.py b/tools/_paths.py new file mode 100644 index 0000000..336719e --- /dev/null +++ b/tools/_paths.py @@ -0,0 +1,28 @@ +"""tools/_paths.py - where the tools find llama.cpp's gguf-py (for the MTP packer and the fixtures). + +Order: $STRATA_GGUF_PY, then /third_party/llama.cpp/gguf-py (what setup.py clones), then the development +tree's ../../.ref/llama.cpp/gguf-py. +""" +from __future__ import annotations + +import os +import sys +from pathlib import Path + +ENGINE = Path(__file__).resolve().parents[1] + + +def gguf_py() -> str: + cands = [os.environ.get("STRATA_GGUF_PY"), ENGINE / "third_party" / "llama.cpp" / "gguf-py", + ENGINE.parents[min(1, len(ENGINE.parents) - 1)] / ".ref" / "llama.cpp" / "gguf-py"] # the dev tree; a shallow install (G:\Strata) has no grandparent + for c in cands: + if c and (Path(c) / "gguf").is_dir(): + return str(c) + sys.exit("llama.cpp's gguf-py was not found: run setup.py (it clones llama.cpp into third_party/), " + "or set STRATA_GGUF_PY") + + +def add_gguf_py() -> None: + p = gguf_py() + if p not in sys.path: + sys.path.insert(0, p) diff --git a/tools/draft_vocab.py b/tools/draft_vocab.py new file mode 100644 index 0000000..b3cc9fc --- /dev/null +++ b/tools/draft_vocab.py @@ -0,0 +1,146 @@ +"""The draft head's token subset (rt/draft_vocab.bin): the vocabulary rows the MTP draft layer may propose. + +The engine reads rt/draft_vocab.bin (int32 token ids) when the draft layer binds and computes the draft logits over +those rows only: a smaller head is faster and takes less VRAM, but a token outside the subset can never be drafted. +The shipped subset was built from English and code and had 27 of the vocabulary's 55,328 Han tokens, so an answer in +Chinese drafted almost nothing (#137). This adds whole scripts to a subset: + + python tools/draft_vocab.py --gguf -00001-of-0000N.gguf --base data/draft_vocab.bin --add cjk \ + --out data/draft_vocab.bin + +--add takes han, kana, hangul, cjk_punct, cjk (those four) or cyrillic. The base ids keep their order; the added ones follow in +id order. --stats prints what a subset holds. + +A language written in a script the base already holds (French, Spanish, German... in Latin letters) needs specific +words and word pieces, not a whole script. --corpus adds the tokens of a text corpus in that language: the most +frequent ones that together cover --coverage (default 0.99) of the corpus's token occurrences (#597): + + python tools/draft_vocab.py --gguf -00001-of-0000N.gguf --base data/draft_vocab_en.bin \ + --corpus fr1.txt fr2.txt ... --coverage 0.99 --out data/draft_vocab_fr.bin + +It prints the share of the corpus's occurrences outside the base and outside the new subset. --add and --corpus +can be combined. +""" +from __future__ import annotations + +import argparse +import sys +from array import array +from collections import Counter +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import strata_tokenizer as ST # noqa: E402 + +SCRIPTS = { + "han": [(0x3400, 0x4DBF), (0x4E00, 0x9FFF), (0xF900, 0xFAFF), (0x20000, 0x2FA1F)], + "kana": [(0x3040, 0x30FF), (0x31F0, 0x31FF), (0xFF66, 0xFF9F)], + "hangul": [(0x1100, 0x11FF), (0x3130, 0x318F), (0xAC00, 0xD7AF)], + "cjk_punct": [(0x3000, 0x303F), (0xFF00, 0xFF65), (0xFFA0, 0xFFEF)], + # Ukrainian, Russian, Bulgarian, Serbian...: the shipped subset held 142 of the vocabulary's 18,580 Cyrillic tokens + "cyrillic": [(0x0400, 0x04FF), (0x0500, 0x052F), (0x1C80, 0x1C8F), (0x2DE0, 0x2DFF), (0xA640, 0xA69F)], +} +GROUPS = {"cjk": ["han", "kana", "hangul", "cjk_punct"]} + + +def scripts_of(text: str) -> set[str]: + found = set() + for ch in text: + c = ord(ch) + for name, ranges in SCRIPTS.items(): + if any(a <= c <= b for a, b in ranges): + found.add(name) + return found + + +def token_text(tok, i: int) -> str | None: + """A token's text, or None when its bytes are not whole UTF-8 characters (a piece of one) or it is special.""" + try: + return tok.token_bytes(i).decode("utf-8") + except (KeyError, UnicodeDecodeError, IndexError): + return None + + +def corpus_counts(tok, paths) -> Counter: + """Token occurrences over the corpus files (UTF-8 text, tokenized as plain text: no special tokens).""" + counts: Counter = Counter() + for path in paths: + counts.update(tok.encode(Path(path).read_text(encoding="utf-8"))) + return counts + + +def covering(counts: Counter, coverage: float) -> list[int]: + """The most frequent ids (ties: the lower id first) that together cover `coverage` of the occurrences.""" + total = sum(counts.values()) + picked, covered = [], 0 + for i, c in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])): + if covered >= coverage * total: + break + picked.append(i) + covered += c + return picked + + +def outside(counts: Counter, ids) -> float: + """The share of the occurrences whose token is not in `ids`.""" + total = sum(counts.values()) + have = set(ids) + return sum(c for i, c in counts.items() if i not in have) / total if total else 0.0 + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--gguf", required=True, help="the model's (first) GGUF file: its vocabulary") + ap.add_argument("--base", help="the subset to extend (int32 ids)") + ap.add_argument("--add", default="", help="comma list: han, kana, hangul, cjk_punct, cjk, cyrillic") + ap.add_argument("--corpus", nargs="+", default=[], help="UTF-8 text files in the language to add (#597)") + ap.add_argument("--coverage", type=float, default=0.99, + help="with --corpus: the share of its token occurrences the added tokens cover (default 0.99)") + ap.add_argument("--out", help="where to write the new subset") + ap.add_argument("--stats", action="store_true", help="print what the base (and the new) subset holds") + a = ap.parse_args() + + tok = ST.Tokenizer.from_gguf(a.gguf) + n = len(tok.tokens) + kinds = [scripts_of(t) if (t := token_text(tok, i)) is not None else set() for i in range(n)] + base = list(array("i", Path(a.base).read_bytes())) if a.base else [] + if any(i < 0 or i >= n for i in base): + sys.exit(f"{a.base} has ids outside the vocabulary ({n})") + + want = set() + for x in filter(None, (s.strip() for s in a.add.split(","))): + names = GROUPS.get(x, [x]) + if any(nm not in SCRIPTS for nm in names): + sys.exit(f"--add {x}: expected one of {', '.join([*SCRIPTS, *GROUPS])}") + want.update(names) + if not 0 < a.coverage <= 1: + sys.exit("--coverage: expected a share in (0, 1]") + counts = corpus_counts(tok, a.corpus) if a.corpus else Counter() + from_corpus = set(covering(counts, a.coverage)) if counts else set() + have = set(base) + added = [i for i in range(n) if i not in have and (kinds[i] & want or i in from_corpus)] + ids = base + added + + def stats(label, sel): + counts = {nm: sum(1 for i in sel if nm in kinds[i]) for nm in SCRIPTS} + full = {nm: sum(1 for k in kinds if nm in k) for nm in SCRIPTS} + print(f"{label}: {len(sel)} ids; " + ", ".join(f"{nm} {counts[nm]}/{full[nm]}" for nm in SCRIPTS)) + + if a.stats or not a.out: + if base: + stats("base", base) + if added: + stats("new", ids) + if counts: + print(f"corpus: {sum(counts.values())} token occurrences, {len(counts)} distinct; " + f"{len(from_corpus)} tokens cover {a.coverage:g}, {len(from_corpus - have)} of them not in the base") + print(f"corpus occurrences outside the base: {outside(counts, base):.2%}, outside the new subset: " + f"{outside(counts, ids):.2%}") + if a.out: + Path(a.out).write_bytes(array("i", ids).tobytes()) + print(f"wrote {a.out}: {len(ids)} ids ({len(added)} added)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gguf_reader.py b/tools/gguf_reader.py new file mode 100644 index 0000000..237d5fd --- /dev/null +++ b/tools/gguf_reader.py @@ -0,0 +1,142 @@ +"""Minimal GGUF v3 header reader - no ggml, no gguf-py. + +Written because the `gguf` PyPI package cannot open this artifact: its `GGMLQuantizationType` +enum has no member for type 42 (`Q2_0`), which is newer than the library. That is itself a P0.S6 +finding - the format this engine is specialized for is ahead of the standard tooling. + +This is the reference implementation for `src/artifact/` (architecture §15: "GGUF v3 reader (mmap, +no ggml dependency)"). It parses the header only; tensor data is never read. +""" +from __future__ import annotations + +import dataclasses +import pathlib +import struct +from typing import Any + +GGUF_MAGIC = 0x46554747 # "GGUF" little-endian + +# ggml_type values. 42 = Q2_0, the GSQ-RCO routed-expert encoding, absent from gguf-py as of 0.19. +GGML_TYPES: dict[int, str] = { + 0: "F32", 1: "F16", 2: "Q4_0", 3: "Q4_1", 4: "Q4_2", 5: "Q4_3", 6: "Q5_0", 7: "Q5_1", + 8: "Q8_0", 9: "Q8_1", 10: "Q2_K", 11: "Q3_K", 12: "Q4_K", 13: "Q5_K", 14: "Q6_K", + 15: "Q8_K", 16: "IQ2_XXS", 17: "IQ2_XS", 18: "IQ3_XXS", 19: "IQ1_S", 20: "IQ4_NL", + 21: "IQ3_S", 22: "IQ2_S", 23: "IQ4_XS", 24: "I8", 25: "I16", 26: "I32", 27: "I64", + 28: "F64", 29: "IQ1_M", 30: "BF16", 31: "Q4_0_4_4", 32: "Q4_0_4_8", 33: "Q4_0_8_8", + 34: "TQ1_0", 35: "TQ2_0", 36: "IQ4_NL_4_4", 37: "IQ4_NL_4_8", 38: "IQ4_NL_8_8", + 39: "MXFP4", 40: "NVFP4", 41: "Q4_0_8_8", 42: "Q2_0", +} + +# GGUF metadata value type ids +GGUF_META = { + 0: ("u8", 1), 1: ("i8", 1), 2: ("u16", 2), 3: ("i16", 2), 4: ("u32", 4), 5: ("i32", 4), + 6: ("f32", 4), 7: ("bool", 1), 8: ("string", None), 9: ("array", None), + 10: ("u64", 8), 11: ("i64", 8), 12: ("f64", 8), +} + +# ggml block geometry for the encodings this model uses: (block elements, bytes per block) +# This is what makes a per-tensor byte count checkable, and it is the contract the kernels share. +BLOCK_GEOMETRY: dict[str, tuple[int, int]] = { + "F32": (1, 4), "F16": (1, 2), "BF16": (1, 2), "F64": (1, 8), + "Q4_0": (32, 18), "Q4_1": (32, 20), "Q5_0": (32, 22), "Q5_1": (32, 24), + "Q8_0": (32, 34), "Q8_1": (32, 36), + "Q2_K": (256, 84), "Q3_K": (256, 110), "Q4_K": (256, 144), "Q5_K": (256, 176), + "Q6_K": (256, 210), "Q8_K": (256, 292), + "IQ2_XXS": (256, 66), "IQ2_XS": (256, 74), "IQ3_XXS": (256, 98), "IQ1_S": (256, 50), + "IQ4_NL": (32, 18), "IQ3_S": (256, 110), "IQ2_S": (256, 82), "IQ4_XS": (256, 136), + "IQ1_M": (256, 56), "Q2_0": (64, 18), "MXFP4": (32, 17), "NVFP4": (64, 36), +} + + +@dataclasses.dataclass +class TensorInfo: + name: str + shape: list[int] + type_id: int + type_name: str + offset: int + + @property + def elements(self) -> int: + n = 1 + for d in self.shape: + n *= d + return n + + def expected_bytes(self) -> int | None: + geom = BLOCK_GEOMETRY.get(self.type_name) + if geom is None: + return None + block_elems, block_bytes = geom + if self.elements % block_elems: + return None + return self.elements // block_elems * block_bytes + + +class GGUFFile: + def __init__(self, path: pathlib.Path): + self.path = pathlib.Path(path) + self.metadata: dict[str, Any] = {} + self.tensors: list[TensorInfo] = [] + self.version = 0 + self.alignment = 32 + with self.path.open("rb") as fh: + self._parse(fh) + self.data_start = self._data_start + + # ------------------------------------------------------------------ internals + def _parse(self, fh) -> None: + magic = struct.unpack(" str: + (n,) = struct.unpack(" dict[str, int]: + out: dict[str, int] = {} + for t in self.tensors: + out[t.type_name] = out.get(t.type_name, 0) + 1 + return dict(sorted(out.items(), key=lambda kv: -kv[1])) + + def find(self, needle: str) -> list[TensorInfo]: + return [t for t in self.tensors if needle in t.name] diff --git a/tools/gguf_writer.py b/tools/gguf_writer.py new file mode 100644 index 0000000..8ad3cd6 --- /dev/null +++ b/tools/gguf_writer.py @@ -0,0 +1,234 @@ +"""A minimal GGUF v3 WRITER, including `Q2_0`. + +Why this exists +--------------- +P1.S1 of the plan says the tiny synthetic model is "written as a real GGUF via `gguf-py`" using +"at least `Q2_0`". That does not work: `gguf-py` has no `GGMLQuantizationType` member for type 42, so +`GGMLQuantizationType(42)` raises `ValueError`. Verified in round 39 and again here. + +`src/artifact/` needs a writer regardless - P1.S2 requires a reader with no ggml dependency, and the +writer is its companion - so this is that writer in Python, where it can be validated immediately +against `tools/gguf_reader.py` and against llama.cpp. + +Scope: enough to build the P1.S1 tiny model. It is NOT a general-purpose quantizer; the only +quantizer implemented is `Q2_0`, and its contract is `docs/q2_0-contract.md`: + block = 64 elements, fp16 scale, 16 bytes of 2-bit codes, LSB-first, 4 codes per byte + d = amax, code = clamp(round(w/d) + 1, 0, 3), symbol = code - 1 -> {-1, 0, +1, +2} + +Self-checking: `python tools/gguf_writer.py` writes a synthetic v3 file, reads it back with +`gguf_reader.py`, and asserts the tensors and metadata survived byte-exactly. +""" +from __future__ import annotations + +import dataclasses +import pathlib +import struct +import sys + +import numpy as np + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +from gguf_reader import GGUF_MAGIC, GGUFFile # noqa: E402 + +# ggml_type ids we can write. Values match GGML_TYPES in gguf_reader.py. +TYPE_IDS = {"F32": 0, "F16": 1, "Q2_0": 42} +DEFAULT_ALIGNMENT = 32 + +_META_IDS = {"u8": 0, "i8": 1, "u16": 2, "i16": 3, "u32": 4, "i32": 5, "f32": 6, + "bool": 7, "string": 8, "array": 9, "u64": 10, "i64": 11, "f64": 12} + + +# ------------------------------------------------------------------ Q2_0, per docs/q2_0-contract.md +def quantize_q2_0(w: np.ndarray) -> bytes: + """(n,) float32 -> concatenated 18-byte blocks. n must be a multiple of 64.""" + w = np.asarray(w, dtype=np.float32).reshape(-1) + if w.size % 64: + raise ValueError(f"Q2_0 needs a multiple of 64 elements, got {w.size}") + blocks = w.reshape(-1, 64) + out = bytearray() + for b in blocks: + amax = float(np.max(np.abs(b))) + d = amax + # d = amax (NOT amax/2) - the grid is asymmetric, symbols land in {-1,0,+1,+2}. + code = np.zeros(64, dtype=np.uint8) if d == 0 else \ + np.clip(np.rint(b / d).astype(np.int32) + 1, 0, 3).astype(np.uint8) + packed = np.zeros(16, dtype=np.uint8) + # j -> byte j//4, bit (j%4)*2 ; four codes per byte, least significant first. + for j in range(64): + packed[j // 4] |= np.uint8(code[j] << ((j % 4) * 2)) + out += struct.pack(" np.ndarray: + """Inverse of the above, for the round-trip check. Mirrors `dequantize_row_q2_0`.""" + nblocks = len(raw) // 18 + out = np.empty(nblocks * 64, dtype=np.float32) + for i in range(nblocks): + d = struct.unpack_from("> ((j % 4) * 2)) & 0x03 + out[i * 64 + j] = (c - 1) * d + return out + + +# ------------------------------------------------------------------ writer +@dataclasses.dataclass +class _Tensor: + name: str + shape: list[int] # GGUF order: dim 0 varies fastest + type_name: str + data: bytes + + +class GGUFWriter: + def __init__(self, alignment: int = DEFAULT_ALIGNMENT): + self.alignment = alignment + self.metadata: dict[str, tuple[str, object]] = {} + self.tensors: list[_Tensor] = [] + + # ---- metadata + def add(self, key: str, value, type_name: str | None = None) -> None: + if type_name is None: + type_name = {bool: "bool", int: "i64", float: "f64", str: "string"}.get(type(value)) + if type_name is None: + if isinstance(value, list) and value: + elem = {bool: "bool", int: "i32", float: "f32", str: "string"}.get(type(value[0])) + if elem is None: + raise TypeError(f"unsupported array element {type(value[0])} for {key}") + type_name = "array:" + elem + else: + raise TypeError(f"cannot infer a GGUF type for {key}") + self.metadata[key] = (type_name, value) + + # ---- tensors + def add_f32(self, name: str, arr: np.ndarray) -> None: + a = np.ascontiguousarray(arr, dtype=" None: + """`arr` is (rows, in_features) row-major with every row `shape[0]` long; `shape` is the FULL + GGUF shape. The shape must be passed explicitly, not inferred as [in, rows]: a fused expert + tensor is [in, out, experts], and inferring 2-D produced `[64, 4096]` where llama.cpp expects + `[64, 256, 16]`. Q2_0 blocks run along dim 0 only, so the extra axes are just a layout. + """ + a = np.asarray(arr, dtype=np.float32) + in_features = shape[0] + if a.ndim != 2 or a.shape[1] != in_features: + raise ValueError(f"{name}: expected (rows, {in_features}), got {a.shape}") + if a.shape[0] * in_features != int(np.prod(shape)): + raise ValueError(f"{name}: {a.shape} does not cover shape {shape}") + per_row = quantize_q2_0(a.reshape(-1)) # row-major: row 0 first + self.tensors.append(_Tensor(name, list(shape), "Q2_0", per_row)) + + # ---- serialisation + def _kv_bytes(self, key: str, type_name: str, value) -> bytes: + out = bytearray() + out += struct.pack(" bytes: + if type_name == "string": + b = v.encode("utf-8") + return struct.pack(" pathlib.Path: + path = pathlib.Path(path) + body = bytearray() + body += struct.pack(" int: + rng = np.random.default_rng(7) + w = GGUFWriter() + w.add("general.architecture", "qwen4exp") + w.add("qwen4exp.block_count", 8, "u32") + w.add("qwen4exp.test.array", [1, 2, 3, 4], "array:i32") + w.add("general.name", "strata tiny") + + A = rng.standard_normal((16, 64)).astype(np.float32) + B = rng.standard_normal((4, 8)).astype(np.float32) + w.add_q2_0("blk.0.ffn_gate_exps.weight", A, 64) + w.add_f32("blk.0.ssm_a", B) + + p = pathlib.Path(__file__).resolve().parent.parent / "bench" / "tiny-selftest.gguf" + w.write(p) + print(f"wrote {p.name} ({p.stat().st_size} B)") + + g = GGUFFile(p) + ok = True + print(f" version {g.version} tensors {len(g.tensors)} metadata {len(g.metadata)}") + if g.metadata.get("general.architecture") != "qwen4exp": print(" FAIL arch"); ok = False + if g.metadata.get("qwen4exp.block_count") != 8: print(" FAIL u32"); ok = False + if g.metadata.get("qwen4exp.test.array") != [1, 2, 3, 4]: print(" FAIL array"); ok = False + + by = {t.name: t for t in g.tensors} + t = by.get("blk.0.ffn_gate_exps.weight") + if t is None or t.type_name != "Q2_0" or t.shape != [64, 16]: + print(f" FAIL tensor dir: {t}"); ok = False + else: + with p.open("rb") as fh: + fh.seek(g.data_start + t.offset) + raw = fh.read(16 * 18) + back = dequantize_q2_0(raw) + err = np.abs(back - A.reshape(-1)).max() + rel = float(np.abs(back - A.reshape(-1)).mean() / np.abs(A).mean()) + print(f" Q2_0 round trip: max abs {err:.4f} mean rel {rel*100:.2f}% " + f"(quantization error, not a write bug)") + # The real check: re-quantizing the DEQUANTIZED values must be a fixed point. + again = dequantize_q2_0(quantize_q2_0(back)) + if not np.array_equal(again, back): + print(" FAIL Q2_0 is not a fixed point under requantization"); ok = False + else: + print(" Q2_0 fixed point: PASS (requantizing the dequantized values is exact)") + print("SELF-CHECK " + ("PASS" if ok else "FAIL")) + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(_selfcheck()) diff --git a/tools/iq_fixture.py b/tools/iq_fixture.py new file mode 100644 index 0000000..8cfcf92 --- /dev/null +++ b/tools/iq_fixture.py @@ -0,0 +1,137 @@ +"""tools/iq_fixture.py - deterministic i-quant fixtures for src/kernels/iq_parity.cpp (TODO 24). + +For each of the ten types iq_parity tests, writes `/.bin` (int32 header: the KERNEL type id, +rows, cols - then the raw GGUF block bytes) and `/.f32` (rows*cols float32 reference values, +dequantized by the same library the comparison treats as ground truth): + + python tools/iq_fixture.py --out build/iq_fixture + python tools/iq_fixture.py --out build/iq_fixture --seed 7 --rows 32 --cols 256 + +Generation is deterministic: an explicit seed and fixed dimensions, and every random choice comes from +numpy's RandomState under that seed. The blocks are synthetic on purpose: the i-quant formats have no +published quantizer in gguf-py (it dequantizes only), so each block combines sane half-precision scales +(written at the layout's scale offsets, see SCALE_OFFSETS below) with seeded index/sub-scale bytes - the +dequantized reference covers real codebook values either way, which is what the parity compares. + +Dependencies: python3 and numpy, plus the repository's VENDORED gguf-py (third_party/llama.cpp/gguf-py - +no pip install; it is put on sys.path relative to this file). Q2_0 is this repository's own format +(GGML type 42, which gguf-py does not carry): its codec comes from tools/gguf_writer.py. + +The kernel ids in the .bin headers are the repo's i-quant dispatch table (iq_kernels.cu is_iq / +iq_row_bytes) and match the vendored gguf-py's enum ids one for one - the layout table below is the +same GGML_QUANT_SIZES both sides compile in. +""" +from __future__ import annotations + +import argparse +import struct +import sys +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "third_party" / "llama.cpp" / "gguf-py")) +sys.path.insert(0, str(ROOT / "tools")) + +try: + import gguf + from gguf.quants import dequantize as gguf_dequantize + from gguf_writer import dequantize_q2_0, quantize_q2_0 +except ImportError as e: # a missing numpy or vendored gguf-py must be explicit, not a traceback + sys.stderr.write(f"iq_fixture: missing dependency: {e}\n" + "numpy and the repository's vendored gguf-py (third_party/llama.cpp/gguf-py) are " + "required. The vendored copy comes with setup's llama.cpp download (the pinned " + "LLAMA_CPP_COMMIT zip); on a fresh checkout run setup once, or fetch that zip and " + "unpack its gguf-py there.\n") + sys.exit(3) + +QT = gguf.GGMLQuantizationType +# name -> (block values, block bytes, the fp16 scale offsets inside a block). The layouts mirror +# gguf-py's dequantize_blocks implementations: every one of these formats keeps its half-precision +# scale(s) at fixed offsets (IQ*_X*: offset 0; Q3_K: after the 32-byte hmask, 64-byte qs and the +# 12 scale bytes) - the rest of the block is indices and sub-scales, which are seeded random bytes. +LAYOUT = { # (block values, block bytes) == the vendored gguf-py's GGML_QUANT_SIZES == the kernels' sizes + "IQ2_XXS": (256, 66), + "IQ2_XS": (256, 74), + "IQ2_S": (256, 82), + "IQ3_XXS": (256, 98), + "IQ3_S": (256, 110), + "IQ1_M": (256, 56), + "IQ4_NL": (32, 18), + "IQ4_XS": (256, 136), + "Q3_K": (256, 110), +} +HALF_ONE = struct.pack(" None: + """Overwrite the fp16 scale bits of every block with a sane value, in place. The index and + sub-scale bytes stay seeded-random (their values are bounded by construction). Layouts mirror + gguf-py's dequantize_blocks: IQ*_X* and IQ4_* keep the fp16 scale at block offset 0; Q3_K keeps + it after the 32-byte hmask, 64-byte qs and 12 scale bytes; IQ1_M is "the only one which stores + the f16 scale in multiple parts" - the fp16 bits are the HIGH NIBBLES of the four uint16s at + bytes 48..56, so a 1.0 scale is nibbles 3, C, 0, 0 on bytes 49, 51, 54, 55.""" + if name == "Q3_K": + raw[:, 108:110] = np.frombuffer(HALF_ONE, dtype=np.uint8) + return + if name == "IQ1_M": + raw[:, 48:56] &= np.uint8(0x0F) # clear the four scale nibbles + for byte, nib in ((49, 0x30), (51, 0xC0), (54, 0x00), (55, 0x00)): + raw[:, byte] |= np.uint8(nib) + return + raw[:, 0:2] = np.frombuffer(HALF_ONE, dtype=np.uint8) +# name -> (the KERNEL type id written into the .bin header, identical to the gguf-py enum id) +KERNEL_IDS = {"IQ2_XXS": 16, "IQ2_XS": 17, "IQ2_S": 22, "IQ3_XXS": 18, "IQ3_S": 21, + "IQ1_M": 29, "IQ4_NL": 20, "IQ4_XS": 23, "Q2_0": 42, "Q3_K": 11} + + +def build(name: str, rows: int, cols: int, seed: int): + """The .bin body (header + raw blocks) and the .f32 reference for one type.""" + kernel_type = KERNEL_IDS[name] + n = rows * cols + rng = np.random.RandomState((seed, hash(name) & 0xFFFF) if False else (seed, KERNEL_IDS[name])) + if name == "Q2_0": # the repository's own codec, gguf-py has no type 42 + w = rng.standard_normal(n).astype(np.float32) + raw = np.frombuffer(quantize_q2_0(w), dtype=np.uint8) + ref = dequantize_q2_0(raw.tobytes()).astype(np.float32) + flat = raw + else: + block_values, block_bytes = LAYOUT[name] + blocks = n // block_values + raw = rng.randint(0, 256, (blocks, block_bytes), dtype=np.uint8) + repair_scales(name, raw) # sane fp16 scales; indices stay seeded-random + flat = raw.reshape(-1) + ref = np.asarray(gguf_dequantize(flat, getattr(QT, name)), dtype=np.float32) + if not np.isfinite(ref).all() or float(np.abs(ref).max()) > 1e4: + raise RuntimeError(f"{name}: the dequantized reference is not finite/tame - the layout table " + f"(block bytes, scale offsets) does not match gguf-py's dequantizer") + header = struct.pack("<3i", kernel_type, rows, cols) + return header + flat.tobytes(), ref + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--out", default="logs/iq_fixture", help="the fixture directory (created; may live in the " + "build directory - the source tree is not written)") + ap.add_argument("--seed", type=int, default=7, help="the fixture RNG seed (deterministic generation)") + ap.add_argument("--rows", type=int, default=32, help="weight rows (rows*cols stays a multiple of 256)") + ap.add_argument("--cols", type=int, default=256, help="the reduction dimension, a multiple of 256") + args = ap.parse_args() + if args.cols % 256 or args.rows * args.cols % 256: + ap.error("--cols must be a multiple of 256 and rows*cols a multiple of 256") + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + for name in KERNEL_IDS: + blob, ref = build(name, args.rows, args.cols, args.seed) + (out / f"{name}.bin").write_bytes(blob) + (out / f"{name}.f32").write_bytes(np.ascontiguousarray(ref, dtype="2} {args.rows} x {args.cols} " + f"{len(blob) - 12} block bytes, {ref.size} reference floats") + print(f"iq_fixture: {len(KERNEL_IDS)} fixtures in {out} (seed {args.seed})") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/iq_pack.py b/tools/iq_pack.py new file mode 100644 index 0000000..8676675 --- /dev/null +++ b/tools/iq_pack.py @@ -0,0 +1,602 @@ +"""tools/iq_pack.py - plan v0.3 P6: a native pack for any of the model files (Q2_0, IQ2_XS, IQ3_XXS). + + python tools/iq_pack.py --gguf -00001-of-00002.gguf --out pack/iq3_xxs (standalone) + python tools/iq_pack.py --gguf -00001-of-00002.gguf --base pack/full --out ... (share dense.bin) + +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 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 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). + 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; 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 (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, a Q2_0/Q8_0 PLE key and the disk-backed PLE +table stay unchanged. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import pathlib +import re +import shutil +import subprocess +import sys + +import numpy as np + +HERE = pathlib.Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import gguf_reader as G # noqa: E402 + +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 + +# 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: + """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 + 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: + from _paths import add_gguf_py + add_gguf_py() + from gguf import GGMLQuantizationType as Q, quants + values = quants.dequantize(raw, Q[type_name]) + if not np.isfinite(values).all(): + raise ValueError("cannot convert non-finite weights to BF16") + # ggml's round-to-nearest-even conversion, including correct halfway rounding. + 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).""" + + def __init__(self, first: pathlib.Path): + import re + m = re.search(r"-(\d{5})-of-(\d{5})\.gguf$", first.name) + paths = [first] + if m: + total = int(m.group(2)) + paths = [first.with_name(first.name[:m.start()] + "-%05d-of-%05d.gguf" % (i, total)) + for i in range(1, total + 1)] + missing = [str(p) for p in paths if not p.is_file()] + 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, g in zip(paths, self.files): + mm = np.memmap(p, dtype=np.uint8, mode="r") + for t in g.tensors: + size = t.expected_bytes() + if size is None or g.data_start + t.offset + size > mm.size: + raise ValueError(f"{p.name}: unsupported or truncated tensor {t.name}") + if t.name in self.where: + raise ValueError(f"{p.name}: duplicate tensor {t.name}") + self.where[t.name] = (g, t, mm, p) + + 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 + + +def read_index(path: pathlib.Path): + rows, header = {}, [] + for line in path.read_text(encoding="utf-8").splitlines(): + if line.startswith("#"): + header.append(line) + continue + f = line.split() + rows[f[0]] = f + return header, rows + + +def tensor_bytes(mm, g, t) -> np.ndarray: + n = t.expected_bytes() + return mm[g.data_start + t.offset: g.data_start + t.offset + n] + + +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: 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, records = [], [] + with open(out / "dense.bin.tmp", "wb") as fo: + 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 + 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, + }, indent=2) + "\n", encoding="utf-8") + print("compat-bf16: %d tensors, %.2f GiB; expert and PLE table bytes unchanged" + % (len(converted), sum(t["bytes"] for t in converted) / 2**30)) + return 0 + + +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.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)) + + +def index_from_base(a, src, base, out, g, T, mm) -> int: + base_src = pathlib.Path(json.loads((base / "manifest.json").read_text(encoding="utf-8"))["source"]["shard1"]) + if not base_src.exists(): + print("cannot find the base pack's shard 1 from its manifest.json") + return 1 + bg = G.GGUFFile(base_src) + BT = {t.name: t for t in bg.tensors} + bmm = np.memmap(base_src, dtype=np.uint8, mode="r") + header, rows = read_index(base / "index.txt") + new_rows, extra = [], [] + served = 0 + for name, f in rows.items(): + t, bt = T.get(name), BT.get(name) + if t is None or bt is None: + print("tensor %s missing from one of the models" % name) + return 1 + if t.type_name in FLOAT and bt.type_name in FLOAT: + if t.type_name != bt.type_name or t.shape != bt.shape or \ + not np.array_equal(tensor_bytes(mm, g, t), tensor_bytes(bmm, bg, bt)): + print("float tensor %s differs from the base model; this pack cannot reuse its dense.bin" % name) + return 1 + new_rows.append(list(f)) + elif t.type_name in FLOAT: + if t.type_name != "BF16": + print("unexpected float type %s for %s" % (t.type_name, name)) + return 1 + nbytes = t.expected_bytes() + off = sum(len(b) + (-len(b)) % ALIGN for b in extra) + extra.append(tensor_bytes(mm, g, t).tobytes()) + # file 3 = extra.bin, raw BF16 (index kind 4) + new_rows.append([name, "3", "4", str(off), str(nbytes), "0", str(nbytes), f[7], f[8]] + ["0"] * 10) + else: + served += 1 + new_rows.append([name, f[1], "0", "0", "0", "0", "0", f[7], f[8], "8", "0", "32"] + ["0"] * 7) + write_index(out, new_rows, src, served, len(extra)) + with open(out / "extra.bin", "wb") as fo: + for b in extra: + fo.write(b) + fo.write(b"\0" * ((-len(b)) % ALIGN)) + dense = out / "dense.bin" + if not dense.exists(): + try: + os.link(base / "dense.bin", dense) + except OSError: + shutil.copyfile(base / "dense.bin", dense) + if (base / "tokenizer").exists() and not (out / "tokenizer").exists(): + shutil.copytree(base / "tokenizer", out / "tokenizer") + 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") + ap.add_argument("--base", help="optional: a Q2_0 canonical pack whose dense.bin holds the shared float tensors") + ap.add_argument("--out", required=True) + ap.add_argument("--skip-experts", action="store_true", help="rewrite the index only") + ap.add_argument("--compat-bf16", action="store_true", + help="dequantize small non-native projections to BF16 for ordinary Qwen4Exp GGUFs " + "(rounds weights; leaves experts and the PLE table unchanged)") + ap.add_argument("--experts-bin", action="store_true", + help="also write experts.bin (the engine otherwise reads the experts from the GGUF itself)") + 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: .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) + out.mkdir(parents=True, exist_ok=True) + + g = G.GGUFFile(src) + mm = np.memmap(src, dtype=np.uint8, mode="r") + model = Model(src) + 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 + + def layer_blobs(blob, ts): + chunk = np.concatenate([model.bytes(t.name).reshape(n_expert, -1) for t in ts], axis=1) + assert chunk.shape == (n_expert, blob) # (n_expert, blob): gate | up | down per expert + return chunk + + if reuse: + # the sidecar names the shards by name and size, which a re-quantized or fine-tuned checkpoint of the same + # geometry packed into the same folder can share: compare the first and last blobs of the first, middle and + # last layers with the GGUF too (six blobs, so an unchanged pack is still reused at once) + with open(path, "rb") as f: + for l, gt, dt, off, blob, ts in (layout[0], layout[len(layout) // 2], layout[-1]): + for e in (0, n_expert - 1): + f.seek(off + e * blob) + want_blob = b"".join(model.bytes(t.name).reshape(n_expert, -1)[e].tobytes() for t in ts) + if f.read(blob) != want_blob: + reuse = False + if not reuse: + print("%s matches %s but not this GGUF's expert blobs" % (path, sidecar.name)) + 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) + if rc: + return rc + if not (out / "tokenizer" / "vocab.json").exists() or not (out / "tokenizer" / "chat_template.jinja").exists(): + subprocess.run([sys.executable, str(HERE / "strata_tokenizer.py"), "--gguf", str(src), "--out", str(out)], + check=True) # writes /tokenizer/ + + # ---- 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(text) + tmp.replace(out / "native_experts.txt") + if a.skip_experts or 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 + if reuse: + print("experts.bin was cut from this model's shards (%s); not rewritten" % sidecar.name) + return 0 + # 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: + fo.write(layer_blobs(blob, ts).tobytes()) + if l % 8 == 0: + print(" layer %2d %-8s/%-7s blob %8d at %.2f GiB" % (l, ts[0].type_name, ts[2].type_name, blob, + off / 2**30), flush=True) + 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 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/make_profile.py b/tools/make_profile.py new file mode 100644 index 0000000..9916cf1 --- /dev/null +++ b/tools/make_profile.py @@ -0,0 +1,119 @@ +"""tools/make_profile.py - the expert-cache profile (`data/expert-profile.bin`): every (layer, expert) pair, ranked. + +`--expert-cache auto` fills the VRAM slots it can afford with the profile's pairs in order, so the ranking decides +which experts start resident (the adaptive tier then swaps in what a conversation routes most). A profile that +ranks fewer pairs than a card can hold caps the cache (issue #46: a 32 GB card stopped at 8,000 slots); this tool +writes one that ranks all 24,576. + +The order: the base profile's ranking (default: the shipped data/expert-profile.bin), then the pairs your routing +traces used, most frequent first, then every pair still missing, interleaved across the layers. The base is only +*appended to*, never reordered - and the shipped profile already ranks all 24,576 pairs, so with it a trace is a +no-op. `--reorder` ranks the traces first and lets the base fill the rest, which is how a workload's trace decides +the top; `--no-base` drops the base entirely. + + python tools/make_profile.py [TRACE ...] [--base data/expert-profile.bin | --no-base] [--reorder] [--out PATH] + [--n-expert 256] (a pruned model: GSQ-RCO Coder keeps 256 of 512) + +A routing trace comes from a one-shot engine run with `--dump-routing FILE` (a prompt typical of your use; the +routed experts of every layer and position are written). Point the model config's `--expert-profile` at the result. +""" +import argparse +import struct +from collections import defaultdict +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +N_LAYER, N_EXPERT = 48, 512 +MAGIC, VERSION = b"STRP", 1 + + +def read_profile(path, n_expert=N_EXPERT): + blob = Path(path).read_bytes() + if blob[:4] != MAGIC: + raise SystemExit(f"{path}: not a Strata profile") + ver, nl, ne, slots, n = struct.unpack_from("<5I", blob, 4) + if (nl, ne) != (N_LAYER, n_expert): + raise SystemExit(f"{path}: {nl}x{ne}, not {N_LAYER}x{n_expert}") + return [struct.unpack_from(" dtype, shape, byte range) +at the start of each shard, so HTTP range requests can read the headers and then only the MTP tensors. + + python tools/mtp_fetch.py inventory --out DIR # headers only (a few KB per shard) + python tools/mtp_fetch.py fetch --out DIR [--only SUBSTR] # the MTP tensors themselves, resumable + python tools/mtp_fetch.py verify --out DIR # the fetched tensors against SHA256 (exit 3: bad ones) + +`fetch` writes one raw file per tensor plus `mtp-manifest.json` (dtype, shape, source shard, byte range, +sha256). It never downloads anything but the ranges named in the headers. Nothing here runs a model. + +#327: a mirror or proxy that ignores the Range header answers 200 with the whole shard - its JSON header and +unrelated tensors - and a proxy may cut that to the requested length, so neither the size nor a hash of what was +downloaded catches it (the drafter then accepts nothing, silently). A range read therefore needs a 206 whose +Content-Range is the range asked for, and every tensor of the pinned revision is checked against SHA256 below. +""" +import argparse +import hashlib +import json +import os +import struct +import sys +import time +import urllib.error +import urllib.request + +# #214: a fixed commit of the checkpoint (its `sha` from https://huggingface.co/api/models/Qwen/Qwen3.8-Flash-Next +# on 2026-09-30), so every install reads the same tensors; STRATA_MTP_REVISION overrides it (e.g. main). When the +# repository no longer has it, the current files are read instead, with a message (resolve_repo). +PINNED_REVISION = "de4b8e4d43b917e7706784d8bb445c9af86a3540" +REVISION = os.environ.get("STRATA_MTP_REVISION") or PINNED_REVISION +# #495: HF_ENDPOINT (a mirror, e.g. https://hf-mirror.com) serves the same revision; the SHA256 checks below still apply +HF_ENDPOINT = (os.environ.get("HF_ENDPOINT") or "").strip().rstrip("/") or "https://huggingface.co" +REPO = HF_ENDPOINT + "/Qwen/Qwen3.8-Flash-Next/resolve/%s/" % REVISION +PINNED = HF_ENDPOINT + "/Qwen/Qwen3.8-Flash-Next/resolve/%s/" % PINNED_REVISION # SHA256's revision +DTYPE_BYTES = {"BF16": 2, "F16": 2, "F32": 4, "F8_E4M3": 1, "I64": 8, "I32": 4} +BAD = 3 # `verify`'s exit code: a tensor is missing or corrupt + +# #327: sha256 of every MTP tensor's bytes at PINNED_REVISION (two independent fetches agree, and 29 of them were read +# again from that revision; the two expert tensors' first and last 16 MiB), so a mirror that ignored the +# Range header (it sent the shard's start: its JSON header) is caught, and an install it corrupted is fetched again. +SHA256 = { + "mtp.fc_embedding.weight": + "241d6e87ded317a61b1aeb3ca4e28c53f1caba09ad5be66092e91fe5e3e14751", + "mtp.fc_hidden.weight": + "97c8e427ad0177e2c713ed24a397d815b523eda15ef453f1ae6463f6c70a8f96", + "mtp.hyper_connection_mixer.hc_norm.weight": + "ce948a398e15aeaa403c424cda34e6eed296ab2570d591bb5ff3da642b255d64", + "mtp.hyper_connection_mixer.input_mix_weight_down.weight": + "c633d2841fda463e82045e0b93fb8cb8d511ec0c9eda616020f01aca18d71947", + "mtp.hyper_connection_mixer.input_mix_weight_up.weight": + "6565285f0ba2923703252763cfc11d8a9bda40ab42e7548e12464b04dbdbec13", + "mtp.layers.0.attn_hyper_connection.block_inject_weight.weight": + "c8afff64e7f54412d02120097c4255033c55245e1c1eed84cc630d428ccb864c", + "mtp.layers.0.attn_hyper_connection.hc_norm.weight": + "1fb619aeaaf637ccd70f46f1f8f8116e6a46448cb43026b246de8ee8286ed809", + "mtp.layers.0.attn_hyper_connection.input_mix_weight_down.weight": + "e80ac8bf3e270e9d5a949ec7c913329dc8de017d69851334820fae7b8c86a7f5", + "mtp.layers.0.attn_hyper_connection.input_mix_weight_up.weight": + "f80f1fd44e1183e7764ea496b11ff89ead9dd758f861d4e79a770bf54956b1a5", + "mtp.layers.0.mlp.experts.down_proj": + "539c46234f73bac70450f731f40e715f77ac32faf77def0f3f800e58aaabbbc0", + "mtp.layers.0.mlp.experts.gate_up_proj": + "839e98f9642ebc884b178abd2090b6dc8b0bcd81ed92d7f7a08314c6a68f96d5", + "mtp.layers.0.mlp.gate.weight": + "f0d35fa41b360a08bc0c5b1e5766aa42df960291716ee189208b5d2599462c20", + "mtp.layers.0.mlp.shared_expert.down_proj.weight": + "d2ced8c81367cc494599d1a8cdc279c3dd6579b628ded05acd7495e99cee01d8", + "mtp.layers.0.mlp.shared_expert.gate_proj.weight": + "f4a81109165853b3b64f36d809f98094b599763364070f5fa079200e1c386d4c", + "mtp.layers.0.mlp.shared_expert.up_proj.weight": + "172586861eea53efbff10afc43ded5b6e49c83879e9efc01e089c652bbb0a156", + "mtp.layers.0.mlp.shared_expert_gate.weight": + "acdd306d9996d356e4667a16ff63af6fef086fc7f570f1bc00bbe882a2a93f6e", + "mtp.layers.0.mlp_hyper_connection.block_inject_weight.weight": + "c5782dd92b479a1f8ef43d683fe9c917fd9e8fba81f23c1aae8817bfe4b476a6", + "mtp.layers.0.mlp_hyper_connection.hc_norm.weight": + "21a504876b5e7b788301557c68dfb757999430eba36c66ec8ab96a63604dbfd1", + "mtp.layers.0.mlp_hyper_connection.input_mix_weight_down.weight": + "b71240036dea954e034d5ae04e097bcd7ac51cb28a44e4c93d198af3447278a1", + "mtp.layers.0.mlp_hyper_connection.input_mix_weight_up.weight": + "40756866bf2a5e82c28e407f717b6fa07614d593f78e79c7ceb2cd4ffe6dda94", + "mtp.layers.0.self_attn.indexer.index_qk_proj.weight": + "2befafae6e944c1fc651fd73d4d527eb6f138a6c1679065b003128ee3150e859", + "mtp.layers.0.self_attn.indexer.k_layernorm.weight": + "2db621f6a08b4085756fc69d60a4a1bd1d7fbf5d406456d2477075842efaae54", + "mtp.layers.0.self_attn.indexer.q_layernorm.weight": + "afaf59f68e251939970ffdeacad0667dffc657a522bea62cdc44a52816fc49d6", + "mtp.layers.0.self_attn.k_norm.weight": + "8f924b0357cf936e14fc34518205d000e1423aa60626827df81b0804fae8cdfd", + "mtp.layers.0.self_attn.k_proj.weight": + "1a295dc2d6e633e808aeb19e00c97856a1817bbfcc83f5b610e2bfcacfcb8c38", + "mtp.layers.0.self_attn.o_proj.weight": + "9d2fcf0ac6ac19de87f638f710cfd1af6ad14141e75b7d3d5d29fbd06f374219", + "mtp.layers.0.self_attn.q_norm.weight": + "57957aa1e7c5a3ac628bff0ec5522ad55a39b8c0b8bd2d324ae640e3771617ef", + "mtp.layers.0.self_attn.q_proj.weight": + "5220aef3d288f40759f7356af9ef453e5ac0256a38749a9bb803a4e9db58150d", + "mtp.layers.0.self_attn.v_proj.weight": + "39cb12f5424e965fa71fb81db0ee230c701b7b1e0b72c36641fde7e0e41bff41", + "mtp.pre_fc_norm_embedding.weight": + "04c4a570850e06f2d8913da8220d54d4c7f87db6eb6d45480b938e8ba41d6a86", + "mtp.pre_fc_norm_hidden.weight": + "b933b44559879449b1baf2af8385c5c237347307e3fd452394870cb53e6eab6d", +} + + +def get(url, start=None, end=None, retries=4): + for attempt in range(retries): + try: + req = urllib.request.Request(url, headers={"User-Agent": "strata-mtp-fetch"}) + if start is not None: + req.add_header("Range", "bytes=%d-%d" % (start, end)) + with urllib.request.urlopen(req, timeout=120) as r: + if start is not None: + check_range(r.status, r.headers.get("Content-Range"), start, end) + data = r.read() + if start is not None and len(data) != end - start + 1: + raise IOError("short range read: %d of %d" % (len(data), end - start + 1)) + return data + except Exception as e: # network errors are retried, then surfaced + if attempt == retries - 1: + raise + time.sleep(2 ** attempt) + print("retry %s: %s" % (url, e), file=sys.stderr) + + +def check_range(status, content_range, start, end): + """#327: a range read is only what was asked for when the server says so: 206 and `bytes START-END/...`.""" + if status != 206: + raise IOError("range request not honoured: HTTP %s instead of 206 (a mirror or proxy that ignores the Range " + "header sends the whole file)" % status) + want = "bytes %d-%d/" % (start, end) + if not (content_range or "").strip().startswith(want): + raise IOError("range request answered with Content-Range %r, not %s..." % (content_range, want)) + + +def pinned(): + """The tensors' hashes are the pinned revision's: they apply when this run reads that revision.""" + return REPO == PINNED + + +def sha256_of(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 24), b""): + h.update(block) + return h.hexdigest() + + +def resolve_repo(): + """REPO, or the repository's current files when the pinned revision is gone from it (a 404 on its index).""" + global REPO + try: + req = urllib.request.Request(REPO + "model.safetensors.index.json", method="HEAD", + headers={"User-Agent": "strata-mtp-fetch"}) + urllib.request.urlopen(req, timeout=120).close() + except urllib.error.HTTPError as e: + if e.code == 404 and "/resolve/main/" not in REPO: + print("the checkpoint's pinned revision %s is gone: reading its current files (main)" % REVISION, + file=sys.stderr) + REPO = REPO.replace("/resolve/%s/" % REVISION, "/resolve/main/") + except OSError: + pass # no answer: get() retries and reports it + return REPO + + +def shard_header(shard): + url = REPO + shard + n = struct.unpack(" r["bytes"]: + os.remove(path) + have = 0 + with open(path, "ab") as f: + pos = r["start"] + have + while pos <= r["end"]: + end = min(pos + chunk - 1, r["end"]) + f.write(get(REPO + r["shard"], pos, end)) + pos = end + 1 + print("%s %.0f%%" % (r["name"], 100 * (pos - r["start"]) / r["bytes"]), file=sys.stderr) + if os.path.getsize(path) != r["bytes"]: + sys.exit("%s: size %d != %d" % (path, os.path.getsize(path), r["bytes"])) + digest = sha256_of(path) + if want is None or digest == want: + break + os.remove(path) # wrong bytes (#327): the whole tensor again, once + if attempt: + sys.exit("%s: sha256 %s is not the checkpoint's %s - the download source sends wrong data (a mirror " + "that ignores Range requests?)" % (r["name"], digest, want)) + print("%s: wrong bytes (sha256 %s...), fetching it again" % (r["name"], digest[:12]), file=sys.stderr) + manifest.append(dict(r, file=os.path.relpath(path, out), sha256=digest)) + with open(os.path.join(out, "mtp-manifest.json"), "w", encoding="utf-8") as f: + json.dump(manifest, f, indent=1) + + +def verify(out): + """#327: the fetched tensors against SHA256 -> the names that are missing or wrong. [] when they are right, or + when there is nothing to check (no tensors/, or STRATA_MTP_REVISION names another revision). A tensor's verdict + is kept in tensors/verified.json by size and mtime, so a later run hashes only what changed.""" + tdir = os.path.join(out, "tensors") + if not pinned() or not os.path.isdir(tdir): + return [] + stamp_path = os.path.join(tdir, "verified.json") + try: + with open(stamp_path, encoding="utf-8") as f: + stamps = json.load(f) + except (OSError, ValueError): + stamps = {} + bad, good = [], {} + for name, want in sorted(SHA256.items()): + path = os.path.join(tdir, name + ".bin") + if not os.path.exists(path): + bad.append(name) + continue + st = os.stat(path) + key = [st.st_size, st.st_mtime_ns, want] + if stamps.get(name) != key and sha256_of(path) != want: + bad.append(name) + continue + good[name] = key + try: + with open(stamp_path, "w", encoding="utf-8") as f: + json.dump(good, f, indent=1) + except OSError: + pass + return bad + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("cmd", choices=["inventory", "fetch", "verify"]) + ap.add_argument("--out", required=True) + ap.add_argument("--only") + a = ap.parse_args() + if a.cmd == "verify": # offline: the hashes are the pinned revision's + bad = verify(a.out) + for name in bad: + print("MTP tensor missing or corrupt: %s" % name, file=sys.stderr) + sys.exit(BAD if bad else 0) + resolve_repo() + inventory(a.out) if a.cmd == "inventory" else fetch(a.out, a.only) + + +if __name__ == "__main__": + main() diff --git a/tools/mtp_pack.py b/tools/mtp_pack.py new file mode 100644 index 0000000..022d2ea --- /dev/null +++ b/tools/mtp_pack.py @@ -0,0 +1,193 @@ +"""tools/mtp_pack.py - plan v0.3 P6 prep: the MTP draft block as a Strata GGUF, from the BF16 tensors. + +llama.cpp's qwen4exp converter drops the MTP head (`supports_mtp_export = False`), and the flyweight MTP GGUF is +no longer on this PC, so Strata packs its own from the 31 `mtp.*` tensors fetched by tools/mtp_fetch.py: + + python tools/mtp_pack.py --src Desktop/Strata/mtp-bf16 --experts q2_0 --out mtp-q2_0.gguf + python tools/mtp_pack.py --src ... --experts q4_0 --out mtp-q4_0.gguf (acceptance comparison arm) + +Layout: dense tensors (attention, indexer, hyper-connections, shared expert, router, fc/norms) stay BF16 (F32 for +1-D norms), ~0.18 GB. The routed experts keep the checkpoint's fused layout - `gate_up_proj` [512, 1280, 2560] and +`down_proj` [512, 2560, 640], quantized along the last (input) axis - in one of: + + q2_0 64-element blocks, grid {-1, 0, 1, 2} x d. The scale is chosen per block to MINIMIZE squared error over + that grid (the ggml reference sets d = max|w| and never uses the +2 level). Same format as the main + model's experts, so Strata's CPU VNNI kernel and GPU hit kernel serve it unchanged. ~0.71 GB. + q4_0 ggml reference rounding. ~1.42 GB. q8_0 ggml reference. ~2.67 GB. + +This is round-to-nearest, not GSQ: the plan picks the expert format by MEASURED draft acceptance (P0.3/P6), not +by this file's reconstruction error, which is reported per tensor only as a sanity check. No model runs here. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +import time +from pathlib import Path + +import numpy as np + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from _paths import add_gguf_py # noqa: E402 +add_gguf_py() +import gguf # noqa: E402 (the pinned llama.cpp gguf-py, which knows Q2_0 = type 42) + +EXPERT_TENSORS = ("mtp.layers.0.mlp.experts.gate_up_proj", "mtp.layers.0.mlp.experts.down_proj") + + +class _Experts: + """Index an expert out of a BF16 memmap as float32 on demand.""" + def __init__(self, raw): + self.raw = raw + + def __getitem__(self, e): + return (np.asarray(self.raw[e]).astype(np.uint32) << 16).view(np.float32) + + +def load_bf16(path: Path, shape: list[int]) -> np.ndarray: + raw = np.fromfile(path, dtype=" np.ndarray: + """[..., n] float32 -> bytes of Q2_0 blocks (fp16 d, 16 bytes of 2-bit codes, code = q + 1, 4 per byte).""" + x = w.reshape(-1, 64).astype(np.float32) + amax = np.abs(x).max(axis=1, keepdims=True) + best_err = np.full((x.shape[0], 1), np.inf, dtype=np.float32) + best_d = np.zeros_like(amax) + # Candidate scales span amax/2 (the +2 level reaches the max) to amax (the ggml reference); 17 steps. + for f in np.linspace(0.5, 1.0, 17, dtype=np.float32): + d = amax * f + inv = np.where(d > 0, 1.0 / np.where(d > 0, d, 1.0), 0.0) + q = np.clip(np.rint(x * inv), -1, 2) + err = ((q * d - x) ** 2).sum(axis=1, keepdims=True) + better = err < best_err + best_err = np.where(better, err, best_err) + best_d = np.where(better, d, best_d) + d16 = best_d.astype(np.float16) + d = d16.astype(np.float32) # quantize against the STORED scale + inv = np.where(d > 0, 1.0 / np.where(d > 0, d, 1.0), 0.0) + codes = (np.clip(np.rint(x * inv), -1, 2) + 1).astype(np.uint8) # 0..3 + c = codes.reshape(-1, 16, 4) + packed = (c[:, :, 0] | (c[:, :, 1] << 2) | (c[:, :, 2] << 4) | (c[:, :, 3] << 6)).astype(np.uint8) + out = np.empty((x.shape[0], 18), dtype=np.uint8) + out[:, :2] = d16.view(np.uint8).reshape(-1, 2) + out[:, 2:] = packed + return out.reshape(-1) + + +def q4_0(w: np.ndarray) -> np.ndarray: + """ggml quantize_row_q4_0_ref: d = max / -8 (signed max), code = clamp(round(x/d + 8.5) truncated, 0, 15).""" + x = w.reshape(-1, 32).astype(np.float32) + idx = np.abs(x).argmax(axis=1) + mx = x[np.arange(x.shape[0]), idx][:, None] + d = mx / -8.0 + inv = np.where(d != 0, 1.0 / np.where(d != 0, d, 1.0), 0.0) + q = np.minimum(15, np.trunc(x * inv + 8.5)).astype(np.uint8) + packed = (q[:, :16] | (q[:, 16:] << 4)).astype(np.uint8) + out = np.empty((x.shape[0], 18), dtype=np.uint8) + out[:, :2] = d.astype(np.float16).view(np.uint8).reshape(-1, 2) + out[:, 2:] = packed + return out.reshape(-1) + + +def q8_0(w: np.ndarray) -> np.ndarray: + x = w.reshape(-1, 32).astype(np.float32) + d = np.abs(x).max(axis=1, keepdims=True) / 127.0 + inv = np.where(d > 0, 1.0 / np.where(d > 0, d, 1.0), 0.0) + q = np.rint(x * inv).astype(np.int8) + out = np.empty((x.shape[0], 34), dtype=np.uint8) + out[:, :2] = d.astype(np.float16).view(np.uint8).reshape(-1, 2) + out[:, 2:] = q.view(np.uint8) + return out.reshape(-1) + + +def dequant(kind: str, blob: np.ndarray, n: int) -> np.ndarray: + if kind == "q2_0": + b = blob.reshape(-1, 18) + d = b[:, :2].copy().view(np.float16).astype(np.float32) + qs = b[:, 2:] + codes = np.stack([(qs >> s) & 3 for s in (0, 2, 4, 6)], axis=2).reshape(-1, 64).astype(np.float32) + return ((codes - 1.0) * d).reshape(-1)[:n] + if kind == "q4_0": + b = blob.reshape(-1, 18) + d = b[:, :2].copy().view(np.float16).astype(np.float32) + qs = b[:, 2:] + q = np.concatenate([qs & 15, qs >> 4], axis=1).astype(np.float32) + return ((q - 8.0) * d).reshape(-1)[:n] + b = blob.reshape(-1, 34) + d = b[:, :2].copy().view(np.float16).astype(np.float32) + return (b[:, 2:].view(np.int8).astype(np.float32) * d).reshape(-1)[:n] + + +QUANT = {"q2_0": (q2_0, gguf.GGMLQuantizationType.Q2_0, 64, 18), + "q4_0": (q4_0, gguf.GGMLQuantizationType.Q4_0, 32, 18), + "q8_0": (q8_0, gguf.GGMLQuantizationType.Q8_0, 32, 34)} + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--src", required=True, help="directory written by tools/mtp_fetch.py fetch") + ap.add_argument("--experts", choices=sorted(QUANT), default="q2_0") + ap.add_argument("--out", required=True) + ap.add_argument("--check-experts", type=int, default=8, help="experts per tensor used for the error report") + a = ap.parse_args() + src = Path(a.src) + manifest = json.loads((src / "mtp-manifest.json").read_text()) + fn, qtype, block, block_bytes = QUANT[a.experts] + w = gguf.GGUFWriter(a.out, "qwen4exp-mtp") + w.add_string("strata.mtp.source", "Qwen/Qwen3.8-Flash-Next BF16 checkpoint, mtp.* tensors") + w.add_string("strata.mtp.source_sha256", hashlib.sha256( + json.dumps({t["name"]: t["sha256"] for t in manifest}, sort_keys=True).encode()).hexdigest()) + w.add_string("strata.mtp.expert_format", a.experts) + w.add_string("strata.mtp.expert_quantizer", "per-block MSE scale search" if a.experts == "q2_0" else "ggml reference") + report = [] + for t in sorted(manifest, key=lambda t: t["name"]): + name, shape = t["name"], t["shape"] + t0 = time.time() + if name in EXPERT_TENSORS: + # Streamed one expert at a time from a read-only view: the fused gate_up tensor alone is 6.7 GB as + # float32, so it is never materialized whole. + raw = np.memmap(src / t["file"], dtype="/mtp-bf16/mtp-q2_0.gguf --out /mtp-bf16/rt + +Writes + experts.bin 512 routed experts in the engine's blob layout (`include/strata/kernels/cpu/expert.hpp`): gate/up + rows interleaved (2r = gate r, 2r+1 = up r), then down rows; the Q2_0 codes in one plane and the fp16 + scales in another. A lossless relayout of the GGUF's Q2_0 blocks (same bytes, `cpu_expert_fixture.py`). + dense.bin every other tensor: the large projections quantized to Q8_0 (ggml's reference rounding) so the + engine's multi-column MMVQ can run them; the hyper-connection and router weights kept BF16; the + RMSNorm weights as F32 with the Gemma "+1" applied (vLLM GemmaRMSNorm scales by 1 + w). + dense.txt one line per tensor: name kind rows cols offset bytes (kind = q8_0 | bf16 | f32) +""" +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from _paths import add_gguf_py # noqa: E402 +add_gguf_py() +import gguf # noqa: E402 + +H, FF, NE = 2560, 640, 512 +BLOB = 3 * (H * FF * 18 // 64) +Q8 = {"fc_embedding.weight", "fc_hidden.weight", "self_attn.q_proj.weight", "self_attn.k_proj.weight", + "self_attn.v_proj.weight", "self_attn.o_proj.weight", "self_attn.indexer.index_qk_proj.weight", + "mlp.shared_expert.gate_proj.weight", "mlp.shared_expert.up_proj.weight", "mlp.shared_expert.down_proj.weight"} + + +def q8_0(x: np.ndarray) -> bytes: + """ggml quantize_row_q8_0_ref over rows of a 2-D float32 array: 32-value blocks, fp16 d = amax / 127.""" + b = x.reshape(-1, 32).astype(np.float32) + amax = np.abs(b).max(axis=1) + d = amax / 127.0 + inv = np.where(d > 0, 1.0 / np.where(d > 0, d, 1.0), 0.0).astype(np.float32) + v = b * inv[:, None] + q = (np.sign(v) * np.floor(np.abs(v) + 0.5)).astype(np.int8) + out = np.empty((b.shape[0], 34), dtype=np.uint8) + out[:, :2] = d.astype(np.float16).view(np.uint8).reshape(-1, 2) + out[:, 2:] = q.view(np.uint8) + return out.tobytes() + + +def blob_of(gu: np.ndarray, dn: np.ndarray) -> bytes: + """gu: (1280, 720) Q2_0 rows (gate rows 0..639, up rows 640..1279); dn: (2560, 180).""" + gub = gu.reshape(2 * FF, H // 64, 18) + inter = np.empty_like(gub) + inter[0::2] = gub[:FF] + inter[1::2] = gub[FF:] + dnb = dn.reshape(H, FF // 64, 18) + parts = [inter[:, :, 2:].tobytes(), dnb[:, :, 2:].tobytes(), inter[:, :, :2].tobytes(), dnb[:, :, :2].tobytes()] + out = b"".join(parts) + assert len(out) == BLOB, len(out) + return out + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--gguf", required=True) + ap.add_argument("--out", required=True) + a = ap.parse_args() + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + r = gguf.GGUFReader(a.gguf) + tens = {t.name: t for t in r.tensors} + gu = np.asarray(tens["mtp.layers.0.mlp.experts.gate_up_proj"].data) + dn = np.asarray(tens["mtp.layers.0.mlp.experts.down_proj"].data) + assert gu.shape == (NE, 2 * FF, 720) and dn.shape == (NE, H, 180), (gu.shape, dn.shape) + with open(out / "experts.bin", "wb") as f: + for e in range(NE): + f.write(blob_of(gu[e], dn[e])) + lines = [] + off = 0 + with open(out / "dense.bin", "wb") as f: + for name, t in tens.items(): + if "experts." in name: + continue + short = name[len("mtp."):] + short = short[len("layers.0."):] if short.startswith("layers.0.") else short + data = np.asarray(t.data) + if int(t.tensor_type) == 0: # F32 norm weights: raw GemmaRMSNorm w -> 1 + w + arr = (data.astype(np.float32) + 1.0) + raw, kind, rows, cols = arr.tobytes(), "f32", 1, arr.size + else: # BF16 + u16 = data.view(np.uint16) if data.dtype != np.uint16 else data + u16 = u16.reshape(data.shape[0], -1) + rows, cols = u16.shape + if short in Q8: + f32 = (u16.astype(np.uint32) << 16).view(np.float32) + raw, kind = q8_0(f32), "q8_0" + else: + raw, kind = u16.tobytes(), "bf16" + pad = (-off) % 256 + f.write(b"\0" * pad) + off += pad + f.write(raw) + lines.append(f"{short} {kind} {rows} {cols} {off} {len(raw)}") + off += len(raw) + (out / "dense.txt").write_text("\n".join(lines) + "\n", encoding="utf-8") + print(f"experts.bin {NE * BLOB} B, dense.bin {off} B, {len(lines)} tensors -> {out}") + for l in lines: + print(" " + l) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/pack_index.py b/tools/pack_index.py new file mode 100644 index 0000000..02678ac --- /dev/null +++ b/tools/pack_index.py @@ -0,0 +1,260 @@ +"""tools/pack_index.py - emit a flat index of the pack's dense tensors for the engine's loader. + +WHY AN INDEX AND NOT A JSON PARSER. The manifest is JSON and the engine is C++. A JSON parser in the engine +would be a new, unaudited component whose failure mode is a wrong byte offset - which decodes to a plausible +weight and produces plausible logits. Python already parses the manifest correctly and is already the tool +that WROTE it, so this flattens what the loader needs into one line per tensor. + +WHY TEXT AND NOT BINARY. `pack/full/index.txt` is ~150 KB for 1,079 tensors. A fixed-size binary record +would save 60 KB and cost a struct-packing contract between two languages that must agree on padding, +endianness and field order - three ways to be wrong for no benefit at this size. Text is also readable when +a load produces the wrong number, which is the only time this file matters. + +THE ENGINE LAYOUT IS NOT THE PACK LAYOUT, and that is the point of `dst_*`. Two independent differences: + + 1. A tensor whose source type is BF16 or F16 is stored in the pack PROMOTED to 32 bits, because that is + lossless and it keeps the canonical decoder simple. A running engine does not have to hold it that way: + re-rounding to 16 bits costs nothing at all, because the value came FROM 16 bits. That is 1.374 GiB of + the 5.305 GiB dense file, and per `tools/pack_budget.py` it is the difference between the dense weights + fitting in VRAM beside the expert cache and not fitting at all. + + 2. **A SCALE PLANE MAY BE 2 BYTES IN THE PACK AND IS ALWAYS 4 IN THE ENGINE.** This is the one that hid + for a whole round. 90 of the 303 quantized tensors - every Q2_0 (all 58 expert tensors), Q4_0, Q5_0, + Q8_0 and IQ4_NL - carry fp16 scales, because that is what the SOURCE ggml block stores (a Q5_0 block is + `{fp16 d; ...}`). 213 tensors (IQ4_XS, Q3_K, Q4_K, Q5_K, Q6_K) carry f32 scales. The manifest has said + which is which all along, in `scales_fp16`. + + `src/core/layer.cpp` did not read that field. It assumed 4 bytes per scale, so it computed a scale plane + twice the real size, the three planes did not add up to the tensor, and the loader REFUSED - which is how + this was found, and the refusal is the only reason it was not a silent wrong answer. The first diagnosis + was "the manifest's `group_elems` must be wrong, the real group is 64". It is not: `group_elems` is 32 + and the scale plane is 2 bytes wide. **The unexamined input was the WIDTH, not the count.** An audit of + all 303 tensors against `scales_fp16`/`offsets_fp16` found zero inconsistencies, which is what settled it. + + The engine widens fp16 scales to f32 at load. That is EXACT - fp16 is a subset of f32 - and it costs + 11,407,360 B (10.88 MiB) of the 4.5 GiB pool, against teaching three kernel families a second scale + width. Note the asymmetry that makes this cheap and the BF16 re-rounding large: re-rounding loses + precision and saves GiB; widening loses nothing and costs MiB. + + `offsets_fp16` is also read, and it is FALSE for all 54 tensors that have an offset plane. It is + honoured anyway rather than assumed, because the next pack may not be. + +Columns: + + name file kind src_off src_bytes dst_off dst_bytes ne0 ne1 code_bits code_bias group_elems codebook + has_offset codes_bytes scales_bytes offset_bytes scales_fp16 + +`kind` is what the loader must DO, spelled out here rather than left for it to infer - the four cases are +distinguishable in the manifest but only by combining `source_type` with `values_fp16`, and getting that +combination wrong produces a plausible tensor: + + 0 VERBATIM copy straight through (BF16-free: F16 already 2 B/elem, F32, and the planes below) + 1 BF16_IN_F32 the pack holds the bf16 value promoted to f32; take the HIGH 16 BITS. Exact, not a + rounding: a bf16 value IS the top half of its f32 image. + 2 F32 copy 4 B/elem + 3 F16_IN_F32 the pack holds an f16 value promoted to f32; needs a real f32->f16 conversion with + round-to-nearest-even, NOT a truncation + +`ne0`/`ne1` are the manifest's own shape in its own order, with ne0 the CONTIGUOUS axis. `form` is the +canonical form letter from the manifest (P16/P32/S2/S4/S8); the SForm attributes are 0 for kinds 1-3. + +`codes_bytes`/`scales_bytes`/`offset_bytes` are the THREE ENGINE-FORM PLANE SIZES, in the order they sit in +the destination. They are emitted rather than left for the loader to re-derive, because re-deriving is where +the width bug lived: two places computing one layout is two places to disagree, and the loader cannot check a +layout it invented. The loader instead checks what it was TOLD: `scales_bytes/2` when `scales_fp16`, and the +three planes summing to both `src_bytes` (source widths) and `dst_bytes` (engine widths). Non-quantized +tensors carry `codes_bytes == dst_bytes` and two zeroes. +""" +from __future__ import annotations + +import argparse +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +FILE_ID = {"dense.bin": 0, "embd.bin": 1, "experts.bin": 2} +VERBATIM, BF16_IN_F32, F32_COPY, F16_IN_F32 = 0, 1, 2, 3 + +# WHICH ACTIVATION THIS WEIGHT WANTS, decided HERE because it is a property of `source_type` and the engine's +# `SForm` cannot recover it. The legacy formats (Q2_0, Q4_0, Q5_0, Q8_0, IQ4_NL) have `vec_dot_type` Q8_0; the +# K-quants and IQ4_XS have Q8_K. **NO COMBINATION OF THE S-FORM FIELDS TELLS THEM APART**: Q5_0 and Q5_K are +# both 8-bit with bias -16 (only `has_offset` differs), and IQ4_NL and IQ4_XS are both 4-bit with the IQ4NL +# codebook and no offset - they differ in NOTHING the S-form carries. That is why this column exists rather +# than the engine re-deriving the rule from `code_bits`. +ACT_Q8_0, ACT_Q8_K = 0, 1 +VDT = { + "Q2_0": ACT_Q8_0, "Q4_0": ACT_Q8_0, "Q5_0": ACT_Q8_0, "Q8_0": ACT_Q8_0, "IQ4_NL": ACT_Q8_0, + "Q3_K": ACT_Q8_K, "Q4_K": ACT_Q8_K, "Q5_K": ACT_Q8_K, "Q6_K": ACT_Q8_K, "IQ4_XS": ACT_Q8_K, +} + +# The plane key is `offsets`, NOT `mins`. The first version of this list said `mins` - which is what ggml calls +# the quantity conceptually, and the manifest does not - and a missing key in a loop like this is not an error, +# it is a SHORTER SPAN: 54 Q4_K/Q5_K tensors loaded with their offset plane never copied. Keys now come from +# the manifest, and the layout is verified against the recorded plane offsets rather than assumed. +PLANE_KEYS = ("codes", "scales", "offsets") + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--pack", default="pack/full") + ap.add_argument("-o", "--out", default=None, help="default: /index.txt") + args = ap.parse_args() + out_path = args.out or os.path.join(args.pack, "index.txt") + + with open(os.path.join(args.pack, "manifest.json"), "r", encoding="utf-8") as fh: + man = json.load(fh) + align = int(man.get("align", 64)) + + def align_up(n: int) -> int: + return (n + align - 1) // align * align + + rows = [] + dst = 0 + n_reduced = 0 + saved = 0 + widened = 0 + n_widened = 0 + kinds: dict[int, int] = {} + for name, v in man["tensors"].items(): + f = v.get("file") + if f not in FILE_ID: + print("unknown file %r for %s" % (f, name), file=sys.stderr) + return 1 + shape = v.get("shape") or [0, 0] + ne0 = int(shape[0]) if len(shape) > 0 else 0 + ne1 = int(shape[1]) if len(shape) > 1 else 0 + elems = int(v.get("elements", 0)) + st = v.get("source_type") or "?" + + codes_bytes = scales_bytes = offset_bytes = 0 + scales_fp16 = 0 + widen_here = 0 + act_kind = ACT_Q8_0 + if "values" in v: + src_off = int(v["values"]["offset"]) + src_bytes = int(v["values"]["bytes"]) + else: + planes = [k for k in PLANE_KEYS if isinstance(v.get(k), dict)] + lo = min(int(v[k]["offset"]) for k in planes) + hi = max(int(v[k]["offset"]) + int(v[k].get("bytes", 0)) for k in planes) + src_off, src_bytes = lo, hi - lo + + # the planes must be CONTIGUOUS, in order, because the loader reads them as one span. If a future + # pack interleaves them this refuses; the alternative is reading the scale plane as offsets and + # decoding a plausible weight. + expect = src_off + for k in PLANE_KEYS: + if k not in planes: + continue + if int(v[k]["offset"]) != expect: + print("%s: plane %r starts at %d but %d was expected - planes are not contiguous" + % (name, k, int(v[k]["offset"]), expect), file=sys.stderr) + return 1 + expect += int(v[k].get("bytes", 0)) + if expect != src_off + src_bytes: + print("%s: plane span %d does not end at %d" % (name, expect, src_off + src_bytes), + file=sys.stderr) + return 1 + + if v.get("has_offset") and "offsets" not in planes: + print("%s says has_offset but has no `offsets` plane (found %s)" % (name, planes), + file=sys.stderr) + return 1 + + act_kind = VDT.get(st, ACT_Q8_0) # refuses below if the type is unknown + code_bits = int(v.get("code_bits") or 0) + group_elems = int(v.get("group_elems") or 0) + if code_bits == 0 or group_elems == 0: + print("%s: a quantized tensor with code_bits=%d group_elems=%d" % (name, code_bits, group_elems), + file=sys.stderr) + return 1 + if ne0 % group_elems: + print("%s: ne0 %d is not a multiple of group_elems %d" % (name, ne0, group_elems), + file=sys.stderr) + return 1 + n_groups = ne0 // group_elems + codes_bytes = elems * code_bits // 8 + scales_fp16 = 1 if v.get("scales_fp16") else 0 + offs_fp16 = 1 if v.get("offsets_fp16") else 0 + # engine-form plane sizes: ALWAYS 4 B per scale. fp16 in the pack is widened; the load is exact. + scales_bytes = ne1 * n_groups * 4 + offset_bytes = ne1 * n_groups * 4 if v.get("has_offset") else 0 + src_planes = (codes_bytes + + ne1 * n_groups * (2 if scales_fp16 else 4) + + (ne1 * n_groups * (2 if offs_fp16 else 4) if v.get("has_offset") else 0)) + if src_planes != int(v["codes"]["bytes"]) + int(v["scales"]["bytes"]) \ + + int(v.get("offsets", {}).get("bytes", 0)): + print("%s: derived planes %d disagree with the manifest's own plane bytes %d" + % (name, src_planes, int(v["codes"]["bytes"]) + int(v["scales"]["bytes"]) + + int(v.get("offsets", {}).get("bytes", 0))), file=sys.stderr) + return 1 + if src_planes != src_bytes: + print("%s: derived planes %d do not fill the span %d" % (name, src_planes, src_bytes), + file=sys.stderr) + return 1 + if scales_fp16: + widen_here = scales_bytes - ne1 * n_groups * 2 + widened += widen_here + n_widened += 1 + + # ---- the engine form, as an explicit KIND rather than a flag to interpret + vf = bool(v.get("values_fp16")) + if st == "BF16": + kind = BF16_IN_F32 + dst_bytes = elems * 2 + saved += src_bytes - dst_bytes + n_reduced += 1 + elif st == "F16" and not vf: + kind = F16_IN_F32 + dst_bytes = elems * 2 + saved += src_bytes - dst_bytes + n_reduced += 1 + elif st == "F16": + kind = VERBATIM # already 2 bytes on disk + dst_bytes = src_bytes + elif st == "F32": + kind = F32_COPY + dst_bytes = elems * 4 + else: + kind = VERBATIM + dst_bytes = codes_bytes + scales_bytes + offset_bytes + # THE ENGINE FORM OF A QUANTIZED TENSOR DIFFERS FROM THE PACK BY EXACTLY THE WIDENING, and saying + # so here is what makes the two plane sizes a CHECK rather than two independent guesses. + if dst_bytes != src_bytes + widen_here: + print("%s: engine form %d != pack %d + widening %d" % (name, dst_bytes, src_bytes, widen_here), + file=sys.stderr) + return 1 + + cb = v.get("codebook") + rows.append((name, FILE_ID[f], kind, src_off, src_bytes, dst, dst_bytes, ne0, ne1, + int(v.get("code_bits") or 0), int(v.get("code_bias") or 0), + int(v.get("group_elems") or 0), 1 if cb == "IQ4NL" else 0, + 1 if v.get("has_offset") else 0, + codes_bytes, scales_bytes, offset_bytes, scales_fp16, act_kind)) + dst = align_up(dst + dst_bytes) + kinds[kind] = kinds.get(kind, 0) + 1 + + with open(out_path, "w", encoding="utf-8", newline="\n") as fh: + fh.write("# strata pack index v3 -- generated by tools/pack_index.py; do not hand-edit\n") + fh.write("# align %d pool %d tensors %d\n" % (align, dst, len(rows))) + fh.write("# name file kind src_off src_bytes dst_off dst_bytes ne0 ne1 code_bits code_bias " + "group_elems codebook has_offset codes_bytes scales_bytes offset_bytes scales_fp16 act_kind\n") + for r in rows: + fh.write("%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n" % r) + + names = {VERBATIM: "VERBATIM", BF16_IN_F32: "BF16_IN_F32", F32_COPY: "F32", F16_IN_F32: "F16_IN_F32"} + print("%s: %d tensors, engine pool %d B (%.3f GiB)" % (out_path, len(rows), dst, dst / 2**30)) + for k in sorted(kinds): + print(" kind %-12s %4d tensors" % (names[k], kinds[k])) + print(" %d tensors re-rounded to 16 bits, saving %d B (%.3f GiB)" + % (n_reduced, saved, saved / 2**30)) + print(" %d tensors widened fp16 scales -> f32, costing %d B (%.3f GiB)" + % (n_widened, widened, widened / 2**30)) + print(" compare with tools/pack_budget.py: the pack's dense+embd engine figure should match this pool") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/pack_layer.py b/tools/pack_layer.py new file mode 100644 index 0000000..1fdf114 --- /dev/null +++ b/tools/pack_layer.py @@ -0,0 +1,123 @@ +"""Strata P0.S9 - build the pack-layout expert arena from the real GGUF. + +The architecture (§3.2) defines one expert blob as 1,382,400 bytes: + + gate_up.codes 2 x 640 rows x 640 B rows interleaved g0,u0,g1,u1,... (share input x) + down.codes 2,560 rows x 160 B + gate_up.scales 2 x 640 x 40 x FP16 + down.scales 2,560 x 10 x FP16 + +and that totals exactly 819,200 + 409,600 + 102,400 + 51,200 = 1,382,400 B, matching the artifact's +Q2_0 expert size to the byte. The conversion is a pure relayout: Q2_0 codes and their FP16 block +scale are copied unchanged, so dequant(pack) == dequant(ggml) bit-exactly. + +Why build this at all rather than read the GGUF in place: the GGUF stores gate, up and down as three +separate tensors, so a fused gate/up pass would read two streams from three arrays. The pack +interleaves gate and up ROWS so one pass over the activation vector serves both, which is the whole +point of the blob layout. + +Expert index is the LAST axis of [in, out, experts] (P0.S6), and ne[0] varies fastest, so expert `e` +is one CONTIGUOUS 460,800-byte run inside each role tensor. Extraction is a strided copy. + +Run: python tools/pack_layer.py [n_layers] (default 1; 48 = the full 34 GB arena) +""" +from __future__ import annotations + +import json +import pathlib +import struct +import sys + +import numpy as np + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +from gguf_reader import GGUFFile # noqa: E402 + +REPO = pathlib.Path(__file__).resolve().parents[1] +STRATA = REPO.parents[min(1, len(REPO.parents) - 1)] # the dev layout's default shards (setup.py passes --gguf) +SHARD1 = STRATA / "Q2_0" / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf" + +H, FF, NE = 2560, 640, 512 +QK, BLOCK_BYTES = 64, 18 # Q2_0 +ROW_BYTES_GU = H * 2 // 8 # 640 B of codes for one 2,560-wide row +ROW_BYTES_D = FF * 2 // 8 # 160 B of codes for one 640-wide row +SCALES_GU = H // QK # 40 blocks per gate/up row +SCALES_D = FF // QK # 10 blocks per down row +ROLE_BYTES = H * FF * BLOCK_BYTES // QK # 460,800 B per role per expert +BLOB_BYTES = 3 * ROLE_BYTES # 1,382,400 + +assert BLOB_BYTES == 1_382_400, BLOB_BYTES +assert 2 * 640 * ROW_BYTES_GU + 2560 * ROW_BYTES_D + 2 * 640 * SCALES_GU * 2 \ + + 2560 * SCALES_D * 2 == BLOB_BYTES + + +def blob_offsets() -> dict[str, int]: + gu_codes = 0 + d_codes = gu_codes + 2 * FF * ROW_BYTES_GU + gu_scales = d_codes + H * ROW_BYTES_D + d_scales = gu_scales + 2 * FF * SCALES_GU * 2 + end = d_scales + H * SCALES_D * 2 + assert end == BLOB_BYTES, end + return {"gate_up_codes": gu_codes, "down_codes": d_codes, + "gate_up_scales": gu_scales, "down_scales": d_scales} + + +OFF = blob_offsets() + + +def build(n_layers: int, out_path: pathlib.Path) -> dict: + g = GGUFFile(SHARD1) + by_name = {t.name: t for t in g.tensors} + src = open(SHARD1, "rb") + manifest = {"blob_bytes": BLOB_BYTES, "offsets": OFF, "layers": [], "n_layers": n_layers} + total = n_layers * NE * BLOB_BYTES + out_path.parent.mkdir(parents=True, exist_ok=True) + + with out_path.open("wb") as out: + for layer in range(n_layers): + roles = {} + for role in ("gate", "up", "down"): + t = by_name[f"blk.{layer}.ffn_{role}_exps.weight"] + roles[role] = t + assert t.type_name == "Q2_0", t.type_name + # expert e is a contiguous run inside the role tensor + per_expert = t.elements // NE + assert per_expert * BLOCK_BYTES // QK == ROLE_BYTES, per_expert + layer_off = out.tell() + # vectorized over the layer's 512 experts (the same bytes the per-block loop wrote; tools/strata_pack.py + # verify checks them): each role is (512 experts, rows, blocks per row, 18 bytes) + def role_blocks(role, rows, per_row): + t = roles[role] + n = NE * ROLE_BYTES + src.seek(g.data_start + t.offset) + a = np.frombuffer(src.read(n), dtype=np.uint8) + assert a.size == n, (role, a.size) + return a.reshape(NE, rows, per_row, BLOCK_BYTES) + gate = role_blocks("gate", FF, SCALES_GU) + up = role_blocks("up", FF, SCALES_GU) + down = role_blocks("down", H, SCALES_D) + gu = np.stack([gate, up], axis=2).reshape(NE, 2 * FF, SCALES_GU, BLOCK_BYTES) # rows g0,u0,g1,u1,... + blobs = np.concatenate([ + gu[:, :, :, 2:].reshape(NE, -1), # gate/up codes + down[:, :, :, 2:].reshape(NE, -1), # down codes + gu[:, :, :, :2].reshape(NE, -1), # gate/up fp16 scales + down[:, :, :, :2].reshape(NE, -1), # down fp16 scales + ], axis=1) + assert blobs.shape == (NE, BLOB_BYTES), blobs.shape + out.write(blobs.tobytes()) + manifest["layers"].append({"layer": layer, "offset": layer_off, + "role_offsets": {r: by_name[f"blk.{layer}.ffn_{r}_exps.weight"].offset + for r in ("gate", "up", "down")}}) + print(f" layer {layer}: wrote {NE} blobs at {layer_off}") + src.close() + manifest["total_bytes"] = total + (out_path.with_suffix(".json")).write_text(json.dumps(manifest, indent=2), encoding="utf-8") + return manifest + + +if __name__ == "__main__": + n = int(sys.argv[1]) if len(sys.argv) > 1 else 1 + dest = REPO / "pack" / ("layer0.bin" if n == 1 else f"experts-{n}l.bin") + print(f"building {n} layer(s) -> {dest} ({(n*NE*BLOB_BYTES)/2**30:.2f} GiB)") + m = build(n, dest) + print(f"done: {m['total_bytes']/2**30:.2f} GiB, {n*NE} blobs") diff --git a/tools/strata_pack.py b/tools/strata_pack.py new file mode 100644 index 0000000..31fbe22 --- /dev/null +++ b/tools/strata_pack.py @@ -0,0 +1,423 @@ +"""Strata P1.S6/S7 - the pack builder and verifier. + +This is `strata-pack build` / `strata-pack verify` / `strata-pack info`. It is the Python implementation of +`docs/pack-format.md`; the C++ `tools/strata-pack` is a port of it, and if the two disagree the C++ is wrong. + +WHY PYTHON FIRST. The canonicalisation in `tools/canonical_xcheck.py` is measured bit-exact over every block +of every tensor (757,139,840 blocks across 1021 tensors, plus Q2_0), against gguf-py and, for Q2_0, backed by +`dequant_xcheck` against ggml itself. That makes the Python mapping table the specification of record. The +pack is Phase 2's prerequisite and can be produced from it today; the port then has a golden artifact to be +tested against instead of being the thing everything else waits on. + +THE ONE RULE. A pack is only valid if, for every tensor, `decode(pack) == dequant_ggml(source)` BIT FOR BIT. +`verify` is that test and it is not optional - it re-reads the written pack from disk and compares it against +the source shard. A pack that has not passed `verify` does not exist. + +SCALE PRECISION. A canonical scale is an FP32 product (`fl(d*sc)`), which is generally NOT representable in +FP16. The packer therefore stores scales as FP16 only when the round-trip is exact and as FP32 otherwise, and +records which per tensor. It never has to decide correctly: `verify` re-checks bit-exactness, so a wrong +choice is a failed build rather than a silently lossy pack. The expert arena is the exception and is FP16 by +construction - architecture §3.2 fixes the blob at exactly 1,382,400 bytes and pack_layer.py asserts it. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import pathlib +import struct +import sys + +import numpy as np + +HERE = pathlib.Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE.parent / "ref")) + +import gguf_reader as G # noqa: E402 +import pack_layer as PL # noqa: E402 +from canonical_xcheck import (MAPPINGS, KV_IQ4NL, open_shard, # noqa: E402 + data_section_offset, reference_values) + +FORMAT_VERSION = 1 +ALIGN = 64 # every plane starts on a 64-byte boundary (P1.S7) +_HERE = pathlib.Path(__file__).resolve() +STRATA = _HERE.parents[min(3, len(_HERE.parents) - 1)] # the development layout; build takes the shard from --gguf +SHARD2 = STRATA / "Q2_0" / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf" + +EXPERT_RE = ("ffn_gate_exps.weight", "ffn_up_exps.weight", "ffn_down_exps.weight") +EMBD_NAME = "token_embd.weight" + + +def is_expert(name: str) -> bool: + return name.startswith("blk.") and name.endswith(EXPERT_RE) + + +def code_bits(form: str) -> int: + return {"S2": 2, "S4": 4, "S8": 8}[form] + + +def pack_codes(codes: np.ndarray, bits: int) -> bytes: + """Pack one code per element into bytes, LSB-first, `8//bits` codes per byte. + + This is Q2_0's own convention (4 codes per byte, byte j/4, bits (j%4)*2), kept for every form so the + kernel has one unpacking loop rather than one per source type. + """ + flat = codes.reshape(-1).astype(np.uint8) + if bits == 8: + return flat.tobytes() + per = 8 // bits + if flat.size % per: + raise ValueError("code count %d is not a multiple of %d per byte" % (flat.size, per)) + g = flat.reshape(-1, per).astype(np.uint16) + out = np.zeros(g.shape[0], dtype=np.uint16) + for k in range(per): + out |= (g[:, k] & ((1 << bits) - 1)) << (k * bits) + return out.astype(np.uint8).tobytes() + + +def unpack_codes(buf: bytes, bits: int, n: int) -> np.ndarray: + if bits == 8: + return np.frombuffer(buf, dtype=np.uint8)[:n].copy() + per = 8 // bits + b = np.frombuffer(buf, dtype=np.uint8) + out = np.empty((b.size, per), dtype=np.uint8) + for k in range(per): + out[:, k] = (b >> (k * bits)) & ((1 << bits) - 1) + return out.reshape(-1)[:n].copy() + + +def choose_scale_dtype(scales: np.ndarray) -> tuple[np.ndarray, bool]: + """FP16 when the round-trip is exact, else FP32. Returns (bytes, is_fp16).""" + as16 = scales.astype(np.float16) + if np.array_equal(as16.astype(np.float32), scales): + return as16.tobytes(), True + return scales.astype(" the canonical planes, as (codes, scales, offsets_or_None, mapping).""" + m = MAPPINGS[tname] + parts = m.enc(raw) + if len(parts) == 3: + return parts[0], parts[1], parts[2], m + return parts[0], parts[1], None, m + + +def tensor_entry(name, meta, tname, raw, seg_offset): + """Encode one tensor and return (blob_bytes, manifest_entry).""" + m = MAPPINGS[tname] + + body = bytearray() + base = seg_offset + + def put(b: bytes) -> dict: + nonlocal body + pad = (-len(body)) % ALIGN + body += b"\0" * pad + off = base + len(body) + body += b + return {"offset": off, "bytes": len(b)} + + common = { + "name": name, "source_type": tname, "form": m.form, "codebook": m.codebook, + "code_bias": m.code_bias, "has_offset": m.has_offset, + "block_elems": m.block_elems, "block_bytes": m.block_bytes, "group_elems": m.group_elems, + "shape": list(meta.shape), "source_offset": meta.offset, + } + + # ---- P16/P32 are pass-through: one value plane, no codes, no scale, no offset + if m.form in ("P16", "P32"): + vals = np.ascontiguousarray(m.dec(m.enc(raw)), dtype=np.float32).reshape(-1) + if m.form == "P32": + vb, v16 = vals.astype(" np.ndarray: + """Decode a tensor from the pack, using ONLY what the manifest says. + + Deliberately manifest-driven: if the manifest does not carry enough to decode the tensor, this cannot + silently fall back on knowledge of the source type, and the omission becomes a failure here. + """ + if ent["form"] in ("P16", "P32"): + vb = head[ent["values"]["offset"]: ent["values"]["offset"] + ent["values"]["bytes"]] + return np.frombuffer(vb, dtype=" str: + h = hashlib.sha256() + with open(path, "rb") as f: + while True: + b = f.read(chunk) + if not b: + break + h.update(b) + return h.hexdigest() + + +def build(gguf: pathlib.Path, out_dir: pathlib.Path, n_layers: int | None, skip_hash: bool) -> int: + out_dir.mkdir(parents=True, exist_ok=True) + g = G.GGUFFile(gguf) + head, flen = open_shard(gguf) + data_off = data_section_offset(g, flen) + print("source %s: %d tensors, data at %d" % (gguf.name, len(g.tensors), data_off)) + + n_layers = 48 if n_layers is None else n_layers + man = { + "format": "strata-pack", "format_version": FORMAT_VERSION, + "source": {"shard1": str(gguf), "shard2": str(SHARD2)}, + "n_layers": n_layers, "align": ALIGN, + "codebooks": {"IQ4NL": [float(x) for x in KV_IQ4NL]}, + "tensors": {}, "experts": {}, "n_experts_per_layer": PL.NE, + } + + # ---- experts.bin: delegated to pack_layer so the blob layout has exactly ONE implementation + # pack_layer reads its own hardcoded SHARD1, so a different --gguf would silently take the expert arena + # from a different file than the dense tensors. Refuse rather than produce a mixed-source pack. + # the expert arena and the dense tensors come from the same file: point pack_layer at it + PL.SHARD1 = pathlib.Path(gguf).resolve() + shard2 = pathlib.Path(str(PL.SHARD1).replace("00001-of-00002", "00002-of-00002")) + man["source"]["shard2"] = str(shard2) + exp_path = out_dir / "experts.bin" + print("experts.bin: %d layers, %.2f GiB" % (n_layers, n_layers * PL.NE * PL.BLOB_BYTES / 2**30)) + em = PL.build(n_layers, exp_path) + man["experts"] = {"blob_bytes": em["blob_bytes"], "offsets": em["offsets"], + "layers": em["layers"], "total_bytes": em["total_bytes"], + "scales_fp16": True, "source_type": "Q2_0", "form": "S2"} + + # ---- dense.bin and embd.bin + dense = [] + embd = [] + for t in g.tensors: + if is_expert(t.name): + continue + (embd if t.name == EMBD_NAME else dense).append(t) + + for fname, group in (("dense.bin", dense), ("embd.bin", embd)): + path = out_dir / fname + seg_base = 0 + with open(path, "wb") as fh: + for t in group: + if t.type_name not in MAPPINGS: + print(" %s: NO MAPPING for %s - refusing to build" % (t.name, t.type_name)) + return 1 + raw = head[data_off + t.offset: data_off + t.offset + (t.expected_bytes() or 0)] + if len(raw) != (t.expected_bytes() or 0): + print(" %s: SHORT READ - refusing to build" % t.name) + return 1 + blob, ent = tensor_entry(t.name, t, t.type_name, raw, seg_base) + ent["file"] = fname + fh.write(blob) + seg_base += len(blob) + man["tensors"][t.name] = ent + print("%s: %d tensors, %.2f GiB" % (fname, len(group), path.stat().st_size / 2**30)) + + man["files"] = {"experts.bin": exp_path.stat().st_size, + "dense.bin": (out_dir / "dense.bin").stat().st_size, + "embd.bin": (out_dir / "embd.bin").stat().st_size} + if not skip_hash: + print("hashing shards (this is the slow part)...") + man["source"]["shard1_sha256"] = sha256(gguf) + man["source"]["shard2_sha256"] = sha256(shard2) if shard2.exists() else None + # shard 2 is NOT copied: the PLE table stays where it is and the manifest records how to find it + if shard2.exists(): + g2 = G.GGUFFile(shard2) + t2 = [t for t in g2.tensors if t.name == "per_layer_token_embd.weight"][0] + man["shard2_tensor"] = {"name": t2.name, "type": t2.type_name, "shape": list(t2.shape), + "offset": t2.offset, "elements": t2.elements, + "path": str(shard2)} + (out_dir / "manifest.json").write_text(json.dumps(man, indent=1), encoding="utf-8") + print("manifest.json: %d tensor entries" % len(man["tensors"])) + return 0 + + +def rebuild_role(blob: bytes, role: str) -> bytes: + """Rebuild one role's raw Q2_0 bytes from an expert blob - the exact inverse of pack_layer's layout. + + The arena stores codes and scales in SEPARATE PLANES and interleaves gate/up ROWS (g0,u0,g1,u1,...), so + a verifier that cannot invert that cannot check the arena. Written as the inverse on purpose: this is + the only independent statement about the blob layout in the tree, and if it and `pack_layer` were the + same code the arena would be unverified by construction. + """ + O, out = PL.OFF, bytearray() + n_blk = PL.H * PL.FF // PL.QK + for blk in range(n_blk): + if role == "down": + row, b_in = blk // PL.SCALES_D, blk % PL.SCALES_D + co = O["down_codes"] + row * PL.ROW_BYTES_D + b_in * 16 + so = O["down_scales"] + (row * PL.SCALES_D + b_in) * 2 + else: + row, b_in = blk // PL.SCALES_GU, blk % PL.SCALES_GU + slot = 2 * row + (0 if role == "gate" else 1) + co = O["gate_up_codes"] + slot * PL.ROW_BYTES_GU + b_in * 16 + so = O["gate_up_scales"] + (slot * PL.SCALES_GU + b_in) * 2 + out += blob[so:so + 2] # fp16 d first, as block_q2_0 has it + out += blob[co:co + 16] # then the 16 packed code bytes + return bytes(out) + + +def verify_experts(gguf: pathlib.Path, out_dir: pathlib.Path, man: dict, every: int) -> int: + """Verify the expert arena: 85% of the pack by bytes and the part Phase 2 reads 480x per token.""" + g = G.GGUFFile(gguf) + head, flen = open_shard(gguf) + data_off = data_section_offset(g, flen) + by_name = {t.name: t for t in g.tensors} + exp_mm, _ = open_shard(out_dir / "experts.bin") + blob = man["experts"]["blob_bytes"] + n_layers = man["n_layers"] + checked = bad = 0 + for layer in range(n_layers): + for e in range(0, PL.NE, every): + base = (layer * PL.NE + e) * blob + b = exp_mm[base:base + blob] + for role in ("gate", "up", "down"): + t = by_name["blk.%d.ffn_%s_exps.weight" % (layer, role)] + per_expert = t.elements // PL.NE + nbytes = per_expert * PL.BLOCK_BYTES // PL.QK + src = head[data_off + t.offset + e * nbytes: data_off + t.offset + (e + 1) * nbytes] + ref = reference_values("Q2_0", src) + got = MAPPINGS["Q2_0"].dec(canonicalise(t.name, "Q2_0", rebuild_role(b, role))[:2]) + checked += 1 + if not np.array_equal(ref, got): + print(" layer %d expert %d %-4s *** MISMATCH *** max|d| %.3e" + % (layer, e, role, np.abs(ref.astype(np.float64) - got.astype(np.float64)).max())) + bad += 1 + print("experts: %d layer/expert/role checks (%d layers, every %dth expert), %d bad" + % (checked, n_layers, every, bad)) + return bad + + +def verify(gguf: pathlib.Path, out_dir: pathlib.Path, limit: int | None, expert_every: int) -> int: + """P1.T3 over the pack: decode it from disk and compare with the source, bit for bit.""" + man = json.loads((out_dir / "manifest.json").read_text(encoding="utf-8")) + # A full verify also reads back the source hash build recorded (absent after --skip-hash, which is how setup + # builds): a pack compared against a different shard than it was built from is a mismatch, not a decode bug. + want = (man.get("source") or {}).get("shard1_sha256") + if want and limit is None: + got = sha256(gguf) + if got != want: + print("%s: sha256 %s, but the pack was built from %s" % (gguf.name, got, want)) + print("tools/strata_pack.py verify FAIL") + return 1 + g = G.GGUFFile(gguf) + head, flen = open_shard(gguf) + data_off = data_section_offset(g, flen) + by_name = {t.name: t for t in g.tensors} + files = {} + bad = 0 + n_t = n_el = 0 + for i, (name, ent) in enumerate(sorted(man["tensors"].items())): + if limit is not None and i >= limit: + break + if ent["file"] not in files: + files[ent["file"]] = open_shard(out_dir / ent["file"])[0] + t = by_name[name] + raw = head[data_off + t.offset: data_off + t.offset + (t.expected_bytes() or 0)] + ref = reference_values(t.type_name, raw) + got = decode_entry(files[ent["file"]], ent) + n_t += 1 + n_el += ref.size + if ref.shape != got.shape or not np.array_equal(ref, got): + d = np.abs(ref.astype(np.float64) - got.astype(np.float64)) if ref.shape == got.shape else None + print(" %-40s *** MISMATCH *** %s" % (name, ("max|d| %.3e" % d.max()) if d is not None else + "shape %s vs %s" % (ref.shape, got.shape))) + bad += 1 + elif i < 3 or i % 200 == 0: + print(" %-40s bit-exact (%d elements, %s)" % (name, ref.size, ent["form"])) + print() + print("verify: %d tensors, %d elements, %d bad" % (n_t, n_el, bad)) + if expert_every > 0: + bad += verify_experts(gguf, out_dir, man, expert_every) + print("tools/strata_pack.py verify " + ("PASS" if bad == 0 else "FAIL")) + return 0 if bad == 0 else 1 + + +def info(out_dir: pathlib.Path) -> int: + man = json.loads((out_dir / "manifest.json").read_text(encoding="utf-8")) + print("strata-pack v%d layers=%d" % (man["format_version"], man["n_layers"])) + for f, n in man.get("files", {}).items(): + print(" %-12s %12.3f GiB" % (f, n / 2**30)) + forms = {} + for e in man["tensors"].values(): + forms[e["form"]] = forms.get(e["form"], 0) + 1 + print(" dense/embd by form: %s" % ", ".join("%s=%d" % kv for kv in sorted(forms.items()))) + print(" experts: %d blobs x %d B, %s" % (man["experts"]["layers"].__len__() * man["n_experts_per_layer"], + man["experts"]["blob_bytes"], man["experts"]["source_type"])) + return 0 + + +def main() -> int: + ap = argparse.ArgumentParser() + sub = ap.add_subparsers(dest="cmd", required=True) + b = sub.add_parser("build") + b.add_argument("--gguf", required=True) + b.add_argument("--out", required=True) + b.add_argument("--layers", type=int, default=None, help="expert layers to emit (default 48)") + b.add_argument("--skip-hash", action="store_true") + v = sub.add_parser("verify") + v.add_argument("--gguf", required=True) + v.add_argument("--out", required=True) + v.add_argument("--limit", type=int, default=None) + v.add_argument("--expert-every", type=int, default=32, + help="verify every Nth expert per layer in the arena (0 disables; the arena is 85%% of " + "the pack and verifying NONE of it is how a pack passes while being wrong)") + n = sub.add_parser("info") + n.add_argument("--out", required=True) + args = ap.parse_args() + if args.cmd == "build": + return build(pathlib.Path(args.gguf), pathlib.Path(args.out), args.layers, args.skip_hash) + if args.cmd == "verify": + return verify(pathlib.Path(args.gguf), pathlib.Path(args.out), args.limit, args.expert_every) + return info(pathlib.Path(args.out)) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/strata_tokenizer.py b/tools/strata_tokenizer.py new file mode 100644 index 0000000..8b79419 --- /dev/null +++ b/tools/strata_tokenizer.py @@ -0,0 +1,331 @@ +"""tools/strata_tokenizer.py - the tokenizer, as the reference implementation of record. + +WHY THIS EXISTS AND WHERE IT SITS. The GGUF carries the whole tokenizer in metadata: `tokenizer.ggml.model` += `gpt2`, 248,320 `tokens`, 247,587 `merges`, `token_type`, `pre` = `qwen35`, and a Jinja `chat_template`. +None of that needs the 35 GB of weights, so it is extracted into the pack's `tokenizer/` directory +(docs/pack-format.md §6) and this module is what reads it back. A C++ port follows and is tested against +this one. + +THE DECISIVE PROPERTY IS THE ROUND TRIP. Byte-level BPE maps each BYTE to a printable unicode character so +that any UTF-8 input is representable with no UNK token. Every failure mode of that mapping - the wrong +offset for a byte, a merge applied in the wrong order, a pre-tokenizer split that drops a character - still +produces plausible token ids. `decode(encode(s)) == s` is the check that sees them, and it is exact because +the byte layer is lossless. It is asserted over a corpus chosen to hit the boundaries: multi-byte UTF-8, +emoji (4-byte), combining marks, whitespace runs, and C0 control bytes. +""" +from __future__ import annotations + +import json +import pathlib +import sys + +import regex + +# ------------------------------------------------------------------ byte <-> unicode (GPT-2 byte-level BPE) +def bytes_to_unicode() -> dict[int, str]: + """The GPT-2 byte encoder: 256 bytes -> 256 printable characters, reversibly. + + Bytes 33..126, 161..172 and 174..255 map to themselves; the remaining 68 (space, newline, the C0 + controls and the high range that would be invisible) are shifted into 256+n so that no byte is + unprintable. The shift is the whole trick and getting its ORDER wrong is invisible in the output ids. + """ + bs = (list(range(0x21, 0x7F)) + list(range(0xA1, 0xAD)) + list(range(0xAE, 0x100))) + cs = bs[:] + n = 0 + for b in range(256): + if b not in bs: + bs.append(b) + cs.append(256 + n) + n += 1 + return dict(zip(bs, (chr(c) for c in cs))) + + +BYTE_TO_UNICODE = bytes_to_unicode() +UNICODE_TO_BYTE = {v: k for k, v in BYTE_TO_UNICODE.items()} + +# The `qwen35` pre-tokenizer, transcribed from the ORACLE rather than from the family resemblance: +# `.ref/llama.cpp/src/llama-vocab.cpp` L396, `case LLAMA_VOCAB_PRE_TYPE_QWEN35`. The commented-out line +# above it is the `tokenizer.json` original, and llama.cpp's active version differs from it - it spells the +# contraction classes out instead of using `(?i:...)`, which is behaviourally the same. +# +# THE `\p{M}` IS THE WHOLE POINT OF THIS BEING TRANSCRIBED. The QWEN3 pattern two cases earlier (L389) is +# the same shape with `\p{L}` where this has `[\p{L}\p{M}]` and without `\p{M}` in the punctuation negation. +# Writing the QWEN3 pattern for `qwen35` looks right, round-trips perfectly, and is wrong: a combining mark +# is `\p{M}`, so without it the mark gets swallowed into the following punctuation run and a token like `_j` +# never forms. It cost 3 strings out of 1875 and only `tokenize_oracle_check` could see it. +QWEN35_PATTERN = ( + r"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])" + r"|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+" + r"|\p{N}" + r"| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*" + r"|\s*[\r\n]+" + r"|\s+(?!\S)" + r"|\s+" +) + + +class Tokenizer: + def __init__(self, tokens: list[str], merges: list[str], token_types: list[int] | None = None, + pre: str = "qwen35", special_ids: dict[str, int] | None = None): + self.tokens = tokens + self.pre = pre + self.token_types = token_types + self.special_ids = special_ids or {} + self.ids = {t: i for i, t in enumerate(tokens)} + if len(self.ids) != len(tokens): + raise ValueError("vocabulary has duplicate tokens: %d entries, %d unique" + % (len(tokens), len(self.ids))) + # Merge rules as (left, right) -> rank. A merge list that is not a total order over its pairs, or one + # naming a token that is not in the vocabulary, would make BPE silently produce different ids than the + # model was trained with, so both are checked here rather than discovered as a bad answer later. + self.ranks: dict[tuple[str, str], int] = {} + for i, m in enumerate(merges): + parts = m.split(" ") + if len(parts) != 2: + raise ValueError("merge %d is not a pair: %r" % (i, m)) + if parts[0] not in self.ids or parts[1] not in self.ids: + raise ValueError("merge %d names a token outside the vocabulary: %r" % (i, m)) + self.ranks[(parts[0], parts[1])] = i + self._re = regex.compile(QWEN35_PATTERN) + + # The literals matched directly instead of being run through BPE. GGUF token types: 3 = CONTROL, + # 4 = USER_DEFINED. The two classes behave DIFFERENTLY and llama.cpp's own tokenizer settled which: + # + # * type 4 (USER_DEFINED: ``, ``, ``, ...) is matched ALWAYS, + # with or without parse_special. + # * type 3 (CONTROL: `<|im_start|>`, `<|im_end|>`, `<|endoftext|>`, ...) is matched ONLY when + # parse_special is set. + # + # Measured, not assumed: with parse_special=False the oracle still emitted `` as one + # token and mine emitted four, and the three disagreements were exactly the type-4 cases while every + # type-3 case agreed. Treating both classes alike costs 3 strings in 1229 and silently changes a chat + # prompt, because `<|im_end|>` decomposed into ordinary pieces is not the token the model expects. + self.special_tokens: dict[str, int] = {} + if token_types: + for i, ty in enumerate(token_types): + if ty in (3, 4): + self.special_tokens[tokens[i]] = i + always = [t for t, i in self.special_tokens.items() if token_types and token_types[i] == 4] + # Longest literal first, or `<|im_end|>` could match a shorter prefix of itself. `regex.escape` so a + # token containing regex metacharacters (several do: `<|`, `[`, `(`) is matched literally. + self._always_re = self._alt(always) + self._special_re = self._alt(list(self.special_tokens)) + + @staticmethod + def _alt(literals: list[str]): + if not literals: + return None + return regex.compile("|".join(regex.escape(s) for s in sorted(literals, key=len, reverse=True))) + + # -------------------------------------------------------------- constructors + @classmethod + def from_gguf(cls, path) -> "Tokenizer": + sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + from gguf_reader import GGUFFile + md = GGUFFile(pathlib.Path(path)).metadata + need = ["tokenizer.ggml.tokens", "tokenizer.ggml.merges"] + missing = [k for k in need if k not in md] + if missing: + raise ValueError("GGUF is missing %s; it does not carry a tokenizer" % ", ".join(missing)) + model = md.get("tokenizer.ggml.model") + if model != "gpt2": + raise ValueError("expected a byte-level BPE tokenizer (model 'gpt2'), got %r" % model) + special = {k: int(md[k]) for k in md + if k.startswith("tokenizer.ggml.") and k.endswith("_token_id")} + return cls(list(md["tokenizer.ggml.tokens"]), list(md["tokenizer.ggml.merges"]), + list(md.get("tokenizer.ggml.token_type") or []) or None, + md.get("tokenizer.ggml.pre", "qwen35"), special) + + # -------------------------------------------------------------- the algorithm + def _bpe(self, word: str) -> list[str]: + """Merge `word` (already byte-mapped) by LOWEST RANK first, repeatedly - not left to right. + + Applying merges in list order rather than rank order is the classic BPE bug: it produces a different + segmentation and a plausible token count. + + A word longer than HEAP_MIN symbols (a long CJK run, a minified blob: one pre-token piece of thousands of + bytes) goes to _bpe_heap, which applies the same merges in the same order without rescanning every pair + after each merge (#268: that rescan is O(n^2) and took seconds on an 8K-character CJK run). + """ + if len(word) > self.HEAP_MIN: + return self._bpe_heap(word) + parts = list(word) + while len(parts) > 1: + best, best_rank = None, None + for i in range(len(parts) - 1): + r = self.ranks.get((parts[i], parts[i + 1])) + if r is not None and (best_rank is None or r < best_rank): + best, best_rank = i, r + if best is None: + break + parts[best:best + 2] = [parts[best] + parts[best + 1]] + return parts + + HEAP_MIN = 64 # words up to this many symbols keep the scan above, unchanged + + def _bpe_heap(self, word: str) -> list[str]: + """_bpe's result in O(n log n): the symbols as a linked list, every adjacent pair with a rank in a heap + keyed (rank, position). Popping the lowest rank and then the lowest position is exactly the order the + scan picks (its strict `<` keeps the leftmost of equal ranks), and a symbol's position is where it starts + in the word, which only its left neighbour's merge can change - so a popped pair whose two symbols are + no longer the ones it was pushed with is stale and skipped.""" + import heapq + parts = list(word) + n = len(parts) + nxt = list(range(1, n)) + [-1] + prv = list(range(-1, n - 1)) + ranks = self.ranks + heap = [] + for i in range(n - 1): + r = ranks.get((parts[i], parts[i + 1])) + if r is not None: + heap.append((r, i, parts[i], parts[i + 1])) + heapq.heapify(heap) + while heap: + r, i, left, right = heapq.heappop(heap) + j = nxt[i] + if parts[i] != left or j < 0 or parts[j] != right: + continue # stale: one of its symbols has merged since + parts[i] = left + right + parts[j] = None # j is gone: i takes its place in the list + k = nxt[j] + nxt[i] = k + if k >= 0: + prv[k] = i + r2 = ranks.get((parts[i], parts[k])) + if r2 is not None: + heapq.heappush(heap, (r2, i, parts[i], parts[k])) + p = prv[i] + if p >= 0: + r2 = ranks.get((parts[p], parts[i])) + if r2 is not None: + heapq.heappush(heap, (r2, p, parts[p], parts[i])) + return [s for s in parts if s is not None] + + def _encode_plain(self, text: str) -> list[int]: + out: list[int] = [] + for piece in self._re.findall(text): + mapped = "".join(BYTE_TO_UNICODE[b] for b in piece.encode("utf-8")) + for tok in self._bpe(mapped): + i = self.ids.get(tok) + if i is None: + raise KeyError("BPE produced a token outside the vocabulary: %r" % tok) + out.append(i) + return out + + def _encode_matching(self, text: str, pat, plain=()) -> list[int]: + """Encode `text`, emitting any literal `pat` matches as single tokens and BPE-ing the rest. + + The split happens on the RAW text, before the byte mapping, because a special token's string is a + literal to match rather than bytes to decompose. Everything between the matches is tokenized + normally - which is why a near-miss like `<|im_star` still costs ordinary tokens. A match that starts + inside one of the `plain` (start, end) spans is left to the text around it (#537). + """ + if pat is None: + return self._encode_plain(text) + out: list[int] = [] + pos = 0 + for m in pat.finditer(text): + if plain and any(a <= m.start() < b for a, b in plain): + continue + if m.start() > pos: + out.extend(self._encode_plain(text[pos:m.start()])) + out.append(self.special_tokens[m.group(0)]) + pos = m.end() + if pos < len(text): + out.extend(self._encode_plain(text[pos:])) + return out + + def encode(self, text: str, parse_special: bool = False, plain=()) -> list[int]: + """Tokenize `text`. + + `parse_special` controls only the type-3 CONTROL literals such as `<|im_end|>`; the type-4 + USER_DEFINED ones such as `` are matched either way. See the note in `__init__`. + `plain`: (start, end) spans of `text` that are ordinary text even where they spell a literal - a + `` quoted in a message (#537) - and are tokenized with the text around them. + """ + return self._encode_matching(text, self._special_re if parse_special else self._always_re, plain) + + def token_bytes(self, i: int) -> bytes: + """The raw bytes of one token (a multi-byte character can be split across tokens).""" + cache = self.__dict__.setdefault("_bytes_cache", {}) + b = cache.get(i) + if b is None: + if i < 0 or i >= len(self.tokens): + raise IndexError("token id %d is outside the vocabulary (%d)" % (i, len(self.tokens))) + raw = bytearray() + for ch in self.tokens[i]: + v = UNICODE_TO_BYTE.get(ch) + if v is None: + raise KeyError("token %d contains a character outside the byte alphabet: %r" % (i, ch)) + raw.append(v) + b = cache[i] = bytes(raw) + return b + + def decode(self, ids: list[int], errors: str = "replace") -> str: + return b"".join(self.token_bytes(i) for i in ids).decode("utf-8", errors=errors) + + +# ------------------------------------------------------------------ the pack's tokenizer/ directory +def extract(gguf_path, out_dir) -> dict: + """Write the tokenizer into `/tokenizer/` so the engine never opens the weight shards for it.""" + out = pathlib.Path(out_dir) / "tokenizer" + out.mkdir(parents=True, exist_ok=True) + tk = Tokenizer.from_gguf(gguf_path) + cfg = { + "model": "gpt2", + "pre": tk.pre, + "vocab_size": len(tk.tokens), + "n_merges": len(tk.ranks), + "special_ids": tk.special_ids, + "add_bos_token": False, + # The pattern is SHIPPED, not recomputed by the reader: it is transcribed from llama.cpp for the + # declared `pre` type, and a C++ port that re-derived it would be free to get `\p{M}` wrong again. + "pre_pattern": QWEN35_PATTERN, + "pre_pattern_source": ".ref/llama.cpp src/llama-vocab.cpp L396 (LLAMA_VOCAB_PRE_TYPE_QWEN35)", + } + (out / "vocab.json").write_text(json.dumps(tk.ids, ensure_ascii=False), encoding="utf-8") + (out / "merges.txt").write_text("\n".join("%s %s" % k for k, _ in + sorted(tk.ranks.items(), key=lambda kv: kv[1])), encoding="utf-8") + (out / "token_type.json").write_text(json.dumps(tk.token_types), encoding="utf-8") + (out / "tokenizer.json").write_text(json.dumps(cfg, ensure_ascii=False, indent=1), encoding="utf-8") + # the model's own chat template: fine-tunes change it (Swift 1.5 differs from Qwen3.8-Flash-Next's) + sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + from gguf_reader import GGUFFile + tpl = GGUFFile(pathlib.Path(gguf_path)).metadata.get("tokenizer.chat_template") + if tpl: + (out / "chat_template.jinja").write_text(tpl, encoding="utf-8", newline="\n") + return cfg + + +def main() -> int: + import argparse + ap = argparse.ArgumentParser() + ap.add_argument("--gguf", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--check", action="store_true", help="round-trip a corpus and report") + args = ap.parse_args() + cfg = extract(args.gguf, args.out) + print("tokenizer/: vocab %d, merges %d, pre %s, specials %s" + % (cfg["vocab_size"], cfg["n_merges"], cfg["pre"], cfg["special_ids"])) + if args.check: + tk = Tokenizer.from_gguf(args.gguf) + corpus = ["", "Hello, world!", " leading and trailing ", "a\n\n\nb", + "def f(x):\n\treturn x # comment\n", "\u4f60\u597d\uff0c\u4e16\u754c", "\u0645\u0631\u062d\u0628\u0627", + "\U0001f600\U0001f680\U0001f1fa\U0001f1f8", "e\u0301\u0301 combining", "\x00\x01\x7f control", + "\u00a0non-breaking\u00a0space", "1234567890", "MixedCASE_and-dashes", "\r\n\r\n", "\u2028\u2029", + "x" * 5000] + bad = 0 + for s in corpus: + ids = tk.encode(s) + back = tk.decode(ids) + if back != s: + print(" *** ROUND TRIP FAILED *** %r -> %d ids -> %r" % (s[:40], len(ids), back[:40])) + bad += 1 + print("round trip: %d strings, %d failed" % (len(corpus), bad)) + return 0 if bad == 0 else 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/test_draft_vocab.py b/tools/test_draft_vocab.py new file mode 100644 index 0000000..2375a22 --- /dev/null +++ b/tools/test_draft_vocab.py @@ -0,0 +1,47 @@ +"""Tests for tools/draft_vocab.py's corpus coverage mode (#597): the most frequent tokens of a corpus that together cover +a given share of its occurrences. No model, no GPU. + + python -m unittest tools.test_draft_vocab +""" +from __future__ import annotations + +import sys +import tempfile +import unittest +from collections import Counter +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import draft_vocab as DV # noqa: E402 + + +class Coverage(unittest.TestCase): + def test_most_frequent_first_until_the_share_is_covered(self): + c = Counter({7: 50, 3: 30, 9: 15, 4: 5}) # 100 occurrences + self.assertEqual(DV.covering(c, 0.5), [7]) + self.assertEqual(DV.covering(c, 0.8), [7, 3]) + self.assertEqual(DV.covering(c, 0.81), [7, 3, 9]) + self.assertEqual(DV.covering(c, 1.0), [7, 3, 9, 4]) + + def test_ties_take_the_lower_id_first(self): + self.assertEqual(DV.covering(Counter({5: 10, 2: 10, 8: 10}), 0.5), [2, 5]) + + def test_share_outside_a_subset(self): + c = Counter({1: 60, 2: 30, 3: 10}) + self.assertAlmostEqual(DV.outside(c, [1]), 0.4) + self.assertAlmostEqual(DV.outside(c, [1, 2, 3]), 0.0) + self.assertEqual(DV.outside(Counter(), [1]), 0.0) + + def test_corpus_counts_reads_every_file(self): + class Tok: # one id per character + def encode(self, text): + return [ord(ch) for ch in text] + with tempfile.TemporaryDirectory() as d: + a, b = Path(d) / "a.txt", Path(d) / "b.txt" + a.write_text("été", encoding="utf-8") + b.write_text("eté", encoding="utf-8") + self.assertEqual(DV.corpus_counts(Tok(), [a, b]), Counter({ord("é"): 3, ord("t"): 2, ord("e"): 1})) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_iq_pack.py b/tools/test_iq_pack.py new file mode 100644 index 0000000..1c83db4 --- /dev/null +++ b/tools/test_iq_pack.py @@ -0,0 +1,528 @@ +"""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 +import sys +import tempfile +import unittest +from unittest.mock import patch + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) # runnable from the repo root too + +from _paths import add_gguf_py +add_gguf_py() +from gguf import GGUFWriter, GGMLQuantizationType as Q, quants +import iq_pack + + +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() + writer.write_kv_data_to_file() + writer.write_tensors_to_file() + writer.close() + + +class CompatibilityTests(unittest.TestCase): + def test_bf16_halfway_rounds_to_even(self): + values = np.array([0x3F808000, 0x3F818000, 0xBF808000, 0xBF818000], dtype=np.uint32) + got = np.frombuffer(iq_pack.bf16_bytes(values.view(np.uint8), "F32"), dtype=np.uint16) + np.testing.assert_array_equal(got, [0x3F80, 0x3F82, 0xBF80, 0xBF82]) + + def test_nonfinite_conversion_refused(self): + with self.assertRaisesRegex(ValueError, "non-finite"): + iq_pack.bf16_bytes(np.array([np.nan], dtype=np.float32).view(np.uint8), "F32") + + def test_projection_conversion_and_native_bytes(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + 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.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), + ]) + before = source.read_bytes() + model = iq_pack.Model(source) + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(iq_pack.index_standalone(source, root, model, True), 0) + _, rows = iq_pack.read_index(root / "index.txt") + dense = (root / "dense.bin").read_bytes() + # A scalar oracle independent of the BF16 encoder: choose the nearest BF16 value, + # using the even representation at exact ties. + decoded = quants.dequantize(quants.quantize(values, Q.Q8_0), Q.Q8_0).ravel() + def rounded(x): + bits = int(np.float32(x).view(np.uint32)) + return (bits >> 16) + ((bits & 65535) > 32768 or + ((bits & 65535) == 32768 and (bits >> 16) & 1)) + expected = np.array([rounded(x) for x in decoded], dtype=np.uint16) + for name in names: + row = rows[name] + 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) + 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"]), 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: + root = Path(tmp) + source = root / "model.gguf" + write_gguf(source, [("blk.0.ffn_gate_inp.weight", np.full((2, 32), 0.10001, np.float32), Q.F32)]) + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 1) + + def test_existing_bf16_pack_remains_byte_identical(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + source = root / "model.gguf" + values = np.linspace(-2, 2, 256, dtype=np.float32).reshape(2, 128) + write_gguf(source, [("blk.0.hc_attn_down.weight", values, Q.BF16)]) + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 0) + self.assertEqual((root / "dense.bin").read_bytes(), quants.quantize(values, Q.BF16).tobytes()) + + def test_quantized_control_weights_need_explicit_conversion(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + source = root / "model.gguf" + write_gguf(source, [("blk.0.hc_attn_down.weight", np.ones((2, 32), np.float32), Q.Q8_0)]) + (root / "dense.bin").write_bytes(b"previous pack") + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 1) + self.assertEqual((root / "dense.bin").read_bytes(), b"previous pack") + + 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")) + + def test_experts_bin_is_kept_only_with_this_ggufs_blobs(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + out = root / "pack" + (out / "tokenizer").mkdir(parents=True) + for name in ["vocab.json", "chat_template.jinja"]: + (out / "tokenizer" / name).touch() + + def model(name, scale): + path = root / name + write_gguf(path, [("blk.%d.hc_attn_down.weight" % l, np.ones((2, 32), np.float32), Q.BF16) + for l in range(3)] + + [("blk.%d.ffn_gate_inp.weight" % l, np.ones((4, 32), np.float32), Q.BF16) + for l in range(3)] + + [("blk.%d.ffn_%s_exps.weight" % (l, r), + scale * np.arange(4 * 2 * 32, dtype=np.float32).reshape(4, 2, 32) / 256, Q.Q8_0) + for l in range(3) for r in ("gate", "up", "down")]) + return path + + def pack(path): + log = io.StringIO() + argv = ["iq_pack.py", "--gguf", str(path), "--out", str(out), "--experts-bin"] + with patch.object(sys, "argv", argv), contextlib.redirect_stdout(log): + self.assertEqual(iq_pack.main(), 0) + return log.getvalue() + + first = model("a.gguf", 1) + pack(first) + written = (out / "experts.bin").read_bytes() + self.assertIn("not rewritten", pack(first)) + self.assertEqual((out / "experts.bin").read_bytes(), written) + # the same geometry with other weights under the same file name: the size and the sidecar (shard names + # and sizes, native_experts.txt) match, the contents do not + second = model("a.gguf", -1) + self.assertIn("not this GGUF's expert blobs", pack(second)) + rewritten = (out / "experts.bin").read_bytes() + self.assertEqual(len(rewritten), len(written)) + self.assertNotEqual(rewritten, written) + self.assertIn("not rewritten", pack(second)) + + def test_snapshot_symlinks_keep_split_discovery(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + snap = root / "snapshot" + snap.mkdir() + first = snap / "model-00001-of-00002.gguf" + second = snap / "model-00002-of-00002.gguf" + 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")], split=(1, 2, 5), arch=False) + try: + first.symlink_to(root / "blob1") + except OSError: # Windows without Developer Mode or admin rights + self.skipTest("symlinks are not available here") + with self.assertRaisesRegex(FileNotFoundError, "missing model shards"): + iq_pack.Model(first) + second.symlink_to(root / "blob2") + out = root / "pack" + (out / "tokenizer").mkdir(parents=True) + for name in ["vocab.json", "chat_template.jinja"]: + (out / "tokenizer" / name).touch() + with patch.object(sys, "argv", ["iq_pack.py", "--gguf", str(first), "--out", str(out), "--compat-bf16"]): + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(iq_pack.main(), 0) + expert_index = (out / "native_experts.txt").read_text() + self.assertIn(second.name, expert_index) + self.assertIn("n_expert 512,", expert_index) + (root / "blob2").write_bytes((root / "blob2").read_bytes()[:-64]) + with self.assertRaisesRegex(ValueError, "truncated tensor"): + iq_pack.Model(first) + + + +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", " the smaller pair first + self.assertEqual(ranked[:3], [(2, 0), (3, 0), (1, 0)]) + + def test_default_appends_only(self): + base = [(0, 0), (0, 1)] + freq = defaultdict(int, {(0, 0): 5, (1, 3): 9}) + ranked, _ = MP.rank_profile(base, freq, NE) + self.assertEqual(ranked[:3], [(0, 0), (0, 1), (1, 3)]) # base first; (0,0) already there, not moved + + def test_no_base_uses_the_traces_then_the_fill(self): + base = [(0, 0), (0, 1)] + freq = defaultdict(int, {(1, 3): 9, (0, 0): 5}) + ranked, counts = MP.rank_profile(base, freq, NE, no_base=True) + self.assertEqual(ranked[:2], [(1, 3), (0, 0)]) + self.assertEqual(counts["base"], 0) + self.assertEqual(len(ranked), MP.N_LAYER * NE) + + def test_reorder_without_traces_is_the_default(self): + base = full_base() + self.assertEqual(MP.rank_profile(base, defaultdict(int), NE, reorder=True)[0], base) + + +class Main(unittest.TestCase): + def run_main(self, argv): + old, sys.argv = sys.argv, ["make_profile.py"] + argv + try: + MP.main() + finally: + sys.argv = old + + def test_end_to_end_reorder_over_a_complete_base(self): + with tempfile.TemporaryDirectory() as d: + base = Path(d) / "base.bin" + out = Path(d) / "out.bin" + trace = Path(d) / "t.bin" + MP.write_profile(str(base), full_base(), NE) + write_trace(str(trace), [(5, [1]), (6, [2]), (6, [2]), (6, [2])]) + self.run_main([str(trace), "--base", str(base), "--reorder", "--n-expert", str(NE), "--out", str(out)]) + ranked = MP.read_profile(str(out), NE) + self.assertEqual(ranked[:2], [(6, 2), (5, 1)]) # most frequent first + self.assertEqual(set(ranked), set(full_base())) + # and without --reorder it is the base's order, untouched + self.run_main([str(trace), "--base", str(base), "--n-expert", str(NE), "--out", str(out)]) + self.assertEqual(MP.read_profile(str(out), NE), full_base()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_mtp_fetch.py b/tools/test_mtp_fetch.py new file mode 100644 index 0000000..f6c442f --- /dev/null +++ b/tools/test_mtp_fetch.py @@ -0,0 +1,201 @@ +"""Tests for tools/mtp_fetch.py (#327): a range read needs a 206 with the asked Content-Range, the pinned revision's +tensors are checked against their sha256 (a wrong one is fetched again; a corrupt install is found by `verify` and +setup fetches it again), and an inventory from another revision is read again. A fake checkpoint behind a mocked +urlopen - nothing is downloaded. + + python -m unittest tools.test_mtp_fetch +""" +from __future__ import annotations + +import contextlib +import hashlib +import io +import json +import os +import struct +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +import mtp_fetch as M # noqa: E402 + + +def shard(tensors): + """A safetensors file: [u64 header length][JSON header][data].""" + header, data = {}, b"" + for name, blob in tensors: + header[name] = {"dtype": "BF16", "shape": [len(blob) // 2], "data_offsets": [len(data), len(data) + len(blob)]} + data += blob + h = json.dumps(header).encode() + return struct.pack("