Compare commits
18
Commits
No files matched your search
@@ -1,24 +1,7 @@
|
||||
# UnbiasedStrata build. Needs CMake 3.24+, a C++20 compiler and the CUDA toolkit. Nothing is downloaded.
|
||||
BUILD_DIR ?= build
|
||||
# Pascal/Volta are a community, experimental build: `make build PASCAL=1` compiles sm_61 (GTX 10-series,
|
||||
# Tesla P40; sm_60/P100 works too, override with CUDA_ARCHS=60) and turns on the engine's
|
||||
# STRATA_EXPERIMENTAL_SM60 path (see README.md and src/core/device.cu). It needs a CUDA 12.x toolkit:
|
||||
# CUDA 13 dropped sm_60/sm_70, so the check below fails early with the reason instead of inside nvcc.
|
||||
PASCAL ?=
|
||||
ifeq ($(PASCAL),1)
|
||||
CUDA_ARCHS ?= 61
|
||||
PASCAL_CMAKE_FLAGS := -DSTRATA_EXPERIMENTAL_SM60=ON
|
||||
NVCC ?= $(shell command -v nvcc 2>/dev/null)
|
||||
NVCC_MAJOR := $(shell $(NVCC) --version 2>/dev/null | sed -n 's/.*release \([0-9]*\).*/\1/p' | head -n1)
|
||||
ifneq ($(NVCC_MAJOR),)
|
||||
ifeq ($(shell [ $(NVCC_MAJOR) -ge 13 ] && echo yes),yes)
|
||||
$(error PASCAL=1 needs a CUDA 12.x toolkit; nvcc $(NVCC_MAJOR) dropped sm_60/sm_70)
|
||||
endif
|
||||
endif
|
||||
else
|
||||
# RTX 30 (86), RTX 40 (89) and RTX 50 (120) in one binary. sm_120 needs CUDA 12.8+, and upstream recommends 13.0+.
|
||||
CUDA_ARCHS ?= 86;89;120
|
||||
endif
|
||||
# capped: inside a container nproc reports the host's CPUs, not the container's quota
|
||||
JOBS ?= $(shell n=$$(nproc 2>/dev/null || echo 4); [ $$n -gt 16 ] && n=16; echo $$n)
|
||||
|
||||
@@ -30,8 +13,7 @@ build:
|
||||
@git -C third_party/llama.cpp apply --check --reverse ../../patches/llama.cpp-qwen3-coder-any-argument-order.patch 2>/dev/null || \
|
||||
git -C third_party/llama.cpp apply ../../patches/llama.cpp-qwen3-coder-any-argument-order.patch
|
||||
cmake -S . -B $(BUILD_DIR) -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON \
|
||||
-DSTRATA_PORTABLE=ON -DSTRATA_BUILD_TESTS=OFF "-DCMAKE_CUDA_ARCHITECTURES=$(CUDA_ARCHS)" \
|
||||
$(PASCAL_CMAKE_FLAGS)
|
||||
-DSTRATA_PORTABLE=ON -DSTRATA_BUILD_TESTS=OFF "-DCMAKE_CUDA_ARCHITECTURES=$(CUDA_ARCHS)"
|
||||
cmake --build $(BUILD_DIR) -j $(JOBS) --target unbiased-strata
|
||||
@echo "built: $(BUILD_DIR)/unbiased-strata"
|
||||
|
||||
|
||||
@@ -26,12 +26,6 @@ ssh host 'cd UnbiasedStrata && make build' # produces build/unbiased-strata
|
||||
The tree is 6 MB plus the pinned llama.cpp submodule in `third_party/` (about 170 MB checked out). The
|
||||
build fetches nothing. `make build JOBS=N` sets the job count; `CUDA_ARCHS` defaults to `86;89;120`.
|
||||
|
||||
Pascal is an experimental, community build: `make build PASCAL=1` compiles sm_61 (GTX 10-series, Tesla P40;
|
||||
`CUDA_ARCHS=60` for P100) and turns on the engine's `STRATA_EXPERIMENTAL_SM60` path. It needs a CUDA 12.x
|
||||
toolkit (CUDA 13 dropped sm_60/sm_70) and is outside the validated configuration above: no tensor cores, so
|
||||
expect the portable FP32 attention path and much lower throughput, and a card under 24 GB leans on the expert
|
||||
cache.
|
||||
|
||||
## Run
|
||||
|
||||
```
|
||||
@@ -42,8 +36,7 @@ cache.
|
||||
| | |
|
||||
| --- | --- |
|
||||
| Endpoints | `POST /v1/chat/completions` (streaming or not), `GET /v1/models`, `GET /health`, on `127.0.0.1:8080` |
|
||||
| Options | `--ctx N` (32768), `--threads N` (default: physical cores, or half the CPU quota in a container), `--host`, `--port`, `--mmproj PATH`, `--vision-tokens N` (1024), `--fit-max-tokens` / `--no-fit-max-tokens` (default: on); engine flags after `--` |
|
||||
| Context | a request whose `max_tokens` would run past `--ctx` has it shortened to the room left; with `--no-fit-max-tokens` it is refused (400) instead |
|
||||
| Options | `--ctx N` (32768), `--threads N` (default: physical cores, or half the CPU quota in a container), `--host`, `--port`, `--mmproj PATH`, `--vision-tokens N` (1024); engine flags after `--` |
|
||||
| Sampling | greedy unless `temperature` > 0 |
|
||||
| Reasoning | returned as `reasoning_content`; `"reasoning_effort": "none"` turns it off |
|
||||
| Tools | OpenAI format (`tools`, `tool_calls`) |
|
||||
|
||||
@@ -0,0 +1,456 @@
|
||||
# Plan: UnbiasedStrata on Qwen3.6-35B-A3B, any single NVIDIA card from Pascal up, 256K context
|
||||
|
||||
Written 2026-10-11, revised the same day three times: after reading
|
||||
[Project Maya](https://github.com/mw00/project-maya); after the target widened from one card to a range;
|
||||
after the llama.cpp-backend fallback was removed. Status: proposed, nothing started.
|
||||
|
||||
Engine base: this repository's Strata snapshot (`6f32ec0`, engine 0.1.39). Maya is a method reference only.
|
||||
llama.cpp appears in two roles only: the external speed baseline (bare `llama-server`, never inside the
|
||||
binary) and the numerical oracle for parity. There is no fallback path.
|
||||
|
||||
## 0. Target and what "adapt" means
|
||||
|
||||
**Target:** one NVIDIA GPU, compute capability 6.1 or newer (GTX 10 series through RTX 50), **6 GB to 32 GB**
|
||||
of VRAM, Linux, x86-64 with AVX2. The engine sizes itself at start: fixed weights first, then the KV cache
|
||||
for the requested context, then every remaining byte of VRAM becomes expert-cache slots. The same binary
|
||||
and the same model files on every card; only speed differs. Q4 is the default quant. Context 262,144 where
|
||||
it fits, never below 131,072 without saying so. **Multi-GPU is out of scope**; the front end already
|
||||
refuses `--gpus`, and that stays.
|
||||
|
||||
The Strata engine in `src/` runs one architecture, Qwen3.8-Flash-Next (`qwen4_exp_text`). Qwen3.6-35B-A3B
|
||||
(`qwen3_5_moe_text`) is the same family one generation earlier, with the extras removed. From the two
|
||||
models' `config.json`:
|
||||
|
||||
| | Qwen3.8-Flash-Next (what the engine runs) | Qwen3.6-35B-A3B (the target) |
|
||||
| --- | --- | --- |
|
||||
| Hidden / layers | 2560 / 48 | 2048 / 40 |
|
||||
| Layer pattern | 3 linear attention then 1 full attention (`full_attention_interval` 4) | the same |
|
||||
| Linear attention (GDN) | 16 k-heads, 48 v-heads, 128-dim, conv 4 | 16 k-heads, **32** v-heads, 128-dim, conv 4 |
|
||||
| Full attention | 24 heads, 2 KV heads, head_dim 256, partial rotary 0.25, output gate, **plus a sparse indexer (QSA)** | 16 heads, 2 KV heads, head_dim 256, partial rotary 0.25, output gate, **dense** |
|
||||
| MoE | 512 experts, top-10, intermediate 640, shared 640 | 256 experts, top-8, intermediate 512, shared 512 |
|
||||
| Residual | hyper-connections (`hc` 4 streams) | plain residual |
|
||||
| PLE / n-gram table | yes (28.8 GB shard 2) | none |
|
||||
| MTP | 1 draft layer | 1 draft layer |
|
||||
| Vocabulary | 248,320 | 248,320, the same tokenizer |
|
||||
| Context | 262K | 262K native |
|
||||
|
||||
Everything Qwen3.6 has, the engine has a kernel for; what it lacks, the engine treats as optional (PLE) or
|
||||
needs a bypass for (hyper-connections, the QSA indexer). Maya's port study (`docs/GLM5-FLASH.md` in that
|
||||
repo) crossed a larger *kernel* gap for GLM-5.3-Flash in about a week: study 2026-09-29, verified
|
||||
streaming runner 2026-10-01, v1.0.0 on 2026-10-07. The Qwen3.6 kernel gap is smaller (no MLA, no sparse
|
||||
indexer to write, no manifold hyper-connections, a SiLU-for-sigmoid change in the GDN gate). The
|
||||
*plumbing* gap is not small: `docs/qwen36-port/geometry-inventory.md` (154 rows, 2026-10-11) shows the
|
||||
hc = 4 gated residual and the QSA indexer assumed structurally in every block, the output head, the
|
||||
verify window, the MTP drafter and prefill; prefill refusing any geometry but 2560/4/320/top-10; native
|
||||
packs decoding only through the verify window; and `ModelGeometry` reading only the expert counts and
|
||||
rope keys from the file. Expect Maya-scale work, with the risk in plumbing rather than kernels.
|
||||
|
||||
**The deliverable:** this tree's engine running Qwen3.6-35B-A3B natively, by Maya's method, behind the
|
||||
existing front end (`frontend/`: OpenAI API, tokenizer, chat template, tool-call parser, vision), which is
|
||||
model-agnostic and stays. The payoff is what llama.cpp's `--n-cpu-moe` cannot do: hot experts cached in
|
||||
VRAM by usage across all layers, the CPU computing the misses concurrently with the GPU, instead of whole
|
||||
layers' experts on the CPU serially. On a 6 GB card that is the difference between a cache holding the
|
||||
hottest 7% of experts and a layer cut holding none.
|
||||
|
||||
Hypotheses:
|
||||
|
||||
- **H1.** Under llama.cpp `--n-cpu-moe N` the GPU is idle most of each decode step, and the idle share
|
||||
grows with N, so it is worst on the smallest cards. (The baseline sweep measures it.)
|
||||
- **H2.** The idle is CPU expert matmul, not PCIe transfer.
|
||||
- **H3.** 256K context fits at Q4 on every card of 11 GB or more; 128K fits on 8 GB; 6 GB at Q4 holds
|
||||
the 256K fixed set only when prefill borrows cache slots, else it takes 131K or the IQ3 file, and the
|
||||
engine must say which it chose.
|
||||
- **H4.** Qwen3.6's routing is skewed enough that a VRAM expert cache serves well above its slot fraction
|
||||
of routes at every budget from 6 GB up. The replay measures the whole curve before any CUDA.
|
||||
- **H5.** The ported engine's decode scales as `1 / max(cpu, gpu)` rather than `1 / (cpu + gpu)`, and beats
|
||||
the llama.cpp baseline at every VRAM budget, by the most at the small end.
|
||||
- **H6.** With 12 GiB of RAM beside the 1080 Ti, Q4 reaches the disk tier and the profile-ranked VRAM
|
||||
and RAM tiers keep disk reads under one expert per token on a warm conversation; IQ3 never reaches the
|
||||
disk. The replay with three tiers predicts this; the engine's tier counters confirm it.
|
||||
|
||||
H4 and H5 are not a go/no-go for building the engine; the port is the deliverable regardless. They decide
|
||||
how the README describes the result and where the expert-cache tuning effort goes.
|
||||
|
||||
**Measured on 2026-10-11 (Phase 0; details in `~/Code/regina/analysis/qwen36-35b-single-gpu-ladder/`):**
|
||||
|
||||
| | Q4_K_XL at 11 GB | IQ3_XXS at 11 GB |
|
||||
| --- | --- | --- |
|
||||
| llama.cpp, 256K, fit edge (`--n-cpu-moe` 32 / 18), smoke test, cold cache, 400 tokens | 8.8 tok/s decode, 129 prefill, GPU busy 15% | 24.6 tok/s decode, 434 prefill, GPU busy 41% |
|
||||
| llama.cpp, the sweep (warm, 1,200 tokens, `baseline-1080ti.md`) | **the number to beat: N = 30, the lowest N that fits (10,415 MiB): 13.4 tok/s decode on the regina request, 16.3 on the short one.** At N = 32: 13.5 / 12.2, 152 prefill; nvprof at N = 32: busy 13.8%, memcpy 0.6%, gaps 86%; warm nvprof at N = 30: busy 15.0%, memcpy 0.6%, 3.1 MiB of activations per token over PCIe; 14 to 21 MiB per token from disk | 33.5 tok/s decode, 907 prefill; GPU busy 56% (nvidia-smi); warm nvprof at N = 20: busy 24.8% under a 2.1x profiler slowdown, memcpy 0.8%; no disk reads |
|
||||
| Sweep slope | 0.67 to 0.93 points of GPU busy and 0.5 to 0.7 tok/s per layer moved to the CPU (the N = 32 point was the first run and carried steal) | one point and 0.58 tok/s per layer |
|
||||
| Route trace, top 40% of experts per layer | 76% of routes (215K routed tokens) | |
|
||||
| Replay at the censused sizes, LFU with 3 spares per layer, prefill borrowing cache slots | 78 slots per layer: 83.2% hit, 36.6 RAM and 17.0 disk reads per token | 149 slots: 95.4% hit, 14.6 RAM and 0 disk reads |
|
||||
| Replay, no borrowing (prompt buffer held in VRAM) | 52 slots: 72.2% hit, 35.8 disk reads | 103 slots: 89.4% hit, 0 disk reads |
|
||||
| Predicted decode, overlap / serial (gpu 17 ms, CPU lane 0.15 ms per expert, disk 1.3 ms; parameters, not measurements), borrowing | 36.2 / 22.4 tok/s | 58.8 / 52.1 tok/s |
|
||||
|
||||
Readings: H1 holds (the GPU idles 86% of each Q4 step by the kernel timeline, 44% at IQ3). H2 holds (memcpy is 0.6% of the window; the idle is CPU matmul and, at Q4, page-ins). H4 holds (83% hit from 35% of the
|
||||
experts). With 12 GiB of RAM the Q4 arm is disk-limited (17 disk reads per token, about 22 ms, more than
|
||||
the whole GPU step), so on this rung IQ3 is the quant that reaches the GPU ceiling and Q4 needs either
|
||||
16 GiB of RAM or 12 GB of VRAM. Prefill borrowing cache slots is worth 11 points of hit rate at Q4. Prefill hit rates are linear in slots (a prompt touches nearly every
|
||||
expert per layer per ubatch), so prompts stream experts over PCIe, as Strata already does. The overlap
|
||||
column saturates at `1000 / gpu_ms`; the GPU step itself is the next thing to measure properly (nvprof,
|
||||
in the sweep).
|
||||
|
||||
## 1. The card ladder
|
||||
|
||||
Real cards in the homelab cover the range, with Pascal at three sizes:
|
||||
|
||||
| Budget | Card | Where | Arch | Role |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 6 GB | GTX 1060 | g7 (192.168.50.185), laptop | sm_61 | the floor; regina's `g7/README.md` has llama.cpp numbers here already |
|
||||
| 8 GB | GTX 1070 Ti | host .4 (`llama-qwen36-35b-mtp.service`, live) | sm_61 | second Pascal point |
|
||||
| 11 GB | GTX 1080 Ti | .57 at PCI `2a:00`, in **VM 211 `gpu-qwen36`** at 192.168.50.43 (cloned from 210 on 2026-10-11: 8 vCPU, 12 GiB, 100 GB on `local-lvm`, Debian 13, driver 550, CUDA 12.4, gcc-13) | sm_61 | the primary measurement card, and the development card until a pod is rented |
|
||||
| 32 GB, rented | A6000 or similar on RunPod | on demand; this fork was already checked on a RunPod 3090 container (README) | sm_86 | only for the 32 GB rung and if the 4090 becomes busy again; the user has approved spending on this |
|
||||
| 24 GB | RTX 4090 | VM 221 (192.168.50.151) on pve2: 16 vCPU, 62 GB RAM, CUDA 12.4, driver 550; root disk nearly full (build trees under `/models/work`, 174 GB free); system gcc is 14, so builds need gcc-13 as the host compiler | sm_89 | **idle since 2026-10-11 17:20, the user's call: the fast-compile development card for Phase 2 steps 3 to 5 and the 24 GB rung.** Both llama-server units there are inactive; leave them so. No RunPod needed while it stays free |
|
||||
| 12, 16, 32 GB | RTX A6000 (48 GB) **capped** | VM 220 (192.168.50.8) on .57 | sm_86 | **in use by another agent**; the emulated rungs wait for it |
|
||||
|
||||
The cap is Maya's `STRATA_GLM_VRAM_GB` idea: the engine limits its own total VRAM so the expert pool gets
|
||||
what a card of that size would leave it. It is built in Phase 2 step 2; the 1080 Ti emulates the 6 and 8 GB
|
||||
rungs with it (the real 1060 and 1070 Ti then check launch failures, FP16 paths and PCIe), and the A6000
|
||||
emulates 12, 16 and 32 GB whenever it is free.
|
||||
|
||||
Consequence of the 1080 Ti being the only local card: **the Pascal build comes first, not last.** Every
|
||||
parity harness and the streaming runner are brought up under `STRATA_EXPERIMENTAL_SM60=ON` on sm_61 from
|
||||
the start, so Pascal surprises surface in the first week. The rented sm_86 pod runs the same harnesses in
|
||||
parallel for fast iteration; a kernel passes when it passes on both.
|
||||
|
||||
Constraints across the ladder:
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| CUDA | one toolkit that compiles sm_61 and sm_120 both: **CUDA 12.8** (12.x is the last with Pascal; 13 dropped it). Upstream saw RTX 50 crashes with 12.8-built engines (issues #220, #224), so RTX 50 is "built, not measured" until a card exists here. Fat binary `CUDA_ARCHS=61;70;75;86;89;120` |
|
||||
| Pascal specifics | dp4a exists on sm_61 (not sm_60, which gets the shim); no tensor cores; no `__nanosleep`; FP16 math at 1/64 rate on GP102/GP104/GP106, so every kernel's *arithmetic* on these cards must be FP32 or dp4a int8 (fp16 *storage* with conversion, as in the KV pools and prefill's stores, is full rate and stays); the prompt MoE's dp4a MMQ path must be enabled on sm_61. Strata refuses sm < 75 unless `STRATA_EXPERIMENTAL_SM60=ON`; that flag becomes the default build (Phase 2, step 6). Nobody has run this engine on Pascal; Maya requires Volta or newer |
|
||||
| Build verification | `cuobjdump --list-elf \| grep sm_` after every build; two past incidents here were wrong-arch binaries |
|
||||
| Profilers | current Nsight Systems: Turing and newer only. Nsight Compute: no Pascal since 2019.5. On Pascal use the `nsys` bundled with CUDA 12.x (2023.x) or `nvprof`; on Turing and newer current `nsys`. Same analysis script either way |
|
||||
| .57 host | Ryzen 7 1700 (Zen 1, AVX2, no AVX-512), 62 GiB usable DDR4-2133. Checked 2026-10-11: VM 220 shrunk to 36 GiB by another agent, host 18 GiB available before VM 211, about 6 GiB after. The 1080 Ti's link is **Gen3 x8** (`LnkSta: 8GT/s, Width x8`), so the June Gen1 problem is gone. VM 220 shares the memory bandwidth and the 8 physical cores (VM 220 has 12 vCPU, VM 211 has 8: oversubscribed when both are busy), so each run's metadata records VM 220's load and measurement windows prefer its idle hours |
|
||||
| Stale pointer | `docs/NEW-GPU-VM.md` says "both GTX 1080 Ti"; slot 29:00 now holds the A6000 |
|
||||
|
||||
## 2. Models, the memory hierarchy, and the budget table the engine must reproduce at start
|
||||
|
||||
**The hierarchy on the primary rung is three tiers, by the user's decision:** 11 GB of VRAM in the 1080 Ti,
|
||||
about 12 GiB of VM RAM (roughly 9 to 10 GB usable for a pinned expert tier after the OS, the process and
|
||||
the KV), then the VM's NVMe disk for the rest. Strata already has the pieces: the VRAM expert cache, the
|
||||
pinned RAM tier, and the low-RAM modes (`--mmap-experts` serving misses from the model file through the
|
||||
page cache; `--resident-experts` copying exactly the non-VRAM experts into RAM when they fit). At Q4 they
|
||||
do not all fit in 12 GiB, so the mapped mode and the disk are in play; at IQ3_XXS the whole expert set fits
|
||||
VRAM plus RAM. Every per-budget number below is therefore a pair: where the experts live, and how many
|
||||
reads per token reach the disk.
|
||||
|
||||
| Arm | File | Size | Where it already is |
|
||||
| --- | --- | --- | --- |
|
||||
| **Q4, default** | `Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` (unsloth, repo commit `a483e9e`) | ~21 GB | not on hand; download once on the Mac, SHA-256 against the repo, copy over LAN |
|
||||
| Q4 + MTP | `Qwen3.6-35B-A3B-UD-Q4_K_M-MTP.gguf` | 22.66 GB | `.4:/mnt/models/qwen3.6/MTP/`, Mac `~/models/qwen3.6/MTP/` |
|
||||
| Q3 | `Qwen3.6-35B-A3B-UD-IQ3_XXS.gguf` | 13.21 GB | `.4`, `.151:/models`, g7 `/home/rk/models` |
|
||||
|
||||
K-quants for the default because most experts run on the CPU on most of the ladder, and K-quant dot
|
||||
products are the fast AVX2 path. The engine needs the MTP block: Strata's draft protocol is built around
|
||||
the model's own MTP layer. Settled on 2026-10-11: the `Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` from unsloth's MTP
|
||||
repository (rev 5bc3e238) already carries the draft block as `blk.40` (753 tensors), so it is the default
|
||||
file, and its `blk.40` serves as the draft pack for the IQ3 arm too (the plain IQ3 file has no draft block).
|
||||
|
||||
Fixed VRAM before any expert slot. Measured and censused on 2026-10-11; the authoritative table is
|
||||
`docs/QWEN36-35B-A3B.md` section 4.1, summarized:
|
||||
|
||||
| Item | Q4_K_XL | IQ3_XXS |
|
||||
| --- | --- | --- |
|
||||
| Non-expert weights on the GPU | 2,038 MiB | 1,597 MiB |
|
||||
| Draft block (dense 40 MiB + its experts + ring KV + logits) | ~520 MiB | ~520 MiB (the Q4 file's) |
|
||||
| KV, q4_0, 10 attention layers, 262K | 1,440 MiB | 1,440 MiB |
|
||||
| Session, CUDA context, reserve | ~0.7 to 1.2 GB | same |
|
||||
| Prompt buffers | 0 when prefill borrows cache slots (a profile exists); 1,904 MiB at chunk 2048 otherwise | 0 / 1,878 MiB |
|
||||
| **Decode-time fixed set at 262K** | **~4.8 GB borrowing, ~6.7 without** | **~4.3 / ~6.2** |
|
||||
| Trunk experts, total / per expert (mean, max) | 18,726 MiB / 1.83 MiB, 2.20 max | 10,594 MiB / 1.04 MiB, 1.17 max |
|
||||
|
||||
What each budget leaves for experts at Q4, 262K (the llama.cpp layer cut on the right is the baseline's
|
||||
equivalent, for the comparison only):
|
||||
|
||||
| Budget | Q4 expert slots in VRAM, prefill borrowing (of 10,240) | IQ3 slots | `--n-cpu-moe` equivalent |
|
||||
| --- | --- | --- | --- |
|
||||
| 6 GB | ~525 (5%); without borrowing the fixed set does not fit at 262K, so 131K or the IQ3 file | ~1,350 (13%) | 40 (all) |
|
||||
| 8 GB | ~1,570 (15%) | ~3,200 (31%) | ~37 |
|
||||
| 11 GB (the 1080 Ti, 11,264 MiB), 12 GiB RAM, NVMe | ~3,550 (35%) in VRAM; ~4,950 (48%) pinned in RAM; ~1,740 (17%) on disk | ~6,700 (66%) in VRAM, the rest in RAM, no disk tier | ~32 (llama.cpp's CPU experts at Q4 exceed 12 GiB, so its baseline on this rung is page-cache bound too) |
|
||||
| 12 GB | ~3,650 (36%) | ~6,880 (67%) | ~31 |
|
||||
| 16 GB | ~5,740 (56%) | all | ~26 |
|
||||
| 24 GB | all, ~1 GB spare | all | 0 |
|
||||
| 32 GB | all; the spare VRAM goes to f16 KV or a bigger prompt chunk | all | 0 |
|
||||
|
||||
The sizing rule the engine implements (Phase 2, step 2): take the fixed total for the requested context;
|
||||
if it does not fit, lower the context toward 131,072, then refuse with the exact numbers and the IQ3 file's
|
||||
name. **KV streaming is not a lever for this model**: Strata streams by resolving the *selected* cells, and
|
||||
dense attention selects every cell (study, 3.3 item 6), so the KV stays in VRAM. Never silently pick a
|
||||
shorter context. Then the RAM tier: free RAM minus a headroom for the OS and the KV
|
||||
stream, filled with the next experts by profile rank; whatever remains stays mapped from the GGUF on disk
|
||||
and is read on a miss. The start-up log states all three counts.
|
||||
|
||||
CPU-side ceiling for the misses: ~12 MiB of expert weight per CPU-computed layer-token at Q4. On the .57
|
||||
host (DDR4-2133, ~30 GB/s) that is ~60 to 70 tok/s before compute; Zen 1's 8 cores will be the lower
|
||||
bound. Prior Pascal data: GTX 1060 6 GB, IQ3_XXS, N = 32: 16 tok/s at 8K depth, 11 at 32K, 355 tok/s
|
||||
prefill, all llama.cpp.
|
||||
|
||||
## 3. Phase 0: environment, baseline, and the replay
|
||||
|
||||
Human steps (Proxmox state is the user's):
|
||||
|
||||
1. (Decided: VM 220 stays up; host RAM already freed for a 12 GiB VM.)
|
||||
2. (Done 2026-10-11.) VM 211 `gpu-qwen36`, a full clone of VM 210: **8 vCPU, 12 GiB RAM, balloon 0,
|
||||
100 GB on `local-lvm` (NVMe)**, `--hostpci0 0000:2a:00,pcie=1`. No `rombar=0`: that was needed only
|
||||
for the boot-VGA card at 29:00 (homelab ticket 002); the 1080 Ti at 2a:00 never needed it. VM 220
|
||||
keeps running. The disk is the third tier, so `fio` its read throughput and 4K random latency once,
|
||||
into `phase0-notes.md`.
|
||||
3. Inside the VM: pin the kernel/driver pair, install `build-essential cmake nvtop linux-perf`, CUDA 12.8
|
||||
(the template has 12.4; 12.8 needs a 570-series driver, still a Pascal-capable branch), confirm
|
||||
`nvidia-smi`, check `LnkSta`, set `perf_event_paranoid` to 1.
|
||||
4. Copy the GGUFs over LAN; `sha256sum` each.
|
||||
|
||||
Agent steps (fresh sonnet agent; brief = this section plus the hosts):
|
||||
|
||||
5. Build bare `llama-server` at the submodule's pinned commit `3cf0325`, `-DGGML_CUDA=ON`, arches
|
||||
`61;86;89`, static; verify with `cuobjdump`. Also the latest release (v0.6.0) for its MTP arm. One
|
||||
build per rung, each verified for its own arch. This binary is the baseline and the oracle, nothing
|
||||
else.
|
||||
6. Profiler check on the 1080 Ti: CUDA 12.x `nsys status -e`, a 10-second `nsys profile -t cuda` of
|
||||
`llama-bench`, `nvprof --print-gpu-trace` as fallback. Record which works.
|
||||
7. Smoke test at 256K on the 1080 Ti with `llama-server`: `-ngl 99 --n-cpu-moe 32 -fa on -c 262144
|
||||
-ctk q4_0 -ctv q4_0 -b 2048 -ub 2048 --parallel 1 --cache-ram 0 -lv 4 -t 8`. Save the `-lv 4` buffer
|
||||
lines; they replace the estimates in Section 2.
|
||||
|
||||
**The baseline sweep (sonnet to drive, haiku to monitor).** Regina's harness (`scripts/sweep_ncpumoe.py`,
|
||||
`plot_ncpumoe_sweep.py`): the N sweep with VRAM (`nvidia-smi` and `-lv 4`), host RAM (`RssFile`), prefill
|
||||
and decode from `timings`, one real launch per point. One env spec per card; the A6000 budgets via
|
||||
`CUDA_VISIBLE_DEVICES` plus a side process holding the surplus VRAM. Regina's hygiene: 30 s settle, drop
|
||||
caches, warmup discarded, `--cache-ram 0`, `--parallel 1`. Workload per point: the Opus system prompt
|
||||
(~27K tokens) + "implement Minesweeper", `n_predict 800`, plus one 3K-prefill / 1200-decode request.
|
||||
Reasoning off, `temp 0`, `seed 42`.
|
||||
|
||||
Instruments, logged per run (the same three serve the engine later):
|
||||
|
||||
- **Level 0, always:** `nvidia-smi --query-gpu=timestamp,utilization.gpu,memory.used,power.draw
|
||||
--format=csv -lms 100`. `utilization.gpu` is the GPU-busy share at 100 ms resolution. nvtop in a tmux
|
||||
pane is for the human, not the record.
|
||||
- **Level 1, per point:** a decode-phase kernel timeline (`nsys` or `nvprof`). A script computes busy
|
||||
fraction, gap histogram, memcpy vs kernel share (the H2 test), per-token period, profiler overhead.
|
||||
- **Level 2:** `perf stat` on the server PID, so gaps match CPU time in ggml matmul threads.
|
||||
|
||||
| # | Where | Arm | N values | ctx | Question |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| B1 | 1080 Ti | Q4 | fit edge, +2, +4, +8, 40 | 262144 | H1, H3 on the primary card; with 12 GiB of RAM the CPU experts page from disk, so `RssFile` and disk reads are recorded per point |
|
||||
| B1b | 1060, 1070 Ti, 4090, A6000 at 12/16/32 | Q4 | the fit edge for that budget, and 40 | 262144, or 131072 where 262K does not fit | the baseline row of the ladder table |
|
||||
| B2 | 1080 Ti | Q4 | fixed N | 262144 | depth 8K, 32K, 128K |
|
||||
| B3 | 1080 Ti, 1060 | Q3 | fit edge, +4, +8, 40 | 262144 | K-quant vs i-quant CPU cost; the 6 GB default |
|
||||
| B4 | 1080 Ti | Q4 + MTP | fixed N | 262144 | multi-token verify on CPU experts (llama.cpp's MTP) |
|
||||
|
||||
B1, B1b and B3 are the baseline. B2 and B4 run when a card is idle. File-based drivers under `tmux`,
|
||||
`DRIVER_DONE` markers. B1 takes 2 to 4 hours at 256K context.
|
||||
|
||||
**E0, the route trace and cache replay (sonnet agent; any GPU host, even the Mac).** From Maya; it
|
||||
answers H4 for the whole ladder before any CUDA and it produces the expert profile the engine loads:
|
||||
|
||||
8. Record routes: a small patch to llama.cpp's `examples/eval-callback` writing one line per token and MoE
|
||||
layer with the 8 selected expert ids (`ffn_moe_topk`). Corpus: regina's coding tasks, the Opus system
|
||||
prompt, a few long chats; ~200K routed tokens.
|
||||
9. Replay: adapt Maya's `tools/glm_tier_replay.py` (MIT; models LFU residents + spares + the CPU-lane
|
||||
pick) to 40 layers × 256 experts **and three tiers** (VRAM slots, RAM slots, disk), and sweep the VRAM
|
||||
slot count from 0 to 10,240 landing on each budget from Section 2, at Q4 and IQ3, with the RAM tier
|
||||
fixed at what 12 GiB leaves. Policies: LFU, LRU, Belady ceiling.
|
||||
10. Output: `phase0-replay.md` with VRAM hits, RAM hits and disk reads per token **vs slots**, the seven
|
||||
budgets marked, and the predicted engine decode ceiling per budget against the baseline, using the
|
||||
measured disk latency from step 2 for the disk term. The trace also seeds `expert-profile.bin`.
|
||||
|
||||
Exit criteria: the baseline ladder row with the 1080 Ti's full N sweep; a working profiler on Pascal; the
|
||||
hit-rate curve with the budgets marked; Section 2's estimates replaced by measured buffer sizes.
|
||||
|
||||
## 4. Phase 1: images and the baseline write-up
|
||||
|
||||
Under `~/Code/regina/analysis/qwen36-35b-single-gpu-ladder/`:
|
||||
|
||||
1. `gpu-busy-vs-N.png`: Level-1 busy fraction and Level-0 utilization vs N on the 1080 Ti, both arms. H1.
|
||||
2. `timeline-N<k>.png`: a 200 ms strip of one decode step, kernels vs memcpys vs gaps. H2.
|
||||
3. `ladder-baseline.png`: decode and prefill vs VRAM budget (6, 8, 11, 12, 16, 24, 32), llama.cpp at the
|
||||
fit edge. The engine's points go on the same axes in Phase 2 step 5. The headline image.
|
||||
4. `vram-vs-N.png`: VRAM vs N with the budget lines and the 262K/131K KV points.
|
||||
5. `dmon-strip-N<k>.png`: the raw 100 ms trace over prefill then decode.
|
||||
6. `replay-hitrate-vs-slots.png`: hit rate vs slots per policy, budgets marked. H4.
|
||||
|
||||
Analysis reads the PNGs and CSVs. The write-up answers with numbers: busy fraction and its slope in N;
|
||||
memcpy vs gap; the default quant per budget; the baseline ladder row; the simulated hit rate per budget
|
||||
and the predicted engine gain, largest-to-smallest card. A fresh agent reviews it, given the data but not
|
||||
the conclusion. This write-up is what the engine must beat; it does not decide whether the engine is built.
|
||||
|
||||
## 5. Phase 2: the engine port, Maya's recipe on a smaller gap
|
||||
|
||||
The design document for this phase is `docs/QWEN36-35B-A3B.md` (2026-10-11): the model exactly from the
|
||||
real GGUF's metadata, the component-by-component gap analysis with file:line citations, the memory plan
|
||||
with the censused fixed set, the ladder, the envelope, the execution plan with effort weights (step 2
|
||||
15%, step 3 45%, step 4 20%, step 5 10%, step 6 5%, step 7 5%) and the risks. Where it and this plan
|
||||
differed, the plan was corrected to the study on 2026-10-11 (its section 8 lists the eight points).
|
||||
|
||||
Where: step 2 on VM 211 (the 1080 Ti, the Pascal build from the first step, Section 1). From step 3 on,
|
||||
kernel work and parity iterate on the 4090 in VM 221 (sm_89, idle since 2026-10-11) and every kernel
|
||||
also passes on the 1080 Ti before its step closes; the 4090 is also the 24 GB rung for step 5. Each step has a parity harness in Strata's negative-test discipline (every wrong reading must
|
||||
differ materially before the right one is judged), as Maya's section 6 did. Steps 1 to 4 need no GPU time
|
||||
beyond seconds of parity runs, so they proceed while the Phase 0 sweeps hold the cards.
|
||||
|
||||
1. **Oracle and fixture (sonnet, no GPU).** Found on 2026-10-11 (`docs/qwen36-port/upstream-tooling.md`):
|
||||
upstream never published its Python oracles (`ref/` holds only `load.py`; `gdn.py`, `moe.py`,
|
||||
`qsa.py`, `docs/semantics.md` are cited but absent), most parity tests carry a host C++ reference
|
||||
inside the test file, two embed generated `.inc` vectors, and the ggml-oracle tests link a llama.cpp
|
||||
build through `STRATA_ORACLE_SOURCE_DIR`. So: `tools/` and `tests/` restored from the import commit `12a7825`
|
||||
(done, commit c00942d: development tooling only, the binary still needs no Python), then write `ref/qwen36.py` new on `ref/load.py`, following the submodule's
|
||||
`qwen35moe.cpp` graph with dumps named by its `cb()` calls; `tools/qwen36_synth_gguf.py` from
|
||||
`test_iq_pack.py`'s `write_gguf()`; invariant tests (top-8 renormalization, GDN state shapes, the
|
||||
output gate). Cross-check with the submodule's `llama-eval-callback` on the same synthetic GGUF.
|
||||
One model difference already known: Flash-Next's GDN output norm gates with sigmoid(z), `qwen35moe`
|
||||
with SiLU(z); `gdn.cu` and `gdn_parity` encode the sigmoid reading, so that is the first negative
|
||||
test. `make_profile.py` hardcodes 48 layers and 512 experts; the MTP tools hardcode Flash-Next tensor
|
||||
names; `iq_pack.py`'s `FORM` table has no `qwen35moe` entry. Dependencies: numpy, regex, gguf-py; no
|
||||
torch, no GPU.
|
||||
**Done 2026-10-11 on branch `qwen36-oracle`** (commits 9630539, f1ef81d, 0c850c3, 2094992, unmerged):
|
||||
the oracle matches llama.cpp's own graph on 2,155 comparisons across 14 cases (max abs error 1.1e-4,
|
||||
identical top-k everywhere, the nextn block included); seven rival readings each fail; 21 invariant
|
||||
tests (24 after review). Independent review: no blockers; the GQA fixture (4 query heads over 2 KV
|
||||
heads) added after review and matching on every seam; `ref/load.py`'s dequant bit-identical to ggml's
|
||||
for Q6_K, IQ2_S, IQ3_XXS and IQ4_XS. **Tolerance policy** (`docs/qwen36-port/oracle-crosscheck.md`):
|
||||
the oracle has a Q8 activation mode (`--act-quant q8`) and a per-layer protocol (`--force-topk`,
|
||||
`--force-inputs`) that starts each layer from llama.cpp's inputs; against that, the per-seam relative
|
||||
spread on the real file is 5e-8 (norm), 7e-7 (qkv), 8e-5 (gdn_out), 1.1e-4 (attn_out), 2.3e-3
|
||||
(moe_out), 4e-7 (logits). Those are the kernel parity tolerances. Without forcing, errors compound
|
||||
5 to 30 times and about half the top-k slots flip, so exact top-k agreement stays an F32-fixture-only
|
||||
test. Branch commits after review: e452c51, 0e5344d, 44b0619. Real-file facts the engine
|
||||
needs: the plain GGUF has no nextn block (only the `-MTP` files do, as block 40); nothing is fused;
|
||||
the router, `ssm_alpha`, `ssm_beta` are F32; down experts are IQ3_XXS in 37 layers and IQ4_XS in
|
||||
layers 34, 38, 39; the untied 2048 × 248,320 head is Q6_K.
|
||||
2. **Geometry, metadata, sizing (default model).** Per the inventory: `ModelGeometry` is a set of
|
||||
Flash-Next defaults; only `qwen4exp.expert_count`, `expert_used_count` and the rope keys are read, and
|
||||
`check_architecture` rejects anything but `qwen4exp`. So: read every field of `ModelGeometry` from
|
||||
the `qwen35moe.*` keys (hidden, layers, head counts, `ssm.*`, `n_ff`, interval); add `hc = 1` as "no
|
||||
gated residual" with a plain-residual path and the `attn_norm` / `post_attention_norm` /
|
||||
`output_norm` tensors the engine never references today; fix the one leak in the native expert path
|
||||
(`expert_layout.cpp:284` passes compile-time 2560/640 to `native_fmt`); make `--ple-gguf` optional at
|
||||
the command line (the kernels already allow no PLE); refuse llama.cpp's fused `ffn_gate_up_exps` and
|
||||
`attn_qkv` forms by name (no shipped Qwen3.6 file uses them; the oracle's fused cases document the
|
||||
layouts if one appears); the draft geometry follows the target; the draft vocab size comes from the
|
||||
pack. The per-layer prefetch hints already exist (`FileExpertSource::warm`, `MADV_WILLNEED` on
|
||||
predicted ids): verify they fire on the Qwen3.6 pack's offsets rather than porting Maya's. **The VRAM planner:** free VRAM minus the fixed set for the requested
|
||||
context; KV streaming engaged when the fixed set does not fit (`--kv-resident`); the context lowered
|
||||
toward 131,072 only after that; a refusal with numbers below it; the remainder becomes expert slots;
|
||||
then the RAM tier from free RAM minus headroom (`--resident-experts` machinery), the rest mapped
|
||||
from disk (the existing `--mmap-experts` source with its `MADV_WILLNEED` warm); `--vram-cap` and
|
||||
`--ram-cap` for emulation. This step is what makes "6 GB to 32 GB" one binary, and it is where the
|
||||
engine's tier counters (VRAM, RAM, disk reads per token) are exposed in the log and on `/health`.
|
||||
3. **Kernels and the block (default model).** In order of risk, each with a parity harness:
|
||||
- the GDN mixer: head pairing `h % h_k` already handles 32 v-heads against 16 k-heads; the gate
|
||||
changes from sigmoid(z) to SiLU(z) in four kernels (`gdn.cu`, `fused_gdn.cu`,
|
||||
`native_gdn_preprocess.cu`, the prefill GDN kernels), with the sigmoid reading as the negative test;
|
||||
- the full-attention layer as *dense* attention: the decode kernel reads KV through an index list and
|
||||
does not care how the list was built, so a "select every cell" producer replaces the indexer; the
|
||||
kernels fixed at 12 query heads per KV head (Qwen3.6 has 8) and the short-context kernel fixed at
|
||||
24 heads become parameters; the prompt path is `qsa_prompt_attn.cu` (on Pascal, the batched decode
|
||||
kernel), parameterized the same way; `native_flash_attn.cu` is a 256-cell diagnostic adapter, not a
|
||||
fallback;
|
||||
- the router at top-8 over 256 (generic already; parity at the selection boundary) and the shared
|
||||
expert at 512 (its Q8_K rule needs a multiple of 256, which 512 satisfies);
|
||||
- the block without hyper-connections: `layer.cpp` *and* `verify.cpp`, because native packs decode
|
||||
only through the verify window, and that window requires the fused hc kernels (fixed at
|
||||
2560/4/320), top-10 and the native indexer today;
|
||||
- prefill: `Prefill::init` refuses anything but 2560/4/320/10 and its GDN, split-q, route and MoE
|
||||
kernels carry literals (48 v-heads, 24 heads, 1280, 640, top-10); parameterize or fork them.
|
||||
Then the layer composition test: one GDN+MoE and one attention+MoE layer against the oracle's dumps.
|
||||
The canonical Q2_0 CPU expert kernel bakes Flash-Next's shapes; Qwen3.6 rides the native pack path
|
||||
(per-layer runtime geometry, ggml dot products, Unsloth's Q4_K/Q5_K types already included), as the
|
||||
Coder with its 256 experts per layer does.
|
||||
4. **Pack and runner.** `iq_pack.py` taught `qwen35moe` and its BF16-preserve list; the MTP head: the
|
||||
engine's drafter reads its own Q8_0 directory with vLLM-style names, canonical Q2_0 experts at
|
||||
2560/640 and the default geometry, and Qwen3.6's single `nextn.eh_proj` over the concatenated
|
||||
embedding and hidden state does not match the two separate projections it expects, so the drafter
|
||||
needs a Qwen3.6 pack format and a small graph change (Maya's `mtp_gguf.py` is the model);
|
||||
`make_profile.py` (hardcoded 48 × 512 today) from the E0 trace;
|
||||
the streaming runner held to the oracle at every position of a short sequence; then the real Q4 file
|
||||
end to end, greedy, compared with llama.cpp's output distribution (not token-for-token; the README's
|
||||
known-problems entry says why).
|
||||
5. **Serve and measure on the 1080 Ti at 11 GB, then capped to 8 and 6; the 12, 16, 24 and 32 rungs when a card frees up.** CPU lane and PCIe
|
||||
share calibrated as Maya's `--calibrate` does, against this engine's own session; the Phase 0
|
||||
harness and instruments; the engine's points onto `ladder-baseline.png`. The H5 measurement. The
|
||||
front end's `make test-chat-parser MODEL=<gguf>` against Qwen3.6's template (the homelab services
|
||||
use a patched `qwen3.6-enhanced.jinja`); the Qwen3-Coder any-argument-order patch checked for
|
||||
misfires on this model's tool-call grammar.
|
||||
6. **The other Pascal cards and the fat binary.** The sm_61 build has been the working build since step
|
||||
1; this step makes `STRATA_EXPERIMENTAL_SM60=ON` the default for the fat binary
|
||||
(`CUDA_ARCHS=61;70;75;86;89;120`, CUDA 12.8) and runs the 1070 Ti and the 1060 against B1b. The
|
||||
sm_75+ paths (tensor-core prompt attention, thread-block clusters) stay compiled in for the cards that
|
||||
have them and are checked on the 4090 or A6000 when one is free.
|
||||
7. **README/UPSTREAM.** The supported model and its checksums, the ladder table with the engine against
|
||||
the baseline, the sizing rule in words, the Pascal caveats (CUDA 12.x, FP32 paths, no Nsight Compute).
|
||||
|
||||
**The base is this repository's `src/` and `include/`: Strata at `6f32ec0`, engine 0.1.39.** Maya's engine
|
||||
is not merged, cherry-picked or vendored: it forked from Strata around engine 0.1.27 and has rewritten the
|
||||
expert tiers, the mixers and the server since, so its C++ does not apply to this tree without a port of its
|
||||
own. Taken from Maya (MIT, by reference to a pinned commit): the method and the Python-side tooling; the
|
||||
list of places Strata's geometry was hardcoded, each re-found and fixed here; the route-log format,
|
||||
`glm_tier_replay.py` and `glm_expert_prior.py` adapted as standalone scripts; the VRAM cap and the
|
||||
CPU-lane calibration as *designs*, implemented against this engine. Left out: the Python installer, the
|
||||
dashboard, the Anthropic API, all multi-GPU work. One binary, no Python at run time, no network, one GPU.
|
||||
|
||||
## 6. Acceptance
|
||||
|
||||
Per budget, at the default quant, the engine must meet:
|
||||
|
||||
| Criterion | Threshold | Basis |
|
||||
| --- | --- | --- |
|
||||
| A1 context | 262,144 on 11 GB and up; 131,072 on 8 GB; on 6 GB whichever the sizing rule picks, stated at start | the stated goal and floor |
|
||||
| A2 decode | beats the baseline's fit-edge decode on the same rung; absolute floors ≥ 15 tok/s at 8K depth and ≥ 10 at 32K on 11 GB, ≥ 10 / 7 on 6 GB, ≥ 60 / 45 on 24 GB | the 1060 did 16/11 at IQ3 under llama.cpp; the 4090 did 100+ |
|
||||
| A3 prefill | ≥ 300 tok/s on Pascal, ≥ 2,000 on Ada | the 1060 did 355 |
|
||||
| A4 stability | 7 consecutive requests, no OOM, ≥ 100 MiB VRAM headroom | g7's "+78 MiB per request" |
|
||||
| A5 serving | chat, streaming, reasoning, tool calls and images through the front end, pi writing and running a program through it, on the 1060, the 1080 Ti and the 4090 with no flags but the model | the README's existing status bar |
|
||||
|
||||
If A2's "beats the baseline" fails on a rung after the cache tuning of step 5, the README reports the
|
||||
rung's numbers against the baseline as they are. The engine still ships for that rung; the comparison is
|
||||
the honest part of the result, not a gate.
|
||||
|
||||
## 7. Agents: who does what, and how cheaply
|
||||
|
||||
Rules:
|
||||
|
||||
- `ark` is human-only. If a phase should run under ark, the plan says so and the user starts it.
|
||||
- One fresh agent per phase boundary, briefed with this file, the phase section, the hosts, the run
|
||||
directory, and the previous phase's write-up (not its transcript).
|
||||
- Fork (same context) only to continue an in-progress phase after a wakeup.
|
||||
- Nothing an agent runs changes Proxmox state. Agents do not touch the live `.4` service except by
|
||||
starting a second server on another port with the production unit stopped, and restoring it.
|
||||
- Unattended sweeps: a file-based driver under tmux, polled on a `/loop` or wakeup every 15 to 30
|
||||
minutes, `DRIVER_DONE` markers.
|
||||
|
||||
Tiering:
|
||||
|
||||
| Work | Model | Why |
|
||||
| --- | --- | --- |
|
||||
| `-lv 4` logs to CSV; `dmon.csv` parsing; nsys/nvprof export to busy-fraction and gap histograms; checksums; marker checks; replay runs at given slot counts; B1b single points on a card with a ready script | **haiku** | mechanical, re-runnable |
|
||||
| Env specs, drivers, plots; llama.cpp builds per arch; the eval-callback route-dump patch; the replay adaptation; the oracle and synthetic fixture (Phase 2 step 1) | **sonnet** | code with a known shape and an example to copy |
|
||||
| The Phase 1 write-up; geometry, the VRAM planner, kernels, pack, runner, the Pascal build (Phase 2 steps 2 to 7); diff review before the user ships | **default (Fable)** | judgment and engine code |
|
||||
| Independent review of the Phase 1 write-up and of each parity harness before it is trusted | fresh **default** agent, given data but not the conclusion | an agent handed a hypothesis tends to confirm it |
|
||||
|
||||
Safe parallelism: the 1080 Ti sweep, the B1b points on the other cards, E0 on the Mac, and Phase 2 steps
|
||||
1 to 4 on the A6000 are independent of each other. If the user wants a multi-agent fan-out for Phase 2,
|
||||
they say "use a workflow".
|
||||
|
||||
## 8. Order of work and checkpoints
|
||||
|
||||
1. User: VM 220 decision; the 1080 Ti VM; GGUFs copied to every rung.
|
||||
2. Agent (sonnet): `llama-server` builds per arch, profiler check, smoke test → `phase0-notes.md`.
|
||||
**Checkpoint: the first `-lv 4` table on the 1080 Ti; Section 2's estimates replaced.**
|
||||
3. Agent (sonnet, then haiku): E0 → `phase0-replay.md` and the expert profile. **Checkpoint: the hit-rate
|
||||
curve with the seven budgets marked.** In parallel, Phase 2 step 1 on the Mac.
|
||||
4. Agents: B1 on the 1080 Ti; B1b on the 1060, 1070 Ti, 4090 and capped A6000; B3. **Checkpoint: the
|
||||
baseline ladder row.** In parallel, Phase 2 steps 2 to 4 on the A6000.
|
||||
5. Agent (default): plots and the baseline write-up; separate reviewer. **Checkpoint: the number to beat
|
||||
on every rung.**
|
||||
6. Agent (default): Phase 2 step 5 across the capped budgets. **Checkpoint: the engine's points on the
|
||||
ladder plot against the baseline, and pi served through the front end on the 4090.**
|
||||
7. Agent (default): step 6 on the three Pascal cards. **Checkpoint: `unbiased-strata --model <gguf>`
|
||||
serving pi on the 1060 and the 1080 Ti with no flags but the model; A1 to A5 on every rung.**
|
||||
8. Step 7, the README. B2 and B4 whenever a card is idle.
|
||||
|
||||
Measurements land in `~/Code/regina/analysis/qwen36-35b-single-gpu-ladder/`, infra notes in
|
||||
`~/homelab/investigations/<date>-vm-1080ti-qwen36.md` with a LOG.md entry, the model-support outcome and
|
||||
the ladder table in this repo's README, and the port study in `docs/QWEN36-35B-A3B.md`. Tickets: one
|
||||
`homelab` for the VM, one `regina` for the harness, one `UnbiasedStrata`-prefixed ticket per Phase 2
|
||||
step, filed when the work starts.
|
||||
@@ -0,0 +1,594 @@
|
||||
# Running Qwen3.6-35B-A3B on UnbiasedStrata - the study
|
||||
|
||||
What it takes for Qwen3.6-35B-A3B (llama.cpp architecture `qwen35moe`) to run on this tree's Strata
|
||||
engine, component by component, with the numbers the decision needs. Written 2026-10-11 against engine
|
||||
0.1.39 (`CMakeLists.txt:11`, the `6f32ec0` snapshot; tree `8634357`). It is the Phase 2 design document
|
||||
of `docs/PLAN-qwen36-35b-a3b.md` and the counterpart of Project Maya's `docs/GLM5-FLASH.md`, whose shape
|
||||
it copies. Every `file:line` is this tree; "row N" is `docs/qwen36-port/geometry-inventory.md`; the model
|
||||
facts come from `docs/qwen36-port/gguf-metadata.md` and `ref/qwen36.py` on branch `qwen36-oracle`; the
|
||||
measurements from regina's `phase0-notes.md` and `replay/phase0-replay.md`.
|
||||
|
||||
Strata is a native implementation of one architecture, Qwen3.8-Flash-Next (`qwen4exp`), with its memory
|
||||
tiers and its speculation stack built around that shape. Qwen3.6-35B-A3B is the same family one generation
|
||||
earlier with three things removed (the hyper-connection residual, the sparse-attention indexer, the PLE
|
||||
table) and one numerical change in the GDN gate. The kernel gap is small. The plumbing gap is not: the
|
||||
removed pieces are assumed structurally in every block, in the verify window that is the only decode path
|
||||
for native packs, in the drafter and in prefill, and `ModelGeometry` is never populated from the model file.
|
||||
|
||||
---
|
||||
|
||||
## 1. The model, exactly
|
||||
|
||||
From the shipped GGUFs (`gguf-metadata.md`, dumped with `tools/gguf_reader.py`; sizes and SHA-256s in
|
||||
`phase0-notes.md`):
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| Architecture | `general.architecture = qwen35moe`; `block_count` 40 (41 in the MTP files); `embedding_length` 2048; `context_length` 262,144 |
|
||||
| Layer pattern | `full_attention_interval` 4: layer `il` is recurrent unless `(il+1) % 4 == 0`, so attention at 3, 7, ..., 39 (10 layers), GDN at the other 30 |
|
||||
| GDN | `ssm.conv_kernel` 4, `ssm.state_size` 128, `ssm.group_count` 16 (k-heads), `ssm.time_step_rank` 32 (v-heads), `ssm.inner_size` 4096; conv channels 8192 = 2x2048 + 4096. Output gate `rms_norm(o) * ssm_norm * SiLU(z)` (`qwen35moe.cpp:267-276`) |
|
||||
| Full attention | 16 heads, 2 KV heads, `key_length`/`value_length` 256, `rope.dimension_count` 64 (0.25 of 256), `rope.dimension_sections` [11, 11, 10, 0], `freq_base` 1e7, eps 1e-6; `attn_q` is 2x wide (query then gate per head, interleaved); output `* sigmoid(gate)`. **Dense**: no indexer |
|
||||
| MoE | 256 experts, top-8, `expert_feed_forward_length` 512, shared expert 512 with a 1-D `ffn_gate_inp_shexp` scalar gate. Softmax over all 256, top-8 weights renormalised to sum 1 (`norm_w = true` hard-coded, `qwen35moe.cpp:506`); no `expert_weights_scale` (never loaded for this architecture) |
|
||||
| Residual | plain: `attn_norm`, `post_attention_norm`, `output_norm`, all multiplicative RMS weights (no "+1") |
|
||||
| MTP | `nextn_predict_layers` **absent in the plain file, 1 in the MTP files**; `blk.40` holds one attention + MoE block plus `nextn.eh_proj` [4096, 2048] over `concat(enorm(emb), hnorm(h))`, `nextn.enorm`, `nextn.hnorm`, `nextn.shared_head_norm`; no `embed_tokens`, no `shared_head_head` (the draft head is the main `output.weight`) |
|
||||
| Vocabulary | 248,320 tokens, `pre = qwen35`, BOS/EOS/PAD 248044/248046/248055; the same tokenizer the engine's `--eos-ids` default already names (row 152) |
|
||||
| Float tensors | the router `ffn_gate_inp`, `ssm_alpha`, `ssm_beta`, the shexp gate and every norm are **F32** in the plain file; the nextn block's router and shexp gate are BF16 |
|
||||
| Mixed quantization | per layer and per role: IQ3_XXS file has IQ2_S gate/up everywhere, IQ3_XXS down on 37 layers and IQ4_XS on 3 (34, 38, 39); the nextn block in the MTP files is Q3_K/Q4_K experts with Q8_0 projections |
|
||||
| Fused forms | none shipped: gate and up are separate `ffn_gate_exps`/`ffn_up_exps`, attention layers carry separate `attn_q`/`attn_k`/`attn_v`; `attn_qkv` exists only in the 30 GDN layers (the conv input) |
|
||||
|
||||
The byte census of the three files on hand (gguf-py over the headers, 2026-10-11; `blk.40` separated):
|
||||
|
||||
| File | Non-expert on the GPU (`output` + projections + norms) | `token_embd` | Trunk experts (40 x 256) | Per expert mean / max | `blk.40` dense / experts |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: |
|
||||
| `UD-Q4_K_XL` (MTP repo, rev 5bc3e238, 21,784 MiB) | **2,038 MiB** (Q8_0 1,939 + F32 100) | 515 MiB Q8_0 | **18,726 MiB** (Q4_K 11,232, Q5_K 6,864, Q6_K 630) | 1.829 / 2.195 MiB (layer 39) | 40 / 464 MiB |
|
||||
| `UD-IQ3_XXS` (12,589 MiB) | **1,597 MiB** (Q6_K 1,497 + F32 100) | 398 MiB Q6_K | **10,594 MiB** (IQ2_S 6,560, IQ3_XXS 3,626, IQ4_XS 408) | 1.035 / 1.172 MiB | none |
|
||||
| `UD-IQ4_XS-MTP` (17,355 MiB) | 2,038 MiB | 515 MiB | 14,514 MiB | 1.417 / 1.883 MiB | 40 / 364 MiB |
|
||||
|
||||
The two non-expert figures are what llama.cpp's `-lv 4` reported on the 1080 Ti once the GPU-resident
|
||||
expert layers are subtracted: Q4 `CUDA0 model` 5,917 MiB minus layers 32 to 39 (3,878 MiB) = 2,039; IQ3
|
||||
7,475 minus layers 18 to 39 (5,878) = 1,597 (`phase0-notes.md`, smoke table). The token embedding stays in
|
||||
host memory in both llama.cpp and this engine (`generate.cpp:2190`, "token embedding in mapped host
|
||||
memory"), so it is not in the fixed set. The plan's Section 2 estimated ~3.1 GB for this item; the real
|
||||
figure is 2.0 GiB.
|
||||
|
||||
## 2. What the engine already is
|
||||
|
||||
The implemented geometry is a struct of Flash-Next defaults (`include/strata/core/layout.hpp:27-59`):
|
||||
n_embd 2560, 48 layers, full attention every 4th, GDN 16 k-heads / 48 v-heads / state 128 / conv 4 with
|
||||
conv channels 10240 and value dim 6144 stored as members (row 2), QSA 24 heads / 2 KV heads / 256 with a
|
||||
4-head 128-wide indexer, hyper-connections `hc` 4 with a 320-wide bottleneck, 512 experts x top-10 x 640.
|
||||
`is_qsa_layer` is `layer % 4 == 3` (`layout.hpp:63`). Per layer (`src/core/layer.cpp:1170-1286`,
|
||||
`1319-1342`):
|
||||
|
||||
gr_read(attn) -> GDN | QSA -> gr_write(attn) -> gr_read(ffn) -> moe_route [doorbell] ... moe_finish -> gr_write(ffn)
|
||||
|
||||
The unit is a captured per-layer CUDA graph replayed by a host loop (`include/strata/core/session.hpp:1-15`)
|
||||
that rings a doorbell at the router so a CPU expert pool starts on the misses while the GPU continues.
|
||||
Experts live in three tiers: a VRAM cache of slots filled by a profile and swapped by decayed usage
|
||||
(`include/strata/core/expert_cache.hpp`), a RAM tier (pinned arena, or `--resident-experts` /
|
||||
`--resident-budget-gib` keeping the complement of the VRAM cache in a compact copy,
|
||||
`generate.cpp:1506-1520`, `expert_source.cpp:1331`), and the model file mapped from disk
|
||||
(`--mmap-experts`, `expert_source.cpp:618-680`) with a `MADV_WILLNEED` warm hint per role on predicted
|
||||
ids (`expert_source.cpp:1129-1160`, called at `1264`). Decode for a *native* pack (experts served from the
|
||||
GGUF in their own ggml types, `include/strata/kernels/cpu/native_expert.hpp`) runs only through the verify
|
||||
window (`expert_source.cpp:1869-1875`, row 114): windows of up to `kVerifyMaxT = 8` rows
|
||||
(`verify_kernels.hpp:21`) drafted by the model's own MTP layer, a separate Q8_0 pack in VRAM
|
||||
(`src/core/mtp.cpp:150-216`, `mtp.hpp:1-20`), plus a prompt-lookup drafter (`generate.cpp:522-524`).
|
||||
Prompts go through a chunked prefill with the experts streamed over PCIe through a ring that borrows
|
||||
cache slots (`generate.cpp:2723`, `4404-4425`; `docs/upstream/DETAILS.md`, "How it works"). The front
|
||||
end (`frontend/`) is model-agnostic: OpenAI API, llama.cpp's chat parser (`frontend/chat_parser_test.cpp`),
|
||||
vision through `mtmd` (`frontend/vision.hpp:4-87`), and it refuses `--gpus` (`frontend/main.cpp:558`).
|
||||
|
||||
## 3. Component-by-component gap analysis
|
||||
|
||||
### 3.1 Applies unchanged
|
||||
|
||||
| Piece | Why |
|
||||
| --- | --- |
|
||||
| Layer pattern | `is_qsa_layer` (`layout.hpp:63`) gives 3, 7, ..., 39 for 40 layers; `n_qsa_layers() = 40/4 = 10` (row 55). Every per-layer loop in `session.cpp` uses `g.n_layers` (row 27). |
|
||||
| GDN decode kernels | State 128, head pairing `head % h_k` (`native_gdn.cu:51`, `fused_gdn.cu:29`), grids from `h_v`, `h_v % h_k == 0` checked (`native_gdn.cu:99-101`, `fused_gdn.cu:148-153`); 32 % 16 = 0. The conv (`d_conv == 4 && state 128`, `layer.cpp:247-248`) matches. |
|
||||
| Router | `router_top10` is a generic softmax top-k over runtime `n_expert <= 512`, `k <= 32` (`router_top10.hpp:21`, row 124); `moe_route` takes it whenever the pack is not 512/10 (`layer.cpp:370`). Semantics equal llama.cpp's: softmax over all, stable descending argsort, renormalise with the 2^-14 clamp (`router_top10.hpp:3-5`; `oracle-crosscheck.md`, "Router and experts"). |
|
||||
| Shared expert | Shape-driven (`layer.cpp:418-451`); its Q8_K activation rule needs `n_ff % 256 == 0` (`shared_expert.cu:237-239`), which 640 failed and 512 satisfies (row 127). |
|
||||
| Native expert kernels | CPU: `native_fmt` is ggml-cpu trait-driven, whole-block checks only (`native_expert.cpp:40-60`); 2048 and 512 are multiples of 256. `kNativeActBytes` 4096 / `kNativeHBytes` 1024 hold a 2048-wide Q8_K (2,336 B) and a 512-wide one (584 B) (row 111). GPU: `iq_kernels.cu:1076-1140` read `L.n_embd`/`L.n_ff` per layer; Q4_K/Q5_K gate-up and Q5_1/Q8_0 down are already present (row 120); the IQ2_S/IQ3_XXS/IQ4_XS/Q6_K of the shipped files are ggml types ggml-cpu has `vec_dot` for. |
|
||||
| Expert cache and tiers | Residency `[n_layers x n_expert]`, slots, the profile header checked against `(n_layers, n_expert)` (`expert_cache.cpp:43`); the file source, the complement copy, the warm hint; all parameterised at runtime (rows 118, 109). |
|
||||
| KV formats and streaming machinery | fp16 / int8 / q4_0 / K8V4 pools at `head_dim 256` (`kv_q4.cu:176`, row 103); paged pools, `--kv-resident`, the resident floor 20,480 cells (`layer.cpp:556`). The *use* of streaming changes (section 4.2). |
|
||||
| RoPE | `n_rot 64`, `head_dim 256` (`native_rope.cu:121`), interleaved M-RoPE sections 11/11/10/0 with `t = h = w` for text (`mrope.hpp:3-12`); the oracle pins the same pairs `(p, p+32)` (`oracle-crosscheck.md`, "Full attention"). |
|
||||
| Vocabulary, sampler, head | `n_vocab` is a kernel argument, merge handles <= 262,144 (`sampler.cu:607`); the native head takes `[n_in, n_out]` with `n_in % 256 == 0` (`native_head.cpp:21`); the drafter reads `n_vocab_ = output.weight.ne1` (`mtp.cpp:430`). |
|
||||
| Speculation protocol | Verify windows, draft policy, prompt lookup; the drafter's *weights* change (3.10). |
|
||||
| Front end | Tokenizer, template, tool-call parser, vision (row 154). |
|
||||
| MTP drafter's attention | Already dense over every cell (`mtp.hpp:16-18`, row 76): the one dense-attention path in the tree. |
|
||||
|
||||
### 3.2 GDN: head pairing, SiLU gate, four kernels (small)
|
||||
|
||||
The geometry changes are runtime except two stored members, `ssm_conv_channels` and `ssm_value_dim`,
|
||||
which must become 8192 and 4096 (row 2; `session.cpp:41-44` derives the state size from them). The one
|
||||
numerical change: the output gate is `sigmoid(z)` in the engine and `SiLU(z)` in Qwen3.6 (row 39;
|
||||
`layer.hpp:16` records the difference). Four kernels carry it:
|
||||
|
||||
| Kernel | Line | Path |
|
||||
| --- | --- | --- |
|
||||
| `gdn_out_norm` | `src/kernels/cuda/gdn.cu:148` | legacy decode |
|
||||
| `gdn_step_norm_kernel` | `src/kernels/cuda/fused_gdn.cu:69` (`1/(1+__expf(-zz))`) | the default native decode, inside the fused step |
|
||||
| out-norm kernel | `src/kernels/cuda/native_gdn_preprocess.cu:110-112` | native unfused |
|
||||
| `gdn_rec_kernel`, `gdn_out_norm_kernel` | `src/prefill/kernels.cu:324, 612` (`sigm(z)`) | prompt |
|
||||
|
||||
The oracle's negative control shows the sigmoid reading moves the layer output by 1.07 relative L1 and the
|
||||
logits by 0.92 (`oracle-crosscheck.md`, negative controls), so the trap is far above the 5% gate.
|
||||
`src/kernels/gdn_parity.cpp:104` pins `h_v = 48` and its reference `sigmoid_f` (`:42`); both are re-pinned
|
||||
at 32 v-heads with SiLU, the sigmoid reading becoming the negative case. The prompt GDN kernels are
|
||||
specialised on `VPK = HV / HK = 3` value heads per key head (`prefill/kernels.cu:478`) and launched on the
|
||||
`HV`/`HK`/`C` constants (`kernels.cu:18-19`, rows 89 to 91); they are the prefill item in 3.6.
|
||||
|
||||
### 3.3 Dense attention replacing QSA (the largest kernel item, and a memory item)
|
||||
|
||||
The decode kernel gathers K/V through `ids` and a page table and does not care how `ids` was built
|
||||
(`qsa_decode_attn.cu:100-120`, row 102). So dense attention is a "select every cell" producer feeding the
|
||||
existing kernel. What stands in the way:
|
||||
|
||||
1. **The producer.** `qsa_layer` runs the indexer unconditionally: the raw key projection (`layer.cpp:945`),
|
||||
the append (`:962-964`), the block scores and top-k (`:966-975`), with `indexer.{k,q}_proj.weight` and
|
||||
`indexer.{k,q}_norm.weight` dereferenced as required tensors (`:891-897`, row 45). The verify window
|
||||
does the same per row (`verify.cpp:757-761`, `772-870`, row 145). A dense path skips those steps and
|
||||
writes `ids = 0..n_kv-1` from `st.step`; the selection width `qsa_selection_width(n_kv, s) =
|
||||
min(n_kv, 2051)` (`qsa.hpp:144-147`) and the capacity `cap = qsa_selection_width(kTopkMaxCells, s)`
|
||||
(`layer.cpp:876`, `verify.cpp:352`, `prefill.cpp:865`) become `n_kv` and `max_cells`.
|
||||
2. **The 12-versus-8 literal.** `G = 12` query heads per KV head, refused with `exit(1)` unless
|
||||
`n_head == 12 * n_head_kv` (`qsa_decode_attn.cu:17, 453, 497`; `qsa_prompt_attn.cu:22, 1447`; row 93, 94).
|
||||
Qwen3.6 is 8. `G` becomes a template parameter instantiated at 8 and 12.
|
||||
3. **The 24-head short-context kernel.** `native_flash_attn.cu:196-206` refuses anything but 24/2/256 and
|
||||
contexts above 256; it is a diagnostic adapter (`layer.hpp:53`, "context <= 256") and is not on the
|
||||
prompt path. It stays as it is.
|
||||
4. **State without the indexer.** `qsa_state_bytes` carves `idx_tail`, `idx_dead`, `idx_pooled` with
|
||||
`pooled_rows = max_cells/4 + 2` (`layer.cpp:559-575`, row 43): at 262,144 cells that is 65,538 x 128 x
|
||||
4 B = 32 MiB per attention layer, 320 MiB over ten, all dead. The drafter's ring already passes a state
|
||||
"which has no indexer" with `pooled_rows = 2` (`layer.cpp:527-531`); the dense state takes the same.
|
||||
5. **The split-K scratch scales with the context.** `qsa_decode_attn_scratch_floats(cap, s) = (cap/64) x
|
||||
n_head x 258 + 64` (`qsa_decode_attn.cu:489-491`). Today `cap` is 2,051; with `cap = 262,144` and 16
|
||||
heads it is 64.5 MiB *per query row*: 516 MiB for the 8-row verify window (`verify.cpp:422`) and
|
||||
`attn_batch` times that in prefill (`prefill.cpp:888`). The dense kernel needs either a larger chunk
|
||||
per block or an online-softmax merge that does not keep a partial per 64-cell chunk.
|
||||
6. **KV streaming no longer saves VRAM.** Streaming keeps the authoritative K/V in host memory and resolves
|
||||
the *selected* blocks into VRAM slots before the read (`layer.hpp:230-236`, `qsa_kv_resolve` at
|
||||
`layer.cpp:976`). With every cell selected every token, every block must be resident every token: the
|
||||
mechanism degenerates to copying the whole KV (1,440 MiB at q4_0) over PCIe per token. Section 4.2
|
||||
and section 8 draw the consequence for the plan's sizing rule.
|
||||
|
||||
KV formats, the Hadamard-rotated q4_0 pool, the page table and the RoPE tables carry over unchanged
|
||||
(`layer.cpp:938-1010`, row 46). The prompt attention has three device paths: cp.async + mma on sm_80+,
|
||||
mma on Turing, an m8n8k4 kernel on Volta, and for `cc < 70` the host returns false
|
||||
(`qsa_prompt_attn.cu:1433`) so prefill falls back to the batched decode kernel
|
||||
(`prefill.cpp:2222-2228`). On Pascal that fallback is the prompt attention; it needs `G = 8` and the
|
||||
scratch fix above, nothing else.
|
||||
|
||||
### 3.4 Router and shared expert (small; one measured-not-asserted parity)
|
||||
|
||||
Both are generic already (3.1). Two form questions remain. The router kernel reads a BF16 weight
|
||||
(`layer.cpp:361-366`, `project_bf16`), `fused_gdn_ab` reads BF16 `ssm_alpha`/`ssm_beta`
|
||||
(`layer.cpp:285-287`), and `moe_shared` refuses a `ffn_gate_inp_shexp` that is not engine form BF16
|
||||
(`layer.cpp:427-437`). All four are F32 in the shipped file (`gguf-metadata.md`, "What was unexpected").
|
||||
The pack rounds them: exactly when the low 16 bits are zero, else only under `--compat-bf16`
|
||||
(`upstream-tooling.md` section 4, the ORCA precedent). That is a numerical change against llama.cpp, which
|
||||
multiplies in F32, and it lands on the one place where rounding is not a rounding error: a flipped top-8
|
||||
selection is a different expert (`layer.hpp:131-139`). The oracle's real-file smoke already shows the
|
||||
F32-versus-quantized router disagreeing on 6 of 32 (token, slot) choices in layer 0 and 12 to 23 in layers
|
||||
30 to 39 (`oracle-crosscheck.md`, "Not covered"), so the harness measures a flip rate at the
|
||||
`logits -> top-8` boundary with the quantized-mode gates Maya calibrated (selection equal at probed layers
|
||||
on an F32 fixture; a bounded rate on the real file), not bitwise equality. `router_top10_parity.cpp`'s tie
|
||||
fixtures (all-equal logits, a 12-way tie, the unreachable clamp) carry over at 256/8.
|
||||
|
||||
### 3.5 The block without hyper-connections: `layer.cpp` *and* `verify.cpp` (the largest plumbing item)
|
||||
|
||||
`hc` sizes the residual `R` (hc, n_embd), `inject`, `gr_rs` and the GR workspace (`layer.cpp:1127-1145`),
|
||||
and every block reads four `hc_attn_*` and four `hc_ffn_*` tensors with required forms
|
||||
(`layer.cpp:1231-1255`, row 22). No `hc = 1` meaning exists (row 4): the GR math on one stream is not a
|
||||
plain residual, and the names Qwen3.6 ships (`attn_norm`, `post_attention_norm`, `output_norm`) are
|
||||
referenced nowhere in `src/` (rows 22, 23). The plain block is
|
||||
|
||||
x = rms_norm(R, attn_norm) -> mixer -> R += out
|
||||
x = rms_norm(R, post_attention_norm) -> MoE -> R += out head: rms_norm(R, output_norm) -> output.weight
|
||||
|
||||
(`qwen35moe.cpp` layer loop; the oracle's `attn_norm-N`, `attn_residual-N`, `attn_post_norm-N`, `l_out-N`,
|
||||
`result_norm` seams). The weighted RMS norm kernel exists (`native_qsa_rms_norm_weighted`, used at
|
||||
`layer.cpp:879` and `mtp.cpp:488`). The places that must grow the plain path:
|
||||
|
||||
| Site | What assumes hc |
|
||||
| --- | --- |
|
||||
| `layer.cpp:1170-1286` `block_layer_pre`, `1319-1342` `block_layer_post` | the two GR halves, the fused-GR fast path (`fused = g_fused_gr && fused_gr_supported(2560, 4, 320)`, `:1195`; `fused_gr.cu:1164-1166`), `pending_ffn` folding |
|
||||
| `layer.cpp:1088-1107` `lm_head_mix` | `output_hc_{norm,down,up}` |
|
||||
| `session.cpp:141-148` | first token = `hc` copies of the embedding (one copy at hc = 1, row 26) |
|
||||
| `verify.cpp:331-340` | refuses unless `fused_gr_supported && ss.k == 10 && state 128 && d_conv 4` and `layer_verify_compatible` demands the fused GR and the native indexer (`layer.cpp:476-486`, row 141) |
|
||||
| `verify.cpp:356-434` | `R_`, `xn_` as `T*HC*N`, `inj_`, `lo_ (T*hc_lr)`, `idx_raw_L_`, `qidx_`, `tail_snap_` |
|
||||
| `verify.cpp:1123-1125` | the head mix |
|
||||
| `verify_kernels.cu:256-291` | `broadcast_streams` / `add_streams_broadcast` (runtime `hc`, row 140) |
|
||||
| `mtp.cpp:503-507, 564-568, 613-625`; `prefill.cpp:972-1086` | the drafter's three hc groups (3.10) |
|
||||
|
||||
Because native packs decode only in verify windows (row 114) and the window refuses a layer without fused
|
||||
GR and the indexer (row 141, 142), the plain block has to land in `verify.cpp` for a single token to come
|
||||
out. The verify window's `ss.k == 10` refusal becomes `k == 8` from the file. `cvec` (the control-vector
|
||||
apply over `hc*n_embd`, row 140) is runtime-shaped and needs no change.
|
||||
|
||||
### 3.6 Prefill (the most literal-heavy subsystem)
|
||||
|
||||
`Prefill::init` refuses unless `n_embd == 2560 && hc == 4 && hc_lr == 320 && k == 10`
|
||||
(`prefill.cpp:737`, row 132); the file-wide constants are `N 2560, HC 4, D, LR 320, K 10, NE 512, C 10240,
|
||||
ZV 6144, HV 48` (`prefill.cpp:90-91`) and `N, HC, D, LR, S, HK 16, HV 48, C 10240` in the kernels
|
||||
(`prefill/kernels.cu:18-19`). The literals, each with its Qwen3.6 value:
|
||||
|
||||
| Site | Literal | Qwen3.6 |
|
||||
| --- | --- | --- |
|
||||
| `prefill.cpp:649-650, 883-884` | `Qf` as `T * 12288` (24 x 512), `q`/`attn` as `T * ZV`; `idx_raw`, `q_idx` | 8,192 (16 x 512), 4,096; the two indexer buffers dead |
|
||||
| `prefill.cpp:681-685, 704-721, 896-907` | MoE buffers `T*K*1280`, `T*K*640`, `1280 * 2560`, `2560 * 640`; `mmq::fits(gt, 1280)`, `matrix_bytes(dt, N, 640)` | `2*n_ff` 1024, `n_ff` 512, `n_embd` 2048 |
|
||||
| `prefill.cpp:854-856, 1000-1026, 1375-1380` | `grs`, `gated`, `inj`, `xq`, `ident` from `HC`, `D`, `LR` | removed with hc |
|
||||
| `prefill/kernels.cu:211-215, 285-304, 345-364, 387-432, 478-570, 893-924` | GDN kernels indexed on `HV`, `HK`, `C`, launched `<<<HV, ...>>>`; `VPK = 3` (`:478`) | 32, 16, 8192; `VPK = 2` |
|
||||
| `prefill/kernels.cu:616-657` | `route_kernel<REG>`: `REG 8` exists for 256 experts but the rank loop and `ids[t*10 + rank]`, `lane < 10` bake top-10 | `k` as a parameter |
|
||||
| `prefill/kernels.cu:752-761` | `split_q_kernel`, `gate_attn_kernel` over `T * 24 * 256` and `h * 512` | 16 heads |
|
||||
| `prefill/moe_fused_iq.cu:59` | `GU_ROWS_K = 2560, D_ROWS_K = 640` (the native-pack fused prompt MoE) | 2048, 512 |
|
||||
| `prefill.cpp:1724` loop, `1303` `RP = 48` | layers from `g.n_layers` (fine, row 134); `RP` | check |
|
||||
|
||||
The GDN kernels are forked per geometry (template on `HV, HK, C`) rather than made runtime, because their
|
||||
shared-memory staging (`sq[2][TB][S]`, `kernels.cu:482-484`) is sized from them. `src/prefill/gdn_rec_parity.cu`
|
||||
mirrors the constants (row 91) and is re-pinned with them. The chunked-versus-single-token equivalence (a
|
||||
prefix through prefill then decoded must agree with token-by-token decode) is the harness that already
|
||||
exists for this path (`tests/cuda/prefill_*_test.cpp`, restored in `c00942d`).
|
||||
|
||||
### 3.7 The native pack path (one leak, otherwise runtime)
|
||||
|
||||
The canonical Q2_0 CPU expert kernel bakes `H 2560, FF 640, NE 512, BLOB 1,382,400`
|
||||
(`include/strata/kernels/cpu/expert.hpp:34-47`, row 107) and `expert_pool_dispatch` refuses any other
|
||||
width (`expert_source.cpp:1863-1868`); Qwen3.6 does not go through it. It rides the native path, as the
|
||||
Coder (256 of 512 experts) does. The path is runtime per layer (`NativeFmt` with `n_embd`, `n_ff`, gate/up
|
||||
and down ggml types, `native_expert.hpp:22-31`) with one leak: `expert_layout_load` builds every layer's
|
||||
format with the compile-time `H, FF` (`src/kernels/cpu/expert_layout.cpp:284`, `native_fmt(gt, dt, H, FF,
|
||||
f, err)`) and then checks `f.bytes == blob`, so a 2048/512 pack fails the "blob is X B but its formats make
|
||||
Y" check (row 108). The fix is the loader taking `n_embd`/`n_ff` from the geometry the caller resolved,
|
||||
which means the call at `generate.cpp:2008-2010` (today `g0.n_layers, g0.n_expert` from a default struct,
|
||||
row 10) must run after the metadata read of 3.8, not before it.
|
||||
|
||||
`native_experts.txt` already carries a type per layer and per role (gate/up share one, down may differ,
|
||||
`upstream-tooling.md` section 4; v3 header `(n_expert N)`, `expert_layout.cpp:271`), so the IQ3_XXS file's
|
||||
37/3 down split and the Q4_K_XL's Q6_K layers need no format change. The engine reads experts as three
|
||||
separate `ffn_{gate,up,down}_exps` tensors (`expert_source.cpp:2475-2500`, row 116); the shipped files are
|
||||
separate, and a fused `ffn_gate_up_exps` is refused by name rather than split (section 8, item 5).
|
||||
|
||||
### 3.8 Metadata and `ModelGeometry`
|
||||
|
||||
`check_architecture` requires `general.architecture == "qwen4exp"` and reads six `qwen4exp.*` keys with
|
||||
defaults 48/2560/24/2 (`include/strata/artifact/gguf_reader.hpp:576-597`); its callers are the native dense
|
||||
loader, the native head and embedding, and the GGUF reader (`native_dense.cpp:103`, `native_head.cpp:29`,
|
||||
`:113`, row 18). Every Qwen3.6 load dies there first. Beyond the guard, only `expert_count`,
|
||||
`expert_used_count` and the rope keys are read, under `qwen4exp.` and only with `--native`
|
||||
(`generate.cpp:2089-2096`, rows 8, 9). What `ModelGeometry` must read, all present in the file
|
||||
(`gguf-metadata.md`, metadata table; row 153):
|
||||
|
||||
| Field | Key |
|
||||
| --- | --- |
|
||||
| `n_embd`, `n_layers` | `qwen35moe.embedding_length`, `block_count` minus `nextn_predict_layers` (0 when absent) |
|
||||
| `qsa_interval` | `full_attention_interval` |
|
||||
| `ssm_state_size`, `ssm_k_heads`, `ssm_v_heads`, `ssm_d_conv`; conv channels and value dim derived | `ssm.state_size`, `ssm.group_count`, `ssm.time_step_rank`, `ssm.conv_kernel`, `ssm.inner_size` |
|
||||
| `n_head`, `n_head_kv`, `head_dim`, `n_rot`, sections, base, eps | `attention.head_count`, `head_count_kv`, `key_length`, `rope.dimension_count`, `rope.dimension_sections`, `rope.freq_base`, `attention.layer_norm_rms_epsilon` |
|
||||
| `n_expert`, `k`, `n_ff` (routed and shared) | `expert_count`, `expert_used_count`, `expert_feed_forward_length`, `expert_shared_feed_forward_length` |
|
||||
| `hc` | 1 (no key; the architecture string decides) |
|
||||
|
||||
The oracle's `read_hparams` (`ref/qwen36.py:125-150`) is the reference for defaults and derived values.
|
||||
Other default-geometry sites: the routing trace's `layer >= 48` bounds (`generate.cpp:771, 795`, row 13),
|
||||
the embedding load with `g0.n_embd` and the literal 248320 (`generate.cpp:2184-2186`, row 11), the draft
|
||||
geometry (`generate.cpp:3026`, 3.10), and the standalone planner's `Geometry` and `expert_blob`
|
||||
(`include/strata/plan/plan.hpp:22-52`, row 19), which is off the serving path.
|
||||
|
||||
### 3.9 PLE, optional at the CLI
|
||||
|
||||
The kernels already run without it: `block_layer_pre` applies the PLE only at layer 1 when `ple != nullptr
|
||||
&& ple->ready()` (`layer.hpp:524-545`, row 30), prefill and verify guard on `ple_on` (rows 68, 69). The CLI
|
||||
does not: `--native` refuses to start without `--ple-gguf` or a shard holding `per_layer_token_embd.weight`
|
||||
(`generate.cpp:1800-1815`), and without `--native` the flag is "required" with `--no-ple` called a
|
||||
"diagnostic ablation" (`:1843-1855`, rows 62, 63). The change is to make the absence of the tensor the
|
||||
normal case when the architecture has no PLE. The fixed `NG_HIST x NG_HC_DIM` history buffer (about 360 KB,
|
||||
`session.cpp:50-52`, row 29) and the `blk.1.ple_key` special cases (row 65) are dead but harmless.
|
||||
|
||||
### 3.10 The MTP drafter
|
||||
|
||||
The drafter is its own pack: `<rt_dir>/dense.txt`, `dense.bin` (every dense weight Q8_0), `experts.bin`
|
||||
written by `tools/mtp_rt.py` (`mtp.cpp:150-216`, row 70). It expects vLLM-style names
|
||||
(`fc_embedding`, `fc_hidden`, `pre_fc_norm_*`, `self_attn.*`, `mlp.shared_expert.*`, `mlp.gate`,
|
||||
`mlp.shared_expert_gate`, three `*hyper_connection*` groups; `mtp.cpp:210-212, 488-495, 503-507, 575`),
|
||||
canonical Q2_0 experts of `n_expert x BLOB` bytes in VRAM through `moe_group_resident` /
|
||||
`moe_grouped_s2` (`mtp.cpp:191, 579-583`; `s2_expert_grouped.cu:37-46` bakes 2560/640, row 121), and the
|
||||
default geometry (`generate.cpp:3026`, "the canonical model's MTP head (512 experts)", row 12).
|
||||
|
||||
Qwen3.6's draft block (`gguf-metadata.md`, "The nextn block"): `concat(rms_norm(emb) * enorm, rms_norm(h)
|
||||
* hnorm)` (embedding first) through one `eh_proj [4096, 2048]`, then a plain attention + MoE block
|
||||
(`attn_norm`, joint q+gate, q/k norm, IMRoPE, causal over its own KV, sigmoid gate, `attn_output`,
|
||||
residual, `post_attention_norm`, the same top-8 MoE plus gated shared expert, residual), `shared_head_norm`,
|
||||
the main `output.weight`. Pairing: token k with the trunk's output-normed hidden state of k-1
|
||||
(`oracle-crosscheck.md`, "Nextn / MTP"; verified at every nextn seam, 50 of 50). What the drafter keeps:
|
||||
dense attention over its own KV ring (rows 76), the main head and the `draft_vocab.bin` subset (row 77,
|
||||
the same 248,320 vocabulary, so `data/draft_vocab*.bin` carry over), `token_embd` embeds (row 78). What
|
||||
changes: the two input projections become one `eh_proj` over the concatenation (`mtp.cpp:488-495`); the
|
||||
three hc groups become three norms (`:503-507, 564-568, 613-625`; the prefill-side pass at
|
||||
`prefill.cpp:972-1086` the same); the draft experts are 256 K-quant blobs (Q5_K/Q4_K, 464 MiB in the
|
||||
Q4_K_XL file; Q3_K/Q4_K, 364 MiB in the IQ4_XS file) served by the native GPU expert kernels
|
||||
(`iq_kernels.cu`, row 120) instead of the Q2_0 grouped kernel; the geometry follows the target.
|
||||
|
||||
A Qwen3.6 draft pack: `dense.txt`/`dense.bin` with llama.cpp's names (`nextn.eh_proj`, `nextn.enorm`,
|
||||
`nextn.hnorm`, `nextn.shared_head_norm`, `attn_norm`, `post_attention_norm`, `attn_{q,k,v,output}`,
|
||||
`attn_{q,k}_norm`, `ffn_gate_inp` BF16, `ffn_gate_inp_shexp` BF16, `ffn_*_shexp`), the projections kept
|
||||
Q8_0 as stored (39 MiB), and a `native_experts.txt`-style line for the one layer's three expert tensors.
|
||||
Because the drafter is separate from the trunk file, the pack cut from the Q4_K_XL file's `blk.40` serves
|
||||
the IQ3_XXS trunk too (the plain IQ3 file has no nextn block). Draft acceptance is an empirical question per
|
||||
model; llama.cpp's own MTP arm (B4) is the external reference.
|
||||
|
||||
### 3.11 Tokenizer, chat template, vision
|
||||
|
||||
Same vocabulary and the same `qwen35` pre-tokenizer family (`gguf-metadata.md`; `tools/strata_tokenizer.py`
|
||||
refuses schemes it has not transcribed, `upstream-tooling.md` section 2). The front end uses llama.cpp's
|
||||
chat parser (`frontend/chat_parser_test.cpp`) and carries the Qwen3-Coder any-argument-order patch
|
||||
(`chat_parser_test.cpp:48`); the plan's step 5 checks it against Qwen3.6's template with
|
||||
`make test-chat-parser MODEL=<gguf>` (`Makefile:35-41`). Vision loads an mmproj through `mtmd`
|
||||
(`frontend/vision.hpp:79-87`); the `Qwen3.6-35B-A3B-MTP-GGUF-mmproj-F16.gguf` is on the VM with its SHA-256
|
||||
(`phase0-notes.md`). Nothing in the engine changes for either.
|
||||
|
||||
## 4. The memory plan
|
||||
|
||||
### 4.1 The fixed set, from measurements
|
||||
|
||||
| Item | Q4_K_XL, 262,144 | IQ3_XXS, 262,144 | Source |
|
||||
| --- | ---: | ---: | --- |
|
||||
| Non-expert weights on the GPU | 2,038 MiB | 1,597 MiB | `-lv 4` minus resident expert layers (section 1); census |
|
||||
| Draft block: 40 MiB dense + 256 experts in VRAM + ring KV + 8 x 248,320 logits | ~520 MiB | ~520 MiB (the Q4 draft pack) | census; `mtp.hpp:19`; `mtp.cpp:430-436` |
|
||||
| KV, q4_0, 10 layers | 1,440 MiB | 1,440 MiB | `phase0-notes.md` smoke rows (both arms) |
|
||||
| Session: RoPE table 64 MiB, scratch; **plus 320 MiB of indexer state unless 3.3 item 4 removes it** | ~164 MiB | ~164 MiB | `layer.cpp:559-576` |
|
||||
| CUDA context | ~230 to 300 MiB | same | nvidia-smi 9,487 (peak 9,565) minus the three buffers, Q4 row |
|
||||
| Reserve | 300 MiB (`kSmallReserveMib`) to 700 (default) | same | `generate.cpp:424, 3249` |
|
||||
| Prompt buffers: borrowed from the cache with a profile, else chunk-sized | 0 (borrow) / 1,904 MiB at chunk 2048 | 0 / 1,878 MiB | `generate.cpp:2723`; llama.cpp `-ub 2048` compute buffer |
|
||||
| **Decode-time fixed set** | **~4,760 MiB** borrowing; ~6,660 without | **~4,320** borrowing; ~6,200 without | sum |
|
||||
| Trunk experts (file) | 18,726 MiB; 1.829 MiB mean, 2.195 max | 10,594 MiB; 1.035 mean, 1.172 max | census |
|
||||
| Dense split-K attention scratch at `cap = 262,144` | 64.5 MiB per query row (516 for the verify window) | same | `qsa_decode_attn.cu:489-491` |
|
||||
|
||||
The replay and the plan used a 5.8 GB (Q4) / 4.6 GB (IQ3) fixed set that includes the 1.9 GB prompt buffer
|
||||
and excludes the drafter, and 17.4 GB / 10.5 GB of experts (`phase0-replay.md`, "Budget to slots"). The
|
||||
census moves the expert total up by 7% at Q4 and the fixed set down by the prompt buffer when prefill
|
||||
borrows; the two roughly cancel at the 11 GB rung (table 4.4).
|
||||
|
||||
### 4.2 The VRAM planner (Phase 2 step 2)
|
||||
|
||||
What exists: `--expert-cache auto` reads free VRAM, subtracts the reserve and the prompt estimate, grants
|
||||
slots at `max_blob` (`generate.cpp:3232-3300`), then for a native pack with a profile re-prices the slots
|
||||
per layer so the same VRAM holds the profile's hottest experts at their own blob sizes
|
||||
(`generate.cpp:3307-3327`, "~30% more IQ3_XXS experts than slots of the largest blob"); the prompt path
|
||||
borrows the last slots (`:4404-4425`); below `min_slots` the reserve shrinks to 300 MiB and then the start
|
||||
refuses with the numbers (`:3267-3290`, "no VRAM is left for the expert cache"). What the step adds, in the
|
||||
plan's order with one change:
|
||||
|
||||
1. Fixed set first: weights, drafter, KV for the requested context, session. **KV streaming is not a lever
|
||||
for this model** (3.3 item 6): the resident-window floor of 20,480 cells (`layer.cpp:556`) exists for a
|
||||
selection of 2,051 cells, and dense attention reads every cell. So the rule's first fallback, "stream
|
||||
the KV to RAM above a resident window", is replaced by: hold the KV in VRAM, and if the fixed set does
|
||||
not fit, lower the context toward 131,072, then refuse with the numbers and the IQ3 file's name. Never
|
||||
silently shorten.
|
||||
2. Every remaining byte becomes expert slots, sized per layer from the profile as today.
|
||||
3. The RAM tier: free RAM minus a headroom (`--resident-experts` uses 4 GiB, `generate.cpp:1508`;
|
||||
`--resident-budget-gib N` sets it, `:1516-1520`), filled with the next experts by profile rank
|
||||
(`pin_cache_complement`, `expert_source.cpp:1331`); whatever remains stays mapped from the GGUF
|
||||
(`--mmap-experts`, `:618-680`) with the `MADV_WILLNEED` warm on predicted ids (`:1129-1160`).
|
||||
4. Emulation: `--vram-cap MiB` clamps every `cudaMemGetInfo` free figure the planner reads (`:3297, 3313`)
|
||||
to `cap - used` and, so the driver sees the same pressure the real card would, allocates a blocker of
|
||||
`total - cap` at start; `--ram-cap GiB` bounds `resident_budget` and the pinned arena. The page cache
|
||||
cannot be capped from inside the process; the 12 GiB VM does that physically, and on a larger host a
|
||||
cgroup `memory.max` does.
|
||||
5. The start-up log and `/health` state the three counts (VRAM slots, RAM copies, mapped) and per-token
|
||||
counters: VRAM hits (`cache_hits`), RAM-copy hits, warm-hint count (`warm_count_`), and disk reads as
|
||||
the major-fault delta from `/proc/self/stat`, since a page-cache miss is not otherwise observable.
|
||||
|
||||
### 4.3 The 6-to-32 GB ladder
|
||||
|
||||
Budgets in the replay's decimal convention (6 GB = 5,722 MiB) except the 1080 Ti (11,264 MiB) and a 24 GB
|
||||
card (24,576 MiB). Slots at the census mean blob; "borrow" is the decode-time fixed set of 4.1, "no borrow"
|
||||
adds the chunk-2048 prompt buffer.
|
||||
|
||||
| Budget | Q4 replay basis (5.8 GB fixed, 1.70 MB/expert) | Q4 derived, no borrow | Q4 derived, borrow | IQ3 replay basis | IQ3 derived, borrow |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: |
|
||||
| 6 GB | 80 (1%) | 0 (fixed set does not fit) | ~525 (5%) | 1,360 (13%) | ~1,350 (13%) |
|
||||
| 8 GB | 1,280 (12%) | ~525 (5%) | ~1,570 (15%) | 3,280 (32%) | ~3,200 (31%) |
|
||||
| 11 GB (decimal) | 3,040 (30%) | ~2,090 (20%) | ~3,130 (31%) | 6,240 (61%) | ~5,960 (58%) |
|
||||
| 1080 Ti, 11,264 MiB | | ~2,510 (25%) | ~3,550 (35%) | | ~6,700 (66%) |
|
||||
| 12 GB | 3,640 (36%) | ~2,610 (26%) | ~3,650 (36%) | 7,200 (70%) | ~6,880 (67%) |
|
||||
| 16 GB | 6,000 (59%) | ~4,700 (46%) | ~5,740 (56%) | all | all |
|
||||
| 24 GB (24,576 MiB) | all | ~9,790 (96%) | all, ~1,090 MiB spare | all | all |
|
||||
| 32 GB | all | all | all | all | all |
|
||||
|
||||
The RAM tier at the replay's 9.5 GB usable: Q4 ~4,950 experts at the census blob (the replay's 5,590 was at
|
||||
1.70 MB), IQ3 ~8,760. The disk tier at Q4 on the 1080 Ti is then 10,240 - 3,550 - 4,950 = ~1,740 experts
|
||||
(17%) with borrowing and ~2,780 (27%) without; the replay modelled 1,610 (16%). At IQ3 everything fits VRAM
|
||||
plus RAM at every rung from 6 GB (`phase0-replay.md`, finding 5). The planner's own log at `--vram-cap`
|
||||
6/8/11/12/16/24/32 is the check of this table, within one slot of the derivation.
|
||||
|
||||
## 5. Expected envelope per budget
|
||||
|
||||
From `phase0-replay.md` (LFU, profile seed, second half of a 214,940-token trace of the IQ3_XXS model,
|
||||
decode only; the Q4 arm reuses the IQ3 routes). The parameters are parameters: `gpu_ms` 17 (an upper
|
||||
estimate from the smoke rows' busy share; 12 is a flag away), `cpu_lane_ms` 0.15 per expert (llama.cpp
|
||||
IQ3 N=18 implies 0.17), `disk_ms` 1.3 (fio 1 MiB random QD4; parallel faults may halve it), `pcie_ms` 0
|
||||
(promotions counted, not charged: 47.7 copies per token at Q4 11 GB, about 12 ms at 0.26 ms each, is the
|
||||
largest omission; charging it takes Q4 11 GB LFU from 42.5 to 27.8 tok/s). "Overlap" is
|
||||
`1000 / max(gpu, cpu, disk)`, "serial" the sum.
|
||||
|
||||
| Budget | Q4 VRAM hit | Q4 disk reads/tok | Q4 tok/s overlap / serial | IQ3 VRAM hit | IQ3 disk/tok | IQ3 tok/s overlap / serial |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||
| 6 GB | 0.0% | 70.7 | 7.7 / 6.8 | 59.7% | 0 | 51.7 / 27.5 |
|
||||
| 8 GB | 57.9% | 51.5 | 12.6 / 10.4 | 84.4% | 0 | 58.8 / 40.9 |
|
||||
| 11 GB | 82.6% | 13.2 | 42.5 / 24.7 | 96.0% | 0 | 58.8 / 52.9 |
|
||||
| 12 GB | 86.8% | 7.1 | 58.8 / 31.8 | 97.7% | 0 | 58.8 / 55.2 |
|
||||
| 16 GB | 95.5% | 0 | 58.8 / 52.2 | 100% | 0 | 58.8 / 58.8 |
|
||||
| 24, 32 GB | 100% | 0 | 58.8 / 58.8 | 100% | 0 | 58.8 / 58.8 |
|
||||
|
||||
58.8 is `1000 / gpu_ms` and the overlap column saturates there by construction. The Belady ceiling at Q4
|
||||
11 GB is 91.0% hit, 6.6 disk reads, 58.8 / 34.6. Against it, the llama.cpp smoke points on the same card:
|
||||
Q4 N=32 **8.78 tok/s** decode, 128.6 prefill, GPU busy 15%; IQ3 N=18 **24.58** decode, 433.9 prefill, GPU
|
||||
busy 41% (`phase0-notes.md`). The plan's floors (A2: 15/10 tok/s at 8K/32K on 11 GB, 10/7 on 6 GB, 60/45 on
|
||||
24 GB; A3: 300 tok/s prefill on Pascal) sit inside these predictions except the Q4 6 GB row, which the
|
||||
plan already routes to the IQ3 file. With the census tiers (4.3) the Q4 11 GB disk term is 17 to 27% of
|
||||
experts rather than 16%, so its disk reads per token sit above 13.2; the replay is re-run with the census
|
||||
blob sizes as part of step 2, not re-derived here. Prefill is not modelled; the engine's chunked MMQ path
|
||||
amortises expert bytes across the chunk, and on Pascal the prompt MoE's fast path is a risk (section 7).
|
||||
|
||||
## 6. Execution plan (Phase 2, steps 2 to 7)
|
||||
|
||||
Step 1, the oracle and fixture, is done on `qwen36-oracle`: `ref/qwen36.py` agrees with the pinned
|
||||
llama.cpp graph on 2,155 comparisons over 116 seam families at 1.1e-4 worst absolute error, the router's
|
||||
integers identical, and all seven rival readings fail at the seam that makes them (`oracle-crosscheck.md`).
|
||||
Every harness below holds the engine to those dumps by llama.cpp's `cb()` names. Each step has a parity
|
||||
harness in the repo's negative-test discipline (`gdn_parity.cpp`: every wrong reading must differ by more
|
||||
than 5% relative L1 before the right one is judged, `upstream-tooling.md` section 3), runs on the 1080 Ti
|
||||
under `STRATA_EXPERIMENTAL_SM60=ON` (sm_61) from the first build and on a rented sm_86 card for compile
|
||||
speed; a kernel passes when it passes on both. Steps 2 to 4 need seconds of GPU per run and proceed while
|
||||
the Phase 0 sweeps hold the card. Effort weights sum to 100 for steps 2 to 7.
|
||||
|
||||
**Step 2, geometry, metadata, sizing (15%).** Files: `gguf_reader.hpp:576-597` (accept `qwen35moe`, read
|
||||
the 3.8 key set), `layout.hpp:27-59` (`hc = 1`, derived conv channels and value dim, no indexer fields),
|
||||
`generate.cpp:2008-2010, 2073-2096, 2184-2186, 771, 795` (geometry from the file before the layout load;
|
||||
the embedding dims from it), `expert_layout.cpp:284` (the leak), `expert_source.cpp:2475-2500` (fused
|
||||
forms refused by name), `generate.cpp:1800-1815, 1843-1855` (PLE optional), the planner
|
||||
(`generate.cpp:3232-3327`) with the 4.2 rule, `--vram-cap`, `--ram-cap`, the counters, `tools/make_profile.py`
|
||||
(`N_LAYER = 48`). Harness: `ModelGeometry` from the synthetic GGUF (`tools/qwen36_synth_gguf.py`) and the
|
||||
real file equals the oracle's `HParams` field by field; the planner's log at the seven caps reproduces
|
||||
table 4.3. Negative tests: a `qwen4exp` file refused with its name; a 48 x 512 profile refused
|
||||
(`expert_cache.cpp:43`); a `--fused-gate-up` fixture refused by tensor name; `--vram-cap` below the fixed
|
||||
set refuses with the context it would need. No GPU beyond the planner's run.
|
||||
|
||||
**Step 3, kernels and the block (45%).** In order of risk:
|
||||
|
||||
- *GDN (3.2):* SiLU in the four kernels; `gdn_parity.cpp` at `h_v 32` with sigmoid as the negative, plus the
|
||||
existing four traps (pairing, decay order, conv direction, l2 epsilon); `gdn_rec_parity.cu` at `VPK 2`.
|
||||
Seams: `conv_output_silu-0`, `new_state-0`, `final_output-0`.
|
||||
- *Dense attention (3.3):* the identity-`ids` producer; `G` templated at 8; the indexer skipped in
|
||||
`qsa_layer` and the verify attention step; the state without indexer buffers; `cap = max_cells`; the
|
||||
split-K scratch bounded. Harness: `qsa_parity.cpp`'s attention cases with `ids` identity against the
|
||||
oracle's `kq_soft_max-3`, `kqv-3`, `attn_gated-3`, and a 300-cell case where the old width (2,051) and
|
||||
the dense width differ. Negative tests: `G = 12` on 16 heads (refused, not mis-indexed), the gate skipped
|
||||
(1.03 relative L1 at `attn_gated-3`), adjacent-pair RoPE (0.20 at `kqv-3`), both from the oracle's
|
||||
controls.
|
||||
- *Router and shared expert (3.4):* `router_top10_parity.cpp` at 256/8 with its tie fixtures; the BF16
|
||||
rounding of the F32 router measured as a flip rate on the real file's first 8 tokens with the quantized-
|
||||
mode gates; `shared_expert_parity.cpp` at 512 with the 1-D F32-to-BF16 gate. Seams: `ffn_moe_topk-N`,
|
||||
`ffn_moe_weights_norm-N`, `ffn_shexp_gated-N`.
|
||||
- *The block without hyper-connections (3.5):* `layer.cpp` and `verify.cpp` both, `session.cpp:141-148`,
|
||||
the head. Harness: the layer composition test, Maya's shape: layer 0 (GDN + MoE) and layer 3 (attention +
|
||||
MoE) of the synthetic model through the engine's kernels, every seam held to the dumps; then the verify
|
||||
window on an 8-token sequence against the oracle's `l_out-N` per position, with the window's row
|
||||
arithmetic required to equal the single-token path (the discipline `verify.cpp:773-774` already states).
|
||||
Negative tests: the GR read with identity weights (not a plain norm), the post-attention norm skipped,
|
||||
`k = 10` on an 8-expert file.
|
||||
- *Prefill (3.6):* the constants and the eight literal sites; the GDN kernels forked at 32/16/8192; the
|
||||
route kernel at `k`; the split-q and gate kernels at 16 heads; `moe_fused_iq.cu` at 2048/512. Harness:
|
||||
the restored `tests/cuda/prefill_*_test.cpp` plus chunked-prefill-then-decode against token-by-token
|
||||
decode on a 40-token sequence (the oracle's `base_c7` case: chunks of 7). Negative tests: `VPK 3` on 32
|
||||
heads, top-10 routing on 8.
|
||||
|
||||
**Step 4, pack, drafter, runner (20%).** `tools/iq_pack.py`: a `qwen35moe` entry in `FORM`/`ROUTERS`
|
||||
(`ssm_alpha`, `ssm_beta`, `ffn_gate_inp`, `ffn_gate_inp_shexp` F32 to BF16 under `--compat-bf16` with
|
||||
`compat-bf16.json`; norms, `ssm_a`, `ssm_dt.bias`, `ssm_conv1d` F32 copied; projections served natively),
|
||||
`native_experts.txt` v3 per layer; `tools/test_iq_pack.py`'s `write_gguf()` fixtures at the new
|
||||
architecture. The draft pack of 3.10 from the MTP file's `blk.40` (a new `tools/mtp_qwen36_pack.py`
|
||||
replacing `mtp_pack.py`/`mtp_rt.py`), `mtp.cpp` and `prefill.cpp:972-1086` on the plain graph, the draft
|
||||
experts through the native GPU kernels, `generate.cpp:3026` following the target. `make_profile.py` from
|
||||
the E0 trace (40 x 256). Harness: the drafter's one-row forward against the oracle's `--mtp` dumps
|
||||
(`mtp_eh_proj`, `mtp_attn_gated`, `mtp_ffn_out`, `result_output`; 50 nextn seams); the streaming runner
|
||||
held to the oracle at every position of the 11- and 40-token cases, autoregressive and chunked
|
||||
(`base_ar`, `base_c7`); then the real Q4 file, greedy, against llama.cpp's output distribution (top-1
|
||||
agreement and KL per teacher-forced position, Maya's quantized-mode gates: no monotone positional drift,
|
||||
selection equal at probed layers). Negative test: a 4 KB weight corruption must move the logits by more
|
||||
than 1e-2 (the mutation-sensitivity gate).
|
||||
|
||||
**Step 5, serve and measure (10%).** The 1080 Ti at 11 GB, then `--vram-cap` 8 and 6; the other rungs when
|
||||
a card frees up. `tools/calibrate.py` for `--pcie-frac`, `--spec-min-p`, `--pool-workers`; regina's harness
|
||||
and the three instruments (`nvidia-smi` 100 ms, `nvprof` on Pascal, `perf stat`); the engine's points on
|
||||
`ladder-baseline.png`; H5. `make test-chat-parser MODEL=<gguf>` against the template; the any-argument-order
|
||||
patch checked for misfires; images through `--mmproj`. Acceptance A1 to A5 per rung.
|
||||
|
||||
**Step 6, the Pascal cards and the fat binary (5%).** `CMakeLists.txt:138-176`: `STRATA_EXPERIMENTAL_SM60`
|
||||
default ON, `CMAKE_CUDA_ARCHITECTURES=61;70;75;86;89;120`, CUDA 12.8 (the sm_120-with-12.8 warning at
|
||||
`:166-169` stays; RTX 50 is built, not measured). `cuobjdump --list-elf | grep sm_` after every build. The
|
||||
1070 Ti and the 1060 against B1b; the sm_75+ paths checked on the 4090 or A6000 when one is free.
|
||||
|
||||
**Step 7, README (5%).** The supported model and checksums, the ladder against the baseline, the sizing
|
||||
rule in words, the Pascal caveats.
|
||||
|
||||
The critical path runs through step 3's block-and-verify rewrite and its composition harness; the dense
|
||||
attention kernel is the one new kernel, the rest is parameterisation and removal.
|
||||
|
||||
## 7. Risks
|
||||
|
||||
1. **Nobody has run this engine on Pascal.** The build refuses `cc < 75` without the experimental flag;
|
||||
the flag is "community-tested, not in the ready-made engine" for sm_60/sm_70 (`CMakeLists.txt:150-160`),
|
||||
and Maya requires Volta. The 1080 Ti is sm_61, so `__dp4a` is native and only the `__nanosleep` shim
|
||||
applies (`dp4a.hpp:27-40`).
|
||||
2. **FP16 on GP102/GP104/GP106 runs at 1/64 rate.** 21 kernel files touch half types. Conversions
|
||||
(`__half2float`, the `hf()` stores in `prefill/kernels.cu:614, 761`, the fp16 K/V reads in
|
||||
`qsa_decode_attn.cu`) are full rate; half *arithmetic* is not. The audit must separate the two in
|
||||
`native_mmvq.cu`, `iq_kernels.cu`, `s_gemv.cu`, `shared_expert.cu` and the prefill kernels. The prompt
|
||||
MoE is the exposed case: the MMQ (dp4a) path is gated by `mmq::built()`/`mmq::fits`
|
||||
(`prefill.cpp:676-684`) and its tests exit 77 below sm_80 (`CMakeLists.txt:1076`); the fallback is the
|
||||
FP16 GEMM path over dequantized fp16 weights (`prefill.cpp:907`), which is exactly the slow case. The
|
||||
A3 floor of 300 tok/s prefill on Pascal depends on the dp4a MMQ running on sm_61, where llama.cpp's own
|
||||
MMQ does run.
|
||||
3. **Prompt attention on Pascal is the decode kernel.** `qsa_prompt_attn_batch` returns false for
|
||||
`cc < 70` (`qsa_prompt_attn.cu:1433`) and prefill falls back to `qsa_decode_attn_batch` over the chunk
|
||||
(`prefill.cpp:2222-2228`): correct, but a 2,048-query chunk through a decode-shaped kernel is a
|
||||
throughput risk, and its split-K scratch is the 64.5 MiB-per-row item of 3.3.
|
||||
4. **Memory items the plan did not count:** the draft block (~520 MiB), the dead indexer state (320 MiB
|
||||
at 256K unless removed), the dense scratch, and the uniform-slot grant before the per-layer re-pricing
|
||||
(`generate.cpp:3307-3327`), which is 17% of capacity at Q4 (2.195 versus 1.829 MiB) if the profile is
|
||||
absent and the re-pricing does not run.
|
||||
5. **KV streaming does not apply** (3.3 item 6): a 6 GB card at 256K holds the KV in VRAM or lowers the
|
||||
context; there is no third option in this engine without a CPU attention path.
|
||||
6. **Numerical:** BF16 rounding of the F32 router and GDN gates (3.4); the router's flip rate is measured
|
||||
on the real file, and the acceptance gates are top-1 and KL, not per-logit tolerances, as Maya's
|
||||
cross-check found (two flips in 512 explained by 1e-5 selection gaps).
|
||||
7. **Verify-only decode.** Every token of a native pack goes through `verify.cpp` with `--spec T >= 2`
|
||||
(`generate.cpp:2178`); the plain IQ3 file has no draft block, so its drafter is the Q4 file's `blk.40`
|
||||
(3.10). Draft acceptance on Qwen3.6 is unmeasured; the prompt-lookup drafter alone leaves short windows.
|
||||
8. **The replay's model:** `pcie_ms` 0, one IQ3 trace reused for Q4, a cache that never resets, no
|
||||
prefill, `gpu_ms` an upper estimate (`phase0-replay.md`, "Limits"); the census blob sizes shift the Q4
|
||||
disk tier up (4.3). The engine's counters, not the replay, decide H4 and H6.
|
||||
9. **The host.** VM 211 has 8 vCPU of a Zen 1 shared with VM 220 and AVX2 only; the native expert path then
|
||||
runs ggml-cpu `vec_dot` for the i-quants and the AVX-2 kernels for the rest (`generate.cpp:2068-2072`).
|
||||
The 0.15 ms CPU lane is the replay's assumption; `perf stat` measures it.
|
||||
10. **Upstream tooling gaps:** no published Python oracle for the Flash-Next kernels, so the parity files'
|
||||
C++ references are the only pins of the existing semantics (`upstream-tooling.md` section 1); the
|
||||
`bench/micro` llama.cpp-oracle tests cannot be restored.
|
||||
|
||||
## 8. Disagreements with the plan
|
||||
|
||||
1. **Section 2, the sizing rule's first fallback ("stream the KV to RAM above a resident window").** Not
|
||||
available for dense attention (3.3 item 6): streaming resolves the selected cells, and every cell is
|
||||
selected. The rule becomes KV in VRAM, then lower the context, then refuse. H3's "6 GB needs the KV
|
||||
streamed" is replaced by: 6 GB at Q4 holds the fixed set at 256K only if prefill borrows from the cache
|
||||
(~525 slots, table 4.3), else it takes 131,072 or the IQ3 file.
|
||||
2. **Section 2, the fixed set.** Non-expert weights are 2,038 MiB at Q4 and 1,597 at IQ3, not ~3.1 / ~1.9
|
||||
GB; the prompt buffer is 1.9 GB at chunk 2048, not 0.8; the drafter (~520 MiB) is missing from the
|
||||
table. The plan says Phase 0 numbers replace the estimates; this study does so and adds the drafter.
|
||||
3. **Section 2, the expert totals.** Q4 trunk experts are 18,726 MiB (19.6 GB), 1.829 MiB mean and 2.195
|
||||
max per expert, not 17.4 GB / 1.7 MiB; IQ3 agrees (10,594 MiB). The 11 GB rung's tiers at Q4 shift to
|
||||
~3,550 VRAM / ~4,950 RAM / ~1,740 disk with borrowing, and the replay's 13.2 disk reads per token is a
|
||||
lower bound until it is re-run at the census sizes.
|
||||
4. **Section 5 step 3, "`native_flash_attn.cu` is the fallback for prompts."** It is a diagnostic adapter
|
||||
for contexts up to 256 with 24 heads hard-coded (`native_flash_attn.cu:196-206`, `layer.hpp:53`). The
|
||||
prompt path is `qsa_prompt_attn.cu`, and on Pascal it is the batched decode kernel (risk 3). The dense
|
||||
prompt attention comes from parameterising those two, not from `native_flash_attn.cu`.
|
||||
5. **Section 5 step 2, "accept llama.cpp's fused `ffn_gate_up_exps` and `attn_qkv` forms or split them at
|
||||
pack time."** No shipped Qwen3.6 file uses either (`gguf-metadata.md`). The study scopes this to a
|
||||
named refusal in `check_experts_gguf` and `native_dense.cpp:31-33`; the oracle's fused cases stay as
|
||||
evidence of the layouts should a file appear.
|
||||
6. **Section 5 step 2, "per-layer prefetch hints as Maya's section 7 added."** This tree already has them:
|
||||
`FileExpertSource::warm` issues `MADV_WILLNEED` per role (`PrefetchVirtualMemory` on Windows) for the
|
||||
predicted ids (`expert_source.cpp:1129-1160`, `1264`). Nothing is ported from Maya; step 2 verifies the
|
||||
hint fires on the Qwen3.6 pack's offsets and counts it.
|
||||
7. **Section 2, "which file" (Q4_K_M-MTP, or Q4_K_XL plus a separately packed head).** The Q4_K_XL from the
|
||||
MTP repository (rev 5bc3e238, SHA in `phase0-notes.md`) already carries `blk.40` (753 tensors). It is
|
||||
the default file, and its `blk.40` is the draft pack for both arms (3.10).
|
||||
8. **Section 1, "every kernel path on these cards must be FP32 or dp4a int8."** Agreed for arithmetic;
|
||||
fp16 *storage* with conversion (the KV pools, the fp16 stores in prefill) is full rate on Pascal and
|
||||
stays. The prompt MoE's dp4a MMQ must be enabled on sm_61 (risk 2), which the plan does not list.
|
||||
|
||||
Nothing else in Sections 0, 2 and 5 is contradicted: the target, the three tiers on the primary rung, the
|
||||
Q4 default with the IQ3 arm, the Pascal-first build, the step order and the acceptance thresholds stand.
|
||||
@@ -0,0 +1,290 @@
|
||||
# Flash-Next geometry and extras baked into the Strata engine (6f32ec0, engine 0.1.39)
|
||||
|
||||
Scope: `src/` and `include/`. Target: Qwen3.6-35B-A3B (hidden 2048, 40 layers, GDN 16 k-heads / 32 v-heads,
|
||||
16 attention heads / 2 KV heads of 256, dense attention, 256 experts top-8 of 512 plus a shared 512, no
|
||||
hyper-connections, no PLE, MTP 1 layer, vocabulary 248,320). No fixes are proposed here.
|
||||
|
||||
Derived Qwen3.6 numbers used below: GDN conv channels 8192 (2*2048 + 4096), GDN value dim 4096, attention
|
||||
`q_full` width 8192 (16 * 2 * 256), attention output width 4096, GQA group 8 (16 / 2), 40 layers = 30 GDN + 10 attention.
|
||||
|
||||
Classes:
|
||||
|
||||
- **RT**: already a runtime parameter (`ModelGeometry`, pack metadata, tensor shape). Fine as is.
|
||||
- **CT**: a compile-time constant that disagrees with Qwen3.6. Must change.
|
||||
- **CT-ok**: a compile-time constant that is an upper bound or a value Qwen3.6 shares. Needs no change.
|
||||
- **ST**: a structural assumption. Needs a code path, not a number.
|
||||
|
||||
Line numbers are from the current tree. Where a path only runs for the canonical Q2_0 pack (not the `--native` GGUF
|
||||
pack that Qwen3.6 would use), the note says "canonical only".
|
||||
|
||||
## A. The central finding: `ModelGeometry` is a default, and only two fields are ever read from the model file
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 1 | include/strata/core/layout.hpp:28-30 | `n_embd = 2560`, `n_layers = 48`, `qsa_interval = 4` | CT | Struct defaults. Nothing reads `n_embd`/`n_layers` from the file. Interval 4 already matches Qwen3.6. |
|
||||
| 2 | include/strata/core/layout.hpp:33-38 | `ssm_k_heads 16`, `ssm_v_heads 48`, `ssm_conv_channels 10240`, `ssm_value_dim 6144` | CT | Conv channels and value dim are stored members, not derived from heads. Changing `ssm_v_heads` alone leaves them wrong. Heads 16 and state 128 and d_conv 4 already match. |
|
||||
| 3 | include/strata/core/layout.hpp:41-45 | `n_head 24`, `idx_q_heads 4`, `idx_key_dim 128` | CT | `n_head` must be 16. `n_head_kv 2` and `head_dim 256` match. Indexer fields are meaningless for Qwen3.6. |
|
||||
| 4 | include/strata/core/layout.hpp:48-49 | `hc = 4`, `hc_lr = 320` | CT / ST | No "hc = 1" meaning exists. `hc` sizes `R`, `inject`, every GR buffer. See section B. |
|
||||
| 5 | include/strata/core/layout.hpp:52-53 | `n_expert = 512`, `n_ff = 640` | CT | One `n_ff` serves routed and shared experts. Qwen3.6 has 512 for both, so one field still works. |
|
||||
| 6 | include/strata/core/layout.hpp:55-58 | `hc_dim() = hc*n_embd`, `n_qsa_layers = n_layers/interval`, `n_gdn_layers` | RT | Derived correctly from the fields. |
|
||||
| 7 | src/program/generate.cpp:2073-2074 | `ModelGeometry g;` with the comment "canonical defaults", and `K = 10` | CT | `g` and `K` start from Flash-Next defaults. |
|
||||
| 8 | src/program/generate.cpp:2089-2092 | Only `qwen4exp.expert_count` -> `g.n_expert` and `qwen4exp.expert_used_count` -> `K` are read, and only when `--native` is given | RT (partial) | The only model-file overrides of geometry. `block_count`, `embedding_length`, head counts, `ssm.*`, `expert_feed_forward_length` are never read. |
|
||||
| 9 | src/program/generate.cpp:2093-2096 | Rope keys read under the `qwen4exp.` prefix | CT | Key prefix must become `qwen35moe.`. Values (base 1e7) happen to match. |
|
||||
| 10 | src/program/generate.cpp:2008-2010 | `const ModelGeometry g0;` passed to `expert_layout_load(o.pack, g0.n_layers, g0.n_expert)` | CT | Runs before the line-2091 override, so it sees 48 layers and 512 experts. The `native_experts.txt` header can still correct `n_expert` (expert_layout.cpp:271). |
|
||||
| 11 | src/program/generate.cpp:2184-2186 | `NativeEmbed::load(..., g0.n_embd, 248320, ...)` | CT | Default `n_embd` 2560 would reject a 2048-wide `token_embd.weight`. The 248320 literal equals Qwen3.6's vocabulary. |
|
||||
| 12 | src/program/generate.cpp:3026 | `static const ModelGeometry draft_geometry{}` handed to `mtp.load` | CT | The comment says the draft layer is "the canonical model's MTP head (512 experts)". Draft geometry does not follow the target. |
|
||||
| 13 | src/program/generate.cpp:771, 795 | Routing trace rejects `layer >= 48` | CT | Literal 48 in two bounds checks. |
|
||||
| 14 | src/program/generate.cpp:5769 | `kImagePad = 248056` (comment: `qwen4exp.ple.image_token_id`) | CT-ok | Only feeds the PLE hash for image cells. Dead without PLE. |
|
||||
| 15 | include/strata/core/session.hpp:48 | `SessionState::k = 10` | CT | Experts per token default. Overwritten from `K` at session init. |
|
||||
| 16 | include/strata/core/expert_source.hpp:194 | `int k_ = 10` | CT-ok | Default only; set per layer at runtime. |
|
||||
| 17 | include/strata/artifact/gguf_reader.hpp:576-578 | `Qwen4ExpGuard{block_count 48, hidden 2560, head_count 24, head_count_kv 2}` | CT | Struct defaults for the architecture guard. |
|
||||
| 18 | include/strata/artifact/gguf_reader.hpp:581-597 | `check_architecture` requires `general.architecture == "qwen4exp"` and reads `qwen4exp.block_count`, `.embedding_length`, `.expert_count`, `.expert_used_count`, `.attention.head_count`, `.attention.head_count_kv` | CT / ST | Callers: native_dense.cpp:103, native_head.cpp:29 and :113, gguf_reader.cpp:57. Every Qwen3.6 load is refused here first. |
|
||||
| 19 | include/strata/plan/plan.hpp:22-42, 49-52, 83, 133 | Standalone planner `Geometry` (48 layers, 12 QSA, 48 v-heads, 10240 channels, indexer cache term), `Costs::expert_blob = 1382400`, `vram_pool_bytes() = 5,943,000,000`, "slots of 1,382,400 B" | CT | Used only by src/plan/plan_main.cpp and src/core/device_main.cpp. Not on the serving path. Has no streaming-KV or RAM-tier model. |
|
||||
| 20 | src/core/graph.cpp (whole file) | None | RT | No geometry. Graphs are keyed by `(LayerType, n_tokens)`. |
|
||||
|
||||
## B. Layer composition: `layer.hpp`, `layer.cpp`, `session.cpp`
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 21 | src/core/layer.cpp:1170-1286 (`block_layer_pre`), 1319-1342 (`block_layer_post`) | Every layer is `gr_read(attn) -> mixer -> gr_write(attn) -> gr_read(ffn) -> router ... moe_finish -> gr_write(ffn)` | ST | The gated-residual read/write wraps both mixer and FFN on every layer. No plain "rms_norm -> mixer -> residual add" branch exists. |
|
||||
| 22 | src/core/layer.cpp:1231-1255 | Four GR tensors per half, prefixes `hc_attn_` and `hc_ffn_` (`norm`, `down`, `up`, `inject`), required engine forms (norm F32, other three BF16) | ST | Qwen3.6 has `attn_norm` and `post_attention_norm` (plain RMS norms) instead. Neither name is referenced anywhere in src/. |
|
||||
| 23 | src/core/layer.cpp:1088-1107 (`lm_head_mix`) | Final mix is `gr_read` with `output_hc_norm/down/up` | ST | Qwen3.6 needs `output_norm.weight` (plain RMS norm). That name is not referenced anywhere in src/. Same in verify.cpp:1123-1125. |
|
||||
| 24 | src/core/layer.cpp:1127-1145 (`block_buffers_bytes/init`) | `R` is `(hc, n_embd)`; `inject`, `inject2`, `gr_rs`, `gr_workspace_bytes(GrShapes{n_embd, hc, hc_lr})` | RT | Sized from `g.hc`. Works for hc = 1 in size, but the GR math is meaningless there. |
|
||||
| 25 | src/core/layer.cpp:1146-1158 (`dump_stride_floats`) | C1-oracle dump layout is `2*n_embd + 2*hc + n_head*head_dim + ...` | RT | Debug only. |
|
||||
| 26 | src/core/session.cpp:141-148 | The first token's residual is `hc` copies of the embedding | RT / ST | Loops `g.hc` times. With hc = 1 it is one copy. |
|
||||
| 27 | src/core/session.cpp:1, 228, 331, 424 etc. | Comments say "48 layers", but loops use `g.n_layers` | RT | Verified: loops at 55, 77, 194-205, 283, 301, 331, 391, 424, 662, 788, 856, 921 all use `g.n_layers`. |
|
||||
| 28 | src/core/session.cpp:41-44 | `gdn_state_floats = S*v_heads*S + conv_channels*(d_conv-1)` | RT | From `ModelGeometry`. Correct once row 2 is fixed. |
|
||||
| 29 | src/core/session.cpp:50-52, 71, 124-126, 159-162 | `ple_hist_bytes() = NG_HIST * NG_HC_DIM * 4` (9 x 10240 floats) is always carved and zeroed | CT-ok | Fixed ~360 KB per session, allocated even with no PLE. Harmless but dead. |
|
||||
| 30 | include/strata/core/layer.hpp:524-587 and src/core/layer.cpp:1192-1229 | PLE runs only at `layer == 1`, and only when `ple != nullptr && ple->ready()` | RT | PLE is optional in the block. See rows 62 to 66 for what forces it on. |
|
||||
| 31 | src/core/layer.cpp:355 | `moe_route` requires `1 <= k <= 64`; `moe_finish`/`moe_combine_parts` the same (456, 472) | RT | K = 8 is fine. |
|
||||
| 32 | src/core/layer.cpp:370 | Native fused router only when `n_expert == 512 && k == 10`, else generic `router_top10` | RT | Guarded at runtime. 256/8 takes the generic kernel (row 87). |
|
||||
| 33 | src/core/layer.cpp:396 | `moe_route_window` batched path excluded when native router active at 512/10 | RT | Same guard. |
|
||||
| 34 | src/core/layer.cpp:335-354 | `moe_buffers_*` sized from `n_expert`, `k`, `n_ff` | RT | |
|
||||
| 35 | src/core/layer.cpp:418-451 (`moe_shared`) | Shared expert has a sigmoid scalar gate `ffn_gate_inp_shexp` that must be engine form BF16 (`Bf16InF32`); the three projections need S-forms | ST | Qwen3.6 has the same scalar gate. Its GGUF dtype (F32 or BF16) has to match what the loader produces; see the tensor tables below. |
|
||||
| 36 | src/core/layer.cpp:223-333 (`gdn_layer`) | Sizes from `g.ssm_*`; recurrence head pairing is `head % h_k` | RT | Matches ggml `repeat` tiling. Needs `h_v % h_k == 0` (32 % 16 = 0). |
|
||||
| 37 | src/core/layer.cpp:247-248 | Fused conv path requires `d_conv == 4 && state_size == 128`; fused step requires `state_size == 128` (306) | CT-ok | Qwen3.6 matches. |
|
||||
| 38 | src/core/layer.cpp:276 | `scale_inplace(b.h, qk, 1/sqrt(S))` on the legacy (non-native) path | RT | |
|
||||
| 39 | src/core/layer.cpp:288-318 and kernels (rows 76-79) | GDN output gate is `rms_norm(o) * ssm_norm * sigmoid(z)` | **ST / CT** | **Qwen3.6 uses SiLU(z), not sigmoid(z).** llama.cpp qwen35moe.cpp:273 `ggml_silu(gate)`, qwen4exp.cpp:481 says "the one numerical difference from Qwen3.5's GDN". The layer.hpp:16 comment records it. This is the only numerical (not geometric) GDN difference. |
|
||||
| 40 | src/core/layer.cpp:505 (`qsa_shapes`) | Starts from `qsa_real_shapes()` then overrides `n_head`, `n_head_kv`, `head_dim`, `idx_*` from `ModelGeometry` | RT / CT | `n_rot = 64`, `idx_block = 4`, `idx_top_k = 2048`, `page_size = 4` stay compile-time (rows 41 to 44). `n_rot 64` matches Qwen3.6 (0.25 * 256). |
|
||||
| 41 | include/strata/kernels/qsa.hpp:98-113 (`qsa_real_shapes`) | `n_head 24`, `idx_n_head 4`, `idx_dim 128`, `idx_block 4`, `idx_top_k 2048`, `page_size 4` | CT | Used by layer.cpp:505, mtp.cpp:71, verify.cpp:~100, prefill.cpp:862 etc. |
|
||||
| 42 | include/strata/kernels/qsa.hpp:144-147, 282 | `qsa_selection_width = min(n_kv, idx_top_k + idx_block - 1)`; `kTopkMaxCells = 32768` | ST | Attention reads only the selected cells, via `ids`. With the indexer absent there is no selection, so every cell must attend. |
|
||||
| 43 | src/core/layer.cpp:559-575, 761-790 | `qsa_state_bytes` / `qsa_buffers_bytes` include `idx_pooled`, `idx_tail`, `idx_dead`, `pooled_rows = max_cells/idx_block + 2`, indexer scratch, `cell_scores` | ST | The KV state always carries indexer state (about `max_cells/4 * 128 * 4` B per layer). The drafter already passes `ring_cells > 0` for a state "which has no indexer" (layer.cpp:527-531, `pooled_rows = 2`). |
|
||||
| 44 | src/core/layer.cpp:876-1019 (`qsa_layer`) | Always runs: `indexer.k_proj` BF16 projection (962), indexer key append (945-948), `indexer.q_proj` + norm + rope (962-964), block scores + top-k (966-975), KV resolve, gather/attend over the selected `ids` | ST | The indexer is not optional in this function. It requires `indexer.{k,q}_proj.weight` BF16 and `indexer.{k,q}_norm.weight` (line 891 and the `Req` list). A dense path would skip steps 3, 5-indexer, 7, 8-score/select and attend over `0..n_kv`. |
|
||||
| 45 | src/core/layer.cpp:891-897 | `w_idxk = v.get("indexer.k_proj.weight")` and `w_idxq` are dereferenced, with a BF16 form check | ST | Null here is an error, not a skip. |
|
||||
| 46 | src/core/layer.cpp:938-1010 | KV in 4 formats (fp16 / int8 / q4_0 / k8v4), hybrid rotations (`fwht256`), paged pools | RT | `head_dim 256` only (kv_q4.cu:176). Same for Qwen3.6. |
|
||||
| 47 | src/core/layer.cpp:556 | `qsa_kv_resident_min() = 20480` cells | CT-ok | Streaming floor. Independent of geometry. |
|
||||
|
||||
## C. Loader, layout, metadata
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 48 | src/core/layout.cpp:50-80 | `check_one` requires per layer: `hc_attn_{down,up,inject}`, `hc_ffn_{down,up,inject}` with `hc_dim x hc_lr` shapes | ST | `blk.N.hc_*` do not exist in a Qwen3.6 GGUF. |
|
||||
| 49 | src/core/layout.cpp:60-63 | `ffn_gate_inp [n_embd, n_expert]`, `ffn_{gate,up}_shexp [n_embd, n_ff]`, `ffn_down_shexp [n_ff, n_embd]` | RT | Use `ModelGeometry`. |
|
||||
| 50 | src/core/layout.cpp:65-70 | GDN: `attn_qkv [n_embd, conv_channels]`, `attn_gate [n_embd, value_dim]`, `ssm_out [value_dim, n_embd]`, `ssm_conv1d [d_conv, channels]`, `ssm_alpha/beta [n_embd, v_heads]` | RT | Same orientation as llama.cpp qwen35moe. |
|
||||
| 51 | src/core/layout.cpp:72-79 | Attention: `attn_q [n_embd, 2*n_head*head_dim]`, `attn_k/v [n_embd, n_kv*head_dim]`, `attn_output`, and `indexer.q_proj`, `indexer.k_proj` | RT / ST | Attention shapes RT. The two indexer tensors are ST (required). |
|
||||
| 52 | src/core/layout.cpp:97-106 | 1-D set: `hc_attn_norm`, `hc_ffn_norm` (`hc_dim`, F32), `ffn_gate_inp_shexp` (BF16), `ssm_a`, `ssm_dt.bias`, `ssm_norm`, `attn_q_norm`, `attn_k_norm`, `indexer.q_norm`, `indexer.k_norm` | ST | Same split as rows 48 and 51. |
|
||||
| 53 | src/core/layout.cpp:162-169 | `check_all` counts `g.n_qsa_layers()` / `g.n_gdn_layers()` | RT | |
|
||||
| 54 | src/core/layout.cpp:141, 149; layout.hpp:91 | `check_layer` / `check_all` have no call site in src/ | n/a | Grep finds none. The shape assertions are not enforced at load in this tree. Parity tools outside src/ may call them. |
|
||||
| 55 | include/strata/core/layout.hpp:63 | `is_qsa_layer = layer % interval == interval - 1` | RT | Layers 3, 7, ..., 39 for Qwen3.6. |
|
||||
| 56 | src/core/weights.cpp:91, 123, 146-191 | Loads whatever `<pack>/index.txt` lists (19 fields per row), into an arena | RT | Name-driven and shape-driven. The model-specific part is the pack builder (`tools/pack_index.py`, `tools/iq_pack.py`, not in this tree). |
|
||||
| 57 | src/core/native_dense.cpp:31-33 | Native dense GGUF suffixes: `.attn_qkv`, `.attn_gate`, `.ssm_out`, `.attn_q`, `.attn_k`, `.attn_v`, `.attn_output`, `.ffn_{gate,up,down}_shexp` (all `.weight`) | RT | The names match llama.cpp. A fused attention-layer `attn_qkv` (a llama.cpp option) would not match the engine's separate q/k/v. |
|
||||
| 58 | src/core/native_dense.cpp:102-104, 169-172 | Needs `general.architecture` passing `check_architecture`; each native tensor must already be in the canonical table with a matching 2-D shape | ST | See row 18. Also requires a pack index entry per tensor. |
|
||||
| 59 | src/core/native_head.cpp:29, 32-39 | `output.weight` must be `[n_in, n_out]`; `n_in % 256 == 0` | RT | 2048 % 256 = 0. `n_out` comes from the pack. |
|
||||
| 60 | src/core/native_head.cpp:108-128 | `token_embd.weight` must be `[n_embd, n_vocab]` | RT | Caller passes the literals from row 11. |
|
||||
| 61 | src/core/layer.cpp:1033-1087 (`embed_row`) | `w->ne0 != g.n_embd` is an error | RT | Follows `g.n_embd`. |
|
||||
|
||||
## D. PLE and the n-gram table
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 62 | src/program/generate.cpp:1800-1815 | `--native` requires `--ple-gguf` (or a shard holding `per_layer_token_embd.weight`); `--native` plus `--no-ple` is refused | ST | Qwen3.6 has no such tensor, so every native launch is refused. |
|
||||
| 63 | src/program/generate.cpp:1843-1855 | Without `--native`, `--ple-gguf` is "required"; `--no-ple` is called a "diagnostic ablation" | ST | PLE is mandatory at the CLI, optional in the kernels. |
|
||||
| 64 | src/program/generate.cpp:2395-2500 | When a PLE table is opened, the pack must contain `blk.1.ple_{key,value,norm_key,norm_query,norm_conv,conv1d}.weight` or the launch fails ("a DIFFERENT MODEL") | ST | Skipped when `--no-ple`. |
|
||||
| 65 | src/core/native_dense.cpp:29-30, 65-73, 156; generate.cpp:2207-2209, 1956 | Special-casing of `blk.1.ple_key.weight` | ST | Dead without PLE. |
|
||||
| 66 | include/strata/kernels/ngram.hpp:31-49 | `NG_N_EMBD 2560`, `PLE_HEAD_DIM 160`, `NGRAM_SIZE 3`, `HEADS_PER_NGRAM 8`, `PLE_N_HEADS 16`, `NG_HC 4`, `NG_HC_DIM 10240`, `NG_HIST 9`, `PLE_TABLE_ROWS 320001536`, `PLE_EOS_TOKEN_ID 248044` | CT-ok | All PLE-only. Dead if PLE is skipped. `NG_HIST` x `NG_HC_DIM` still sizes a session buffer (row 29). |
|
||||
| 67 | src/kernels/cuda/ple.cu:238; native_ple_postops.cu:35, 98; include/strata/kernels/native_ple_postops.hpp:6 | `static_assert(NG_N_EMBD == 2560 ...)`; `N = 2560, H = 4, HISTORY = 9` | CT-ok | Compiles regardless; never launched without PLE. |
|
||||
| 68 | src/prefill/prefill.cpp:543-549, 806-814, 924-925, 1401, 1590-1599, 1683-1714, 1920 | Prefill allocates `ple_emb`, `ple_norm`, pinned PLE staging; runs the PLE at layer 1 when `ss.ple.ready()` | RT | Guarded by `ple_on`. Buffers are still allocated (about `T * 2560 * 4`, `NG_HC_DIM * 4`). |
|
||||
| 69 | src/core/verify.cpp:370, 408, 559, 636-675, 1311, 1405 | Verify window stages and runs the PLE at layer 1 when `ss.ple.ready() && ple_stage()` | RT | Guarded. |
|
||||
|
||||
## E. MTP drafter (`mtp.cpp`, `mtp.hpp`)
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 70 | src/core/mtp.cpp:150-216 | Loads `<rt_dir>/dense.txt`, `dense.bin`, `experts.bin` produced by `tools/mtp_rt.py` (not in this tree), all dense weights as Q8_0 | ST | The drafter does not read the GGUF. |
|
||||
| 71 | src/core/mtp.cpp:210-212 | Required tensors: `fc_embedding.weight`, `fc_hidden.weight`, `self_attn.{q,k,v,o}_proj.weight`, `mlp.shared_expert.{gate,up,down}_proj.weight` | ST | vLLM-style names. Qwen3.6's MTP has one `nextn.eh_proj [2*n_embd, n_embd]` over `[enorm(emb), hnorm(h)]`, not two separate projections. |
|
||||
| 72 | src/core/mtp.cpp:488-495 | `pre_fc_norm_embedding` -> `fc_embedding`; `pre_fc_norm_hidden` over `hc*n_embd` -> `fc_hidden` per stream -> `R = h + e` broadcast over `hc` streams | ST | Qwen3.6: `eh_proj(concat(enorm(emb), hnorm(h)))`, one stream. |
|
||||
| 73 | src/core/mtp.cpp:503-507, 564-568, 613-625 | Three hyper-connection groups: `attn_hyper_connection.*`, `mlp_hyper_connection.*`, `hyper_connection_mixer.*` | ST | Same gated-residual structure as rows 21-23. |
|
||||
| 74 | src/core/mtp.cpp:191, 200, 306-308, 579 | Drafter experts are `n_expert * cpu::BLOB` bytes in VRAM, canonical Q2_0 at 2560/640, run through `moe_group_resident` | CT | `BLOB = 1,382,400`. Qwen3.6 Q2_0 blob would be `3 * 2048 * 512 * 18/64` = 884,736 B. Message text says "the 512 experts do not fit". |
|
||||
| 75 | src/core/mtp.cpp:575, 598 | Draft router `mlp.gate.weight` BF16 `[n_embd, n_expert]`; `mlp.shared_expert_gate.weight` BF16 | RT | Shape-driven. |
|
||||
| 76 | src/core/mtp.cpp:71-78, 218-249 | Draft KV is dense attention (no indexer state read), shapes from `ModelGeometry` | RT | The header says it is "identical to the model's sparse selection below 2,051 cells". The only existing dense-attention path. |
|
||||
| 77 | src/core/mtp.cpp:428-454 | Head is the main `output.weight`; `n_vocab_ = wo->ne1`; optional `draft_vocab.bin` subset | RT | Vocabulary size is a runtime value. Subset files (`data/draft_vocab_*.bin`) are token ids into the same 248,320 vocabulary. |
|
||||
| 78 | src/core/mtp.cpp:477, 488 | Draft embeds from `token_embd.weight` | RT | |
|
||||
| 79 | src/core/mtp.cpp:251-268 | Buffers from `g.hc`, `g.hc_lr`, `g.n_head` | RT | |
|
||||
| 80 | src/prefill/prefill.cpp:972-1086 | MTP prefill reads `attn_hyper_connection.hc_norm.weight`, uses `LR`, `HC`, `fc_hidden` per stream | ST / CT | Same vLLM-style structure as row 72. |
|
||||
|
||||
## F. GDN kernels
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 81 | src/kernels/cuda/native_gdn.cu:37, 100-102, 117 | `S = 128`; grid `h_v` x `S/4`; requires `h_v % h_k == 0`, `h_v <= 65535` | RT | Heads from `GdnShapes`. State layout `(S, h_v, S)`. |
|
||||
| 82 | src/kernels/cuda/native_gdn.cu:51 | `q_head = head % h_k` | RT | Modulo pairing. |
|
||||
| 83 | src/kernels/cuda/fused_gdn.cu:12-14, 22-24, 127-129, 148-153 | `S = 128`, `RG = 4`; grid `h_v`; `qk_heads` blocks for conv+L2; `h_v % h_k == 0` | RT | |
|
||||
| 84 | src/kernels/cuda/gdn.cu:46-59, 156 | `MAX_H = 8` heads per block, `S <= 128` | RT | Legacy path; only a performance shape. |
|
||||
| 85 | src/kernels/cuda/gdn.cu:148 | `y = o * rms * ssm_norm * sigmoid_f(z)` | **CT** | **SiLU for Qwen3.6.** See row 39. |
|
||||
| 86 | src/kernels/cuda/fused_gdn.cu:69 | `... * (1/(1+exp(-zz)))` in `gdn_step_norm_kernel` | **CT** | **SiLU for Qwen3.6.** The default decode path for native packs. |
|
||||
| 87 | src/kernels/cuda/native_gdn_preprocess.cu:110-112 | `weighted * sigmoid(z)` in the out-norm kernel | **CT** | **SiLU for Qwen3.6.** The same file's `conv_silu` (53-67) and `beta_sigmoid` (86-88) are correct for both models. |
|
||||
| 88 | src/prefill/kernels.cu:324, 612 | `sigm(z)` in `gdn_rec_kernel` and `gdn_out_norm_kernel` | **CT** | **SiLU for Qwen3.6.** Prompt path. |
|
||||
| 89 | src/prefill/kernels.cu:18-19 | `N = 2560, HC = 4, D = N*HC, LR = 320`; `S = 128, HK = 16, HV = 48, C = 10240` | CT | Constants for every prompt-path GDN, GR and gate kernel. |
|
||||
| 90 | src/prefill/kernels.cu:211-215, 285-304, 345-364, 387-432, 478-570, 893-924 | GDN prompt kernels index with `HV`, `HK`, `C`; launched `<<<HV, ...>>>`, `<<<HV*NCB>>>`, `<<<HK*NCB>>>` | CT | Includes `VPK = HV/HK = 3` value heads per key head (478): 2 for Qwen3.6. `gdn_rec_kh_kernel` is specialised on it. |
|
||||
| 91 | src/prefill/gdn_rec_parity.cu | Parity harness for the above | CT | Mirrors the same constants. |
|
||||
| 92 | include/strata/kernels/gdn.hpp:11, 64; layer.hpp:10, 21, 23, 546 | Comments cite 10240 / 48 / 2560 | n/a | Comments only. |
|
||||
|
||||
## G. Attention kernels (the QSA path)
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 93 | src/kernels/cuda/qsa_decode_attn.cu:16-17, 110, 272, 453, 497 | `HD = 256`, `G = 12` (query heads per KV head); refuses with `exit(1)` unless `n_head == 12 * n_head_kv` | CT | The main decode kernel. Qwen3.6 has G = 8. |
|
||||
| 94 | src/kernels/cuda/qsa_prompt_attn.cu:21-22, 115-116, 1442-1447 | `HD = 256`, `G = 12`; refuses unless `n_head == 12 * n_head_kv` | CT | The prompt attention kernels (tensor-core). |
|
||||
| 95 | src/kernels/cuda/native_flash_attn.cu:55, 196-197, 206 | `kv = head / 12`; refuses unless `n_head == 24 && n_head_kv == 2 && head_dim == 256`; grid 24; context 1..256 | CT | Short-context adapter only. |
|
||||
| 96 | src/kernels/cuda/qsa.cu:96 | Generic `qsa_attend`/`kv_append`/`kv_gather`; requires `n_head % n_head_kv == 0` | RT | Reference-quality path. |
|
||||
| 97 | src/kernels/cuda/native_rope.cu:121 | `head_dim in {128, 256}`, `n_rot == 64` | CT-ok | Matches Qwen3.6 (partial rotary 0.25 of 256). |
|
||||
| 98 | include/strata/kernels/mrope.hpp:3-12 | Interleaved M-RoPE sections 11/11/10/0; text has `t = h = w` | CT-ok | Qwen3.6 uses the same sections. |
|
||||
| 99 | src/kernels/cuda/native_qsa_score.cu:31, 194 | Indexer: `D = 128, HEADS = 4, R = 4`, `idx_top_k == 2048` | ST | Indexer-only. Not reachable without the indexer. |
|
||||
| 100 | src/kernels/cuda/native_qsa_indexer.cu:35, 231, 259 | `D = 128, R = 4, ROT = 64` | ST | Indexer-only. |
|
||||
| 101 | src/kernels/cuda/qsa_select.cu:17-19, 161-165, 467-475, 1081, 1115, 1220 | `IDX_DIM 128`, `IDX_HEADS 4`, `R 4`; requires `cap >= qsa_selection_width(kTopkMaxCells, s)` | ST | Indexer-only. With the indexer absent nothing here runs, and nothing else produces the `ids` that `qsa_decode_attn` consumes. |
|
||||
| 102 | src/kernels/cuda/qsa_decode_attn.cu | The kernel gathers K/V through `ids` and `pools.page_table`, so it is selection-agnostic | RT | An identity `ids` would attend over every cell. No other dense decode kernel exists. |
|
||||
| 103 | src/kernels/cuda/kv_q4.cu:176, kv_q8.cu | `head_dim == 256` | CT-ok | Matches Qwen3.6. |
|
||||
| 104 | src/kernels/cuda/kv_stream.cu:23 | `RT = 1024` resolve block | CT-ok | Streaming resolve granularity. Reads `ids`. |
|
||||
| 105 | src/prefill/kernels.cu:752-761, 1016, 1020 | `split_q_kernel`, `gate_attn_kernel`: `T * 24 * 256`, `24 * 512` | CT | Prompt-path q/gate split and gate. 16 heads for Qwen3.6. |
|
||||
| 106 | src/prefill/prefill.cpp:649-650, 883-884 | `T * 12288` (= 24 * 512) for `Qf`; `T * 512` for `Kc/Vc` (2*256, unchanged); `T * ZV` for `q` and attn; `T * 128`, `T * 512` for `idx_raw`, `q_idx` | CT | `12288` and `ZV = 6144` must change. `512` for K/V stays. The two indexer buffers are dead without the indexer. |
|
||||
|
||||
## H. Experts, router, shared expert
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 107 | include/strata/kernels/cpu/expert.hpp:34-36, 40-47 | `H = 2560`, `FF = 640`, `NE = 512`, `BLOB = 1,382,400`, `ROW_GU`, `SC_GU` | CT | Canonical Q2_0 blob geometry. Canonical only. Used by the rows below. |
|
||||
| 108 | src/kernels/cpu/expert_layout.cpp:284 | `native_fmt(gt, dt, H, FF, f, err)` | **CT** | **The one compile-time leak in the native-pack path.** The layout loader builds each layer's `NativeFmt` with 2560/640 and then checks `f.bytes == blob`. A 2048/512 pack fails the "blob is X B but its formats make Y" check. |
|
||||
| 109 | src/kernels/cpu/expert_layout.cpp:233-244, 271 | `native_experts.txt` header "(n_expert N)" overrides `n_expert`; absent file means canonical pack, total = `n_layers*n_expert*BLOB` | RT | |
|
||||
| 110 | include/strata/kernels/cpu/expert_layout.hpp:20, 32, 35-37 | `n_expert = NE` default, `max_blob = BLOB` default | CT-ok | Overwritten for native packs. |
|
||||
| 111 | include/strata/kernels/cpu/native_expert.hpp:17-19; src/kernels/cpu/native_expert.cpp:64 | `kNativeActBytes = 4096`, `kNativeHBytes = 1024` upper bounds, checked at layout time | CT-ok | 2048-wide Q8_K is 2336 B; 512-wide Q8_K is 584 B. Both fit. |
|
||||
| 112 | src/kernels/cpu/native_expert.cpp:40-60 | `native_fmt(gu_type, d_type, n_embd, n_ff)` is runtime; requires whole ggml blocks | RT | 2048 and 512 are multiples of 256 and 32. K-quants and Q8_K activations work for n_ff = 512 (unlike 640). |
|
||||
| 113 | src/core/expert_source.cpp:1863-1868 (`expert_pool_dispatch`) | Refuses `n_embd != H` ("compiled for a 2560-wide activation") | CT | Canonical single-token path only. |
|
||||
| 114 | src/core/expert_source.cpp:1869-1875 | `expert_pool_dispatch` refuses a native pack outright ("single-token expert path does not take a native pack") | **ST** | **Native-pack experts run only in verify windows.** generate.cpp:~2180 also requires `--spec T >= 2` and `--prefill`. Every decoded token therefore goes through verify.cpp. |
|
||||
| 115 | src/core/expert_source.cpp:367-376, 2328; include/strata/core/expert_source.hpp:241 | Canonical size checks with `BLOB`; `ExpertDispatch::n_expert = cpu::NE`; hit path uses `cpu::H` | CT | Canonical only. `n_expert` is overwritten at generate.cpp:3683. |
|
||||
| 116 | src/core/expert_source.cpp:2475-2500 (`check_experts_gguf`) | Native experts are read from `blk.N.ffn_{gate,up,down}_exps.weight` as three separate tensors, each `[cols, rows, n_expert]` | ST | llama.cpp may fuse gate and up into `ffn_gate_up_exps` (`create_tensor_gate_up_exps`, llama-model.cpp:3253). The engine accepts only the separate form. |
|
||||
| 117 | src/core/expert_source.cpp:1979-1980 | `MAXT * 10 <= kMaxWindowEntries (128)` | CT-ok | 8 * 10 = 80; with k = 8 it is 64. |
|
||||
| 118 | src/core/expert_cache.cpp, include/strata/core/expert_cache.hpp | Slots, residency `[n_layers * n_expert]`, profile file `(n_layers, n_expert)` header, `n_layers/n_expert <= 65535` | RT | All sizes passed in. The profile header is checked against `(n_layers, n_expert)` (cache.cpp:43). |
|
||||
| 119 | src/kernels/cuda/iq_kernels.cu:1076-1140, 2543 | Native GPU expert kernels read `L.n_embd` and `L.n_ff` per layer; the fast sub-warp paths apply only when `n_ff == 640` (else 8-row fallback) | RT | Runtime guard. |
|
||||
| 120 | src/kernels/cuda/iq_kernels.cu:309-350, 512-518 | Unsloth UD-Q4_K_XL expert types already supported: Q4_K / Q5_K gate-up, Q5_1 / Q8_0 down | RT | Native GPU expert dequant kernels exist for the Qwen3.6 UD quant family. |
|
||||
| 121 | src/kernels/cuda/s2_expert_grouped.cu:37-46, 139-195, 301-346 | `H = 2560`, `FF = 640`, `ROW_GU`, `SC_GU`, blob offsets | CT | Canonical Q2_0 VRAM-hit kernels. Used for the MTP drafter's experts (row 74), not for native packs. |
|
||||
| 122 | src/core/remote_experts.cpp:16-18, 246; src/core/peer_experts.cpp:25-26, 115, 130; src/core/remote_expert_opt.cu:13-14 | `H`, `FF` from `cpu::`, `CAP = MAXT * 10`, `k != 10` refused | CT | Multi-GPU expert tiers. Out of scope for a single card. |
|
||||
| 123 | src/program/generate.cpp:3721 | `moe_hit_grouped_scratch_bytes(K, g.n_embd, cpu::FF)` | CT-ok | Over-allocates by 640 vs 512. |
|
||||
| 124 | src/kernels/cuda/router_top10.cu:65-215; include/strata/kernels/router_top10.hpp:21 | Generic top-k softmax router: `n_expert <= 512`, `k <= 32`, runtime `n_expert` and `k` | RT | Handles 256 / 8. |
|
||||
| 125 | src/kernels/cuda/native_router.cu:49, 54, 73, 97, 111-122 | Fused pinned router: `512` logits, `10` outputs, `REG 16`, hard-coded in the kernel and the validity checks | CT | Used only when `n_expert == 512 && k == 10` (row 32). Otherwise bypassed. |
|
||||
| 126 | src/kernels/cuda/native_moe.cu:62-63, 79-80 | `native_moe_combine` requires `1 <= k <= 15` | RT | |
|
||||
| 127 | src/kernels/cuda/shared_expert.cu:191, 237-239, 325-328 | `n_tok 1..8`; Q8_K activation needs `n_ff % 256 == 0` | RT | 640 failed this; 512 passes. Header comments in s_gemv.hpp:122-124 and layer.cpp:419-437 ("Q8_K is structurally impossible") describe Flash-Next only. |
|
||||
| 128 | src/prefill/kernels.cu:616-657, 928-936 | Prompt `route_kernel<REG>`: `REG 16` for 512, `REG 8` for 256; rank loop `< 10`, writes `ids[t*10 + rank]`, `lane < 10` | CT | A 256 variant exists, but top-10 is baked into the kernel. |
|
||||
| 129 | src/prefill/kernels.cu:660-692, 947, 951; moe_fused.cu:46-53, 199-203, 343; moe_mmq.cu:60-75, 249 | Canonical Q2_0 blob dequant and fused kernels: `1280 * 640`, `2560 * 160`, `n * 640`, `10 * AB` | CT | Canonical only. |
|
||||
| 130 | src/prefill/moe_fused_iq.cu:59 | `GU_ROWS_K = 2560, D_ROWS_K = 640` | CT | Native-pack fused prompt MoE. Used as K of gate/up and of down. |
|
||||
| 131 | src/prefill/prefill.cpp:90-91 | `N = 2560, HC = 4, D = N*HC, LR = 320, K = 10, NE = 512; C = 10240, ZV = 6144, HV = 48` | CT | File-wide constants. |
|
||||
| 132 | src/prefill/prefill.cpp:737 | `Prefill::init` refuses unless `g.n_embd == N && g.hc == HC && g.hc_lr == LR && ss.k == K` | CT / ST | Hard refusal; every chunked-prefill launch fails on Qwen3.6. |
|
||||
| 133 | src/prefill/prefill.cpp:681-685, 704-721, 896-907, 1294-1322, 1391 | Prompt MoE buffers: `T*K*1280`, `T*K*640`, `q8_bytes(.., 640)`, `1280 * 2560`, `2560 * 640`, `RP = 48` (1303) | CT | `1280 = 2*n_ff`, `640 = n_ff`, `2560 = n_embd`. |
|
||||
| 134 | src/prefill/prefill.cpp:1724 and loops | Iterates `g.n_layers` and `is_qsa_layer` | RT | |
|
||||
| 135 | src/prefill/prefill.cpp:854-856, 1000-1026, 1375-1380 | `grs`, `gated`, `inj`, `xq`, `ident` sized from `HC`, `D`, `LR` | CT | Hyper-connection buffers in prefill. |
|
||||
| 136 | include/strata/prefill/kernels.hpp:15-16, 40, 52, 54, 58, 79 | Declarations documented as `2560 / 4 / 320`, `48 v heads`, `512, top-10`, `[1280, 2560]`, `640`, `[T, 24, 512]` | CT | Comments describing the constants above. |
|
||||
|
||||
## I. Hyper-connection (gated residual) kernels
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 137 | src/kernels/cuda/fused_gr.cu:20-28, 253-254, 320-321, 1164-1166 | `N = 2560, HC = 4, LR = 320, D = 10240`; `DOWN_BLOCKS = LR/8`, `UP_BLOCKS = N/32`, `UPM_BLOCKS = N/16`; `fused_gr_supported()` returns `n_embd == N && hc == HC && hc_lr == LR` | CT | Default decode and verify GR kernels. |
|
||||
| 138 | src/core/layer.cpp:1195, 1319-1342, verify.cpp:336 | `fused = g_fused_gr && ... fused_gr_supported(...)`; verify refuses without it | CT / ST | Row 142. |
|
||||
| 139 | src/kernels/cuda/gr.cu, native_gr_norm.cu, native_gr_postops.cu | Generic `GrShapes{n_embd, hc, hc_lr}` unfused path | RT | The generic GR is runtime-shaped, but its semantics (down/up/inject mixing) are the hyper-connection. |
|
||||
| 140 | src/kernels/cuda/cvec.cu:11-17; verify_kernels.cu:256-291 (`broadcast_streams`, `add_streams_broadcast`) | Control-vector apply on `hc*n_embd`; stream broadcast | RT | `MAXK = 16` supports `n_embd <= 4096`. |
|
||||
|
||||
## J. Verify window (`verify.cpp`) and the speculation protocol
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 141 | src/core/verify.cpp:331-334 and layer.cpp:476-486 (`layer_verify_compatible`) | The verify window needs native BF16 projections, fused GR, fused native GDN, split-K decode attention, block top-k selection, **native QSA indexer** | ST | Verify is the only decode path for native packs (row 114). It cannot be built on a layer that has no fused GR and no indexer. |
|
||||
| 142 | src/core/verify.cpp:336-340 | Refuses unless `fused_gr_supported && ss.k == 10 && ssm_state_size == 128 && ssm_d_conv == 4` ("geometry differs from the artifact's") | CT / ST | |
|
||||
| 143 | src/core/verify.cpp:356-434 | Buffers `R_ (T*HC*N)`, `inj_`, `lo_ (T*hc_lr)`, `xn_ (T*HC*N)`, `idx_raw_L_`, `qidx_`, `tail_snap_` | RT / ST | Sized from `g.hc`, `g.hc_lr`, `idx_*`. |
|
||||
| 144 | src/core/verify.cpp:550-559 | `IQ = idx_q_heads`, `ID = idx_key_dim`, `NE = n_expert`, `TS = (idx_block-1)*ID` | RT | |
|
||||
| 145 | src/core/verify.cpp:757-761, 772-870, 1271-1311 | Attention step: `need(v, "indexer.k_proj.weight")`, `indexer.q_proj`, `indexer.q_norm`, `indexer.k_norm`; indexer append, block scores, top-k per window row; commit restores the indexer tail | ST | Same as row 44, for the multi-token path. |
|
||||
| 146 | src/core/verify.cpp:916 | Batched native router only when `NE == 512 && K == 10` | RT | Guarded. |
|
||||
| 147 | src/core/verify.cpp:1123-1125 | Head mix needs `output_hc_{norm,down,up}.weight` | ST | Row 23. |
|
||||
| 148 | src/core/verify.cpp:347-349 | `n_vocab_ = output.weight.ne1` | RT | |
|
||||
| 149 | include/strata/kernels/verify_kernels.hpp:21 | `kVerifyMaxT = 8` | CT-ok | Draft window cap. |
|
||||
| 150 | src/kernels/cuda/verify_kernels.cu:366, 397-401, 506 | Grid `48 * 8`; `kVerifyMaxT * 10 <= kResidentPlanMax` | CT-ok | The 48 is a block count, not a layer count. |
|
||||
|
||||
## K. Vocabulary, sampler, metadata keys
|
||||
|
||||
| # | file:line | Assumption | Class | Note |
|
||||
|---|---|---|---|---|
|
||||
| 151 | src/kernels/cuda/sampler.cu:102-700 | `n_vocab` is a kernel argument everywhere; the split top-k merge handles `n_vocab <= 262,144` (607) | RT | 248,320 fits. |
|
||||
| 152 | src/program/generate.cpp:479-481 | Default EOS ids `{248044, 248046}` | CT-ok | Same tokenizer; override with `--eos-ids`. |
|
||||
| 153 | include/strata/artifact/gguf_reader.hpp:581-597 | All keys read use the `qwen4exp.` prefix | CT | Row 18. The Qwen3.6 GGUF uses `qwen35moe.*`. Also needed and not read anywhere: `qwen35moe.ssm.{conv_kernel,inner_size,state_size,time_step_rank,group_count}`, `.expert_feed_forward_length`, `.expert_shared_feed_forward_length`, `.full_attention_interval`, `.rope.dimension_sections`, `.nextn_predict_layers`. |
|
||||
| 154 | frontend/ | Tokenizer, template, tool-call parser, vision | n/a | Model-agnostic per the plan. Not part of this inventory. |
|
||||
|
||||
## Tensor names the loader expects (engine side) against llama.cpp qwen35moe
|
||||
|
||||
Engine names come from layout.cpp:50-106, layer.cpp, native_dense.cpp:31-33 and expert_source.cpp:2491.
|
||||
llama.cpp names come from `third_party/llama.cpp/src/models/qwen35moe.cpp:43-138` and `src/llama-arch.cpp:435-587`
|
||||
(pinned commit 3cf0325).
|
||||
|
||||
**One GDN layer, `blk.N.`**
|
||||
|
||||
| Engine expects | Shape / form | llama.cpp qwen35moe | Match |
|
||||
|---|---|---|---|
|
||||
| `hc_attn_norm.weight`, `hc_attn_down.weight`, `hc_attn_up.weight`, `hc_attn_inject.weight` | `[hc_dim]` F32; BF16 | none | **Engine-only (hyper-connection)** |
|
||||
| `hc_ffn_norm.weight`, `hc_ffn_down.weight`, `hc_ffn_up.weight`, `hc_ffn_inject.weight` | same | none | **Engine-only** |
|
||||
| (none) | | `attn_norm.weight` `[n_embd]` | **llama.cpp-only** |
|
||||
| (none) | | `post_attention_norm.weight` `[n_embd]` (pre-FFN norm; there is no `ffn_norm`) | **llama.cpp-only** |
|
||||
| `attn_qkv.weight` | `[n_embd, conv_channels]` | `attn_qkv.weight` `[n_embd, 2*key_dim + value_dim]` | yes |
|
||||
| `attn_gate.weight` | `[n_embd, value_dim]` | `attn_gate.weight` | yes |
|
||||
| `ssm_conv1d.weight` | `[d_conv, conv_channels]` F32 | `ssm_conv1d.weight` | yes |
|
||||
| `ssm_alpha.weight`, `ssm_beta.weight` | `[n_embd, v_heads]` BF16 | same names, `{n_embd, n_v_heads}` | yes, dtype to confirm |
|
||||
| `ssm_a` | `[v_heads]` F32 | `ssm_a` (no `.weight`) | yes |
|
||||
| `ssm_dt.bias` | `[v_heads]` F32 | `ssm_dt.bias` | yes |
|
||||
| `ssm_norm.weight` | `[128]` F32 | `ssm_norm.weight` `{head_v_dim}` | yes |
|
||||
| `ssm_out.weight` | `[value_dim, n_embd]` | `ssm_out.weight` | yes |
|
||||
| `ffn_gate_inp.weight` | `[n_embd, n_expert]` BF16 | same | yes, dtype to confirm |
|
||||
| `ffn_gate_exps.weight`, `ffn_up_exps.weight`, `ffn_down_exps.weight` | `[n_embd, n_ff, n_expert]` x2, `[n_ff, n_embd, n_expert]` | same, or fused `ffn_gate_up_exps.weight` `[n_embd, 2*n_ff, n_expert]` | yes if unfused |
|
||||
| `ffn_gate_shexp.weight`, `ffn_up_shexp.weight`, `ffn_down_shexp.weight` | `[n_embd, n_ff]`, `[n_ff, n_embd]` | same | yes |
|
||||
| `ffn_gate_inp_shexp.weight` | `[n_embd]` engine form BF16 | `ffn_gate_inp_shexp.weight` `{n_embd}` | yes, dtype to confirm |
|
||||
|
||||
**One attention layer, `blk.N.` (layers 3, 7, ..., 39)**
|
||||
|
||||
| Engine expects | Shape / form | llama.cpp qwen35moe | Match |
|
||||
|---|---|---|---|
|
||||
| the six `hc_*` tensors and two `hc_*_norm` as above | | none | **Engine-only** |
|
||||
| (none) | | `attn_norm.weight`, `post_attention_norm.weight` | **llama.cpp-only** |
|
||||
| `attn_q.weight` | `[n_embd, 2*n_head*head_dim]` (q then gate per head, interleaved) | `attn_q.weight` `{n_embd, head_dim*n_head*2}` | yes |
|
||||
| `attn_k.weight`, `attn_v.weight` | `[n_embd, n_kv*head_dim]` | same | yes, unless the GGUF fuses them into `attn_qkv.weight` (`create_tensor_qkv`) |
|
||||
| `attn_output.weight` | `[n_head*head_dim, n_embd]` | `attn_output.weight` | yes |
|
||||
| `attn_q_norm.weight`, `attn_k_norm.weight` | `[head_dim]` F32 | same | yes |
|
||||
| `indexer.q_proj.weight`, `indexer.k_proj.weight`, `indexer.q_norm.weight`, `indexer.k_norm.weight` | BF16 / F32 | none | **Engine-only (QSA indexer)** |
|
||||
| the same five MoE tensors, three shexp tensors, `ffn_gate_inp_shexp` as a GDN layer | | same | as above |
|
||||
|
||||
**Global tensors**
|
||||
|
||||
| Engine expects | llama.cpp qwen35moe |
|
||||
|---|---|
|
||||
| `token_embd.weight` `[n_embd, n_vocab]` | same |
|
||||
| `output.weight` `[n_embd, n_vocab]` (native head; mtp.cpp:428 and verify.cpp:347 read `ne1`) | `output.weight` (optional; falls back to `token_embd.weight`) |
|
||||
| `output_hc_norm.weight`, `output_hc_down.weight`, `output_hc_up.weight` | `output_norm.weight` `{n_embd}` |
|
||||
| `blk.1.ple_{key,value,norm_key,norm_query,norm_conv,conv1d}.weight` and `per_layer_token_embd.weight` | none |
|
||||
| MTP: `<rt_dir>/dense.txt` names `fc_embedding`, `fc_hidden`, `pre_fc_norm_embedding`, `pre_fc_norm_hidden`, `self_attn.*`, `mlp.*`, three `*hyper_connection*` groups | `blk.40.nextn.eh_proj.weight` `{2*n_embd, n_embd}`, `blk.40.nextn.enorm.weight`, `blk.40.nextn.hnorm.weight`, optional `blk.40.nextn.{embed_tokens,shared_head_head,shared_head_norm}.weight`, plus a full attention + MoE block under `blk.40.` (attn_norm, post_attention_norm, attn_q/k/v/output, attn_q_norm, attn_k_norm, ffn_gate_inp, ffn_*_exps, ffn_*_shexp, ffn_gate_inp_shexp) |
|
||||
|
||||
## Summary of which subsystems are runtime-parameterized
|
||||
|
||||
1. **Already parameterized:** the GDN decode kernels (state 128, head counts and head pairing by `h % h_k`, grids from `h_v`), the generic router, the shared expert (and 512 now satisfies its Q8_K rule), the native CPU and GPU expert kernels (`NativeFmt` and `L.n_embd`/`L.n_ff` per layer, UD-Q4_K_XL types already present), the expert cache, the weight loader, the sampler, `output.weight` and vocabulary size, and the drafter's dense-attention KV.
|
||||
2. **The geometry struct is never populated from the model.** Only `expert_count` and `expert_used_count` (and rope keys) are read, under a `qwen4exp.` prefix, and only with `--native`. `n_embd`, `n_layers`, head counts, `ssm.*` and `n_ff` stay at Flash-Next defaults. `check_architecture` refuses any other architecture string.
|
||||
3. **The gated residual is structural.** Every block, the output head, the verify window, the drafter and prefill assume `hc` streams with down/up/inject mixing. The fused kernels are hard-coded to 2560/4/320, and `hc = 1` has no plain-norm meaning. The plain `attn_norm`, `post_attention_norm` and `output_norm` tensors are never referenced.
|
||||
4. **Dense attention is structural.** `qsa_layer`, `verify.cpp`, the KV state size and the selection width all assume the indexer. The decode and prompt attention kernels are compile-time for group 12 (Qwen3.6 is 8) and the short-context kernel is compile-time for 24 heads. The attention kernel reads through `ids`, so it is selection-agnostic, but no producer of dense `ids` exists.
|
||||
5. **GDN output gate differs numerically:** Qwen3.6 applies SiLU(z) where the engine applies sigmoid(z) in four kernels (gdn.cu, fused_gdn.cu, native_gdn_preprocess.cu, prefill/kernels.cu). This is a semantic change, not a size change.
|
||||
6. **Native-pack decode is verify-window only.** The single-token expert dispatch refuses native packs, and the verify window demands fused GR, K = 10, and the native indexer. Any hc = 1 or dense-attention work has to land in verify.cpp as well as layer.cpp.
|
||||
7. **Prefill is the most compile-time-heavy subsystem.** `Prefill::init` refuses non-2560/4/320/10, and GDN, gate, split-q, route and MoE buffers all use literal constants (HV 48, 24 heads, 1280, 640, top-10).
|
||||
8. **One leak inside otherwise-runtime expert code:** `expert_layout.cpp:284` passes compile-time `H, FF` to `native_fmt`, so a 2048/512 pack fails the blob-size check.
|
||||
9. **PLE is optional in kernels but mandatory in the CLI.** `--native` refuses to start without `--ple-gguf`, and a table implies `blk.1.ple_*` tensors. Qwen3.6 has neither. A small session buffer (about 360 KB) is allocated regardless.
|
||||
10. **MTP drafter is separate from the GGUF** (Q8_0 `rt_dir` from `tools/mtp_rt.py`, canonical Q2_0 experts at 2560/640, three hyper-connection groups, two fc projections). It gets the canonical default geometry, not the target's. The `tools/` packers are not in this tree, so the pack and MTP tensor names are defined by scripts that were not inspected.
|
||||
@@ -0,0 +1,106 @@
|
||||
# Upstream Strata tooling the Qwen3.6 port needs back
|
||||
|
||||
Surveyed 2026-10-11. Read-only references:
|
||||
|
||||
- `/Users/robertkarl/Code/strata-upstream-6f32ec0`: exact snapshot, exported with `git archive 12a7825` from this repository's first commit ("Import Strata at 6f32ec0, unmodified"). Use this one.
|
||||
- `/Users/robertkarl/Code/strata-upstream`: a clone of `Niko1221/Strata` main (1859 commits). **Commit `6f32ec0` is not in the public history**: `git checkout` fails with "unable to read tree", so the pinned commit was force-rewritten or never public. Main still carries the same tooling and adds `bench/bench_vs_llama.py`.
|
||||
|
||||
Nothing was built. UnbiasedStrata was not modified.
|
||||
|
||||
## 1. The finding that changes the plan
|
||||
|
||||
Upstream's Python oracle is **not** published. `ref/` contains only `ref/load.py`, in the snapshot and in main, in every commit. The engine source cites `ref/gdn.py` (22 times), `ref/qsa.py` (26), `ref/moe.py` (12), `ref/gr.py` (11), `ref/ngram.py` (10), `ref/model.py` (9) and `ref/quant.py` (7), and `docs/semantics.md` and `docs/activation-contract.md` do not exist in any commit. The same holds for `bench/micro/` (the ggml-oracle tests), `tests/python/gen_ple_oracle.py`, `scripts/_gen_f16_oracle.py` and `tests/CMakeLists.txt`. The published CMake says so: "the test suite and the micro benchmarks live in tests/ and bench/micro/, which the published source leaves out".
|
||||
|
||||
So the Maya recipe (`ref/glm.py` plus a synthetic GGUF and dumps) has no upstream Strata counterpart to restore for the mixers or the MoE. What is restorable is `ref/load.py`, the pack tools, the in-C++ parity tests, and the discipline. The Qwen3.6 oracle is new code. It is specified from the pinned llama.cpp graph `third_party/llama.cpp/src/models/qwen35moe.cpp`, as Maya specified `ref/glm.py` from `glm5-next.cpp`.
|
||||
|
||||
## 2. Inventory
|
||||
|
||||
### `ref/`
|
||||
|
||||
- `ref/load.py` (212 lines). `Gguf(path)`: a demand-paged view of a possibly sharded GGUF (shard discovery from the `-0000N-of-0000M` suffix, a directory, or a list). `tensor(name)` returns FP32 shaped (out, in[, experts]). `expert(name, e)` decodes one expert of a fused `[in, out, experts]` tensor without touching the others. `rows(name, idx)` gathers rows of a 2-D tensor (built for the 27 GB PLE table; Qwen3.6 has no PLE). One dequant dispatch `_dequant_flat`: F32, F16, BF16 by hand; Q2_0 through `tools/gguf_writer.dequantize_q2_0`; everything else through gguf-py `quants.dequantize` (the table GEOM holds 13 entries: F32 F16 BF16 Q4_0 Q5_0 Q8_0 IQ4_NL Q3_K Q4_K Q5_K Q6_K IQ4_XS Q2_0). It lacks Q4_1, Q5_1, Q2_K and the IQ1/IQ2/IQ3 types the engine itself serves; a Q4_K_M or UD-Q4_K_XL Qwen3.6 file needs only Q4_K, Q5_K, Q6_K, Q8_0, F32, BF16 or F16, all present. It imports `gguf` without adding it to `sys.path`, so `PYTHONPATH` or `STRATA_GGUF_PY` must point at gguf-py (see section 5).
|
||||
|
||||
### `tools/` (the ones a port uses)
|
||||
|
||||
- `tools/iq_pack.py` (602 lines). The native-pack builder, described in section 4. Hardcodes Flash-Next assumptions listed in section 6.
|
||||
- `tools/gguf_reader.py` (142). A GGUF v3 header reader with no gguf-py dependency; knows ggml type ids to 42 (Q2_0). Used by `iq_pack`, the tokenizer exporter and `ref/load.py`. It is the Python twin of `src/artifact/gguf_reader.cpp`.
|
||||
- `tools/gguf_writer.py` (234). A minimal GGUF v3 writer with a Q2_0 quantizer. Its self-test writes a synthetic file with `general.architecture = qwen4exp`. Not a model generator.
|
||||
- `tools/iq_fixture.py` (137). Writes deterministic i-quant blocks plus gguf-py's dequantized reference for `iq_parity` (see section 3). It is the one fixture generator upstream ships.
|
||||
- `tools/test_iq_pack.py` (528). The closest thing to a synthetic-GGUF generator upstream ships: `write_gguf()` builds tiny sharded GGUFs with gguf-py's `GGUFWriter` and `quants.quantize`, then asserts pack behaviour (BF16 rounding to even, refused inexact F32 routers, split shards, a layer split across shards, interrupted packs, stale `experts.bin`). Arch string is `qwen4exp`.
|
||||
- `tools/make_profile.py` (119). Writes `expert-profile.bin`, a ranking of every (layer, expert) pair, from the base profile plus routing traces from `generate --dump-routing FILE`. Has `--n-expert` but `N_LAYER = 48` is hardcoded (line 26) and the output header carries layer and expert counts that the engine checks. Test: `tools/test_make_profile.py`. The shipped `data/expert-profile.bin` is for Flash-Next and is useless for Qwen3.6 (40 layers, 256 experts).
|
||||
- `tools/mtp_fetch.py` (308). Range-reads the 31 `mtp.*` tensors out of the 131-shard BF16 checkpoint over HTTP and verifies SHA256s (`inventory`, `fetch`, `verify`). Pinned to Qwen3.8-Flash-Next.
|
||||
- `tools/mtp_pack.py` (193). Quantizes those tensors into an MTP GGUF (`--experts q2_0|q4_0|q8_0`). Hardcodes the Flash-Next tensor names and the 512-expert fused shapes.
|
||||
- `tools/mtp_rt.py` (111). Turns the MTP GGUF into the engine's runtime files: `experts.bin`, `dense.bin`, `dense.txt`. Applies Gemma-style `+1` to RMSNorm weights.
|
||||
- `tools/draft_vocab.py` (+ `test_draft_vocab.py`). Extends `draft_vocab.bin`, the token subset the draft head may propose, by script (`--add han|kana|...`) or corpus (`--corpus`, `--coverage`). Data files `data/draft_vocab*.bin` are tied to the Flash-Next vocabulary of 248,320 tokens.
|
||||
- `tools/strata_tokenizer.py` (331). Exports `tokenizer/` (vocab, merges, chat template) from GGUF metadata. Refuses pre-tokenizer schemes it has not transcribed; Qwen3.6 uses `qwen35`, same family as Flash-Next. Called by `iq_pack` when `<out>/tokenizer/` is missing. Needs `regex`.
|
||||
- `tools/strata_pack.py`, `pack_layer.py`, `pack_index.py`, `canonical_xcheck.py`. The canonical Q2_0 pack (bakes in the 1,382,400-byte Flash-Next blob). The plan says Qwen3.6 rides the native pack instead, so these are reference only. `canonical_xcheck.py` shows the "bit-exact against gguf-py over every block" style.
|
||||
- `tools/calibrate.py`, `needle_bench.py`, `batch_test.py`, `test_conversation_cache_*.py`. Server-level measurement and regression harnesses. `calibrate.py` tunes `--pcie-frac`, `--spec-min-p`, `--pool-workers` through an engine's per-request keys. `needle_bench.py` is recall at 32K to 262K through the HTTP API. `batch_test.py` checks batched against solo greedy tokens.
|
||||
- `tools/_paths.py`. Finds gguf-py: `$STRATA_GGUF_PY`, then `<repo>/third_party/llama.cpp/gguf-py`. That second path exists in this fork's submodule, so the tools work unmodified.
|
||||
- Not needed: `setup.py`/`test_setup_*.py` (the installer), `strata_mcp.py`, `embd_bf16_pack.py`, `ple_fp8_pack.py` (Flash-Next PLE), `hip/`, `vision/`.
|
||||
|
||||
### `tests/` and the parity sources
|
||||
|
||||
- `tests/` in the snapshot has 30 files and no `CMakeLists.txt`: `tests/core/*.cpp` (loader and cache tests, `gguf_fixture.hpp` is a C++ synthetic-GGUF writer with pattern-filled tensors), `tests/cuda/prefill_*_test.cpp`, `tests/hip/*`, `tests/data/native_experts/*.txt` (golden `native_experts.txt` files for q2_0, iq2_xs, iq3_s, iq3_xxs, coder-iq1_m, swift-iq2_xs).
|
||||
- The root `CMakeLists.txt` references 23 `tests/` sources that are **absent in UnbiasedStrata** (the snapshot has 30 files there), and four `bench/micro/*` sources that upstream never published. Configuring this fork with `-DSTRATA_BUILD_TESTS=ON` would fail at `tests/core/gguf_split_test.cpp` (line 231). Restoring `tests/` fixes all but the `bench/micro` ones, which sit under the oracle option.
|
||||
- The 36 `src/kernels/*_parity.cpp` files, `src/prefill/gdn_rec_parity.cu`, `src/prefill/gemm_bf16_parity.cu` and `src/kernels/cpu/*_parity.cpp` are **still in UnbiasedStrata**. Relevant to the port: `gdn_parity.cpp`, `router_top10_parity.cpp`, `shared_expert_parity.cpp`, `gr_parity.cpp` (the Flash-Next hyper-connection residual, which Qwen3.6 lacks), `rope_parity.cpp`, `qsa_parity.cpp` (indexer path, bypassed for dense attention), `native_expert_parity.cpp`, `native_grouped_parity.cpp`, `sampler_parity.cpp`, `kv_*_parity.cpp`, `iq_parity.cpp`, `gdn_rec_parity.cu`.
|
||||
|
||||
### Docs
|
||||
|
||||
- `docs/semantics.md`, `docs/activation-contract.md`: **do not exist upstream** (no commit). The semantics live in comments in the parity files and in the unpublished `ref/*.py`.
|
||||
- `docs/ORCA.md` (95 lines) and `ORCA_Q4_K_S.md` (36). These are the precedent for a **different quantization of the same geometry** (512 experts), not for a different expert count: `iq_pack.py --compat-bf16` rounds the small projections the engine reads as BF16, records each in `compat-bf16.json`, and the pack carries its own tokenizer and `dense.bin`. The precedent for a **different expert count** is the Coder (256 of 512 experts): `iq_pack` reads `n_expert` from the router's shape, `make_profile.py --n-expert 256`, and `tests/data/native_experts/coder-iq1_m.txt`. `docs/MODELS.md` describes it.
|
||||
- `docs/DETAILS.md` (1127 lines; this fork keeps it as `docs/upstream/DETAILS.md`), `docs/HOW_IT_WORKS.md`, `docs/OLDER_GPUS.md`, `docs/NVIDIA_V100.md`, `docs/paper/`.
|
||||
|
||||
### `bench/`
|
||||
|
||||
- Snapshot: results only (`bench/results/<date>-<topic>/` with `README.md`, `matrix.md`, `matrix.json`). Useful as the format for reporting. The speed matrix of `2026-09-28-speed-0114` records the flags the setup writes (`--prefill auto`, `--expert-cache auto`, `--kv-resident`, `--spec 4 --spec-min-p 0.5`).
|
||||
- Main only: `bench/bench_vs_llama.py` drives Strata's and llama.cpp's OpenAI-compatible servers with the same prompts and GGUF, takes server-side prompt and decode tokens per second, peak VRAM from `nvidia-smi` polling, RSS from `psutil`, interleaves engines across rounds, and has `prompts`, `run`, `quality`, `summary` subcommands. Needs `psutil`. This is the closest match for the plan's baseline-versus-engine comparison, and it is not in the pinned snapshot.
|
||||
- The engine itself prints a `strata decode GPU stages (ms/window)` line and takes `--dump-routing` (`src/program/generate.cpp:1310`).
|
||||
|
||||
## 3. How upstream produces oracle dumps for a parity test today
|
||||
|
||||
1. There is no dump pipeline for the model. No script in the published tree runs a forward pass of the model and writes per-seam tensors. Everything below is what exists.
|
||||
2. Most parity tests are self-contained: the oracle is a **host C++ transcription of the spec**, inside the test file. `gdn_parity.cpp` has `ref_step()` and `ref_conv()` "a transcription of `ref/gdn.py`", in double precision, with boolean switches for the rival readings. `router_top10_parity.cpp` has `reference()` (softmax, stable sort, renormalise). Random inputs come from `std::mt19937(2024)`. Nothing is read from `data/`.
|
||||
3. Registration: `add_test(NAME gdn_parity COMMAND gdn_parity --selftest)` in the root `CMakeLists.txt` under `if(STRATA_BUILD_TESTS)` and a CUDA or HIP backend. `STRATA_BUILD_TESTS` defaults ON only when `tests/CMakeLists.txt` and `bench/micro` both exist, so a published checkout builds none of it unless `-DSTRATA_BUILD_TESTS=ON` is given. Run with `ctest` or the binary with `--selftest`. Exit 0 pass, 1 fail, 77 or 3 skip (`SKIP_RETURN_CODE`).
|
||||
4. Vector tests embed the oracle as a generated header: `ple_oracle_vectors.inc` ("GENERATED by tests/python/gen_ple_oracle.py") holds token windows and expected hash rows; `qsa_oracle_vectors.inc` holds float32-to-float16 bit pairs from `np.float16(np.float32(x))`. Both generators are unpublished. Regenerating means rewriting them.
|
||||
5. Fixture tests generate files into the build directory at test time: `iq_parity_fixtures` runs `tools/iq_fixture.py --out <build>/iq_fixture`, which writes `<name>.bin` (int32 header: kernel type id, rows, cols, then raw block bytes) and `<name>.f32` (reference values from gguf-py). `iq_parity <dir>` reads them. CMake probes interpreters for numpy (`-DIQ_FIXTURE_PYTHON` overrides) and uses `FIXTURES_SETUP`/`FIXTURES_REQUIRED` for ordering. This is the only dump-like flow in the published tree, and only for dequantization.
|
||||
6. Real-GGUF tests take a path from an environment variable or argument: `STRATA_PLE_GGUF` (default `../../Q2_0/...-00002-of-00002.gguf`) and `--pack`, plus binary captures `bench/micro/ple_in.bin` and `ple_out.bin` recorded from ggml's graph by an unpublished `ple_layer_xcheck.cpp`, which "records EVERY intermediate" so a failure is attributable to a stage.
|
||||
7. The independent-oracle tests (`bench/micro/native_{mmvq,bf16,shared,gr_norm,moe,gdn,gr_postops,router,gdn_preprocess,gdn_pipeline,qsa,rope,ple_postops,flash_attn,qsa_indexer,qsa_score}_parity.cpp`) link a pinned llama.cpp CUDA build as the oracle: `-DSTRATA_ORACLE_SOURCE_DIR=<llama.cpp>` and `-DSTRATA_ORACLE_BUILD_DIR=<build>` (CMake lines 387 to 408; libraries `ggml`, `ggml-base`, `ggml-cpu`, `ggml-cuda` located with `find_library`). These sources are unpublished, so the 16 names are a list of what to rewrite, and the CMake foreach is the wiring to restore.
|
||||
8. No dump file naming convention exists upstream. Maya's convention (llama.cpp `cb()` names, files under `data/glm5-synth-dumps/`) is the one to adopt.
|
||||
|
||||
**Negative-test discipline, from `gdn_parity.cpp`.** Before the kernel is judged, each wrong reading of the spec is computed with the same reference and must differ from the right one by more than 5 % (relative L1). Four traps are pinned: modulo versus interleaved head pairing, decay before versus after the rank-1 update, conv slide direction (state rows labelled so every position is identifiable), and `l2_norm`'s epsilon on the squared norm versus the mean. It prints `yes` or `*** NO ***` for "is the rival observable" and counts a failure when it is not. The first fixture for the decay trap showed only 3.25 % apart, so the gate and the input range were changed (decay in (0.0025, 0.135], beta in [0, 1)) until the trap was clearly visible. The state layout test fills the state with `0.001*(i + 2j + 3h) - 1` so a layout mix-up yields a different number, not a plausible one. `router_top10_parity.cpp` shows the same idea for selection: all-equal logits, a 12-way tie, a dominant expert, and an assertion that the 2^-14 renormalisation clamp is unreachable (top-k sum at least k/n). Comparisons are NaN-safe (`le`/`gt` demand finite values first) after a NaN fixture once printed a perfect score.
|
||||
|
||||
## 4. How a native pack is built from a GGUF
|
||||
|
||||
Entry point: `python tools/iq_pack.py --gguf <first-shard>.gguf --out <dir> [--compat-bf16] [--experts-bin] [--skip-experts] [--base <pack>]`. All sibling shards must exist (`Model.__init__` reads `-0000N-of-0000M`, a missing one is an error). `main()` runs `expert_layout()` first so a model that cannot be packed is refused before any file changes, then `index_standalone()`, then the tokenizer export, then writes `native_experts.txt` last.
|
||||
|
||||
- **`native_experts.txt`** is the completion marker and the expert map. One line per layer: `layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard]`. `gu_type` and `d_type` are ggml type ids (gate and up must match; down may differ, e.g. IQ3_XXS gate/up with Q2_0 down). `offset` is the layer's start in the virtual `experts.bin`. `blob_bytes` is the per-expert size of gate + up + down. The last three are absolute byte offsets of the three role tensors in their GGUF shard. Header `v3`; `v4` only if one layer's roles sit in different shards (column becomes `gate,up,down`). The engine reads the experts straight from the GGUF unless `experts.bin` exists. Golden examples: `tests/data/native_experts/*.txt`.
|
||||
- **`index.txt`**: "strata pack index v3", one row per non-expert tensor: `name, ?, kind, offset, bytes, arena_offset, arena_bytes, ne0, ne1, ...`. Kind 4 = BF16, 5 = F16, 2 = F32, 3 = F32 narrowed to F16 by the loader. A quantized tensor the engine serves natively from the GGUF has zero offsets and only its shape. The arena is 64-byte aligned.
|
||||
- **`dense.bin`**: the float tensors the engine reads from the pack, in the form it reads them (table `FORM`: routers, hyper-connection and indexer projections, SSM gates BF16; norms, `ssm_a`, `ssm_conv1d`, `ssm_dt.bias`, `ssm_norm` F32; PLE conv F16). Exact conversions are the default (F32 whose low 16 bits are zero to BF16; F16 or BF16 widened to F32). Rounding conversions need `--compat-bf16`. Anything the engine requires in a form the GGUF does not hold, without the flag, is a hard error.
|
||||
- **`conversions.json`** (schema 1): every converted tensor: shard, source and destination types, method, exact or not, max absolute error, SHA-256 of the source bytes, plus the source shard names and sizes.
|
||||
- Also: `experts.bin` plus `experts.bin.src.json` (optional, only with `--experts-bin`, reuse is checked by shard sizes, the hash of `native_experts.txt` and six sampled blobs), `tokenizer/`, and `compat-bf16.json` with the flag. All files are written under `.tmp` names and renamed, so an interrupted run leaves no completion marker.
|
||||
|
||||
## 5. Dependencies and GPU
|
||||
|
||||
- Pack tools and `ref/load.py`: Python 3.10+, `numpy`, gguf-py from llama.cpp (the submodule's `third_party/llama.cpp/gguf-py` works through `_paths.py`; `ref/load.py` needs `PYTHONPATH` set to it). `regex` for the tokenizer export. `requirements.txt` pins numpy, jinja2, regex, pyyaml, tqdm. `psutil` for `bench_vs_llama.py`. `mtp_fetch.py` uses the standard library's HTTP client.
|
||||
- **No torch, no safetensors library, no GPU** anywhere in `tools/` or `ref/`. The oracle is NumPy on the CPU. Maya's `ref/glm.py` is also NumPy; the full-attention and GDN loops are slow but small models are fine, and the synthetic GGUF keeps them fast.
|
||||
- GPU is needed only to run the C++ parity binaries and the engine.
|
||||
- For cross-checking, the submodule has `examples/eval-callback`, `src/models/qwen35moe.cpp`, `src/models/delta-net-base.cpp` and `convert_hf_to_gguf.py`. llama.cpp's `cb()` names in `qwen35moe.cpp` include `conv_output_silu`, `gate_sigmoid`, `beta_sigmoid` and `shared_expert_gate_sigmoid`.
|
||||
|
||||
## 6. Hardcoded Flash-Next assumptions found while reading (each must be generalized or bypassed)
|
||||
|
||||
- `iq_pack.py`: `FORM`/`ROUTERS` name Flash-Next tensors (`hc_*`, `indexer.*`, `ple_*`); `is_expert()` matches any `*_exps.weight`; `expert_layout()` takes `n_expert` from `blk.0.ffn_gate_inp.weight` and demands every layer to have all three expert tensors (true for qwen35moe, which has no dense-lead layers); tensors with more than two dimensions outside experts are refused; the `FORM` table has no qwen35moe entries, so SSM and attention tensors are served natively from the GGUF where quantized and copied as stored where float. Whether the engine needs `ssm_alpha`/`ssm_beta`, the router and the shared-expert gate as BF16 for the GDN and router kernels is a step 3 and 4 question; the `FORM` table is where that gets decided. `ffn_gate_inp_shexp.weight` is already in `ROUTERS`.
|
||||
- `make_profile.py`: `N_LAYER = 48`, `N_EXPERT = 512`.
|
||||
- `mtp_fetch.py`, `mtp_pack.py`, `mtp_rt.py`: Flash-Next tensor names, the 512-expert fused shapes, the revision pin. The Qwen3.6 MTP head comes from the MTP GGUF's `nextn` tensors per the plan.
|
||||
- `gdn_parity.cpp` and `src/kernels/cuda/gdn.cu`: the out-norm is `rms_norm(o) * ssm_norm * sigmoid(z)` (`gdn.cu:148`), and the parity test's negative case asserts SiLU is the wrong reading. llama.cpp's `qwen35moe` `build_norm_gated` uses `ggml_silu(gate)`. The test's geometry is fixed at S = 128, h_k = 16, h_v = 48 against Qwen3.6's 32 v-heads. Re-pin both before reusing either.
|
||||
- `tests/data/native_experts/` and `data/*.bin`: Flash-Next only.
|
||||
|
||||
## 7. What to restore and what to write
|
||||
|
||||
Restore into a dev checkout (copy from `/Users/robertkarl/Code/strata-upstream-6f32ec0`; a dev branch, or keep out of the fork's release tree):
|
||||
|
||||
1. `ref/load.py`.
|
||||
2. `tools/`: `_paths.py`, `gguf_reader.py`, `gguf_writer.py`, `iq_pack.py`, `test_iq_pack.py`, `make_profile.py`, `test_make_profile.py`, `strata_tokenizer.py`, `mtp_pack.py`, `mtp_rt.py`, `mtp_fetch.py` (for reference), `draft_vocab.py`, `iq_fixture.py`, `needle_bench.py`, `calibrate.py`, `batch_test.py`.
|
||||
3. `tests/` whole (30 files), so that `-DSTRATA_BUILD_TESTS=ON` configures. `bench/micro/` cannot be restored; the CMake foreach for the llama.cpp-oracle parity tests stays dormant.
|
||||
4. `requirements.txt` (numpy, regex, jinja2).
|
||||
5. From upstream main only: `bench/bench_vs_llama.py`.
|
||||
|
||||
Write new (nothing upstream to copy): `ref/qwen36.py`, `tools/qwen36_synth_gguf.py`, the oracle invariant tests, qwen35moe parity binaries (GDN at 32 v-heads with SiLU gating, the top-8 over 256 router with shared-expert gate, the gated full-attention layer), the layer composition test, and the streaming runner test.
|
||||
+31
-26
@@ -41,10 +41,6 @@ namespace {
|
||||
|
||||
const char* const kModelName = "qwen3.8-flash-next-iq3_xxs";
|
||||
|
||||
// The engine's serve loop refuses a request unless prompt + max_new + this margin fits --ctx
|
||||
// (src/program/generate.cpp:6403): the last cells are the engine's own, not ours to hand out.
|
||||
constexpr long long kEngineReserve = 8;
|
||||
|
||||
struct Options {
|
||||
std::string model; // shard 1 of the GGUF
|
||||
std::string pack; // the prepared pack directory
|
||||
@@ -55,7 +51,6 @@ struct Options {
|
||||
int port = 8080;
|
||||
long long ctx = 32768;
|
||||
int threads = 0; // CPU expert workers; 0 = the engine's default (every physical core)
|
||||
bool fit_max_tokens = true; // shorten a request's max_tokens to the room left instead of refusing it
|
||||
std::vector<std::string> extra; // after `--`: passed to the engine as they are
|
||||
};
|
||||
|
||||
@@ -68,8 +63,6 @@ void usage() {
|
||||
" --mmproj PATH enable image input using this vision encoder (CPU)\n"
|
||||
" --vision-tokens N maximum tokens per image (default 1024)\n"
|
||||
" --ctx N context length in tokens (default 32768)\n"
|
||||
" --fit-max-tokens / --no-fit-max-tokens\n"
|
||||
" shorten a request's max_tokens to the room left instead of refusing it (default: on)\n"
|
||||
" --threads N CPU threads for the experts the GPU does not hold (default: every physical core,\n"
|
||||
" or half the CPU quota inside a container that has one)\n"
|
||||
" --host ADDR address to listen on (default 127.0.0.1)\n"
|
||||
@@ -234,27 +227,21 @@ struct Server {
|
||||
p.parser.parse_tool_calls = true;
|
||||
if (!cp.parser.empty()) p.parser.parser.load(cp.parser);
|
||||
|
||||
// The engine refuses a request unless prompt + max_new + 8 <= context (generate.cpp, the GEN handler), so
|
||||
// the slots it keeps back are not ours to promise. Without this a client that asks for "as much as fits"
|
||||
// (pi sends max_tokens 32768 on a 64K card) was refused on every prompt longer than ctx - max_tokens.
|
||||
constexpr long long kEngineReserve = 8;
|
||||
const long long n = (long long) p.ids.size();
|
||||
const long long room = opt.ctx - n - kEngineReserve;
|
||||
if (room < 1) {
|
||||
err = "the prompt is " + std::to_string(n) + " tokens, which leaves no room to generate in the context of " +
|
||||
if (n + 1 + kEngineReserve > opt.ctx) {
|
||||
err = "the prompt is " + std::to_string(n) + " tokens, which does not fit the context of " +
|
||||
std::to_string(opt.ctx);
|
||||
return false;
|
||||
}
|
||||
long long max_new = room;
|
||||
long long max_new = opt.ctx - n - kEngineReserve;
|
||||
for (const char* key : {"max_completion_tokens", "max_tokens"})
|
||||
if (body.contains(key) && body.at(key).is_number()) {
|
||||
const long long want = body.at(key).get<long long>();
|
||||
if (want >= 1) {
|
||||
if (want <= room) max_new = want;
|
||||
else if (opt.fit_max_tokens) max_new = room;
|
||||
else {
|
||||
err = "the request asks for " + std::to_string(want) + " tokens and the prompt is " +
|
||||
std::to_string(n) + ", which does not fit the context of " + std::to_string(opt.ctx) +
|
||||
" (--fit-max-tokens shortens the request to the room left)";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (want >= 1) max_new = std::min(max_new, want);
|
||||
break;
|
||||
}
|
||||
p.max_new = max_new;
|
||||
@@ -331,9 +318,14 @@ struct Server {
|
||||
|
||||
/// Runs one request. The text produced so far is parsed by llama.cpp's chat parser after every token, and
|
||||
/// `emit` gets what changed (reasoning, answer text, tool-call pieces); it returns false when the client has
|
||||
/// gone. `final_msg` is the whole parsed message.
|
||||
/// gone. `final_msg` is the whole parsed message. `keepalive`, when given, is called whenever 15 s pass
|
||||
/// without an emit (content and tool calls are published only once the message is complete, so a long answer
|
||||
/// is silent for minutes): the stream writes an SSE comment, which keeps clients with an idle timeout (pi:
|
||||
/// 5 minutes) attached and notices a client that has gone, so the generation is cancelled instead of
|
||||
/// running to the end for nobody.
|
||||
GenResult run(const Prepared& p, common_chat_msg& final_msg,
|
||||
const std::function<bool(const std::vector<common_chat_msg_diff>&)>& emit) {
|
||||
const std::function<bool(const std::vector<common_chat_msg_diff>&)>& emit,
|
||||
const std::function<bool()>& keepalive = {}) {
|
||||
std::lock_guard<std::mutex> lk(engine.mu);
|
||||
std::fprintf(stderr, "unbiased-strata: request %s start: prompt=%zu header=%s\n",
|
||||
p.request_id.c_str(), p.ids.size(), p.header.c_str());
|
||||
@@ -341,6 +333,7 @@ struct Server {
|
||||
common_chat_msg msg;
|
||||
std::vector<std::string> call_ids;
|
||||
bool client_ok = true;
|
||||
auto last_write = std::chrono::steady_clock::now();
|
||||
auto update = [&](bool partial) {
|
||||
common_chat_msg now;
|
||||
try {
|
||||
@@ -365,7 +358,10 @@ struct Server {
|
||||
now.set_tool_call_ids(call_ids, [] { return "call_" + make_id().substr(9); });
|
||||
const std::vector<common_chat_msg_diff> diffs = common_chat_msg_diff::compute_diffs(msg, now);
|
||||
msg = now;
|
||||
if (client_ok && !diffs.empty()) client_ok = emit(diffs);
|
||||
if (client_ok && !diffs.empty()) {
|
||||
client_ok = emit(diffs);
|
||||
last_write = std::chrono::steady_clock::now();
|
||||
}
|
||||
};
|
||||
GenResult r = engine.generate(p.header, p.ids, [&](llama_token id) {
|
||||
if (llama_vocab_is_eog(vocab, id)) return client_ok;
|
||||
@@ -376,6 +372,13 @@ struct Server {
|
||||
pending.erase(0, n);
|
||||
update(true);
|
||||
}
|
||||
if (client_ok && keepalive) {
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (now - last_write >= std::chrono::seconds(15)) {
|
||||
client_ok = keepalive();
|
||||
last_write = now;
|
||||
}
|
||||
}
|
||||
return client_ok;
|
||||
});
|
||||
text += pending;
|
||||
@@ -491,6 +494,10 @@ struct Server {
|
||||
ok = ok && chunk(d, nullptr, nullptr);
|
||||
}
|
||||
return ok;
|
||||
}, [&]() {
|
||||
static const std::string ka = ": keepalive\n\n"; // an SSE comment: every client ignores it
|
||||
ok = ok && sink.write(ka.data(), ka.size());
|
||||
return ok;
|
||||
});
|
||||
if (ok) {
|
||||
if (r.ok) {
|
||||
@@ -567,8 +574,6 @@ bool parse_args(int argc, char** argv, Options& o) {
|
||||
else if (a == "--host") o.host = next("--host");
|
||||
else if (a == "--port") o.port = std::atoi(next("--port").c_str());
|
||||
else if (a == "--ctx") o.ctx = std::atoll(next("--ctx").c_str());
|
||||
else if (a == "--fit-max-tokens") o.fit_max_tokens = true;
|
||||
else if (a == "--no-fit-max-tokens") o.fit_max_tokens = false;
|
||||
else if (a == "--threads") o.threads = std::atoi(next("--threads").c_str());
|
||||
else if (a == "--") {
|
||||
for (++i; i < argc; ++i) {
|
||||
|
||||
+212
@@ -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()
|
||||
@@ -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 <cuda_runtime.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<int64_t>(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;
|
||||
}
|
||||
@@ -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 <cuda_runtime.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<uint8_t> 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<uint8_t> 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<int64_t>(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;
|
||||
}
|
||||
@@ -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 <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<Tensor> 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<Tensor> 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<uint8_t> 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<uint8_t> 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 <tests/data/native_experts>\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;
|
||||
}
|
||||
@@ -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 <cstdio>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
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<int32_t, int32_t>;
|
||||
const int64_t L = 3, E = 4; // 12 pairs, index = layer * 4 + expert
|
||||
std::vector<uint8_t> resident(12, 0);
|
||||
resident[5] = 1; // (1, 1)
|
||||
resident[2] = 1; // (0, 2)
|
||||
std::vector<double> 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<Pair> prior = {{2, 0}, {1, 3}, {0, 1}}; // a profile that ranks three pairs
|
||||
const std::vector<Pair> r = strata::core::rank_learned_profile(L, E, resident, heat, prior);
|
||||
check(r.size() == 12, "every pair is ranked");
|
||||
const std::vector<Pair> 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<Pair> 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<uint8_t> 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<int32_t> 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<uint8_t> 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<Pair> 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;
|
||||
}
|
||||
@@ -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 <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <system_error>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
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<std::pair<uint64_t, char>>& 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<uint64_t> 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<uint64_t>{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<uint64_t> 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<uint64_t> 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<uint64_t> 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<uint64_t> 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<uint64_t> 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<uint64_t>::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;
|
||||
}
|
||||
}
|
||||
@@ -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 <cstdint>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<uint64_t> 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<Kv> 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<uint64_t> 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>& kv, const std::vector<Tensor>& ts,
|
||||
uint64_t cut = 0) {
|
||||
std::vector<uint8_t> 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<uint64_t> 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
|
||||
@@ -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 <chrono>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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 <class F> std::vector<std::string> write_model(const fs::path& dir, F mutate, uint64_t total = 7) {
|
||||
std::vector<std::string> paths;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
std::vector<fixture::Kv> 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<Tensor> 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<fixture::Kv>&, std::vector<Tensor>&, uint64_t&) {};
|
||||
|
||||
std::string error_of(const std::vector<std::string>& 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<std::string> 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;
|
||||
}
|
||||
@@ -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 <cuda_runtime.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<fixture::Kv> 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<char> 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<std::string> 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<std::string> 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<unsigned char> 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<std::string> 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;
|
||||
}
|
||||
@@ -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 <cuda_runtime.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <random>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
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 <typename T> 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<int> 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<float> 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<uint8_t> make_blob(const Pair& p, const Geo& g, std::mt19937& rng) {
|
||||
std::vector<uint8_t> 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<uint8_t>& b, std::vector<float>& gu, std::vector<float>& 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<float> make_x(int T, std::mt19937& rng, int zero) {
|
||||
std::vector<float> x((size_t) T * N);
|
||||
std::normal_distribution<float> nd(0.0f, 1.0f);
|
||||
std::uniform_int_distribution<int> 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<int32_t> make_ids(int T, int E, std::mt19937& rng, int hot, int unused) {
|
||||
std::vector<int32_t> ids((size_t) T * K);
|
||||
std::uniform_int_distribution<int> 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<int32_t> cnt, off, src; // per expert; sorted row -> token (rows in pair order within an expert)
|
||||
std::vector<int32_t> row_of; // pair -> sorted row
|
||||
};
|
||||
Routing sort_rows(const std::vector<int32_t>& 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<int32_t> 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<const uint8_t*>& 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<int32_t> 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<int32_t> 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<int32_t>(), 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<uint8_t>() + q * gub,
|
||||
b.grp_d.as<uint8_t>() + 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<int64_t>(maxr, r.cnt[(size_t) order[i]]);
|
||||
if (!direct) {
|
||||
ck(cudaMemsetAsync(b.grp_gu.as<uint8_t>() + (size_t) ngx * gub, 0, 4096, s), "tail");
|
||||
ck(cudaMemsetAsync(b.grp_d.as<uint8_t>() + (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<int32_t>() + j0; gu.ids = b.ident.as<int32_t>();
|
||||
gu.total_rows = rows; gu.max_rows = maxr; gu.dst = b.gu.as<float>(); gu.ld_dst = 1280;
|
||||
ctx.run(gu, s);
|
||||
mmq::swiglu(b.gu.as<float>() + r0 * 1280, b.h.as<float>() + r0 * FF, nr, FF, false, s);
|
||||
mmq::quantize(b.h.as<float>() + 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<int32_t>() + n + 1 + g * (GROUP + 1);
|
||||
dn.ids = b.ident.as<int32_t>(); dn.total_rows = nr; dn.max_rows = maxr; dn.dst = b.dm.as<float>() + 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<int>& cuts, const std::vector<const uint8_t*>& 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<int32_t>(), rows, K, E, b.scratch.p, b.slot.as<int32_t>(), b.src.as<int32_t>(), 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<int32_t>(), b.ha.p, b.dm.as<float>(), 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 <typename RA, typename RB>
|
||||
Err compare(const std::vector<float>& a, RA row_a, const std::vector<float>& 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<float> download(const Dev& d, size_t n) {
|
||||
std::vector<float> h(n);
|
||||
ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download");
|
||||
return h;
|
||||
}
|
||||
std::vector<int32_t> download_i(const Dev& d, size_t n) {
|
||||
std::vector<int32_t> 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<std::vector<uint8_t>> host((size_t) E);
|
||||
std::vector<std::unique_ptr<Dev>> dev;
|
||||
std::vector<const uint8_t*> 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<Dev>(geo.bytes + 4096 * (size_t) (e % 3) + 64)); // unrelated addresses
|
||||
uint8_t* q = dev.back()->as<uint8_t>() + 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<float> x = make_x(T, rng, ZERO);
|
||||
const std::vector<int32_t> 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<float>(), src_dev.as<int32_t>(), 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<float>(), T, E, {0, 1, 20, E}, blob, s);
|
||||
ck(cudaStreamSynchronize(s), "sync");
|
||||
const std::vector<float> y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N);
|
||||
const std::vector<int32_t> 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<float> ref((size_t) rows * N);
|
||||
std::vector<std::thread> 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<float> 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<uint8_t> 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<uint8_t>() + (size_t) e * stride, b.data(), geo.bytes, cudaMemcpyHostToDevice),
|
||||
"blob");
|
||||
}
|
||||
}
|
||||
std::vector<const uint8_t*> blob((size_t) E);
|
||||
for (int e = 0; e < E; ++e) blob[(size_t) e] = blobs.as<uint8_t>() + (size_t) e * stride;
|
||||
const std::vector<float> x = make_x(T, rng, -1);
|
||||
const std::vector<int32_t> 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<float>(), src_dev.as<int32_t>(), blob, rows, s); };
|
||||
auto fused_run = [&] { run_fused(p, geo, fb, x_dev.as<float>(), 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<float>(), src_dev.as<int32_t>(), 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<int32_t> 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<uint8_t>() + (size_t) rows * N * 4), fb.dm.p,
|
||||
(void*) (fb.dm.as<uint8_t>() + (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<float> 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<float> 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<float> y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N);
|
||||
const std::vector<int32_t> 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<int32_t> 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<int32_t> 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<int32_t> 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<int32_t>(), rows, K, E, fb.scratch.p, fb.slot.as<int32_t>(), fb.src.as<int32_t>(), s);
|
||||
ck(cudaStreamSynchronize(s), "sync");
|
||||
std::vector<int32_t> 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<int32_t> fsrc = download_i(fb.src, (size_t) rows);
|
||||
std::vector<std::pair<double, size_t>> 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<size_t> pick;
|
||||
for (size_t i = 0; i < 96; ++i) pick.push_back((i * 2654435761u) % (size_t) rows);
|
||||
std::vector<float> ref(pick.size() * N), ym(pick.size() * N), yf(pick.size() * N);
|
||||
std::vector<uint8_t> hb(geo.bytes);
|
||||
std::vector<float> 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<Pair> 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<int> 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;
|
||||
}
|
||||
}
|
||||
@@ -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 <cuda_runtime.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <random>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
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 <typename T> 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<uint8_t> make_blob(std::mt19937& rng) {
|
||||
std::vector<uint8_t> b(BLOB);
|
||||
std::uniform_int_distribution<int> byte(0, 255);
|
||||
std::uniform_real_distribution<float> 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<uint8_t>& b, std::vector<float>& gu, std::vector<float>& 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<float> make_x(int T, std::mt19937& rng, int zero) {
|
||||
std::vector<float> x((size_t) T * N);
|
||||
std::normal_distribution<float> nd(0.0f, 1.0f);
|
||||
std::uniform_int_distribution<int> 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<int32_t> make_ids(int T, int E, std::mt19937& rng, int hot, int unused) {
|
||||
std::vector<int32_t> ids((size_t) T * K);
|
||||
std::uniform_int_distribution<int> 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<int32_t> cnt, off, src; // per expert; sorted row -> token (rows in pair order within an expert)
|
||||
std::vector<int32_t> row_of; // pair -> sorted row
|
||||
};
|
||||
Routing sort_rows(const std::vector<int32_t>& 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<int32_t> 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<const uint8_t*>& 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<int32_t> 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<int32_t> 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<int32_t>(), 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<uint8_t>() + q * gub, b.grp_d.as<uint8_t>() + 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<int64_t>(maxr, r.cnt[(size_t) order[i]]);
|
||||
ck(cudaMemsetAsync(b.grp_gu.as<uint8_t>() + (size_t) ngx * gub, 0, 4096, s), "tail");
|
||||
ck(cudaMemsetAsync(b.grp_d.as<uint8_t>() + (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<int32_t>() + j0; gu.ids = b.ident.as<int32_t>();
|
||||
gu.total_rows = rows; gu.max_rows = maxr; gu.dst = b.gu.as<float>(); gu.ld_dst = 1280;
|
||||
ctx.run(gu, s);
|
||||
mmq::swiglu(b.gu.as<float>() + r0 * 1280, b.h.as<float>() + r0 * FF, nr, FF, true, s);
|
||||
mmq::quantize(b.h.as<float>() + 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<int32_t>() + n + 1 + g * (GROUP + 1);
|
||||
dn.ids = b.ident.as<int32_t>(); dn.total_rows = nr; dn.max_rows = maxr; dn.dst = b.dm.as<float>() + 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<int>& cuts,
|
||||
const std::vector<const uint8_t*>& 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<int32_t>(), rows, K, E, b.scratch.p, b.slot.as<int32_t>(), b.src.as<int32_t>(), 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<int32_t>(), b.ha.p, b.dm.as<float>(), 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 <typename RA, typename RB>
|
||||
Err compare(const std::vector<float>& a, RA row_a, const std::vector<float>& 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<float> download(const Dev& d, size_t n) {
|
||||
std::vector<float> h(n);
|
||||
ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download");
|
||||
return h;
|
||||
}
|
||||
std::vector<int32_t> download_i(const Dev& d, size_t n) {
|
||||
std::vector<int32_t> 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<std::vector<uint8_t>> host((size_t) E);
|
||||
std::vector<std::unique_ptr<Dev>> dev;
|
||||
std::vector<const uint8_t*> blob((size_t) E);
|
||||
for (int e = 0; e < E; ++e) {
|
||||
host[(size_t) e] = make_blob(rng);
|
||||
dev.push_back(std::make_unique<Dev>(BLOB + 4096 * (size_t) (e % 3))); // unrelated addresses
|
||||
uint8_t* p = dev.back()->as<uint8_t>() + 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<float> x = make_x(T, rng, ZERO);
|
||||
const std::vector<int32_t> 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<float>(), src_dev.as<int32_t>(), 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<float>(), T, E, {0, 1, 20, E}, blob, s);
|
||||
ck(cudaStreamSynchronize(s), "sync");
|
||||
const std::vector<float> y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N);
|
||||
const std::vector<int32_t> 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<float> ref((size_t) rows * N);
|
||||
std::vector<std::thread> 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<float> 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<uint8_t> 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<uint8_t>() + (size_t) e * BLOB, b.data(), BLOB, cudaMemcpyHostToDevice), "blob");
|
||||
}
|
||||
}
|
||||
std::vector<const uint8_t*> blob((size_t) E);
|
||||
for (int e = 0; e < E; ++e) blob[(size_t) e] = blobs.as<uint8_t>() + (size_t) e * BLOB;
|
||||
const std::vector<float> x = make_x(T, rng, -1);
|
||||
const std::vector<int32_t> 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<float> 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<float>(), src_dev.as<int32_t>(), blob, rows, s); });
|
||||
const float t_f = time([&] { run_fused(fb, x_dev.as<float>(), T, E, {0, E}, blob, s); });
|
||||
const float t_f1 = time([&] { // one launch per 16 experts, MMQ's group size
|
||||
std::vector<int> cuts;
|
||||
for (int e = 0; e <= E; e += 16) cuts.push_back(e);
|
||||
run_fused(fb, x_dev.as<float>(), T, E, cuts, blob, s);
|
||||
});
|
||||
const std::vector<float> y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N);
|
||||
const std::vector<int32_t> 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;
|
||||
}
|
||||
}
|
||||
@@ -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 <cuda_runtime.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <numeric>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<uint8_t> 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<uint8_t> out((size_t) rows * rb);
|
||||
std::vector<float> 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<float> make_x(int rows, int64_t cols, int trial) {
|
||||
std::vector<float> 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<int32_t> perm(int n, int shift, bool reverse) {
|
||||
std::vector<int32_t> 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<int>& 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<int32_t> 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<float> 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<std::vector<uint8_t>> ws;
|
||||
std::vector<uint8_t> 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<float> 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<float> 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<std::vector<int>> 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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,60 @@
|
||||
#include "strata/platform/direct_file.hpp"
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#include <unistd.h>
|
||||
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<char*>(memory) + i * 4096, 4096, i, error), error.c_str());
|
||||
std::vector<bool> 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<char*>(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;
|
||||
}
|
||||
}
|
||||
@@ -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 <engine>/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)
|
||||
@@ -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 <model>-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 <model>-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())
|
||||
@@ -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("<I", fh.read(4))[0]
|
||||
if magic != GGUF_MAGIC:
|
||||
raise ValueError(f"{self.path.name}: not a GGUF file (magic {magic:#x})")
|
||||
self.version, n_tensors, n_kv = struct.unpack("<IQQ", fh.read(20))
|
||||
if self.version != 3:
|
||||
raise ValueError(f"{self.path.name}: GGUF v{self.version}, this reader handles v3")
|
||||
for _ in range(n_kv):
|
||||
key = self._str(fh)
|
||||
self.metadata[key] = self._value(fh)
|
||||
for _ in range(n_tensors):
|
||||
name = self._str(fh)
|
||||
(n_dims,) = struct.unpack("<I", fh.read(4))
|
||||
shape = list(struct.unpack(f"<{n_dims}Q", fh.read(8 * n_dims)))
|
||||
type_id, offset = struct.unpack("<IQ", fh.read(12))
|
||||
self.tensors.append(TensorInfo(name, shape, type_id,
|
||||
GGML_TYPES.get(type_id, f"type{type_id}"), offset))
|
||||
align = self.metadata.get("general.alignment")
|
||||
if isinstance(align, int) and align:
|
||||
self.alignment = align
|
||||
pos = fh.tell()
|
||||
self._data_start = (pos + self.alignment - 1) // self.alignment * self.alignment
|
||||
|
||||
def _str(self, fh) -> str:
|
||||
(n,) = struct.unpack("<Q", fh.read(8))
|
||||
return fh.read(n).decode("utf-8", "replace")
|
||||
|
||||
def _value(self, fh):
|
||||
(t,) = struct.unpack("<I", fh.read(4))
|
||||
name, size = GGUF_META[t]
|
||||
if name == "string":
|
||||
return self._str(fh)
|
||||
if name == "array":
|
||||
(et,) = struct.unpack("<I", fh.read(4))
|
||||
(count,) = struct.unpack("<Q", fh.read(8))
|
||||
ename, esize = GGUF_META[et]
|
||||
if ename == "string":
|
||||
return [self._str(fh) for _ in range(count)]
|
||||
fmt = {"u8": "B", "i8": "b", "u16": "H", "i16": "h", "u32": "I", "i32": "i",
|
||||
"f32": "f", "bool": "?", "u64": "Q", "i64": "q", "f64": "d"}[ename]
|
||||
raw = fh.read(esize * count)
|
||||
return list(struct.unpack(f"<{count}{fmt}", raw))
|
||||
fmt = {"u8": "B", "i8": "b", "u16": "H", "i16": "h", "u32": "I", "i32": "i",
|
||||
"f32": "f", "bool": "?", "u64": "Q", "i64": "q", "f64": "d"}[name]
|
||||
return struct.unpack(f"<{fmt}", fh.read(size))[0]
|
||||
|
||||
# ------------------------------------------------------------------ helpers
|
||||
def by_type(self) -> 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]
|
||||
@@ -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("<e", d) # fp16 scale
|
||||
out += packed.tobytes()
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def dequantize_q2_0(raw: bytes) -> 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("<e", raw, i * 18)[0]
|
||||
qs = raw[i * 18 + 2: i * 18 + 18]
|
||||
for j in range(64):
|
||||
c = (qs[j // 4] >> ((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="<f4")
|
||||
self.tensors.append(_Tensor(name, list(a.shape), "F32", a.tobytes()))
|
||||
|
||||
def add_q2_0(self, name: str, arr: np.ndarray, shape: list[int]) -> 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("<Q", len(key)) + key.encode("utf-8")
|
||||
if type_name.startswith("array:"):
|
||||
elem = type_name.split(":", 1)[1]
|
||||
out += struct.pack("<I", _META_IDS["array"])
|
||||
out += struct.pack("<I", _META_IDS[elem])
|
||||
out += struct.pack("<Q", len(value))
|
||||
for v in value:
|
||||
out += self._scalar(elem, v)
|
||||
return bytes(out)
|
||||
out += struct.pack("<I", _META_IDS[type_name])
|
||||
out += self._scalar(type_name, value)
|
||||
return bytes(out)
|
||||
|
||||
@staticmethod
|
||||
def _scalar(type_name: str, v) -> bytes:
|
||||
if type_name == "string":
|
||||
b = v.encode("utf-8")
|
||||
return struct.pack("<Q", len(b)) + b
|
||||
fmt = {"u8": "<B", "i8": "<b", "u16": "<H", "i16": "<h", "u32": "<I", "i32": "<i",
|
||||
"f32": "<f", "bool": "<?", "u64": "<Q", "i64": "<q", "f64": "<d"}[type_name]
|
||||
return struct.pack(fmt, v)
|
||||
|
||||
def write(self, path) -> pathlib.Path:
|
||||
path = pathlib.Path(path)
|
||||
body = bytearray()
|
||||
body += struct.pack("<I", GGUF_MAGIC)
|
||||
body += struct.pack("<I", 3) # GGUF v3
|
||||
body += struct.pack("<Q", len(self.tensors))
|
||||
body += struct.pack("<Q", len(self.metadata))
|
||||
for k, (t, v) in self.metadata.items():
|
||||
body += self._kv_bytes(k, t, v)
|
||||
|
||||
# Tensor directory: offsets are relative to the start of the data section.
|
||||
offset = 0
|
||||
infos = bytearray()
|
||||
for t in self.tensors:
|
||||
infos += struct.pack("<Q", len(t.name)) + t.name.encode("utf-8")
|
||||
infos += struct.pack("<I", len(t.shape))
|
||||
infos += struct.pack(f"<{len(t.shape)}Q", *t.shape)
|
||||
infos += struct.pack("<I", TYPE_IDS[t.type_name])
|
||||
infos += struct.pack("<Q", offset)
|
||||
offset += len(t.data)
|
||||
offset = (offset + self.alignment - 1) // self.alignment * self.alignment
|
||||
body += infos
|
||||
|
||||
pad = (-len(body)) % self.alignment
|
||||
body += b"\0" * pad
|
||||
for t in self.tensors:
|
||||
body += t.data
|
||||
pad = (-len(t.data)) % self.alignment
|
||||
body += b"\0" * pad
|
||||
|
||||
path.write_bytes(bytes(body))
|
||||
return path
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ self-check
|
||||
def _selfcheck() -> 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())
|
||||
@@ -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 `<out>/<name>.bin` (int32 header: the KERNEL type id,
|
||||
rows, cols - then the raw GGUF block bytes) and `<out>/<name>.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("<e", 1.0) # fp16 1.0 = 0x3c00: a tame, exactly-representable scale
|
||||
|
||||
|
||||
def repair_scales(name: str, raw: np.ndarray) -> 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="<f4").tobytes())
|
||||
print(f" {name:<8} type {KERNEL_IDS[name]:>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())
|
||||
@@ -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 <model>-00001-of-00002.gguf --out pack/iq3_xxs (standalone)
|
||||
python tools/iq_pack.py --gguf <model>-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 (<name>-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("<u2").tobytes() # the exact BF16 values
|
||||
rec.update(method="f32->bf16: the values are BF16's (low 16 bits zero)", exact=True, max_abs_err=0.0)
|
||||
return "4", data, len(data), rec
|
||||
if not compat_bf16:
|
||||
what = "F32 with values that are not BF16" if type_name == "F32" else type_name
|
||||
return f"{name} is {what}, but the engine requires BF16; use --compat-bf16 (rounds to nearest-even)"
|
||||
data = bf16_bytes(raw, type_name)
|
||||
got = (np.frombuffer(data, dtype="<u2").astype(np.uint32) << 16).view(np.float32)
|
||||
rec.update(method="dequantize->bf16 round-to-nearest-even (--compat-bf16)" if type_name not in FLOAT else
|
||||
"%s->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("<f2").tobytes()
|
||||
return "5", data, len(data), rec
|
||||
# form == "F32"
|
||||
if type_name not in ("F16", "BF16") and not compat_bf16:
|
||||
return f"{name} is {type_name}, but the engine reads F32; use --compat-bf16"
|
||||
data = values.astype("<f4").tobytes()
|
||||
rec.update(method="%s->f32 widening" % type_name.lower(), exact=True, max_abs_err=0.0)
|
||||
return "2", data, len(data), rec
|
||||
|
||||
|
||||
def index_standalone(src, out, model: Model, compat_bf16: bool = False) -> 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 <out>/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())
|
||||
@@ -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("<HH", blob, 24 + 4 * i) for i in range(n)]
|
||||
|
||||
|
||||
def read_trace(path, n_expert=N_EXPERT):
|
||||
"""(layer, k, k expert ids, k weights) records, as `--dump-routing` writes them."""
|
||||
blob = Path(path).read_bytes()
|
||||
off, freq = 0, defaultdict(int)
|
||||
while off + 8 <= len(blob):
|
||||
layer, k = struct.unpack_from("<ii", blob, off)
|
||||
off += 8
|
||||
for e in struct.unpack_from("<%di" % k, blob, off):
|
||||
if 0 <= layer < N_LAYER and 0 <= e < n_expert:
|
||||
freq[(layer, e)] += 1
|
||||
off += 8 * k # the ids and the weights
|
||||
return freq
|
||||
|
||||
|
||||
def write_profile(path, ranked, n_expert=N_EXPERT):
|
||||
table = [[-1] * n_expert for _ in range(N_LAYER)]
|
||||
for slot, (layer, e) in enumerate(ranked):
|
||||
table[layer][e] = slot
|
||||
with open(path, "wb") as f:
|
||||
f.write(MAGIC + struct.pack("<5I", VERSION, N_LAYER, n_expert, len(ranked), len(ranked)))
|
||||
for layer, e in ranked:
|
||||
f.write(struct.pack("<HH", layer, e))
|
||||
for layer in range(N_LAYER):
|
||||
f.write(struct.pack("<%di" % n_expert, *table[layer]))
|
||||
|
||||
|
||||
def rank_profile(base_pairs, trace_freq, n_expert=N_EXPERT, no_base=False, reorder=False):
|
||||
"""The ranked (layer, expert) list and the counts it was built from (`base`, `trace`, `fill`).
|
||||
|
||||
Default: the base's order, then the traces' pairs most frequent first, then the fill. With `reorder` (or
|
||||
`no_base`) the traces' pairs come first, so a base that already ranks every pair no longer hides them; the base
|
||||
(unless `no_base`) and then the fill follow. A base is never reordered against itself - it only ever fills."""
|
||||
ranked, seen, counts = [], set(), defaultdict(int)
|
||||
|
||||
def take(pairs, key):
|
||||
for p in pairs:
|
||||
p = (int(p[0]), int(p[1]))
|
||||
if p not in seen:
|
||||
seen.add(p)
|
||||
ranked.append(p)
|
||||
counts[key] += 1
|
||||
|
||||
trace_pairs = [p for p, _ in sorted(trace_freq.items(), key=lambda kv: (-kv[1], kv[0]))]
|
||||
if no_base or reorder:
|
||||
take(trace_pairs, "trace")
|
||||
if not no_base:
|
||||
take(base_pairs, "base")
|
||||
if not (no_base or reorder):
|
||||
take(trace_pairs, "trace")
|
||||
take(((layer, e) for e in range(n_expert) for layer in range(N_LAYER)), "fill")
|
||||
return ranked, counts
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
||||
ap.add_argument("traces", nargs="*", help="routing traces from --dump-routing")
|
||||
ap.add_argument("--base", default=str(ROOT / "data" / "expert-profile.bin"), help="ranking to keep first")
|
||||
ap.add_argument("--no-base", action="store_true", help="rank by the traces only")
|
||||
ap.add_argument("--reorder", action="store_true",
|
||||
help="rank the traces' pairs before the base's (the base, then the fill, follow); needed with a "
|
||||
"base that already ranks every pair, where --base alone cannot change the order")
|
||||
ap.add_argument("--out", default=str(ROOT / "data" / "expert-profile.bin"))
|
||||
ap.add_argument("--n-expert", type=int, default=N_EXPERT, help="experts per layer (default 512)")
|
||||
a = ap.parse_args()
|
||||
|
||||
ne = a.n_expert
|
||||
freq = defaultdict(int)
|
||||
for t in a.traces:
|
||||
for p, c in read_trace(t, ne).items():
|
||||
freq[p] += c
|
||||
base_pairs = [] if a.no_base else read_profile(a.base, ne)
|
||||
ranked, counts = rank_profile(base_pairs, freq, ne, no_base=a.no_base, reorder=a.reorder)
|
||||
write_profile(a.out, ranked, ne)
|
||||
assert read_profile(a.out, ne) == ranked, "the profile did not survive the round trip"
|
||||
print(f"wrote {a.out}: {len(ranked)} ranked pairs ({counts['base']} from the base, {counts['trace']} from the "
|
||||
f"traces, {counts['fill']} filled in)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,308 @@
|
||||
"""tools/mtp_fetch.py - plan v0.3, P0.3/P6: the MTP block from the BF16 checkpoint, without the checkpoint.
|
||||
|
||||
The GSQ-RCO GGUF ships no MTP head. The BF16 checkpoint (Qwen/Qwen3.8-Flash-Next, 360 GB in 131 shards) does:
|
||||
31 `mtp.*` tensors scattered over 28 shards. Safetensors puts a JSON header (name -> 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("<Q", get(url, 0, 7))[0]
|
||||
header = json.loads(get(url, 8, 8 + n - 1))
|
||||
return 8 + n, header
|
||||
|
||||
|
||||
def inventory(out):
|
||||
index = json.loads(get(REPO + "model.safetensors.index.json"))["weight_map"]
|
||||
mtp = {k: v for k, v in index.items() if k.startswith("mtp.")}
|
||||
rows, total = [], 0
|
||||
for shard in sorted(set(mtp.values())):
|
||||
base, header = shard_header(shard)
|
||||
for name, meta in header.items():
|
||||
if name in mtp and mtp[name] == shard:
|
||||
a, b = meta["data_offsets"]
|
||||
rows.append(dict(name=name, shard=shard, dtype=meta["dtype"], shape=meta["shape"],
|
||||
start=base + a, end=base + b - 1, bytes=b - a))
|
||||
total += b - a
|
||||
missing = sorted(set(mtp) - set(r["name"] for r in rows))
|
||||
if missing:
|
||||
sys.exit("tensors named in the index but absent from their shard headers: %s" % missing)
|
||||
rows.sort(key=lambda r: r["name"])
|
||||
os.makedirs(out, exist_ok=True)
|
||||
with open(os.path.join(out, "mtp-inventory.json"), "w", encoding="utf-8") as f:
|
||||
json.dump(dict(repo=REPO, total_bytes=total, tensors=rows), f, indent=1)
|
||||
lines = ["# MTP block in the BF16 checkpoint", "", "%d tensors, %.3f GB, in %d shards." % (len(rows), total / 1e9, len(set(r["shard"] for r in rows))), "",
|
||||
"| tensor | dtype | shape | MB |", "|---|---|---|---:|"]
|
||||
for r in rows:
|
||||
lines.append("| `%s` | %s | %s | %.1f |" % (r["name"], r["dtype"], "x".join(map(str, r["shape"])), r["bytes"] / 1e6))
|
||||
text = "\n".join(lines) + "\n"
|
||||
with open(os.path.join(out, "mtp-inventory.md"), "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
print(text)
|
||||
return rows
|
||||
|
||||
|
||||
def fetch(out, only):
|
||||
inv_path = os.path.join(out, "mtp-inventory.json")
|
||||
tdir = os.path.join(out, "tensors")
|
||||
inv = None
|
||||
if os.path.exists(inv_path):
|
||||
try:
|
||||
with open(inv_path, encoding="utf-8") as f:
|
||||
inv = json.load(f)
|
||||
except ValueError:
|
||||
inv = None
|
||||
# The byte ranges belong to one revision: an inventory read from another repository or revision is read again,
|
||||
# and a tensor fetched from there is not resumed - it is kept only when it is the pinned revision's (sha256).
|
||||
same = isinstance(inv, dict) and inv.get("repo") == REPO
|
||||
rows = inv["tensors"] if same else inventory(out)
|
||||
os.makedirs(tdir, exist_ok=True)
|
||||
manifest = []
|
||||
chunk = 64 << 20
|
||||
for r in rows:
|
||||
if only and only not in r["name"]:
|
||||
continue
|
||||
path = os.path.join(tdir, r["name"] + ".bin")
|
||||
want = SHA256.get(r["name"]) if pinned() else None
|
||||
if os.path.exists(path) and not same and (
|
||||
want is None or os.path.getsize(path) != r["bytes"] or sha256_of(path) != want):
|
||||
os.remove(path)
|
||||
for attempt in range(2):
|
||||
have = os.path.getsize(path) if os.path.exists(path) else 0
|
||||
if have > 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()
|
||||
@@ -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="<u2")
|
||||
if raw.size != int(np.prod(shape)):
|
||||
raise ValueError(f"{path}: {raw.size} values, expected shape {shape}")
|
||||
return (raw.astype(np.uint32) << 16).view(np.float32).reshape(shape)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ quantizers
|
||||
def q2_0(w: np.ndarray) -> 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="<u2", mode="r", shape=tuple(shape))
|
||||
x = _Experts(raw)
|
||||
if shape[-1] % block:
|
||||
raise ValueError(f"{name}: inner dim {shape[-1]} not a multiple of {block}")
|
||||
parts = [fn(x[e]) for e in range(shape[0])] # one expert at a time bounds memory
|
||||
blob = np.concatenate(parts)
|
||||
errs = []
|
||||
for e in range(min(a.check_experts, shape[0])):
|
||||
ref = x[e].reshape(-1)
|
||||
got = dequant(a.experts, parts[e], ref.size)
|
||||
errs.append(float(np.sqrt(((got - ref) ** 2).mean()) / (np.sqrt((ref ** 2).mean()) + 1e-12)))
|
||||
# gguf-py takes the quantized bytes with the ELEMENT shape; ggml order is innermost-first.
|
||||
w.add_tensor(name, blob, raw_shape=list(shape[:-1]) + [shape[-1] // block * block_bytes], raw_dtype=qtype)
|
||||
report.append({"tensor": name, "format": a.experts, "bytes": int(blob.size),
|
||||
"relative_rms_error_first_experts": round(float(np.mean(errs)), 5),
|
||||
"seconds": round(time.time() - t0, 1)})
|
||||
elif len(shape) == 1:
|
||||
x = load_bf16(src / t["file"], shape)
|
||||
w.add_tensor(name, x.astype(np.float32))
|
||||
report.append({"tensor": name, "format": "F32", "bytes": x.size * 4})
|
||||
else:
|
||||
bf = np.fromfile(src / t["file"], dtype="<u2").reshape(shape)
|
||||
w.add_tensor(name, bf, raw_dtype=gguf.GGMLQuantizationType.BF16)
|
||||
report.append({"tensor": name, "format": "BF16", "bytes": bf.size * 2})
|
||||
print(f"{name}: {report[-1]['format']} {report[-1]['bytes'] / 1e6:.1f} MB", flush=True)
|
||||
w.write_header_to_file()
|
||||
w.write_kv_data_to_file()
|
||||
w.write_tensors_to_file()
|
||||
w.close()
|
||||
total = sum(r["bytes"] for r in report)
|
||||
Path(a.out + ".report.json").write_text(json.dumps({"total_bytes": total, "tensors": report}, indent=1))
|
||||
print(f"wrote {a.out}: {total / 1e9:.3f} GB of tensor data")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
"""tools/mtp_rt.py - plan v0.3 P6: the MTP draft layer's runtime files, from the packed MTP GGUF.
|
||||
|
||||
python tools/mtp_rt.py --gguf <Strata>/mtp-bf16/mtp-q2_0.gguf --out <Strata>/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())
|
||||
@@ -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: <pack>/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())
|
||||
@@ -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")
|
||||
@@ -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("<f4").tobytes(), False
|
||||
|
||||
|
||||
def canonicalise(name: str, tname: str, raw: bytes):
|
||||
"""Source bytes -> 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("<f4").tobytes(), False
|
||||
else:
|
||||
a16 = vals.astype(np.float16)
|
||||
if not np.array_equal(a16.astype(np.float32), vals):
|
||||
raise ValueError("%s: P16 would lose precision, so this tensor needs P32" % name)
|
||||
vb, v16 = a16.tobytes(), True
|
||||
ent = dict(common, elements=int(vals.size), values_fp16=v16)
|
||||
ent["values"] = put(vb)
|
||||
return bytes(body), ent
|
||||
|
||||
codes, scales, offsets, m = canonicalise(name, tname, raw)
|
||||
codes = np.ascontiguousarray(codes)
|
||||
scales = np.ascontiguousarray(scales.reshape(-1), dtype=np.float32)
|
||||
n_el = int(codes.size)
|
||||
bits = code_bits(m.form)
|
||||
codes_b = pack_codes(codes, bits)
|
||||
scales_b, sc16 = choose_scale_dtype(scales)
|
||||
|
||||
ent = dict(common, elements=n_el, code_bits=bits)
|
||||
ent["codes"] = put(codes_b)
|
||||
ent["scales"] = put(scales_b)
|
||||
ent["scales_fp16"] = sc16
|
||||
if offsets is not None:
|
||||
ob, o16 = choose_scale_dtype(np.ascontiguousarray(offsets.reshape(-1), dtype=np.float32))
|
||||
ent["offsets"] = put(ob)
|
||||
ent["offsets_fp16"] = o16
|
||||
return bytes(body), ent
|
||||
|
||||
|
||||
def decode_entry(head: bytes, ent: dict) -> 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="<f2" if ent["values_fp16"] else "<f4").astype(np.float32)
|
||||
|
||||
n = ent["elements"]
|
||||
codes = unpack_codes(head[ent["codes"]["offset"]: ent["codes"]["offset"] + ent["codes"]["bytes"]],
|
||||
ent["code_bits"], n)
|
||||
sc = head[ent["scales"]["offset"]: ent["scales"]["offset"] + ent["scales"]["bytes"]]
|
||||
sc = np.frombuffer(sc, dtype="<f2" if ent["scales_fp16"] else "<f4").astype(np.float32)
|
||||
if "offsets" in ent:
|
||||
ob = head[ent["offsets"]["offset"]: ent["offsets"]["offset"] + ent["offsets"]["bytes"]]
|
||||
off = np.frombuffer(ob, dtype="<f2" if ent.get("offsets_fp16") else "<f4").astype(np.float32)
|
||||
else:
|
||||
off = None
|
||||
if ent["codebook"] == "IQ4NL":
|
||||
v = KV_IQ4NL[codes]
|
||||
else:
|
||||
v = (codes.astype(np.int32) + ent["code_bias"]).astype(np.float32)
|
||||
g = ent["group_elems"]
|
||||
if g == 1: # one scale for the whole tensor
|
||||
return (v * sc[0]).reshape(-1) if off is None else (v * sc[0] + off[0]).reshape(-1)
|
||||
out = v.reshape(-1, g) * sc[:, None]
|
||||
if off is not None:
|
||||
out = out + off[:, None]
|
||||
return out.reshape(-1)
|
||||
|
||||
|
||||
def sha256(path: pathlib.Path, chunk: int = 1 << 24) -> 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())
|
||||
@@ -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: `<think>`, `<tool_call>`, `<tool_response>`, ...) 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 `<tool_response>` 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 `<think>` 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
|
||||
`</think>` 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 `<out_dir>/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())
|
||||
@@ -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()
|
||||
@@ -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, "<u2"), (x.view(np.uint32) >> 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", "<u2")
|
||||
np.testing.assert_array_equal(got, np.frombuffer(iq_pack.bf16_bytes(x.view(np.uint8).ravel(), "F32"),
|
||||
dtype="<u2"))
|
||||
r = conv["tensors"][0]
|
||||
back = (got.astype(np.uint32) << 16).view(np.float32)
|
||||
self.assertFalse(r["exact"])
|
||||
self.assertAlmostEqual(r["max_abs_err"], float(np.max(np.abs(back - x.ravel()))))
|
||||
self.assertLessEqual(r["max_abs_err"], 2.0 ** -8)
|
||||
self.assertIn("--compat-bf16", r["method"])
|
||||
|
||||
def test_non_finite_is_refused(self):
|
||||
for bad in (0x7FC00000, 0x7F800000, 0xFF800000): # NaN and +-Inf: their low 16 bits are zero too
|
||||
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
||||
x = bits([[0x3F800000] * 31 + [bad]] * 2)
|
||||
(Path(tmp) / "dense.bin").write_bytes(b"previous pack")
|
||||
for flags in ((), (True,)):
|
||||
rc, log, *_ = pack_one(Path(tmp), [("blk.0.ssm_alpha.weight", x, Q.F32)], *flags)
|
||||
self.assertEqual(rc, 1, (hex(bad), flags))
|
||||
self.assertIn("non-finite", log)
|
||||
self.assertEqual((Path(tmp) / "dense.bin").read_bytes(), b"previous pack")
|
||||
self.assertFalse((Path(tmp) / "dense.bin.tmp").exists())
|
||||
rc, log, *_ = pack_one(Path(tmp), [("blk.1.ple_conv1d.weight", x, Q.F32)])
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn("non-finite", log)
|
||||
|
||||
def test_ple_conv1d_f32_is_narrowed_by_the_loader(self):
|
||||
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
||||
conv1d = np.random.default_rng(3).normal(0, 0.0062, (32, 4)).astype(np.float32)
|
||||
rc, log, rows, dense, conv = pack_one(Path(tmp), [("blk.1.ple_conv1d.weight", conv1d, Q.F32)])
|
||||
self.assertEqual(rc, 0, log) # no --compat-bf16 needed
|
||||
row = rows["blk.1.ple_conv1d.weight"]
|
||||
self.assertEqual((row[2], row[4], row[6]), ("3", str(conv1d.nbytes), str(conv1d.nbytes // 2)))
|
||||
np.testing.assert_array_equal(stored(rows, dense, "blk.1.ple_conv1d.weight", "<f4"), conv1d.ravel())
|
||||
r = conv["tensors"][0]
|
||||
self.assertEqual((r["src_type"], r["dst_type"]), ("F32", "F16"))
|
||||
self.assertIn("index kind 3", r["method"])
|
||||
h = conv1d.astype(np.float16).astype(np.float32)
|
||||
self.assertEqual(r["exact"], bool(np.array_equal(h, conv1d)))
|
||||
self.assertAlmostEqual(r["max_abs_err"], float(np.max(np.abs(h - conv1d))))
|
||||
self.assertIn("narrowed to F16 by the loader", log)
|
||||
# an F16 conv (the GSQ-RCO files) stays as it is: index kind 5, nothing recorded
|
||||
rc, log, rows, dense, conv = pack_one(Path(tmp), [("blk.1.ple_conv1d.weight", conv1d, Q.F16)])
|
||||
self.assertEqual((rows["blk.1.ple_conv1d.weight"][2], conv["tensors"]), ("5", []))
|
||||
# beyond F16's range: refused, not saturated
|
||||
rc, log, *_ = pack_one(Path(tmp), [("blk.1.ple_conv1d.weight", conv1d * 1e7, Q.F32)])
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn("beyond F16", log)
|
||||
|
||||
def test_q8_0_projections_need_compat_and_are_recorded(self):
|
||||
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
||||
v = np.random.default_rng(4).normal(0, 0.05, (4, 64)).astype(np.float32)
|
||||
tensors = [("blk.1.ple_value.weight", v, Q.Q8_0), ("blk.2.hc_attn_up.weight", v, Q.Q8_0),
|
||||
("blk.1.ple_key.weight", v, Q.Q8_0)]
|
||||
rc, log, *_ = pack_one(Path(tmp), tensors)
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn("use --compat-bf16", log)
|
||||
self.assertNotIn("ple_key", log) # the Q8_0 key stays native
|
||||
rc, log, rows, dense, conv = pack_one(Path(tmp), tensors, True)
|
||||
self.assertEqual(rc, 0, log)
|
||||
self.assertEqual(rows["blk.1.ple_key.weight"][2], "0")
|
||||
recs = {r["name"]: r for r in conv["tensors"]}
|
||||
self.assertEqual(set(recs), {"blk.1.ple_value.weight", "blk.2.hc_attn_up.weight"})
|
||||
deq = quants.dequantize(quants.quantize(v, Q.Q8_0), Q.Q8_0).ravel()
|
||||
got = (stored(rows, dense, "blk.1.ple_value.weight", "<u2").astype(np.uint32) << 16).view(np.float32)
|
||||
r = recs["blk.1.ple_value.weight"]
|
||||
self.assertEqual((r["src_type"], r["dst_type"]), ("Q8_0", "BF16"))
|
||||
self.assertAlmostEqual(r["max_abs_err"], float(np.max(np.abs(got - deq))))
|
||||
self.assertEqual(conv["compat_bf16"], True)
|
||||
|
||||
|
||||
# ---- split artifacts: Unsloth's UD-Q4_K_XL in miniature. Shard 1 holds the metadata and no tensor; shard 2 the
|
||||
# routers, layer 0 and layer 1's down; shard 3 layer 1's gate and up (a shard boundary inside a layer, like its
|
||||
# layer 11); shard 4 one float tensor. 4 experts of 32 x 32, Q8_0 and F32.
|
||||
N_EXPERT = 4
|
||||
|
||||
|
||||
def expert(seed, shape):
|
||||
return np.random.default_rng(seed).standard_normal((N_EXPERT, *shape)).astype(np.float32)
|
||||
|
||||
|
||||
def split_model(root, name="model", split_layer=True, dup=False, split_no=None, gate1=Q.Q8_0, seed=0):
|
||||
"""Writes the 4 shards; returns their paths."""
|
||||
gu, dn = (32, 32), (32, 32)
|
||||
router = [(f"blk.{l}.ffn_gate_inp.weight", np.full((N_EXPERT, 32), 0.5, np.float32), Q.F32) for l in (0, 1)]
|
||||
l0 = [(f"blk.0.ffn_{r}_exps.weight", expert(seed + 10 + i, gu if r != "down" else dn), Q.Q8_0)
|
||||
for i, r in enumerate(("gate", "up", "down"))]
|
||||
l1_gu = [("blk.1.ffn_gate_exps.weight", expert(seed + 20, gu), gate1),
|
||||
("blk.1.ffn_up_exps.weight", expert(seed + 21, gu), Q.Q8_0)]
|
||||
l1_d = [("blk.1.ffn_down_exps.weight", expert(seed + 22, dn), Q.F32)]
|
||||
shards = [[], router + l0 + (l1_d if split_layer else []), l1_gu + ([] if split_layer else l1_d),
|
||||
[("output_norm.weight", np.ones(32, np.float32), Q.F32)]]
|
||||
if dup:
|
||||
shards[3].append(l1_gu[1])
|
||||
total = sum(len(s) for s in shards)
|
||||
paths = []
|
||||
for i, tensors in enumerate(shards):
|
||||
p = root / f"{name}-{i + 1:05d}-of-00004.gguf"
|
||||
no = split_no.get(i, i) if split_no else i
|
||||
write_gguf(p, tensors, split=(no, 4, total), arch=i == 0)
|
||||
paths.append(p)
|
||||
return paths
|
||||
|
||||
|
||||
def run_pack(first, out, *extra):
|
||||
(out / "tokenizer").mkdir(parents=True, exist_ok=True)
|
||||
for n in ["vocab.json", "chat_template.jinja"]:
|
||||
(out / "tokenizer" / n).touch()
|
||||
buf = io.StringIO()
|
||||
with patch.object(sys, "argv", ["iq_pack.py", "--gguf", str(first), "--out", str(out), *extra]):
|
||||
with contextlib.redirect_stdout(buf):
|
||||
rc = iq_pack.main()
|
||||
return rc, buf.getvalue()
|
||||
|
||||
|
||||
def expected_experts(model):
|
||||
"""experts.bin from first principles: per layer, per expert, gate | up | down slices."""
|
||||
parts = []
|
||||
for l in (0, 1):
|
||||
ts = [model.bytes(f"blk.{l}.ffn_{r}_exps.weight").reshape(N_EXPERT, -1) for r in ("gate", "up", "down")]
|
||||
parts.append(np.concatenate(ts, axis=1).tobytes())
|
||||
return b"".join(parts)
|
||||
|
||||
|
||||
class SplitArtifactTests(unittest.TestCase):
|
||||
def test_four_shards_and_a_layer_split_per_role(self):
|
||||
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
||||
root = Path(tmp)
|
||||
paths = split_model(root)
|
||||
rc, log = run_pack(paths[0], root / "pack", "--experts-bin")
|
||||
self.assertEqual(rc, 0, log)
|
||||
text = (root / "pack" / "native_experts.txt").read_text()
|
||||
head, line0, line1 = text.splitlines()
|
||||
self.assertTrue(head.startswith("# strata native experts v4:"), head)
|
||||
self.assertIn("(n_expert 4,", head)
|
||||
s2, s3 = paths[1].name, paths[2].name
|
||||
self.assertEqual(line0.split()[8:], [s2])
|
||||
self.assertEqual(line1.split()[8:], [f"{s3},{s3},{s2}"])
|
||||
# every role's offset is absolute in ITS shard: shard 3's data_start for gate/up, shard 2's for down
|
||||
m = iq_pack.Model(paths[0])
|
||||
for line, l in ((line0, 0), (line1, 1)):
|
||||
f = line.split()
|
||||
for r, role in enumerate(("gate", "up", "down")):
|
||||
g, t, _, _ = m.where[f"blk.{l}.ffn_{role}_exps.weight"]
|
||||
self.assertEqual(int(f[5 + r]), g.data_start + t.offset)
|
||||
self.assertNotEqual(m.where["blk.1.ffn_gate_exps.weight"][0].data_start,
|
||||
m.where["blk.1.ffn_down_exps.weight"][0].data_start)
|
||||
self.assertEqual((root / "pack" / "experts.bin").read_bytes(), expected_experts(m))
|
||||
side = json.loads((root / "pack" / "experts.bin.src.json").read_text())
|
||||
self.assertEqual([s["name"] for s in side["shards"]], [p.name for p in paths])
|
||||
self.assertFalse(list((root / "pack").glob("*.tmp")))
|
||||
# the index: routers as BF16, nothing of the experts
|
||||
_, rows = iq_pack.read_index(root / "pack" / "index.txt")
|
||||
self.assertNotIn("blk.1.ffn_gate_exps.weight", rows)
|
||||
self.assertEqual(rows["blk.1.ffn_gate_inp.weight"][2], "4")
|
||||
|
||||
def test_unsplit_layers_keep_the_v3_file(self):
|
||||
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
||||
root = Path(tmp)
|
||||
paths = split_model(root, split_layer=False)
|
||||
rc, log = run_pack(paths[0], root / "pack")
|
||||
self.assertEqual(rc, 0, log)
|
||||
head, line0, line1 = (root / "pack" / "native_experts.txt").read_text().splitlines()
|
||||
self.assertTrue(head.startswith("# strata native experts v3: layer gu_type d_type offset blob_bytes "
|
||||
"gate_off up_off down_off [shard] (n_expert 4, total "), head)
|
||||
self.assertEqual(line1.split()[8:], [paths[2].name])
|
||||
|
||||
def test_missing_shard(self):
|
||||
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
||||
paths = split_model(Path(tmp))
|
||||
paths[3].unlink()
|
||||
with self.assertRaisesRegex(FileNotFoundError, "missing model shards.*00004-of-00004"):
|
||||
iq_pack.Model(paths[0])
|
||||
|
||||
def test_duplicate_tensor_across_shards(self):
|
||||
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
||||
paths = split_model(Path(tmp), dup=True)
|
||||
with self.assertRaisesRegex(ValueError, "duplicate tensor blk.1.ffn_up_exps.weight"):
|
||||
iq_pack.Model(paths[0])
|
||||
|
||||
def test_shard_of_another_split(self):
|
||||
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
||||
paths = split_model(Path(tmp), split_no={2: 1})
|
||||
with self.assertRaisesRegex(ValueError, "does not declare itself shard 3 of 4"):
|
||||
iq_pack.Model(paths[0])
|
||||
|
||||
def test_truncated_shard(self):
|
||||
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
||||
paths = split_model(Path(tmp))
|
||||
paths[2].write_bytes(paths[2].read_bytes()[:-64])
|
||||
with self.assertRaisesRegex(ValueError, "truncated tensor"):
|
||||
iq_pack.Model(paths[0])
|
||||
|
||||
def test_wrong_type_or_shape_leaves_the_pack_alone(self):
|
||||
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
||||
root = Path(tmp)
|
||||
paths = split_model(root, gate1=Q.F32) # layer 1: gate F32, up Q8_0
|
||||
pack = root / "pack"
|
||||
pack.mkdir()
|
||||
(pack / "native_experts.txt").write_text("previous pack")
|
||||
rc, log = run_pack(paths[0], pack)
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn("layer 1: gate and up differ in type", log)
|
||||
self.assertEqual((pack / "native_experts.txt").read_text(), "previous pack")
|
||||
self.assertFalse((pack / "dense.bin").exists())
|
||||
|
||||
def test_interrupted_pack(self):
|
||||
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
||||
root = Path(tmp)
|
||||
paths = split_model(root)
|
||||
pack = root / "pack"
|
||||
real = np.concatenate
|
||||
calls = []
|
||||
|
||||
def dies_on_layer_1(parts, axis):
|
||||
calls.append(1)
|
||||
if len(calls) == 2:
|
||||
raise KeyboardInterrupt("stopped part-way")
|
||||
return real(parts, axis=axis)
|
||||
with patch.object(iq_pack.np, "concatenate", dies_on_layer_1):
|
||||
with self.assertRaises(KeyboardInterrupt):
|
||||
run_pack(paths[0], pack, "--experts-bin")
|
||||
self.assertFalse((pack / "experts.bin").exists())
|
||||
self.assertFalse((pack / "experts.bin.src.json").exists())
|
||||
# the index stops part-way too: the old pack's files stay as they were
|
||||
before = {n: (pack / n).read_bytes() for n in ("index.txt", "dense.bin", "native_experts.txt")}
|
||||
with patch.object(iq_pack, "write_index", side_effect=KeyboardInterrupt("stopped")):
|
||||
with self.assertRaises(KeyboardInterrupt):
|
||||
run_pack(paths[0], pack)
|
||||
self.assertEqual(before, {n: (pack / n).read_bytes() for n in before})
|
||||
rc, log = run_pack(paths[0], pack, "--experts-bin")
|
||||
self.assertEqual(rc, 0, log)
|
||||
self.assertEqual((pack / "experts.bin").read_bytes(), expected_experts(iq_pack.Model(paths[0])))
|
||||
|
||||
def test_stale_same_size_experts_bin(self):
|
||||
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
||||
root = Path(tmp)
|
||||
(root / "a").mkdir()
|
||||
(root / "b").mkdir()
|
||||
other = split_model(root / "a", name="other", seed=100)
|
||||
paths = split_model(root / "b")
|
||||
pack = root / "pack"
|
||||
rc, log = run_pack(other[0], pack, "--experts-bin") # another model, the same geometry
|
||||
self.assertEqual(rc, 0, log)
|
||||
stale = (pack / "experts.bin").read_bytes()
|
||||
want = expected_experts(iq_pack.Model(paths[0]))
|
||||
self.assertEqual(len(stale), len(want))
|
||||
self.assertNotEqual(stale, want)
|
||||
# without --experts-bin the engine would read it: refused, nothing rewritten
|
||||
rc, log = run_pack(paths[0], pack)
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn("another source", log)
|
||||
self.assertEqual((pack / "experts.bin").read_bytes(), stale)
|
||||
# with it: rewritten, not reused by its size
|
||||
rc, log = run_pack(paths[0], pack, "--experts-bin")
|
||||
self.assertEqual(rc, 0, log)
|
||||
self.assertEqual((pack / "experts.bin").read_bytes(), want)
|
||||
# and now reused
|
||||
rc, log = run_pack(paths[0], pack, "--experts-bin")
|
||||
self.assertIn("not rewritten", log)
|
||||
# an experts.bin without its sidecar (an older packer) is rewritten too
|
||||
(pack / "experts.bin.src.json").unlink()
|
||||
(pack / "experts.bin").write_bytes(stale)
|
||||
rc, log = run_pack(paths[0], pack, "--experts-bin")
|
||||
self.assertEqual((pack / "experts.bin").read_bytes(), want)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Tests for tools/make_profile.py, without a model: synthetic profiles and routing traces.
|
||||
|
||||
python -m unittest tools.test_make_profile
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tools"))
|
||||
import make_profile as MP # noqa: E402
|
||||
|
||||
NE = 4 # a tiny "experts per layer"; the layer count is fixed at MP.N_LAYER
|
||||
|
||||
|
||||
def write_trace(path, records):
|
||||
"""One record per (layer, [expert ids]); the reader skips k weights after the k ids."""
|
||||
with open(path, "wb") as f:
|
||||
for layer, experts in records:
|
||||
f.write(struct.pack("<ii", layer, len(experts)))
|
||||
f.write(struct.pack("<%di" % len(experts), *experts))
|
||||
f.write(struct.pack("<%df" % len(experts), *([1.0] * len(experts))))
|
||||
|
||||
|
||||
def full_base():
|
||||
"""Every pair, in an order that differs from rank_profile's fill (e-major then layer)."""
|
||||
return [(layer, e) for layer in range(MP.N_LAYER) for e in range(NE)]
|
||||
|
||||
|
||||
class RankProfile(unittest.TestCase):
|
||||
def test_a_complete_base_hides_the_trace(self):
|
||||
# the shipped profile's situation: it already ranks every pair, so the trace cannot move anything
|
||||
base = full_base()
|
||||
freq = defaultdict(int, {(5, 1): 10, (6, 2): 7})
|
||||
ranked, counts = MP.rank_profile(base, freq, NE)
|
||||
self.assertEqual(ranked, base)
|
||||
self.assertEqual(counts["trace"], 0)
|
||||
self.assertEqual(counts["base"], MP.N_LAYER * NE)
|
||||
|
||||
def test_reorder_puts_the_traces_first(self):
|
||||
base = full_base()
|
||||
freq = defaultdict(int, {(5, 1): 10, (6, 2): 7})
|
||||
ranked, counts = MP.rank_profile(base, freq, NE, reorder=True)
|
||||
self.assertEqual(ranked[:2], [(5, 1), (6, 2)])
|
||||
self.assertEqual(set(ranked), set(base)) # still every pair, once
|
||||
self.assertEqual(len(ranked), len(base))
|
||||
self.assertEqual(counts["trace"], 2)
|
||||
self.assertEqual(counts["base"], MP.N_LAYER * NE - 2) # the base fills the rest, minus the two
|
||||
|
||||
def test_frequency_and_tie_break_order_the_trace(self):
|
||||
freq = defaultdict(int, {(1, 0): 1, (2, 0): 3, (3, 0): 3})
|
||||
ranked, _ = MP.rank_profile([], freq, NE, no_base=True) # (2,0)/(3,0) tie -> 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()
|
||||
@@ -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("<Q", len(h)) + h + data
|
||||
|
||||
|
||||
A, B, X = bytes(range(64)), bytes(range(100, 164)) * 2, b"\x07" * 48
|
||||
FILES = {"model-1.safetensors": shard([("model.x", X), ("mtp.a", A)]), "model-2.safetensors": shard([("mtp.b", B)])}
|
||||
INDEX = json.dumps({"weight_map": {"model.x": "model-1.safetensors", "mtp.a": "model-1.safetensors",
|
||||
"mtp.b": "model-2.safetensors"}}).encode()
|
||||
HASHES = {"mtp.a": hashlib.sha256(A).hexdigest(), "mtp.b": hashlib.sha256(B).hexdigest()}
|
||||
|
||||
|
||||
class Response(io.BytesIO):
|
||||
def __init__(self, body, status, headers):
|
||||
super().__init__(body)
|
||||
self.status, self.headers = status, headers
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.close()
|
||||
|
||||
|
||||
class Mirror:
|
||||
"""urlopen for the fake checkpoint. `ignore_range`: 200 and the whole file (`cut`: cut to the asked length, as
|
||||
the proxy in #327 did); `wrong`: the bytes of these tensors' ranges are flipped (a source that sends bad data)."""
|
||||
|
||||
def __init__(self, ignore_range=False, cut=False, wrong=()):
|
||||
self.ignore_range, self.cut, self.wrong, self.ranges = ignore_range, cut, set(wrong), []
|
||||
|
||||
def __call__(self, req, timeout=None):
|
||||
name = req.full_url.rsplit("/", 1)[1]
|
||||
body = INDEX if name == "model.safetensors.index.json" else FILES[name]
|
||||
rng = req.get_header("Range")
|
||||
if rng is None:
|
||||
return Response(body, 200, {"Content-Length": str(len(body))})
|
||||
a, b = map(int, rng.split("=")[1].split("-"))
|
||||
self.ranges.append((name, a, b))
|
||||
if self.ignore_range:
|
||||
return Response(body[:b - a + 1] if self.cut else body, 200, {})
|
||||
part = body[a:b + 1]
|
||||
if any(t in self.wrong and self.span(name, t) == (a, b) for t in ("mtp.a", "mtp.b")):
|
||||
part = bytes(x ^ 0xFF for x in part)
|
||||
return Response(part, 206, {"Content-Range": "bytes %d-%d/%d" % (a, b, len(body))})
|
||||
|
||||
@staticmethod
|
||||
def span(name, tensor):
|
||||
raw = FILES[name]
|
||||
n = struct.unpack("<Q", raw[:8])[0]
|
||||
meta = json.loads(raw[8:8 + n]).get(tensor)
|
||||
return (8 + n + meta["data_offsets"][0], 8 + n + meta["data_offsets"][1] - 1) if meta else None
|
||||
|
||||
|
||||
class FetchCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.out = Path(self.tmp.name)
|
||||
self.patches = [mock.patch.object(M, "SHA256", HASHES), mock.patch.object(M.time, "sleep", lambda s: None),
|
||||
mock.patch.object(M, "REPO", M.PINNED)]
|
||||
for p in self.patches:
|
||||
p.start()
|
||||
|
||||
def tearDown(self):
|
||||
for p in reversed(self.patches):
|
||||
p.stop()
|
||||
self.tmp.cleanup()
|
||||
|
||||
def fetch(self, mirror):
|
||||
with mock.patch.object(M.urllib.request, "urlopen", mirror), contextlib.redirect_stdout(io.StringIO()), \
|
||||
contextlib.redirect_stderr(io.StringIO()) as err:
|
||||
M.fetch(str(self.out), None)
|
||||
return err.getvalue()
|
||||
|
||||
def tensor(self, name):
|
||||
return (self.out / "tensors" / (name + ".bin")).read_bytes()
|
||||
|
||||
|
||||
class Ranges(FetchCase):
|
||||
def test_check_range(self):
|
||||
M.check_range(206, "bytes 10-19/100", 10, 19)
|
||||
for status, cr in ((200, None), (200, "bytes 10-19/100"), (206, "bytes 0-9/100"), (206, None)):
|
||||
with self.subTest(status=status, cr=cr), self.assertRaises(IOError):
|
||||
M.check_range(status, cr, 10, 19)
|
||||
|
||||
def test_a_mirror_that_ignores_range_is_refused(self):
|
||||
for cut in (False, True): # the whole file, or cut to the asked length (#327's proxy)
|
||||
with self.subTest(cut=cut), mock.patch.object(M.urllib.request, "urlopen", Mirror(True, cut)), \
|
||||
contextlib.redirect_stderr(io.StringIO()), self.assertRaisesRegex(IOError, "not honoured"):
|
||||
M.get(M.REPO + "model-1.safetensors", 8, 15)
|
||||
|
||||
def test_fetch_from_an_honest_mirror(self):
|
||||
self.fetch(Mirror())
|
||||
self.assertEqual((self.tensor("mtp.a"), self.tensor("mtp.b")), (A, B))
|
||||
manifest = json.loads((self.out / "mtp-manifest.json").read_text())
|
||||
self.assertEqual({r["name"]: r["sha256"] for r in manifest}, HASHES)
|
||||
self.assertEqual(M.verify(str(self.out)), [])
|
||||
|
||||
def test_wrong_bytes_are_fetched_again_once_then_refused(self):
|
||||
self.fetch(Mirror())
|
||||
bad = bytes(len(A)) # an install the #327 mirror corrupted: right size, wrong bytes
|
||||
(self.out / "tensors" / "mtp.a.bin").write_bytes(bad)
|
||||
self.assertEqual(M.verify(str(self.out)), ["mtp.a"])
|
||||
err = self.fetch(Mirror()) # setup runs fetch again: the bad one is fetched again
|
||||
self.assertIn("mtp.a: wrong bytes", err)
|
||||
self.assertEqual(self.tensor("mtp.a"), A)
|
||||
self.assertEqual(M.verify(str(self.out)), [])
|
||||
os.remove(self.out / "tensors" / "mtp.b.bin")
|
||||
with self.assertRaises(SystemExit) as cm:
|
||||
self.fetch(Mirror(wrong={"mtp.b"})) # a source that keeps sending wrong data
|
||||
self.assertIn("is not the checkpoint's", str(cm.exception))
|
||||
self.assertFalse((self.out / "tensors" / "mtp.b.bin").exists())
|
||||
|
||||
def test_an_inventory_from_another_revision_is_read_again(self):
|
||||
self.fetch(Mirror())
|
||||
inv = json.loads((self.out / "mtp-inventory.json").read_text())
|
||||
inv["repo"] = "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/main/"
|
||||
for r in inv["tensors"]:
|
||||
r["start"] += 1 # that revision's ranges: not this one's
|
||||
r["end"] += 1
|
||||
(self.out / "mtp-inventory.json").write_text(json.dumps(inv))
|
||||
(self.out / "tensors" / "mtp.b.bin").write_bytes(B[:10]) # half a tensor from that revision
|
||||
mirror = Mirror()
|
||||
self.fetch(mirror)
|
||||
self.assertEqual(json.loads((self.out / "mtp-inventory.json").read_text())["repo"], M.REPO)
|
||||
self.assertEqual((self.tensor("mtp.a"), self.tensor("mtp.b")), (A, B))
|
||||
fetched = [r for r in mirror.ranges if r[2] - r[1] + 1 in (len(A), len(B))]
|
||||
self.assertEqual(fetched, [("model-2.safetensors",) + Mirror.span("model-2.safetensors", "mtp.b")],
|
||||
"mtp.a was right and is kept; mtp.b is fetched whole")
|
||||
|
||||
def test_verify_keeps_its_verdict_and_skips_other_revisions(self):
|
||||
self.fetch(Mirror())
|
||||
self.assertEqual(M.verify(str(self.out)), [])
|
||||
stamps = json.loads((self.out / "tensors" / "verified.json").read_text())
|
||||
self.assertEqual(sorted(stamps), ["mtp.a", "mtp.b"])
|
||||
with mock.patch.object(M, "sha256_of", side_effect=AssertionError("hashed an unchanged file")):
|
||||
self.assertEqual(M.verify(str(self.out)), [])
|
||||
with mock.patch.object(M, "REPO", "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/main/"):
|
||||
(self.out / "tensors" / "mtp.a.bin").write_bytes(b"x")
|
||||
self.assertEqual(M.verify(str(self.out)), []) # STRATA_MTP_REVISION: other hashes
|
||||
self.assertEqual(M.verify(str(self.out)), ["mtp.a"])
|
||||
self.assertEqual(M.verify(str(self.out / "nothing")), [])
|
||||
|
||||
|
||||
class Pinned(unittest.TestCase):
|
||||
def test_every_tensor_has_a_hash(self):
|
||||
self.assertEqual(len(M.SHA256), 31)
|
||||
for name, h in M.SHA256.items():
|
||||
self.assertTrue(name.startswith("mtp."))
|
||||
self.assertRegex(h, "^[0-9a-f]{64}$")
|
||||
self.assertIn(M.PINNED_REVISION, M.PINNED)
|
||||
|
||||
|
||||
class Setup(unittest.TestCase):
|
||||
def test_setup_rebuilds_a_corrupt_install(self):
|
||||
import setup
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
mtp = Path(d)
|
||||
self.assertFalse(setup.mtp_corrupt(mtp)) # no tensors kept: nothing to check
|
||||
(mtp / "tensors").mkdir()
|
||||
for code, want in ((0, False), (3, True), (1, False)):
|
||||
with self.subTest(code=code), mock.patch.object(
|
||||
setup.subprocess, "run", return_value=mock.Mock(returncode=code)) as run:
|
||||
self.assertEqual(setup.mtp_corrupt(mtp), want)
|
||||
self.assertIn("verify", run.call_args[0][0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user