From a69e61116b0b0372d4ac289d06523e0366b391ef Mon Sep 17 00:00:00 2001 From: vincent <84759+skygunner@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:44:59 +1000 Subject: [PATCH 01/18] qwen4: read the published 35B-A3B trunk view, add its MTP drafter and 128K serving The published qwen4exp file was refused: block_count 41 counts an in-file nextn MTP block, and read_geometry starts from the compiled shape, so a trunk view carrying no nextn_predict_layers key inherited n_mtp_layers=1 and then failed the 40-entry compress_ratios check. Reset it to 0 before reading the key, let that array cover trunk + MTP (an MTP block is full attention), and drop n_mtp_layers from the kernel-shape guard: it is file layout, not a shape the kernels run. qsa_pattn keeps G=12 instead of deriving it from the geometry. Its reduce-scatter is written for 24:2 - r[s+6], sp[h0] and px_head all need 12 slots - so deriving G=8 for q4_lite's 16:2 would read and write out of bounds. The existing runtime head-count check refuses it and the QSA layers keep the usual attention path; supporting G=8 needs a new reduction tree. Also pin the WMMA wave for G<=8 and count non-finite parity outputs, which otherwise pass every comparison silently (NaN > x is false). Tools: qwen4_split_gguf.py writes the 40-layer trunk view, splitting the four fused tensors byte for byte along their quantized rows, so nothing is requantized; iq_pack.py refuses a fused file with the split command and skips the MTP block; make_profile.py takes --n-layer; mtp_qwen4_rt.py turns the MTP sidecar into a drafter runtime. The tokenizer accepts qwen4 as an alias of the qwen35 split but with ignore_merges, as llama.cpp master reads it - 201 single-piece vocabulary entries, mostly multi-character CJK, are unreachable by any chain of merges without it. Measured on one RTX 3080 Ti 12 GB, 46 GB RAM: MTP --spec 2 decodes at 155.32 tok/s against 106.12 without (+46%), and beats --spec 3 (146.99) and --spec 4 (128.33) on the same teacher-forced text. Serving at 131072 with --kv-grow: 165.5 tok/s on a Chinese answer, 2899 tok/s reading a 24282-token prompt, 3305 resident experts. reasoning_budget_tokens closes the think block politely instead of cutting it off. Flash-Next defaults are unchanged: make_profile still defaults to 48 layers, and the new iq_pack guards are inert at nextn=0 with no fused tensors. 114 tests pass. --- docs/QWEN4.md | 285 ++++++++++++++++++ docs/models/qwen4.zh-CN.md | 83 +++++ .../include/strata/artifact/gguf_reader.hpp | 31 +- engine/include/strata/core/family_layout.hpp | 4 +- .../strata/core/geometries/q4_lite.hpp | 5 +- engine/src/kernels/cuda/qsa_pattn.cu | 6 +- engine/src/kernels/cuda/qsa_prompt_attn.cu | 4 + engine/src/kernels/qsa_prompt_attn_parity.cpp | 6 + terminal/models.json | 13 + terminal/tools/iq_pack.py | 38 +++ terminal/tools/make_profile.py | 43 +-- terminal/tools/mtp_qwen4_rt.py | 223 ++++++++++++++ terminal/tools/qwen4_split_gguf.py | 145 +++++++++ terminal/tools/strata_tokenizer.py | 12 +- terminal/tools/test_qwen4_intake.py | 5 +- terminal/tools/test_qwen4_split_gguf.py | 191 ++++++++++++ terminal/tools/test_strata_tokenizer.py | 30 +- 17 files changed, 1088 insertions(+), 36 deletions(-) create mode 100644 docs/QWEN4.md create mode 100644 docs/models/qwen4.zh-CN.md create mode 100644 terminal/models.json create mode 100644 terminal/tools/mtp_qwen4_rt.py create mode 100644 terminal/tools/qwen4_split_gguf.py create mode 100644 terminal/tools/test_qwen4_split_gguf.py diff --git a/docs/QWEN4.md b/docs/QWEN4.md new file mode 100644 index 0000000000..9774367ba9 --- /dev/null +++ b/docs/QWEN4.md @@ -0,0 +1,285 @@ +# Qwen4-35B-A3B: the trunk view, the MTP layer and speed + +This page is for people who run [Qwen4-35B-A3B](https://huggingface.co/Qwen/Qwen4-35B-A3B) (35B mixture of experts, +3B active, 256 experts, top-8) with PolyStrata on the Strata project's own engine path. The GGUF architecture is +`qwen4exp`: 40 trunk layers, 30 of them recurrent (GDN) and 10 full attention with a compressed KV selection (QSA), +plus hyper-connections on every block. For sizes and memory see [MODELS.md](MODELS.md). + +The numbers below were measured on one RTX 3080 Ti (12 GB). This is a 12 GB hybrid-mode run: about a third of the +experts stay in VRAM and the rest are read from RAM over PCIe, so a card with more memory will be faster. + +## What the published file contains + +Unsloth's [Qwen4-35B-A3B-GGUF](https://huggingface.co/unsloth/Qwen4-35B-A3B-GGUF) ships three things the engine reads +separately: + +| File | What it holds | +| --- | --- | +| `UD-IQ4_XS/...-00001-of-00002.gguf` | The trunk **and** the MTP block: `block_count` 41, `nextn_predict_layers` 1, so `blk.40.*` is the drafter, not a trunk layer. Also the fused projections. | +| `UD-IQ4_XS/...-00002-of-00002.gguf` | One tensor, `per_layer_token_embd.weight` (PLE), and no metadata at all. | +| `MTP/mtp-Qwen4-35B-A3B-Q8_0.gguf` | The same `blk.40` drafter on its own, Q8_0, 2.0 GB. | + +Two consequences for the pack: + +- **The trunk view.** The engine's geometry counts `block_count - nextn_predict_layers` layers, and the MTP block is + loaded as a drafter, not as layer 40. `tools/qwen4_split_gguf.py` writes a 40-layer view of shard 1: it drops + `blk.40.*` and `per_layer_token_embd.weight`, sets `block_count` to 40, removes `nextn_predict_layers`, truncates + `attention.compress_ratios` and `attention.recurrent_layers` to the trunk, and removes the `split.*` keys. +- **The fused projections.** `attn_qkv_gate`, `ssm_beta_alpha` and the hyper-connections' `*_down_inject` are one + tensor each where the engine expects two or three. The splitter separates them **by byte rows, without + re-quantizing**: every block format here (Q8_0, Q5_K, Q4_K, IQ4_XS) is self-contained along the input dimension, so + an output-row slice of the quantized bytes is exactly the quantized slice of the matrix. The row order is the one + llama.cpp's `qwen4exp` loader reads: qkv then gate, beta then alpha, down then inject. The widths come from the + metadata (`state` 128, `group` 16, `inner` 4096 here), not from constants. + +`tools/iq_pack.py` refuses a file that still has fused names and points at the splitter, so a pack can never be built +from the unsplit shard by accident. + +## Quick start + +Four steps, then run. `M` is the model directory and `P` the pack directory. + +```sh +# 1. the 40-layer trunk view (keeps the quantized bytes; ~20 GB, needs room beside the original) +python terminal/tools/qwen4_split_gguf.py \ + --gguf "$M/UD-IQ4_XS/Qwen4-35B-A3B-UD-IQ4_XS-00001-of-00002.gguf" \ + --out "$M/trunk40/Qwen4-35B-A3B-UD-IQ4_XS-trunk40.gguf" + +# 2. the native pack (--compat-bf16 is required: the small projections must reach the engine as BF16) +python terminal/tools/iq_pack.py --gguf "$M/trunk40/Qwen4-35B-A3B-UD-IQ4_XS-trunk40.gguf" \ + --out "$P" --compat-bf16 + +# 3. an even expert profile: 40 layers x 256 experts (make_profile.py defaults to Flash-Next's 48) +python terminal/tools/make_profile.py --no-base --n-layer 40 --n-expert 256 --out "$P/expert-profile.bin" + +# 4. the MTP sidecar as a drafter runtime (optional, but it is where the speed is) +python terminal/tools/mtp_qwen4_rt.py --gguf "$M/MTP/mtp-Qwen4-35B-A3B-Q8_0.gguf" --out "$P/mtp-rt" +``` + +Then: + +```sh +T="$M/trunk40/Qwen4-35B-A3B-UD-IQ4_XS-trunk40.gguf" +./build-q4lite/strata --pack "$P" \ + --native "$T" --native-dense-gguf "$T" \ + --ple-gguf "$M/UD-IQ4_XS/Qwen4-35B-A3B-UD-IQ4_XS-00002-of-00002.gguf" \ + --expert-profile "$P/expert-profile.bin" \ + --mtp "$P/mtp-rt" --spec 2 --prefill auto \ + --tokens-file prompt.txt --max-new 256 --greedy --vram-reserve-mib 512 +``` + +Three things that are easy to get wrong: + +- **Name the trunk view in `--native-dense-gguf` too.** With only `--native`, the engine adds the `--ple-gguf` file to + the dense list, and shard 2 then arrives twice; the load is refused as a duplicate tensor. +- **`--ple-gguf` is shard 2**, the PLE file, not a second half of the trunk. +- **`--expert-profile` is not optional in practice.** A native IQ pack needs `--spec T` (T >= 2) and `--prefill`, and + serving without a profile has been reported to crash ([#7777](https://github.com/Niko1221/Strata/issues/7777)). + +The build used here: + +```sh +cmake -G Ninja -S engine -B build-q4lite -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=ON \ + -DSTRATA_BUILD_TESTS=OFF -DSTRATA_GEOMETRY=q4_lite -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_Q6K_EXPERTS=ON \ + "-DCMAKE_CUDA_ARCHITECTURES=86-real;86-virtual" \ + -DCMAKE_C_COMPILER=gcc-14 -DCMAKE_CXX_COMPILER=g++-14 -DCMAKE_CUDA_HOST_COMPILER=g++-14 +cmake --build build-q4lite --target strata -j"$(nproc)" +``` + +## Serving it + +The run config is `terminal/strata-qwen4-35b-ud-iq4_xs.json`; `terminal/models.json` supplies the registry facts the +engine path cannot derive from a `--model` argument (this config names its file with `--native`, which the Strata +engine's main argument loop reads — `--model` is only recognised by the qwen35moe family pre-scan). + +```sh +cd terminal +.venv/bin/python -m serve.server --engine strata \ + --config strata-qwen4-35b-ud-iq4_xs.json --host 127.0.0.1 --port 8080 +``` + +The server adds `--serve` itself. It binds loopback only and sets no API key; add `api_key` to the config before +binding any other address. + +**Context: 131072 tokens with `--kv-grow`.** A 12 GB card cannot reserve KV for 128K tokens up front, so the config +uses `--kv-grow`: KV occupies only the cells a request actually reaches, the rest of VRAM stays with the expert cache, +and slots are handed back as the context grows. It requires a single GPU and `--expert-profile`, both of which this +config already has. At 131072 the cache holds **3305 resident experts in 5.24 GiB** (3539 / 5.62 GiB at 8192), so the +long context costs about 234 experts, not the answer quality. `--kv fp16|int8|q4_0|k8v4` and `--kv-resident N` are the +other levers if you need to trade KV precision or stream KV from RAM; neither is used here. + +Both protocols were checked against the running server at `--max-context 8192`: + +| Request | Result | +| --- | --- | +| `GET /v1/models` | lists `qwen4-35b-a3b-ud-iq4_xs` | +| `POST /v1/chat/completions`, Chinese, one word | `巴黎`, `finish_reason: stop`, 0.61 s | +| `POST /v1/messages` (Anthropic), English, one word | `Paris`, `stop_reason: end_turn`, 0.42 s | +| `POST /v1/chat/completions`, Chinese short prose | 344 tokens in 2,226 ms = **154.5 tok/s**, `stop`, drafts 166/207 accepted | + +And again at the shipped `--max-context 131072 --kv-grow --spec 2`: + +| Request | Result | +| --- | --- | +| English story, `reasoning_budget_tokens: 512`, `max_tokens 900` | 698 tokens, `stop`, 969 characters of `content`, 3.92 s end to end | +| Engine-side decode, 37-token prompt | 450 tokens in 2,745 ms = **163.9 tok/s**, drafts 190/263 accepted | +| Chinese, "explain the blue sky in three sentences" | 360 tokens in 2,175 ms = **165.5 tok/s**, `stop`, drafts 153/206 accepted, 2.47 s end to end | +| Engine-side decode, 505-token prompt, 486 reused | 230 tokens in 662 ms = 347.5 tok/s, drafts 208/211 accepted | +| Long prompt read | **24,282 tokens in 8,375 ms = 2,899 tok/s** prefill | + +The 347.5 tok/s row is a highly predictable continuation (98.6% of drafts accepted) and is not a representative chat +rate; 163.9 tok/s at 72% acceptance is. The serving rate matches the CLI's 155.32 tok/s, and the server **does** stop at +the end of the turn — the CLI's `--max-new` overrun below is a harness difference, not a model one. + +**Thinking budgets.** This is a thinking model: the answer arrives in `content` and the reasoning in +`reasoning_content`. A prompt that asks for an exact word count can spend the whole budget reasoning — asked for a +200-word story, it enumerated word counts inside the think block ("three(8) sentences(9) on(10)…") and used 700 tokens +without reaching `content`, `finish_reason: length`. That is the model being careful, not a loop. + +The config sets **`reasoning_budget_tokens: 512`**, which closes the think block politely (wrap-up, then ``, +then the answer) instead of cutting it off. The same 200-word prompt that previously returned empty `content` then +produced 969 characters of story with `finish_reason: stop`. A per-request `reasoning_budget_tokens` overrides the +config value, and Anthropic's `thinking.budget_tokens` maps to it; `0` or absent means unlimited. Raise it for tasks +that genuinely need long deliberation. + +**RAM is the serving constraint on this box.** The engine holds about 20 GB RSS (16.25 GiB of experts loaded into RAM +and partly locked for the GPU). With a desktop session also running, `MemAvailable` fell to 12 GB and zram swap to +6.6 GB, and the first long request decoded at **24.7 tok/s** while the CPU pool read **2.6 GB/s**. The same request +after the working set warmed ran at 143.9 tok/s. Watch the same bandwidth line as in +[the validity gate](#the-validity-gate-watch-the-cpu-pools-bandwidth); on a 46 GB box with other programs open, expect +the first long answer after a start to be slow. + +## Speed + +> **Measured on:** one NVIDIA RTX 3080 Ti 12 GB (CUDA 12.8, sm_86), 46 GB RAM, PCIe link read at 25.4 GB/s, +> Unsloth UD-IQ4_XS, engine `strata 0.1.66` built with `-DSTRATA_GEOMETRY=q4_lite`. Workload: a 28-token story prompt, +> 256 greedy tokens, `--prefill auto --vram-reserve-mib 512`, one request at a time. Every run quoted here passed the +> validity gate below. + +**Natural greedy decode** — each setting generates its own continuation: + +| Drafter | Decode | Acceptance | Tokens per round | +| --- | ---: | ---: | ---: | +| none (`--spec 2`, suffix drafts only) | 106.28 tok/s | 0.056 | 1.06 | +| **MTP `--spec 2`** | **153.35 tok/s** | 0.675 | 1.71 | +| MTP `--spec 3` | 144.07 tok/s | 0.483 | 1.97 | +| MTP `--spec 4` | 126.87 tok/s | 0.374 | 2.12 | + +**Same text for every setting** (`--spec-follow`, teacher-forced on the 256 tokens above). This is the fair +comparison: the rows above are not the same continuation, and a wider window looks better or worse partly because the +text it happened to produce was easier or harder to predict. + +| Drafter | Decode | Acceptance | Tokens per round | +| --- | ---: | ---: | ---: | +| none (`--spec 2`) | 106.12 tok/s | 0.056 | 1.06 | +| **MTP `--spec 2`** | **155.32 tok/s** | 0.703 | 1.74 | +| MTP `--spec 3` | 146.99 tok/s | 0.516 | 2.04 | +| MTP `--spec 4` | 128.33 tok/s | 0.383 | 2.14 | + +Both agree: **`--spec 2` is the best window on this card, about 46% faster than no MTP.** A wider window proposes more +tokens per round but accepts a smaller share of them, and on 12 GB the extra verification reads more experts from RAM. +`--spec-follow` is a diagnostic: it replaces the output before acceptance, so it measures speed on a fixed text, not +what the model would have said. + +A community run on a different card agrees about the window: an RTX 3090 24 GB with 62 GiB of RAM, same UD-IQ4_XS +file, measured `--spec 2` at **+27% chat and +17% agent decode against `--spec 4`** +([#7780](https://github.com/Niko1221/Strata/issues/7780)). That box reached 179.6 tok/s chat decode with MTP `--spec 2`, +against 155.32 here — the difference is the experts it can keep in VRAM. + +Prompt read on the same workload: 200 to 233 tok/s, time to first token 196 to 216 ms. Short answers are slower per +token because the fixed costs do not amortize: a 32-token English answer decoded at 79.6 tok/s and a 64-token Chinese +one at 94.2 tok/s without MTP. + +**What the MTP layer costs.** It takes 1,915 MiB of VRAM (816 experts, 580 dense, the rest head and norms), and the +resident expert count drops from about 4,835 to about 3,645 of 10,240. The speedup is what is left after paying that: +on a card where every expert already fits, the trade is different. + +### The validity gate: watch the CPU pool's bandwidth + +The CPU expert pool has to read weights from RAM. When memory pressure has pushed those pages into zram swap, the +pool decompresses them instead and the run is meaningless — not slow hardware, just a contaminated measurement. The +line to check is in every run's stats: + +``` +pool multi gate/up 0.930 quantize 0.016 down 0.498 ms/round; 66.3 GB/s over the rows phases +``` + +Healthy runs on this box read **60 to 70 GB/s**. Two runs of the same `--spec 4` setting measured 126.87 tok/s at +66.5 GB/s and 23.74 tok/s at **1.2 GB/s**; the second had 8.9 GB of zram swap in use and `allocstall_movable` climbing. +It is not a performance cliff at `--spec 4`. Any number below roughly 50 GB/s should be re-measured after the box +settles, and consecutive large runs are exactly what creates the pressure. + +## The tokenizer: `qwen4` takes `ignore_merges` + +The GGUF's `tokenizer.ggml.pre` is `qwen4`. It uses the same pre-tokenizer pattern as `qwen35`, but **with +`ignore_merges` on**, as upstream llama.cpp does (`src/llama-vocab.cpp`, the `qwen4` branch sets +`pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN35; ignore_merges = true;`). The `qwen35` branch does not set it. + +This is not a detail. With `ignore_merges`, a whole piece that is in the vocabulary stays one token instead of being +built from merges: `俱乐部` encodes to the single token 104328. About 201 single-piece CJK tokens in this vocabulary +cannot be reproduced by the merge path at all, which is the evidence for the flag, not against it. + +An English-only oracle comparison cannot tell the two apart — English text does not contain those pieces — so the +regression test asserts the flag directly and adds a case that distinguishes the two rules with no merges present. + +## Limits + +- **The CLI does not stop at the end of the turn.** `--max-new N` keeps generating past `<|im_end|>` and + `<|endoftext|>`, so a short probe's tail is garbage. That is the benchmark harness, not the model: the server owns + the stop. Judge correctness on the text before the first end marker. +- **`qsa_pattn` is not used for this geometry.** Its reduce-scatter is written for 24:2 (G = 12): `px_head`'s + permutation and the `r[s + 6]` exchange need 12 slots, and `sp[h0]` indexes up to 11. Qwen4 is 16:2 (G = 8), so + `qsa_pattn_batch_any_arch` checks `s.n_head != G * s.n_head_kv` and refuses, and the QSA layers keep the usual + attention path. See [the divergence](#relationship-to-pr-7774) below. +- **12 GB is hybrid mode.** At the shipped 131072 context, 6,935 of 10,240 experts are not in VRAM (3,305 resident, + 5.24 GiB); at 8192 it was 6,701. Either way the answer depends on the PCIe link and on RAM bandwidth. The prefill CPU + share is on by default and can change the text slightly (the engine prints the mean KL it expects). +- **Greedy text is not bit-stable across speculation widths.** With `--spec` the verify window computes several + positions in one pass, which changes reduction order; near-tie argmaxes then break differently. Two runs of the same + prompt diverged at token 52 and both continued as coherent prose. Use `--spec-follow` to compare settings on one + text, and `--window-hashes` with `--adapt-every 0` to compare two builds' arithmetic. +- The in-file MTP block and the sidecar are the same weights. Loading the sidecar (`--mtp`) is what enables drafting; + the trunk view deliberately does not carry `blk.40`. + +## Testing + +```sh +cd terminal +.venv/bin/python -m unittest tools.test_strata_tokenizer tools.test_qwen4_split_gguf \ + tools.test_qwen4_intake tools.test_make_profile +``` + +59 tests, 4 skipped (the skips need a tokenizer fixture that is not present). + +| Test | Checks | +| --- | --- | +| `test_qwen4_split_gguf.py` | The metadata truncation and F32 bytes; **Q8_0 block bytes survive the split unchanged**; a row count that does not match the metadata is refused. | +| `test_strata_tokenizer.py` | `qwen4` is the `qwen35` rule with `ignore_merges`, including a case that separates the two rules; the English oracle. | +| `test_make_profile.py` | `--n-layer` and the unchanged 48-layer default. | + +## Relationship to PR #7774 + +[Niko1221/Strata#7774](https://github.com/Niko1221/Strata/pull/7774) is the reference implementation for this model. +The splitter, the MTP runtime tool, `--n-layer`, the `qwen4` tokenizer rule and the geometry changes follow it. Three +deliberate differences: + +1. **`qsa_pattn.cu` keeps `G = 12` and refuses other ratios at runtime.** The PR derives `G` from the geometry, which + makes it 8 for `q4_lite`. That is not safe as it stands: the reduction reads `r[s + 6]` for `s` up to 5 (slots 8 to + 11 of an 8-element array) and writes `sp[h0]` with `h0` up to 11 into `[G][CHUNK]`. The PR's own review thread flags + the same out-of-bounds read and the `px_head` permutation. Keeping 12 and letting the existing shape check refuse + 16:2 costs the QSA fast path but cannot corrupt memory. Making the kernel work at G = 8 means rewriting the + reduction tree and the permutation, not changing a constant. +2. **`gguf_reader.hpp` resets `g.n_mtp_layers = 0` before reading the key.** `read_geometry` starts from + `g = core::kCompiledGeometry`, not a default-constructed geometry, so with `q4_lite` declaring one MTP layer a file + *without* `nextn_predict_layers` inherited 1 and counted 41 layers against a 40-entry `compress_ratios`. The trunk + view was refused. Absent key must mean no MTP block. Flash-Next is unaffected (its compiled value is already 0). + `compiled_geometry_mismatch` also no longer compares `n_mtp_layers`, so a build that declares the layer and a trunk + view that does not carry it accept each other. +3. **The DFlash2 tap work is not ported.** `core/tap_plan.hpp`, the `verify.*` changes and the `--draft-tap` option in + `generate.cpp` serve `--draft dflash2` block-input taps, a different drafter. They are guarded by + `STRATA_HAVE_DFLASH2` and default to the old behaviour. Nothing on the MTP path needs them, and the PR's own note + says a 12 GB NVIDIA card is slower with DFlash2 than with the MTP at every cap but code. + +Ported from the PR beyond the above: the WMMA wave pin in `qsa_prompt_attn.cu` (a store guard that only half the wave +passes must not pull the WMMAs into that branch, which matters at G <= 8 on gfx11/gfx12) and the non-finite output +count in `qsa_prompt_attn_parity.cpp` (a NaN fails every later comparison silently). \ No newline at end of file diff --git a/docs/models/qwen4.zh-CN.md b/docs/models/qwen4.zh-CN.md new file mode 100644 index 0000000000..4afb24b850 --- /dev/null +++ b/docs/models/qwen4.zh-CN.md @@ -0,0 +1,83 @@ +# Qwen4-35B-A3B + +返回 [README.zh-CN.md](../../README.zh-CN.md) + +**Qwen4-35B-A3B**:35B 混合专家模型,每次回答只用到其中 3B。需要 **12 GB 或以上显存**的 NVIDIA 显卡和 **32 GB 或以上内存**。 +本页的速度是在一张 RTX 3080 Ti(12 GB)上实测的。 + +> **文件准备目前需要手动做。** 这个模型还没有进安装程序的菜单,要按 +> [QWEN4.md](../QWEN4.md)(英文技术页)里的四条命令准备文件。准备好之后,启动服务是一条命令: +> +> ```sh +> cd terminal +> .venv/bin/python -m serve.server --engine strata \ +> --config strata-qwen4-35b-ud-iq4_xs.json --host 127.0.0.1 --port 8080 +> ``` +> +> 然后就能用 OpenAI 兼容接口(`http://127.0.0.1:8080/v1/chat/completions`)或 Anthropic 接口 +> (`/v1/messages`)对话。只监听本机,不设密钥;要开放给局域网请先在配置里加 `api_key`。 + +## 速度有多快? + +> **实测机器:** 一张 NVIDIA RTX 3080 Ti(12 GB 显存)、46 GB 内存、Linux,引擎 strata 0.1.66。 +> 模型规格是 Unsloth 的 UD-IQ4_XS(约 4 bit)。测的是写一段 256 token 的故事,提示词 28 token,一次只回答一个问题。 + +| 设置 | 写回答 | 读提示 | +| --- | ---: | ---: | +| **开启 MTP 加速(推荐)** | **155 tokens/s** | 约 200-230 tokens/s | +| 不开启 MTP | 106 tokens/s | 约 200-230 tokens/s | + +开启 MTP 后**快约 46%**。MTP 是模型自带的一个「草稿层」:它先猜几个词,主模型一次核对,猜对就一起收下。 + +通过服务接口对话时实测同样是 **154.5 tokens/s**(一段中文短文,344 token,正常结束)。把上下文开到 128K 之后重测, +服务接口写回答 **163.9 tokens/s**(450 token,草稿猜中 72%),中文提问「用三句话解释为什么天空是蓝色的」实测 +**165.5 tokens/s**(360 token,正常结束,全程 2.47 秒),读长提示 **2899 tokens/s**(一次读入 24282 token)。 +如果接着写一段高度可预测的文字,猜中率升到 98%,速度能到 347 tokens/s——那不是日常聊天的代表性数字。 + +短回答会慢一些,因为固定的启动开销摊不开:32 token 的英文回答约 80 tokens/s,64 token 的中文回答约 94 tokens/s(未开 MTP)。 + +**显存更大的显卡会更快。** 12 GB 装不下全部专家,约三分之二要在回答时从内存读取,速度受内存和 PCIe 带宽限制。 +24 GB 及以上的显卡能把更多专家留在显存里。社区在 RTX 3090(24 GB、62 GB 内存)上,同样是 UD-IQ4_XS 规格、同样开启 +MTP `--spec 2`,测到约 180 tokens/s([#7780](https://github.com/Niko1221/Strata/issues/7780))。 + +## 你需要什么 + +| | | +| --- | --- | +| **显卡** | NVIDIA GeForce RTX 20、30、40 或 50 系列,**12 GB 或以上显存**。本页数据来自 RTX 3080 Ti。 | +| **内存** | **32 GB 或以上**,实测机器是 46 GB。内存不够时专家要反复从硬盘读,会明显变慢。 | +| **硬盘** | 准备文件的过程中约需 **55 GB** 可用空间(原始文件 30 GB + 拆分出的 40 层视图 19 GB + 草稿层 2 GB + 打包 3 GB)。尽量用 SSD。 | +| **系统** | Linux 或 Windows,以及最新的 NVIDIA 显卡驱动。 | + +**内存压力会让测速失真。** 如果电脑同时开着很多占内存的程序,专家权重可能被挤到交换区,回答速度会掉到正常值的几分之一。 +这不是模型或显卡的问题。技术页里说明了怎么一眼看出这种情况([有效性判据](../QWEN4.md#the-validity-gate-watch-the-cpu-pools-bandwidth))。 + +## 中文支持 + +这个模型的分词器对中文做了专门处理:像「俱乐部」这样的词会作为一个整词识别,而不是拆成几个碎片。 +引擎已经按模型作者的方式适配(`ignore_merges`),中文提示能被正确理解。 + +实测:用中文问「法国的首都是哪里?只回答一个词」,模型思考后回答**巴黎**,正确。 + +## 已知限制 + +- **这是「先思考再回答」的模型,字数预算要给够。** 回答正文在 `content` 字段,思考过程在 `reasoning_content` 字段。 + 如果要求它写「正好 200 词」的故事,它会在思考里逐词数数,可能把预算全用在思考上而没写出正文(此时结束原因是 + `length` 而不是 `stop`)。这不是故障。**配置里已经设了 512 token 的思考预算**:到点会礼貌地收尾思考再作答, + 上面那个「正文为空」的例子因此已经能正常写出 969 字符的故事。需要更长思考的任务,可以在单次请求里传 + `reasoning_budget_tokens` 调大(`0` 表示不限)。 +- **内存紧张时,启动后的第一个长回答会很慢。** 引擎要把约 20 GB 的专家权重放进内存。如果同时开着浏览器等占内存的程序, + 第一个长回答可能只有正常速度的几分之一,之后就恢复了。实测同一请求先 24.7 tokens/s、预热后 143.9 tokens/s。 + 关掉一些程序,或等它跑完第一个回答再判断速度。 +- **命令行工具不会在回答结束时自动停下。** 用 `--max-new` 指定字数时,它会在回答结束后继续输出无意义的内容。 + 这是测试工具的行为,不是模型的问题;**服务接口会正常停止**(已实测)。判断回答对不对,看结束标记之前的部分。 +- **还没有图片能力。** 模型目录里有视觉编码器文件(`mmproj-F16.gguf`),但本次适配没有接入,只做了文字。 +- **一次只测了一个请求。** 多请求并发的表现没有实测数据。 +- **上下文开到 128K(131072 token)。** 12 GB 显存不可能一开始就为这么长的上下文预留空间,所以用了「按需增长」 + (`--kv-grow`):只给实际用到的部分分配显存,其余留给加速缓存,上下文变长时再逐步让出。代价是缓存里少放约 234 个 + 专家(3539 → 3305),回答质量不受影响。这个模式要求单显卡并且带专家画像文件,本配置都满足。 + 想再省显存还可以换 KV 精度(`--kv int8` 等)或把 KV 放到内存(`--kv-resident`),本次没有启用。 + +## 它是怎么工作的? + +技术细节、完整的准备命令、实测方法,以及和参考实现的三处有意差异:[QWEN4.md](../QWEN4.md)。 \ No newline at end of file diff --git a/engine/include/strata/artifact/gguf_reader.hpp b/engine/include/strata/artifact/gguf_reader.hpp index 53546bc65b..e378aca937 100644 --- a/engine/include/strata/artifact/gguf_reader.hpp +++ b/engine/include/strata/artifact/gguf_reader.hpp @@ -826,6 +826,20 @@ inline std::string read_geometry(const GgufFile& f, core::ModelGeometry& g) { for (const Key& k : keys) if (!read_int(k.key, g.*k.field, k.required)) return err; + // An in-file MTP (nextn) block is counted in block_count but is not a trunk layer: the trunk is + // block_count - nextn_predict_layers. The MTP block is served by the external drafter (--mtp), not the + // trunk decode, so the geometry the kernels run is the trunk's. Absent: the file has no MTP block, so 0 - + // not the compiled shape's count, which a trunk-view file (qwen4_split_gguf.py) does not carry. + g.n_mtp_layers = 0; + if (const MetaValue* mtp = f.get(p + "nextn_predict_layers")) { + if (!mtp->is_num() || mtp->type == MetaType::F32 || mtp->type == MetaType::F64 || mtp->type == MetaType::BOOL) + return p + "nextn_predict_layers is not an integer"; + if ((int64_t) mtp->u >= g.n_layers) + return p + "nextn_predict_layers is not smaller than " + p + "block_count"; + g.n_mtp_layers = (int64_t) mtp->u; + g.n_layers -= g.n_mtp_layers; + } + int64_t value_length = g.head_dim, ff_shexp = g.n_ff; if (!read_int("attention.value_length", value_length, false) || !read_int("expert_shared_feed_forward_length", ff_shexp, false)) @@ -861,16 +875,18 @@ inline std::string read_geometry(const GgufFile& f, core::ModelGeometry& g) { return p + "rope.dimension_count = " + std::to_string(g.n_rot) + " is not an even slice of the head widths"; // The layer split, twice over: the interval, and a ratio per layer that is non-zero (the indexer's pooling - // block) exactly on the full-attention layers. + // block) exactly on the full-attention layers. The array covers the trunk AND any in-file MTP block; an MTP + // block is full attention (the drafter's own QSA), so its entry is non-zero like a trunk full-attention layer. if (const MetaValue* v = f.get(p + "attention.compress_ratios")) { - if (v->type != MetaType::ARRAY || v->count != (uint64_t) g.n_layers || v->items.size() != v->count) - return p + "attention.compress_ratios must list one entry for each of the " + std::to_string(g.n_layers) + + const int64_t n_all = g.n_layers + g.n_mtp_layers; + if (v->type != MetaType::ARRAY || v->count != (uint64_t) n_all || v->items.size() != v->count) + return p + "attention.compress_ratios must list one entry for each of the " + std::to_string(n_all) + " layers"; // A list of zeros only is a converter's placeholder, not a layer split (#2396: orcarouter's // Qwen3.8-Flash-Next-Uncensored GGUFs carry 48 zeros; 0.1.43 never read the key): it is treated as absent // and the compiled pooling block is used. A list with any non-zero entry is checked in full below. bool given = false; - for (int64_t l = 0; l < g.n_layers && !given; ++l) given = v->items[(size_t) l].u != 0; + for (int64_t l = 0; l < n_all && !given; ++l) given = v->items[(size_t) l].u != 0; if (!given) { static bool said = false; // the guard runs several times in one process: one line if (!said) { @@ -882,12 +898,13 @@ inline std::string read_geometry(const GgufFile& f, core::ModelGeometry& g) { return {}; } int64_t block = 0; - for (int64_t l = 0; l < g.n_layers; ++l) { + for (int64_t l = 0; l < n_all; ++l) { const int64_t r = (int64_t) v->items[(size_t) l].u; - if ((r != 0) != core::is_qsa_layer(g, l) || r < 0 || (block && r && r != block)) + const bool full = l < g.n_layers ? core::is_qsa_layer(g, l) : true; // an MTP block is full attention + if ((r != 0) != full || r < 0 || (block && r && r != block)) return p + "attention.compress_ratios[" + std::to_string(l) + "] = " + std::to_string(r) + ", but full_attention_interval = " + std::to_string(g.qsa_interval) + " makes layer " + - std::to_string(l) + (core::is_qsa_layer(g, l) ? " full attention" : " linear attention") + + std::to_string(l) + (full ? " full attention" : " linear attention") + (block && r ? " (and the other full-attention layers pool " + std::to_string(block) + ")" : ""); if (r) block = r; } diff --git a/engine/include/strata/core/family_layout.hpp b/engine/include/strata/core/family_layout.hpp index 64ba91e127..110a360437 100644 --- a/engine/include/strata/core/family_layout.hpp +++ b/engine/include/strata/core/family_layout.hpp @@ -77,6 +77,7 @@ inline bool geometry_from_gguf(const strata::GgufFile& meta, ModelGeometry& g, i num("hyper_connection.low_rank", g.hc_lr); num("attention.indexer.head_count", g.idx_q_heads); num("attention.indexer.key_length", g.idx_key_dim); + num("nextn_predict_layers", g.n_mtp_layers); // an in-file MTP block: the trunk is block_count - nextn } g.n_layers = block_count - g.n_mtp_layers; g.ssm_conv_channels = 2 * g.ssm_state_size * g.ssm_k_heads + g.ssm_value_dim; @@ -104,6 +105,8 @@ inline bool geometry_from_gguf(const strata::GgufFile& meta, ModelGeometry& g, i /// The first geometry field that differs from the shapes this engine's kernels are built for (ModelGeometry's /// defaults, Flash-Next's), as " is , this engine's kernels are built for "; empty when none. /// n_expert and top-k are run-time sizes (the Coder ships 256 experts) and n_vocab is the embedding's business. +/// n_mtp_layers is file layout, not a kernel shape: the kernels run the trunk, so a build that declares the +/// published file's in-file MTP block still reads a trunk-view GGUF (and the other way round). inline std::string compiled_geometry_mismatch(const ModelGeometry& g) { const ModelGeometry& c = kCompiledGeometry; if (g.family != c.family) @@ -132,7 +135,6 @@ inline std::string compiled_geometry_mismatch(const ModelGeometry& g) { {"hyper_connection.low_rank", g.hc_lr, c.hc_lr}, {"expert_feed_forward_length", g.n_ff, c.n_ff}, {"expert_shared_feed_forward_length", g.n_ff_shexp, c.n_ff_shexp}, - {"the in-file MTP layers", g.n_mtp_layers, c.n_mtp_layers}, }; for (const F& f : fields) if (f.got != f.want) { diff --git a/engine/include/strata/core/geometries/q4_lite.hpp b/engine/include/strata/core/geometries/q4_lite.hpp index 210e6d92ad..26ad3587c9 100644 --- a/engine/include/strata/core/geometries/q4_lite.hpp +++ b/engine/include/strata/core/geometries/q4_lite.hpp @@ -1,5 +1,7 @@ // include/strata/core/geometries/q4_lite.hpp - G1, the 35B-A3B class scaled onto Flash-Next's layer set: hidden 2048, 40 layers, 16:2 heads, 32 GDN value heads, 256 experts top-8, ff 512, hc low rank 256 -// A synthetic target (phaseA-tests/qwen4/GEOMETRY-MAP.md section 5), not a published model. +// Matches the published Qwen4-35B-A3B (qwen4exp): 40 trunk layers + 1 in-file nextn MTP block (block_count 41). +// The MTP block is served by the external drafter (--mtp), not the trunk decode; n_mtp_layers records it so the +// geometry guard accepts the file. Originally a synthetic target (phaseA-tests/qwen4/GEOMETRY-MAP.md section 5). #pragma once namespace strata::core { @@ -19,6 +21,7 @@ inline constexpr ModelGeometry kCompiledGeometry = [] { g.n_expert_used = 8; g.n_ff = 512; g.n_ff_shexp = 512; + g.n_mtp_layers = 1; return g; }(); diff --git a/engine/src/kernels/cuda/qsa_pattn.cu b/engine/src/kernels/cuda/qsa_pattn.cu index 0b1174a798..77326cd912 100644 --- a/engine/src/kernels/cuda/qsa_pattn.cu +++ b/engine/src/kernels/cuda/qsa_pattn.cu @@ -54,9 +54,11 @@ int pattn_mode() { namespace { constexpr int HD = 256; +// The reduce-scatter below is written for 24:2 (G = 12): px_head's permutation and the r[s + 6] exchange need 12 +// slots, and a shorter r would be read past its end. Another query:KV ratio (q4_lite is 16:2, G = 8) keeps the +// usual attention - qsa_pattn_batch_any_arch checks s.n_head against G * s.n_head_kv and refuses it. constexpr int G = 12; -static_assert(HD == strata::core::kCompiledGeometry.head_dim && - G == strata::core::kCompiledGeometry.n_head / strata::core::kCompiledGeometry.n_head_kv, +static_assert(HD == strata::core::kCompiledGeometry.head_dim, "qsa_pattn is compiled for core/geometry.hpp"); constexpr int CHUNK = 64; constexpr int THREADS = 256; diff --git a/engine/src/kernels/cuda/qsa_prompt_attn.cu b/engine/src/kernels/cuda/qsa_prompt_attn.cu index 40fa3cb3fa..ba2de7454d 100644 --- a/engine/src/kernels/cuda/qsa_prompt_attn.cu +++ b/engine/src/kernels/cuda/qsa_prompt_attn.cu @@ -2101,6 +2101,10 @@ __device__ __forceinline__ void prompt_attn_wmma_body(const float* __restrict__ s = wmma_f16(qh[kk], b, s); if constexpr (SPLIT) s = wmma_f16(ql[kk], b, s); } + // the WMMA needs the whole wave: pin s here, so a store guard that only one half of the wave passes + // (G <= 8: rows 8..15 are all padding) cannot pull the WMMAs into that branch +#pragma unroll + for (int i = 0; i < 8; ++i) asm volatile("" : "+v"(s[i])); #pragma unroll for (int i = 0; i < 8; ++i) if (!TR || PA_ROW(i, half) < G) S.part[warp][PA_ROW(i, half)][nt * 16 + col] = s[i] * cd.ksc[nt]; } diff --git a/engine/src/kernels/qsa_prompt_attn_parity.cpp b/engine/src/kernels/qsa_prompt_attn_parity.cpp index 0a7b8b0976..2ec95a8056 100644 --- a/engine/src/kernels/qsa_prompt_attn_parity.cpp +++ b/engine/src/kernels/qsa_prompt_attn_parity.cpp @@ -238,6 +238,12 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16, 2 for (float x : nw) { uint32_t u; std::memcpy(&u, &x, 4); hh = (hh ^ u) * 1099511628211ull; } std::printf("NEWHASH %016llx\n", (unsigned long long) hh); } + { // a non-finite output fails every comparison below silently (NaN > x is false): count them first + long long bad = 0; + for (float x : nw) bad += !std::isfinite(x); + for (float x : im) bad += !std::isfinite(x); + if (bad) { std::printf("FAIL ctx %lld, %lld queries: %lld non-finite outputs\n", (long long) ctx, (long long) nq, bad); return 1; } + } // 1. FP64 reference on a sample of queries double err_old = 0, err_new = 0, err_im = 0, ref_scale = 0; for (int64_t i = 0; i < nq; i += std::max(1, nq / 16)) { diff --git a/terminal/models.json b/terminal/models.json new file mode 100644 index 0000000000..cab7bc9fb8 --- /dev/null +++ b/terminal/models.json @@ -0,0 +1,13 @@ +{ + "qwen4-35b-a3b-ud-iq4_xs": { + "display_name": "Qwen4-35B-A3B UD-IQ4_XS (MTP)", + "backend": "qwen4exp", + "params_total": "35B", + "params_active": "3B", + "quantization": "UD-IQ4_XS", + "mtp": true, + "ram_gb": 32.3, + "aliases": ["qwen4", "qwen4-35b", "Qwen4-35B-A3B"], + "notes": "Strata engine path, geometry q4_lite. Measured on one RTX 3080 Ti 12 GB: 155 tok/s decode with MTP --spec 2, 106 without. Needs the trunk40 view (tools/qwen4_split_gguf.py), not the published shard 1. See docs/QWEN4.md." + } +} \ No newline at end of file diff --git a/terminal/tools/iq_pack.py b/terminal/tools/iq_pack.py index d62801664d..2c5abd29c2 100644 --- a/terminal/tools/iq_pack.py +++ b/terminal/tools/iq_pack.py @@ -228,6 +228,32 @@ def is_expert(name: str) -> bool: return name.startswith("blk.") and name.endswith(("_exps.weight",)) +def nextn_layers(meta: dict) -> int: + """The in-file nextn (MTP) block count. block_count counts it; the trunk does not. The external drafter + (--mtp) serves the MTP block, so the trunk pack skips it. 0 for a model without nextn (every Flash-Next file).""" + arch = meta.get("general.architecture", "") + return int(meta.get(arch + ".nextn_predict_layers", 0) or 0) + + +def trunk_layers(meta: dict): + """The trunk layer count (block_count - nextn), or None when the file carries no block_count.""" + arch = meta.get("general.architecture", "") + bc = int(meta.get(arch + ".block_count", 0) or 0) + return bc - nextn_layers(meta) if bc else None + + +# llama.cpp's fused tensors in the published Qwen4-35B-A3B file: the engine's layout wants each part on its own. +MERGED_SUFFIXES = ("attn_qkv_gate.weight", "ssm_beta_alpha.weight", + "hc_attn_down_inject.weight", "hc_ffn_down_inject.weight") + + +def merged_tensors(model) -> list: + """The fused tensor names this model carries. Packing them as they are cannot work: the projection kernels + read an S-form, which only a quantized tensor has, and one fused name is not the two the layout names. + qwen4_split_gguf.py writes the trunk view with the parts split byte for byte.""" + return sorted(n for n in model.where if n.endswith(MERGED_SUFFIXES)) + + 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.""" @@ -280,9 +306,12 @@ 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 = [], [] + n_trunk = trunk_layers(model.files[0].metadata) # an in-file nextn (MTP) block is the drafter's, not the trunk's for name, (g, t, mm, p) in model.where.items(): if is_expert(t.name) or t.name in NOT_IN_PACK: continue + if n_trunk is not None and name.startswith("blk.") and int(name.split(".")[1]) >= n_trunk: + continue if len(t.shape) > 2: print("tensor %s has %d dimensions; the index holds two" % (t.name, len(t.shape))) return 1 @@ -441,6 +470,7 @@ def expert_layout(model: Model, src: pathlib.Path): 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_layers -= nextn_layers(model.files[0].metadata) # the in-file MTP block's experts are the drafter's, not the trunk's 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" @@ -625,6 +655,14 @@ def main() -> int: model = Model(src) if len(model.paths) > 1: print("model shards: " + ", ".join(p.name for p in model.paths)) + fused = merged_tensors(model) + if fused: + print("%s carries %d fused tensors (%s first). This engine's layout wants the parts apart, and a fused " + "quantized tensor cannot be dequantized into the pack: the projection kernels read its S-form. " + "Split the file first, then pack the result:\n" + " python terminal/tools/qwen4_split_gguf.py --gguf %s --out .gguf" + % (src.name, len(fused), fused[0], src)) + return 1 # ---- 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): diff --git a/terminal/tools/make_profile.py b/terminal/tools/make_profile.py index cf8599c09a..1c2b2b041e 100644 --- a/terminal/tools/make_profile.py +++ b/terminal/tools/make_profile.py @@ -20,6 +20,7 @@ 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) + [--n-layer 40] (a shorter trunk: Qwen4-35B-A3B runs 40 layers, not 48) 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. @@ -34,48 +35,52 @@ MAGIC, VERSION = b"STRP", 1 -def read_profile(path, n_expert=N_EXPERT): +def read_profile(path, n_expert=N_EXPERT, n_layer=None): + nl = N_LAYER if n_layer is None else n_layer blob = Path(path).read_bytes() if blob[:4] != MAGIC: raise SystemExit(f"{path}: not a PolyStrata 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}") + ver, got_nl, ne, slots, n = struct.unpack_from("<5I", blob, 4) + if (got_nl, ne) != (nl, n_expert): + raise SystemExit(f"{path}: {got_nl}x{ne}, not {nl}x{n_expert}") return [struct.unpack_from("