diff --git a/docs/DETAILS.md b/docs/DETAILS.md index ce2faa145b..f8d7b9da3b 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -399,7 +399,7 @@ that reads this line must accept `ms/window = adapt wait` for a serial run. | `--mtp` | Use the model's MTP draft layer (setup passes it). The server also runs without it: drafts then come from the suffix and prompt-lookup drafter only, every token is still verified, and the draft layer's ~0.7-1 GiB of VRAM goes to the expert cache. | | `--spec N`, `--spec-min-p P` | Draft depth and the confidence needed to add a guess. Setup's default is `--spec 4 --spec-min-p 0.5`. | | `--draft-vocab en\|cyrillic\|fr\|latin` (setup) | The draft layer can only propose tokens from a subset of the vocabulary. The default subset includes every Chinese, Japanese and Korean token. `en` keeps the English and code subset (~110 MiB less VRAM, English 1-2% faster, CJK gets almost no drafts). `cyrillic` and `fr` add those scripts; `latin` adds German, Spanish, French and Polish together. With no choice, PolyStrata picks `cyrillic` or `latin` by itself when the languages of this computer (display language, regional format, keyboards) are Cyrillic or Latin-script and none of them is Chinese, Japanese or Korean; the pick is made at every start and written nowhere, and a choice you make always wins. On an RTX PRO 5000 (IQ3_S), default file -> chosen file, tok/s: Russian 180.0 -> 227.6 (`cyrillic`); German 211.7 -> 233.6, Spanish 220.1 -> 244.5, French 221.9 -> 249.1, Polish 188.4 -> 203.2 (`latin`); English 265.2 with the default, 266.0 with `latin`, 266.6 with `cyrillic`; Chinese 238.4 -> 199.2 and Japanese 222.2 -> 194.4 with `latin`, which is why any Chinese, Japanese or Korean signal keeps the default. `terminal/tools/draft_vocab.py` builds and inspects subsets. | -| `--lookup-chain-min M`, `--mtp-hnorm stream`, `--mtp-draft-vocab FILE` | Finer controls: the shortest context match `--lookup-chain` extends (default 3), one norm per stream, and a token subset of your own. | +| `--lookup-chain-min M`, `--mtp-hnorm pooled`, `--mtp-draft-vocab FILE` | Finer controls: the shortest context match `--lookup-chain` extends (default 3), one RMS over all four hyper-connection streams instead of the default one per stream (`stream`, which is what the reference MTP graphs do), and a token subset of your own. | When the start stops with "the draft head does not fit" (a 12 GB card with a long context), the engine says how much it needs and which smaller subset fits. Setup suggests `--draft-vocab en` on cards under 14 GB and does not set it. diff --git a/docs/DGX_SPARK_LINUX.md b/docs/DGX_SPARK_LINUX.md index 0193200d30..9afc8dc851 100644 --- a/docs/DGX_SPARK_LINUX.md +++ b/docs/DGX_SPARK_LINUX.md @@ -36,7 +36,7 @@ The Spark settings in the run config: | `--mmap-experts` | the experts are read from the model files in place, so the GPU's cache holds all 24,576 of them instead of a second copy in RAM | | `--prefill auto:32768` | a 32,768-token prompt chunk; the automatic 8,192 measured 2 to 6% slower here | | `--mtp-q4 all` | the draft layer as 4-bit copies: +3.5% decode, the answers do not change because the target checks every draft | -| `--mtp-hnorm stream` | one norm per hyper-connection stream in the draft layer: draft acceptance 0.60 to 0.63, +4.3% decode | +| `--mtp-hnorm stream` | one norm per hyper-connection stream in the draft layer: draft acceptance 0.60 to 0.63, +4.3% decode. Now the engine's default on every card (the reference MTP graphs normalize per stream); `pooled` is the opt-out | Setup prints `--draft-vocab en` as a tip and does not set it: it measured +3.1% decode on English prompts, and it would cut the Chinese, Japanese and Korean drafts. diff --git a/docs/QWEN4.md b/docs/QWEN4.md new file mode 100644 index 0000000000..f43419ffbc --- /dev/null +++ b/docs/QWEN4.md @@ -0,0 +1,576 @@ +# Qwen4-35B-A3B: the trunk view, the MTP layer and speed + +[中文版](QWEN4.zh-CN.md) + +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). + +For how this strata-engine adaptation relates to upstream main's native `strata-poly` Qwen4 implementation — +route differences, default behaviour and a same-box measurement snapshot — see +[QWEN4_ENGINE_PATHS.md](QWEN4_ENGINE_PATHS.md) ([中文版](QWEN4_ENGINE_PATHS.zh-CN.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. + +## How this branch adapts the model + +The published GGUF is readable by llama.cpp, but not by this engine as shipped. Four mismatches have to be resolved, +in this order, and each one is a separate, testable change rather than a patch to the model: + +``` +Unsloth shard 1 (41 blocks, fused tensors) + │ 1. geometry: 41 blocks = 40 trunk + 1 in-file MTP drafter + │ 2. tokenizer: pre "qwen4" = the qwen35 split + ignore_merges + ▼ +40-layer trunk view (qwen4_split_gguf.py, quantized bytes untouched) + │ 3. split the four fused projections into the layout the kernels read + ▼ +native pack + even expert profile (iq_pack.py --compat-bf16, make_profile.py --n-layer 40) + │ + ├── shard 2 is not trunk data: it is the PLE table, passed as --ple-gguf + └── MTP sidecar → drafter runtime (mtp_qwen4_rt.py) → --mtp … --spec 2 + ▼ +serve.server + models.json → OpenAI and Anthropic APIs, 131072 tokens with --kv-grow +``` + +**1. Geometry is the first blocker.** `read_geometry` starts from the compiled shape (`q4_lite` declares one MTP +layer), so the trunk view — which deliberately drops the key — inherited `n_mtp_layers = 1` and was rejected for +counting 41 layers against a 40-entry `compress_ratios`. The fix resets the field to 0 before reading the key, +validates the ratio array over trunk + MTP (an MTP block is full attention), and removes `n_mtp_layers` from the +kernel-shape guard, because it describes the file's layout, not the shapes the kernels execute. `q4_lite.hpp` now +documents that it matches the published model rather than a synthetic target. + +**2. The tokenizer is a correctness issue, not a speed one.** `pre_tokenizer_kind` accepts `qwen4` as an alias of the +`qwen35` split, but `IGNORE_MERGES` gains `qwen4`. Without it, whole CJK pieces that exist in the vocabulary are +rebuilt from merges and never match; about 201 single-piece tokens are unreachable that way. See +[the tokenizer section](#the-tokenizer-qwen4-takes-ignore_merges). + +**3. Tensor layout is solved without losing a single bit of quantization.** The four fused tensors are concatenations +along output rows, and every block format used here is self-contained along the input dimension. The splitter therefore +copies quantized rows byte for byte — no dequantize/requantize round trip — and writes a GGUF whose metadata describes +only the trunk. `iq_pack.py` then packs that view and *refuses* an unsplit file, so the mistake cannot come back. + +**4. Speed comes from the model's own MTP block, and 128K comes from growing KV on demand.** The sidecar is the same +weights as `blk.40`, repackaged as a drafter runtime; `--spec 2` is the measured optimum on 12 GB +([why](#speed)). `--kv-grow` allocates KV only for the cells a request reaches instead of reserving 131072 tokens up +front, which is what makes the long context affordable on this card: 3,305 resident experts instead of 3,539. + +The serving layer needed no engine change. `terminal/models.json` supplies the facts the engine path cannot derive +(the config names its GGUF with `--native`, not `--model`), and the run config carries the arguments and the thinking +budget. A sibling `*.shared-settings.json` can hold the default output cap for clients that do not send one. The +server does speak Qwen4's own reasoning-effort words and applies its model-card sampling with MTP — both are described +under [Serving it](#serving-it). + +**Deliberate non-goals:** the `qsa_pattn` fast path now handles 16:2 (`G = 8`) behind a parity gate instead of deriving +`G` unsafely, but it stays SM60-gated, so this geometry's production sm_86 build does not compile it and serving is +unchanged; the DFlash2 tap work is not ported. Both are explained under +[Relationship to PR #7774](#relationship-to-pr-7774). + +## 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, 1.87 GiB. | + +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 + +**One command, on a fresh clone:** `./qwen4-run.sh` checks the machine, builds the engine if needed, prepares the four +artifacts idempotently, writes the run config and starts the server. Use `./qwen4-run.sh --download` if the Unsloth +files are not on disk yet (about 32 GiB to download), or `--check` to run only the preflight. Details and options are +in the script's `--help`. The four manual steps below are what it runs, and are still the reference for debugging. + +The preflight runs before anything is downloaded or built: GPU 0's **free** VRAM (other workloads may already hold +some), a bindable serving port, system RAM, and free disk on the filesystems that would hold the model and the pack. +`--check` runs exactly these checks and changes nothing — no directories, no venv, no config. The Python environment +installs the full `terminal/requirements.txt` (the conversion tools need `regex` and `jinja2`, not just `numpy`), and +the engine build targets the detected compute capability (`QWEN4_CUDA_ARCH` overrides it). + +Artifacts are reused only when they are **complete**: the pack needs `native_experts.txt`, its completion marker, +which `iq_pack.py` publishes last, after every selected expert artifact; the MTP runtime needs `complete.json`, a +size-checked record of all four files that also states whether the runtime carries the drafter's indexer. A record +without that field predates the indexer and is reconverted: its sizes are self-consistent, so they alone cannot reveal +the missing tensors, and serving it would silently keep the dense-attention approximation. A half-written pack or +drafter from an interrupted run is rebuilt, not served. +The run config is written atomically (temporary file, then rename), and an existing `*.shared-settings.json` is merged: +your keys are kept, only missing defaults are filled in. + +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)" +``` + +(`86-real;86-virtual` is the tested RTX 3080 Ti; `qwen4-run.sh` derives the architecture from the GPU instead.) + +## 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 PolyStrata +engine's main argument loop reads — `--model` is only recognised by the qwen35moe family pre-scan). + +The config is **not in the repository**: `.gitignore` excludes `/terminal/strata-*.json`, because it names paths on one +machine. Save this as `terminal/strata-qwen4-35b-ud-iq4_xs.json`, with `/path/to/packs/` and `/path/to/models/` pointing +at the `$P` and `$M` of the quick start above: + +```json +{ + "exe": "build-q4lite/strata", + "args": [ + "--pack", "/path/to/packs/qwen4-35b-ud-iq4_xs-trunk40", + "--native", "/path/to/models/Qwen4-35B-A3B-GGUF/trunk40/Qwen4-35B-A3B-UD-IQ4_XS-trunk40.gguf", + "--native-dense-gguf", "/path/to/models/Qwen4-35B-A3B-GGUF/trunk40/Qwen4-35B-A3B-UD-IQ4_XS-trunk40.gguf", + "--ple-gguf", "/path/to/models/Qwen4-35B-A3B-GGUF/UD-IQ4_XS/Qwen4-35B-A3B-UD-IQ4_XS-00002-of-00002.gguf", + "--expert-profile", "/path/to/packs/qwen4-35b-ud-iq4_xs-trunk40/expert-profile.bin", + "--mtp", "/path/to/packs/qwen4-35b-ud-iq4_xs-trunk40/mtp-rt", + "--spec", "2", "--prefill", "auto", + "--max-context", "131072", "--kv-grow", "--vram-reserve-mib", "512" + ], + "cwd": ".", + "tokenizer": "/path/to/packs/qwen4-35b-ud-iq4_xs-trunk40/tokenizer", + "model_name": "qwen4-35b-a3b-ud-iq4_xs", + "aliases": ["qwen4", "qwen4-35b", "Qwen4-35B-A3B"], + "display_name": "Qwen4-35B-A3B UD-IQ4_XS (MTP)", + "log": "terminal/strata-qwen4-35b-ud-iq4_xs.log", + "port": 8080, + "gpu": 0, + "host": "127.0.0.1", + "open_browser": false, + "answer_room": true, + "reasoning_budget_tokens": 512 +} +``` + +`tokenizer` must be the pack's tokenizer directory: it has to contain `vocab.json`, which is what `serve.models.describe()` +reads. `aliases` are the names the OpenAI API accepts besides `model_name` (the runner writes the same list as +`terminal/models.json`). On a card with less than 12 GB, or to leave more VRAM for experts, lower `--max-context`; +`--kv-grow` is what makes 131072 affordable here (below). + +If the engine cannot find its CUDA libraries, add `"lib_dirs": ["/usr/local/cuda/bin", "/usr/local/cuda/lib64"]` (your own +CUDA paths). It is optional — the server only prepends those directories to the library search path — but the run measured +here sets it, because CUDA 12.8 lives in `/usr/local/cuda` rather than on the default loader path. + +```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. + +**Reasoning effort: Qwen4's own words.** The official levels are `xhigh`, `high`, `low` and `off`, default `high`; +the template itself has no `medium`. The server accepts those words (plus the usual off-aliases +`none`/`minimal`/`disabled`/`false`, and `max`/`maximum` for `xhigh`) and maps a client's `medium` to the default +`high` instead of erroring, so clients that only know the generic words keep working. Anthropic's +`thinking.budget_tokens` maps to `low` below 2048, `high` from 2048 to 8191, and `xhigh` from 8192. The dialect is +selected from the tokenizer's `pre="qwen4"`, **not** from the GGUF architecture: Qwen3.8-Flash-Next shares `qwen4exp` +and keeps the generic Qwen words. The same dialect applies to the run config, the shared settings and `POST /settings`, +and the tokenizer is read before the config's effort value is validated, so a Qwen4 config with `xhigh` loads. + +**Sampling with MTP.** For other models, an MTP request that names no sampling stays greedy (#3354), so drafts are +not silently disabled by card defaults. Qwen4 is the exception: its model-card sampling applies with the drafter too — +thinking `temperature 1.0, top_p 0.95, top_k 20`; non-thinking `temperature 0.7, top_p 0.80, top_k 20, +presence_penalty 1.5`. Explicit request fields, shared settings and the config's sampling block still win over the +card, and an explicit `temperature: 0` is still greedy. `GET /props` reports the same defaults the generation path uses. + +**`preserve_thinking` is two different things.** Qwen4's chat template preserves reasoning that the *client* already +sends back in the history. Separately, the server can remember this session's reasoning and restore it when the client +returns only the answer text — that is the opt-in `preserve_thinking` run-config key, and the runner does **not** enable +it. The template's behaviour is not server-side memory. + +**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. + +**A real agent workload, not a benchmark prompt.** A longer session through the serving API (117 requests, prompts +growing to about 78K tokens, 97% prompt reuse) averaged **192.9 tok/s decode and 1,906 tok/s prefill**, with per-request +decode between 126.9 and 256.0 tok/s and a 73-81% expert VRAM hit rate. One turn produced 1,955 tokens at 169.1 tok/s. +The monitor showed 11.4 of 12 GB VRAM, 3,305 cached experts and 39.5 of 47 GB system RAM. This is the configuration +shipped here (131072 context, `--kv-grow`, MTP `--spec 2`), and it is faster than the short-prompt numbers above +because the cached prefix does most of the prompt work. + +![The serving monitor during that session: 192.9 tok/s decode, 1,906 tok/s prefill, 117 requests, 3,305 cached experts](media/qwen4-35b-a3b-monitor.png) + +**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 MTP drafter's indexer (MTP QSA) + +`mtp_qwen4_rt.py` converts the sidecar's `blk.40.indexer.{q_proj,k_proj,q_norm,k_norm}`, and the engine runs the draft +layer's own indexer/top-k KV selection (QSA) — the same computation the trunk runs: project the indexer key, pool and +rotate it on each block completion, score every block, take the top-k, attend to the selected cells. A sidecar without +those tensors, or `STRATA_MTP_INDEXER=0`, keeps the previous **dense-attention approximation** over the retained cells. + +- The target model verifies every draft either way, so an accepted token is the target's own. The path changes the + draft distribution and the acceptance rate, not the correctness of an accepted token. +- With the indexer the drafter reads a bounded selection (2,048 cells plus the tail) instead of every retained cell, + so its per-round cost stops growing with the context. +- The drafter has no turn checkpoint, so a conversation snapshot carries its whole indexer block with its K/V. A + borrowed prefix ends inside a block: the tail is cleared and the spare row takes the dead key, as a checkpoint + restore does. At most `idx_block - 1` cells of that one pooled key are then approximate — one block of 8,192 at a + 32K prefix, and nothing at all below 2,048 cells. The trunk is exact here because its checkpoint exists. + +**Long context, indexer against the dense approximation.** A 64K prompt (65,570 tokens of real repository prose with +a needle spliced at half depth), 256 greedy tokens, `--spec 2`, 2,000 expert cache slots so the resident expert set +matches, `STRATA_PREFILL_CPU_SHARE=0`. Every arm read 72.6-80.4 GB/s, inside the validity gate below. + +| Drafter | Decode | Acceptance | ms/round | +| --- | ---: | ---: | ---: | +| dense approximation | 125.51 tok/s | 0.814 | 1.050 | +| **indexer** | **139.03 tok/s** | 0.697 | 0.983 | +| indexer compiled in, `STRATA_MTP_INDEXER=0` | 125.01 tok/s | 0.814 | 1.049 | + +The indexer trades acceptance for a cheaper round and wins on decode (**+10.8%**). The `STRATA_MTP_INDEXER=0` arm +reproduces the dense runtime's emitted ids exactly, so the approximation is unchanged for anyone who keeps it. + +At 32K and 128K the two paths' acceptance overlaps within this box's run-to-run spread, and **every arm retrieved the +needle correctly at 128K** — selection still finds the right blocks at the longest context tested. Those two batches +read 52-72 GB/s, so their decode timings are not quoted; the acceptance counts and the needle check are. + +The spread is real and worth knowing before reading any acceptance number here: two runs of the *same* configuration +(`--mtp-q4 proj` and `--mtp-q4 all`, which are identical on this pack because the head subset is absent) measured 0.733 +and 0.826 acceptance and 135.5 and 127.1 tok/s. Natural greedy decode is not bit-reproducible on this engine — the +adaptive VRAM tier and the CPU pool's reduction order move with timing. + +#### The step record's width: a context-dependent overflow + +`qsa_block_topk` reads `step[kStepWidth]` and takes `n_kv <= width` as "everything is selected": it then writes `n_kv` +ascending ids and returns. The ids buffer holds `cap` ids per query. The dense path fills `n_kv` and `window_ids` +overwrites it with the window's own count (and its `cap` is sized to the context anyway); the indexer path has no such +overwrite and its `cap` is the constant selection width, so filling `n_kv` there sent the kernel down the identity +branch and wrote past the buffer by `n_kv - cap` ids. + +That is why the first indexer runs looked healthy at 32K and collapsed at 64K: the overflow grows with the context. +Measured acceptance was 0.715 at 32K and **0.217 at 64K, twice**, against 0.76-0.89 for the same runtime with the +indexer off. All five host fill sites now go through `MtpDrafter::fill_step`, which calls `qsa_step_fill` — the one +writer of the quadruple — for the indexer and keeps the old arithmetic for the dense path. After the fix the 64K +acceptance is 0.697 / 0.660 and the 128K needle is found. + +`mtp_step_test` is the regression: it checks the arithmetic without a device and runs the real selection over a guarded +ids buffer with one. Fail-first on the old filling, **16 checks failed**, the overflow measured at 30,751 ids past the +buffer for a 32,802-cell context and 63,519 for 65,570. + +### Two defaults, measured + +**`--mtp-hnorm` now defaults to `stream`.** It was frozen at `pooled` pending a same-box A/B; that measurement is done +and the structural question is settled. `pre_fc_norm_hidden.weight` is 8192 = 4 x 2048 wide, and the reference readings +normalize **each hyper-connection stream on its own**, scaled by its slice of the weight: + +- upstream's `q4_mtp_eh_concat_kernel` launches one block per (token, stream), sums squares over `n_embd` only, and + reads `w_hnorm + c * n_embd`; +- llama.cpp's `qwen4exp` MTP graph does the same; +- `tools/mtp_qwen4_rt.py` documents the conversion as "applied per hc stream to `hnorm(h)`". + +`pooled` — one RMS over all four streams — matches none of them. On this box at 32K, two runs of each: + +| `--mtp-hnorm` | Acceptance | Decode | Tokens per round | +| --- | ---: | ---: | ---: | +| `pooled` (the old default) | 0.679, 0.679 | 138.73, 137.56 tok/s | 1.71 | +| **`stream` (the new default)** | **0.815, 0.852** | **142.30, 137.78 tok/s** | 1.90 | + +The two `pooled` runs were bit-identical; both `stream` runs accepted more and needed fewer rounds, and both decoded +faster despite reading *less* bandwidth (60.0 / 52.1 GB/s against 62.2 / 65.2). A DGX Spark run independently recorded +`stream` at **+4.3% decode** ([DGX_SPARK_LINUX.md](DGX_SPARK_LINUX.md)). `pooled` stays available as the opt-out. + +**`--spec-min-p` stays `0.0`.** Swept on the indexer path at 32K, one run per value: 0.05 gave 0.777 acceptance and +146.74 tok/s, 0.10 gave 0.678 / 139.01, 0.20 gave 0.748 / 137.71, 0.40 gave 0.837 / 134.22, against the 0.0 baseline's +0.679 / ~138.1. The ordering is not monotonic and the differences sit inside the run-to-run spread measured above, so +one run per value cannot settle it. 0.40 shows the expected trade — the highest acceptance, the lowest decode, because +a draft below the threshold ends the chain. Changing this default needs repeats per value on a quiet box. + +**`--mtp-q4` stays off, and is not a VRAM saving here.** The Q4_0 copies are *additive*: the prompt path's batched K/V +pass keeps the Q8_0 originals. On this card 11 projections as Q4_0 cost **+566 MiB** (1,989 -> 2,555 MiB) and displaced +26 resident experts (3,000 -> 2,974 slots). Acceptance rose (0.733 / 0.826) but decode did not (135.5 / 127.1 tok/s +against the baseline's 135.4). `head` and the head part of `all` are inert without a draft-head subset +(`rt/draft_vocab.bin` or `--mtp-draft-vocab`); the engine says so rather than silently drafting over the full head. On a +card where the experts already fit the trade is different — a DGX Spark run recorded `--mtp-q4 all` at **+3.5% decode** +([DGX_SPARK_LINUX.md](DGX_SPARK_LINUX.md)). The 12 GB result is a residency result, not a verdict on Q4_0 drafting. + +### 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` supports this geometry now, but production here still does not use it.** The reduce-scatter and + `px_head` permutation are templated on G (8 or 12), so 16:2 no longer trips the head-count check. The kernel remains + gated on `STRATA_EXPERIMENTAL_SM60`, which the shipped `q4_lite` build leaves off: on sm_86 prefill falls back to the + decode loop exactly as before, and the G=8 work brings no speedup on this card. It is exercised through the any-arch + parity entry, which bypasses only the compute-capability gate. 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`. +- **The drafter's indexer is implemented; one snapshot corner stays approximate.** A borrowed prefix ends inside an + indexer block, so at most `idx_block - 1` cells of that one pooled key are rebuilt from the resumed position (above). + The rest is the model's own selection. Every number here is one RTX 3080 Ti. + +## 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 tools.test_iq_pack \ + tools.test_mtp_qwen4_rt tools.test_qwen4_run +``` + +115 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; a failed or interrupted write keeps the previous output and leaves no temporary file. | +| `test_strata_tokenizer.py` | `qwen4` is the `qwen35` rule with `ignore_merges`, including a case that separates the two rules; the English oracle; a real GGUF → `extract()` → `from_dir()` round trip with an empty merge set, CJK whole words, combining marks, emoji and control characters. | +| `test_make_profile.py` | `--n-layer` and the unchanged 48-layer default; the full 40-layer CLI path with its re-read verification. | +| `test_qwen4_intake.py` | A `pre="qwen4"` set builds and probes (case A); the drafter report points at `tools/mtp_qwen4_rt.py` for Qwen4 and keeps `tools/mtp_pack.py` for Flash-Next. | +| `test_iq_pack.py` | `native_experts.txt` is published last: an interrupted run leaves no completion marker, a resume does not depend on it, and a complete old pack survives a later interrupted index write. | +| `test_mtp_qwen4_rt.py` | The four drafter artifacts are published only after a successful conversion, with a size-checked `complete.json`; a failed run keeps the previous set. The indexer tensors convert with their real kinds, rows and byte-exact payloads; `--plus-one-norms` reaches the indexer norms; an older sidecar without an indexer still converts and carries none of those tensors; the completion record reports the indexer's presence in both directions. | +| `test_qwen4_run.py` | The launcher, offline with fake hardware and tools: `--check` changes nothing, free VRAM and a busy port are refused before preparation, the build uses the detected architecture and the full requirements, incomplete packs/drafters are rebuilt, a drafter record predating the indexer is reconverted while a current one is reused, and shared settings are merged without losing user keys. | + +The serving changes have their own regressions — `serve.test_effort_paths` and `serve.test_model_card_sampling` +(34 tests: the Qwen4 effort dialect on all three API paths, config/shared/settings, and the Qwen4+MTP model-card +defaults with explicit overrides) — and were re-run together with the wider serving suite around them (19 modules +covering the frontend, models, settings, security, reasoning and thinking paths): 826 tests, 3 skipped, all passing. +The effort dialect maps a client's `medium` to `high` (the template itself has no `medium` and would raise): the +updated `Qwen4EffortPaths` regressions failed on the old code first — 19 tests, 13 failures and 2 errors, all on the +`medium` paths — and pass after the mapping was added to the frontend table and the shared-settings validator. + +The engine-side work has its own regressions, run against a GPU build (`build-q4lite-tests`, sm_86): + +| Test | Checks | +| --- | --- | +| `mtp_step_test` | The step quadruple contract: the arithmetic fill matches `qsa_step_fill` at every cell count; a guarded real selection at 32K/40K/64K/128K writes only inside the capacity, and the cells below the selection width stay identity. Fail-first on the old code: 16 failures, up to 63519 out-of-bounds ids at 65570 KV. | +| `conversation_snapshot_test` | 4639 checks, including the new `draft_indexer_roundtrip`: the block-span layout round-trips byte-exactly, a stale prefix resets, and a borrowed prefix keeps the block-granular approximation honest. | +| CTest (GPU build) | 426 of 448 pass. The 22 failures are the pre-existing set plus two attributed ones: `native_i8_parity` fails 3/3 with the indexer changes stashed (a stochastic carved-tm parity check, pre-existing), and `poly_bell_test` passes when the machine is idle (load-sensitive timing flake). Neither is touched by this work. | + +## 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` is templated on G (8 or 12), not derived from the geometry unchecked.** The PR derives `G` from the + geometry, which makes it 8 for `q4_lite`, but its 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. Here the permutation generalises to + `P_L(i) = HALF*((i/HALF)^b3) + ((i%HALF + QUARTER*b2)%HALF)` with `HALF=G/2` and `QUARTER=G/4`, the reduction keeps + `warp_sum_x`'s xor nesting (16,8,4,2,1) so every partial sum adds in the same order, and the third-quarter lane fold + exists only for G=12 (`if constexpr`). The parity gate separates "not built" from "geometry refused" and runs both + ratios through the same 468 cases: G=8 **0 differ** (19,644,888 nonzero outputs), G=12 **0 differ** (29,724,792) — + the G=12 path stays bit for bit. Fail-first on the old kernel: 468/468 differ. The kernel is still SM60-gated, so + production sm_86 serving is unchanged. +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). + +## TODO + +- **setup menu integration.** Preparing this model still means running the four commands above (or `qwen4-run.sh`); it + is not an option in the installer yet. The work is a setup entry that knows the trunk view is required — a normal + family entry would offer the published shard 1 and fail — plus pack size, RAM and disk guidance. Serving was done + first deliberately; this is a separate, contained piece. +- **QSA at 16:2 in production.** The G=8 reduction tree and `px_head` permutation are done and parity-gated (above), + but the kernel is still SM60-gated. Enabling it for sm_86 prefill is its own measurement, not a flag flip. +- **`--spec-min-p`.** Still `0.0`: the sweep's differences sit inside this box's run-to-run spread and need repeats per + value on a quiet box before the default changes (above). `--mtp-hnorm` is settled and now defaults to `stream`. +- **An IQ4_NL drafter.** The community direction is a ~780 MiB IQ4_NL sidecar against this Q8_0 one's 2,194 MiB. It is + not implemented: this conversion chain requires Q8_0, and neither an IQ4_NL sidecar nor the Qwen4 MTP HF weights exist + on the tested box, so nothing here measures it. `--mtp-q4` is a different thing (Q4_0 copies of the Q8_0 projections) + and costs VRAM here rather than saving it (above). +- **Vision is not wired.** The model directory ships `mmproj-F16.gguf`; this adaptation is text-only. +- **Concurrency and other cards are unmeasured.** All numbers are one request at a time on one RTX 3080 Ti. Multi-slot + batching, AMD/Intel paths and cards with more VRAM need their own measurements before any claim is made. \ No newline at end of file diff --git a/docs/QWEN4.zh-CN.md b/docs/QWEN4.zh-CN.md new file mode 100644 index 0000000000..93b228e954 --- /dev/null +++ b/docs/QWEN4.zh-CN.md @@ -0,0 +1,536 @@ +# Qwen4-35B-A3B:trunk 视图、MTP 层与速度 + +[English version](QWEN4.md) + +本页面向在 Strata 项目自有引擎路径上、用 PolyStrata 运行 [Qwen4-35B-A3B](https://huggingface.co/Qwen/Qwen4-35B-A3B) +(35B 混合专家,3B 激活,256 个专家,top-8)的读者。GGUF 架构为 `qwen4exp`:40 个 trunk(主干)层, +其中 30 层是循环层(GDN),10 层是带压缩 KV 选择(QSA)的全注意力层,每个块上还有 hyper-connection。 +尺寸与内存需求见 [MODELS.md](MODELS.md)。 + +关于本 strata 引擎适配与上游 main 原生 `strata-poly` Qwen4 实现的关系——路线差异、默认行为与同机测量快照——见 +[QWEN4_ENGINE_PATHS.zh-CN.md](QWEN4_ENGINE_PATHS.zh-CN.md)([English version](QWEN4_ENGINE_PATHS.md))。 + +下面的数字在一张 RTX 3080 Ti(12 GB)上测得。这是一次 12 GB 混合模式运行:约三分之一的专家留在显存, +其余通过 PCIe 从内存读取,所以显存更大的卡会更快。 + +## 本分支如何适配模型 + +出版的 GGUF 能被 llama.cpp 读取,但本引擎出厂状态下读不了。必须按以下顺序解决四个不匹配, +每一个都是独立、可测试的改动,而不是对模型的补丁: + +``` +Unsloth 分片 1(41 个块,融合张量) + │ 1. 几何:41 块 = 40 trunk + 1 个文件内嵌 MTP 草稿模型 + │ 2. 分词器:pre "qwen4" = qwen35 切分 + ignore_merges + ▼ +40 层 trunk 视图(qwen4_split_gguf.py,量化字节原样不动) + │ 3. 把四个融合投影拆成内核读取的布局 + ▼ +native pack + 均匀专家 profile(iq_pack.py --compat-bf16,make_profile.py --n-layer 40) + │ + ├── 分片 2 不是 trunk 数据:它是 PLE 表,以 --ple-gguf 传入 + └── MTP sidecar → 草稿运行时(mtp_qwen4_rt.py)→ --mtp … --spec 2 + ▼ +serve.server + models.json → OpenAI 与 Anthropic API,配合 --kv-grow 支持 131072 tokens +``` + +**1. 几何是第一个拦路问题。**`read_geometry` 从编译形状出发(`q4_lite` 声明一个 MTP 层), +所以有意丢弃该键的 trunk 视图继承了 `n_mtp_layers = 1`,按 41 层去对只有 40 项的 `compress_ratios` 计数而被拒绝。 +修复是在读键前把该字段重置为 0,按 trunk + MTP 校验比例数组(MTP 块是全注意力),并把 `n_mtp_layers` 从内核形状守卫中移除, +因为它描述的是文件布局,不是内核执行的形状。`q4_lite.hpp` 现在注明它匹配的是出版模型,而不是合成目标。 + +**2. 分词器是正确性问题,不是速度问题。**`pre_tokenizer_kind` 接受 `qwen4` 作为 `qwen35` 切分的别名, +但 `IGNORE_MERGES` 增加了 `qwen4`。不开它,词表中存在的整个 CJK 片段会被合并规则重建而永远对不上; +约 201 个整词 token 因此不可达。见[分词器一节](#the-tokenizer-qwen4-takes-ignore_merges)。 + +**3. 张量布局的解决不损失任何一位量化信息。**四个融合张量是沿输出行的拼接, +而这里用到的每种块格式沿输入维度都是自包含的。因此拆分器逐字节复制量化行——没有反量化/重量化往返—— +并写出一个元数据只描述 trunk 的 GGUF。`iq_pack.py` 随后打包该视图,并*拒绝*未拆分的文件,所以这个错误不会回来。 + +**4. 速度来自模型自带的 MTP 块,128K 来自按需增长的 KV。**sidecar 与 `blk.40` 是同一份权重, +重新打包为草稿运行时(drafter runtime);`--spec 2` 是 12 GB 上的实测最优([原因](#speed))。 +`--kv-grow` 只为请求实际到达的单元分配 KV,而不是一开始就预留 131072 tokens, +这正是长上下文在这张卡上可负担的原因:3,305 个驻留专家,而不是 3,539 个。 + +服务层不需要改引擎。`terminal/models.json` 补齐引擎路径推导不出的事实(该配置用 `--native` 而非 `--model` 指名 GGUF), +运行配置携带参数与思考预算。旁边的 `*.shared-settings.json` 可以保存默认输出上限,供不发送该值的客户端使用。 +服务端确实讲 Qwen4 自己的思考力度词,并在开着 MTP 时应用其模型卡采样——两者都在[运行服务](#serving-it)一节描述。 + +**有意不做的:**`qsa_pattn` 快速路径现在在 parity 门禁之后支持 16:2(`G = 8`),而不是不加检查地推导 `G`; +但它仍受 SM60 守卫,所以本几何的生产 sm_86 构建不编译它,服务行为不变。DFlash2 tap 工作没有移植。 +两者都在[与 PR #7774 的关系](#relationship-to-pr-7774)一节解释。 + +## 出版文件里有什么 + +Unsloth 的 [Qwen4-35B-A3B-GGUF](https://huggingface.co/unsloth/Qwen4-35B-A3B-GGUF) 提供三样东西,引擎分别读取: + +| 文件 | 内容 | +| --- | --- | +| `UD-IQ4_XS/...-00001-of-00002.gguf` | trunk **和** MTP 块:`block_count` 41,`nextn_predict_layers` 1,所以 `blk.40.*` 是草稿模型,不是 trunk 层。还有融合投影。 | +| `UD-IQ4_XS/...-00002-of-00002.gguf` | 一个张量 `per_layer_token_embd.weight`(PLE),完全没有元数据。 | +| `MTP/mtp-Qwen4-35B-A3B-Q8_0.gguf` | 单独的同一份 `blk.40` 草稿模型,Q8_0,1.87 GiB。 | + +这对 pack 有两个后果: + +- **trunk 视图。**引擎的几何按 `block_count - nextn_predict_layers` 计层数,MTP 块作为草稿模型加载,而不是第 40 层。 + `tools/qwen4_split_gguf.py` 写出分片 1 的 40 层视图:丢弃 `blk.40.*` 与 `per_layer_token_embd.weight`, + 把 `block_count` 设为 40,移除 `nextn_predict_layers`,把 `attention.compress_ratios` 与 + `attention.recurrent_layers` 截断到 trunk,并移除 `split.*` 键。 +- **融合投影。**`attn_qkv_gate`、`ssm_beta_alpha` 与 hyper-connection 的 `*_down_inject` 各是一个张量, + 而引擎期望两个或三个。拆分器**按字节行分离,不重量化**:这里每种块格式(Q8_0、Q5_K、Q4_K、IQ4_XS) + 沿输入维度自包含,所以量化字节的一个输出行切片恰好就是矩阵的量化切片。行顺序就是 llama.cpp `qwen4exp` + 加载器读取的顺序:先 qkv 后 gate,先 beta 后 alpha,先 down 后 inject。宽度来自元数据 + (这里 `state` 128、`group` 16、`inner` 4096),不是常量。 + +`tools/iq_pack.py` 拒绝仍带融合名字的文件并指向拆分器,所以绝不可能意外地用未拆分分片构建 pack。 + +## 快速开始 + +**一条命令,在全新克隆上:**`./qwen4-run.sh` 检查机器、按需构建引擎、幂等地准备四个产物、 +写入运行配置并启动服务。Unsloth 文件还不在磁盘上时用 `./qwen4-run.sh --download`(约需下载 32 GiB), +只跑预检用 `--check`。细节与选项在脚本的 `--help` 里。下面四个手动步骤就是它执行的内容,也仍是调试时的参考。 + +预检在任何下载或构建之前运行:GPU 0 的**空闲**显存(其他负载可能已占用一部分)、可绑定的服务端口、系统内存, +以及将存放模型与 pack 的文件系统上的空闲磁盘。`--check` 只运行这些检查,什么都不改——不建目录、不建 venv、不写配置。 +Python 环境安装完整的 `terminal/requirements.txt`(转换工具需要 `regex` 与 `jinja2`,不只是 `numpy`), +引擎构建以检测到的计算能力为目标(`QWEN4_CUDA_ARCH` 可覆盖)。 + +产物只有**完整**才会被复用:pack 需要 `native_experts.txt`——它的完成标记,由 `iq_pack.py` 在所有选定专家产物之后 +最后发布;MTP 运行时需要 `complete.json`——一份对全部四个文件做过尺寸校验的记录,并写明该运行时是否携带草稿层的 +indexer。缺这个字段的记录早于 indexer,会被重转:它的尺寸自洽,单看尺寸发现不了张量缺失,直接拿去服务就会静默 +退回稠密注意力近似。中断运行留下的半成品 pack 或草稿模型会被重建,而不是被拿去服务。运行配置原子写入(先临时文件,再改名),已有的 `*.shared-settings.json` +会被合并:保留你的键,只填补缺失的默认值。 + +四个步骤,然后运行。`M` 是模型目录,`P` 是 pack 目录。 + +```sh +# 1. 40 层 trunk 视图(保留量化字节;~20 GB,需要在原文件旁留出空间) +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. native pack(--compat-bf16 是必需的:小投影必须以 BF16 到达引擎) +python terminal/tools/iq_pack.py --gguf "$M/trunk40/Qwen4-35B-A3B-UD-IQ4_XS-trunk40.gguf" \ + --out "$P" --compat-bf16 + +# 3. 均匀专家 profile:40 层 x 256 专家(make_profile.py 默认是 Flash-Next 的 48) +python terminal/tools/make_profile.py --no-base --n-layer 40 --n-expert 256 --out "$P/expert-profile.bin" + +# 4. 把 MTP sidecar 转成草稿运行时(可选,但速度就来自这里) +python terminal/tools/mtp_qwen4_rt.py --gguf "$M/MTP/mtp-Qwen4-35B-A3B-Q8_0.gguf" --out "$P/mtp-rt" +``` + +然后: + +```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 +``` + +三件容易做错的事: + +- **`--native-dense-gguf` 里也要指名 trunk 视图。**只给 `--native` 时,引擎会把 `--ple-gguf` 文件加进稠密列表, + 分片 2 于是到达两次;加载因重复张量被拒绝。 +- **`--ple-gguf` 是分片 2**,即 PLE 文件,不是 trunk 的另一半。 +- **`--expert-profile` 实际上不是可选的。**native IQ pack 需要 `--spec T`(T >= 2)与 `--prefill`, + 不带 profile 的服务已被报告会崩溃([#7777](https://github.com/Niko1221/Strata/issues/7777))。 + +这里使用的构建: + +```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)" +``` + +(`86-real;86-virtual` 是实测的 RTX 3080 Ti;`qwen4-run.sh` 则从 GPU 推导架构。) + +## 运行服务 + + +运行配置是 `terminal/strata-qwen4-35b-ud-iq4_xs.json`;`terminal/models.json` 补齐引擎路径无法从 `--model` 参数 +推导的注册事实(该配置用 `--native` 指名文件,由 PolyStrata 引擎的主参数循环读取——`--model` 只被 qwen35moe +家族预扫描识别)。 + +该配置**不在仓库里**:`.gitignore` 排除 `/terminal/strata-*.json`,因为它记录的是某一台机器上的路径。 +把下面内容保存为 `terminal/strata-qwen4-35b-ud-iq4_xs.json`,其中 `/path/to/packs/` 与 `/path/to/models/` +指向上面快速开始里的 `$P` 与 `$M`: + +```json +{ + "exe": "build-q4lite/strata", + "args": [ + "--pack", "/path/to/packs/qwen4-35b-ud-iq4_xs-trunk40", + "--native", "/path/to/models/Qwen4-35B-A3B-GGUF/trunk40/Qwen4-35B-A3B-UD-IQ4_XS-trunk40.gguf", + "--native-dense-gguf", "/path/to/models/Qwen4-35B-A3B-GGUF/trunk40/Qwen4-35B-A3B-UD-IQ4_XS-trunk40.gguf", + "--ple-gguf", "/path/to/models/Qwen4-35B-A3B-GGUF/UD-IQ4_XS/Qwen4-35B-A3B-UD-IQ4_XS-00002-of-00002.gguf", + "--expert-profile", "/path/to/packs/qwen4-35b-ud-iq4_xs-trunk40/expert-profile.bin", + "--mtp", "/path/to/packs/qwen4-35b-ud-iq4_xs-trunk40/mtp-rt", + "--spec", "2", "--prefill", "auto", + "--max-context", "131072", "--kv-grow", "--vram-reserve-mib", "512" + ], + "cwd": ".", + "tokenizer": "/path/to/packs/qwen4-35b-ud-iq4_xs-trunk40/tokenizer", + "model_name": "qwen4-35b-a3b-ud-iq4_xs", + "aliases": ["qwen4", "qwen4-35b", "Qwen4-35B-A3B"], + "display_name": "Qwen4-35B-A3B UD-IQ4_XS (MTP)", + "log": "terminal/strata-qwen4-35b-ud-iq4_xs.log", + "port": 8080, + "gpu": 0, + "host": "127.0.0.1", + "open_browser": false, + "answer_room": true, + "reasoning_budget_tokens": 512 +} +``` + +`tokenizer` 必须是 pack 的分词器目录:它必须包含 `vocab.json`,这是 `serve.models.describe()` 读取的文件。 +`aliases` 是 OpenAI API 在 `model_name` 之外接受的名字(runner 把同一份列表写入 `terminal/models.json`)。 +显存小于 12 GB 的卡,或想给专家留更多显存时,调低 `--max-context`;`--kv-grow` 正是 131072 在这里可负担的原因(见下文)。 + +如果引擎找不到 CUDA 库,加上 `"lib_dirs": ["/usr/local/cuda/bin", "/usr/local/cuda/lib64"]`(你自己的 CUDA 路径)。 +这是可选的——服务端只是把这些目录前置到库搜索路径——但这里实测的运行设置了它,因为 CUDA 12.8 装在 +`/usr/local/cuda`,不在默认加载器路径上。 + +```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 +``` + +服务端自己会加 `--serve`。它只绑定回环地址,不设 API 密钥;绑定任何其他地址之前先在配置里加 `api_key`。 + +**上下文:配合 `--kv-grow` 支持 131072 tokens。**12 GB 的卡无法一开始就为 128K tokens 预留 KV,所以配置使用 +`--kv-grow`:KV 只占用请求实际到达的单元,其余显存留给专家缓存,上下文增长时逐步让出槽位。它要求单 GPU 与 +`--expert-profile`,本配置都已具备。131072 下缓存持有 **3305 个驻留专家,占 5.24 GiB**(8192 下为 3539 / 5.62 GiB), +所以长上下文的代价是约 234 个专家,不是回答质量。`--kv fp16|int8|q4_0|k8v4` 与 `--kv-resident N` 是另外两个调节手段, +用于权衡 KV 精度或从内存流式读取 KV;这里都没有使用。 + +两个协议都在运行中的服务端上、以 `--max-context 8192` 检查过: + +| 请求 | 结果 | +| --- | --- | +| `GET /v1/models` | 列出 `qwen4-35b-a3b-ud-iq4_xs` | +| `POST /v1/chat/completions`,中文,一个词 | `巴黎`,`finish_reason: stop`,0.61 s | +| `POST /v1/messages`(Anthropic),英文,一个词 | `Paris`,`stop_reason: end_turn`,0.42 s | +| `POST /v1/chat/completions`,中文短文 | 344 tokens 用时 2,226 ms = **154.5 tok/s**,`stop`,草稿 166/207 被接受 | + +再以出货的 `--max-context 131072 --kv-grow --spec 2` 检查: + +| 请求 | 结果 | +| --- | --- | +| 英文故事,`reasoning_budget_tokens: 512`,`max_tokens 900` | 698 tokens,`stop`,969 字符的 `content`,端到端 3.92 s | +| 引擎侧 decode,37-token 提示 | 450 tokens 用时 2,745 ms = **163.9 tok/s**,草稿 190/263 被接受 | +| 中文,"用三句话解释蓝天" | 360 tokens 用时 2,175 ms = **165.5 tok/s**,`stop`,草稿 153/206 被接受,端到端 2.47 s | +| 引擎侧 decode,505-token 提示,复用 486 | 230 tokens 用时 662 ms = 347.5 tok/s,草稿 208/211 被接受 | +| 长提示读取 | **24,282 tokens 用时 8,375 ms = 2,899 tok/s** prefill | + +347.5 tok/s 那一行是高度可预测的续写(98.6% 的草稿被接受),不是有代表性的聊天速度;72% 接受率下的 163.9 tok/s 才是。 +服务速度与 CLI 的 155.32 tok/s 一致,而且服务端**确实**会在回合结束时停止——下文 CLI `--max-new` 的超量生成 +是 harness 差异,不是模型差异。 + +**思考预算。**这是一个思考模型:回答在 `content` 里,推理在 `reasoning_content` 里。要求精确字数的提示可能把整个预算 +花在推理上——要求写 200 词的故事时,它在思考块里逐词计数("three(8) sentences(9) on(10)…"),用了 700 tokens +还没到 `content`,`finish_reason: length`。这是模型在认真,不是死循环。 + +配置设置了 **`reasoning_budget_tokens: 512`**,它会礼貌地关闭思考块(收尾,然后 ``,然后回答),而不是硬切。 +之前返回空 `content` 的那个 200 词提示,随后产出了 969 字符的故事,`finish_reason: stop`。单次请求的 +`reasoning_budget_tokens` 覆盖配置值,Anthropic 的 `thinking.budget_tokens` 映射到它;`0` 或缺省表示不限。 +确实需要长时间思考的任务可以调大。 + +**思考力度:Qwen4 自己的词。**官方档位是 `xhigh`、`high`、`low` 与 `off`,默认 `high`;模板本身没有 `medium`。 +服务端接受这些词(外加常见的 off 别名 `none`/`minimal`/`disabled`/`false`,以及 `xhigh` 的 `max`/`maximum`), +客户端传 `medium` 时映射为默认的 `high` 而不是报错,只认通用档位的客户端因此不会中断。 +Anthropic 的 `thinking.budget_tokens` 映射为:低于 2048 → `low`, +2048 到 8191 → `high`,8192 起 → `xhigh`。方言由分词器的 `pre="qwen4"` 选定,**不是**由 GGUF 架构选定: +Qwen3.8-Flash-Next 同样使用 `qwen4exp`,仍保留通用 Qwen 词表。同一套方言适用于运行配置、shared settings 与 +`POST /settings`,并且分词器在配置的 effort 值被校验之前读取,所以带 `xhigh` 的 Qwen4 配置能加载。 + +**开着 MTP 时的采样。**对其他模型,未指名采样的 MTP 请求保持 greedy(#3354),这样草稿不会被模型卡默认值静默禁用。 +Qwen4 是例外:它的模型卡采样在开着草稿模型时同样适用——思考模式 `temperature 1.0, top_p 0.95, top_k 20`; +非思考模式 `temperature 0.7, top_p 0.80, top_k 20, presence_penalty 1.5`。显式的请求字段、shared settings +与配置的采样块仍优先于模型卡,显式 `temperature: 0` 仍是 greedy。`GET /props` 报告的就是生成路径使用的同一套默认值。 + +**`preserve_thinking` 是两件不同的事。**Qwen4 的聊天模板保留*客户端*已经在历史里回传的推理。另外,服务端可以记住 +本会话的推理,并在客户端只回传回答文本时恢复它——那是需显式开启(opt-in)的 `preserve_thinking` 运行配置键, +runner **没有**启用它。模板的行为不等于服务端记忆。 + +**在这台机器上,内存是服务的约束。**引擎持有约 20 GB RSS(16.25 GiB 专家加载进内存,部分为 GPU 锁定)。 +同时跑着桌面会话时,`MemAvailable` 降到 12 GB,zram 交换区到 6.6 GB,第一个长请求 decode 只有 **24.7 tok/s**, +而 CPU 专家池读取带宽为 **2.6 GB/s**。同一请求在工作集预热后跑 143.9 tok/s。盯住与 +[有效性判据](#the-validity-gate-watch-the-cpu-pools-bandwidth)相同的那条带宽线;在开着其他程序的 46 GB 机器上, +启动后的第一个长回答慢是预期内的。 + +## 速度 + + +> **实测机器:**一张 NVIDIA RTX 3080 Ti 12 GB(CUDA 12.8,sm_86),46 GB 内存,PCIe 链路读取 25.4 GB/s, +> Unsloth UD-IQ4_XS,引擎 `strata 0.1.66`,以 `-DSTRATA_GEOMETRY=q4_lite` 构建。负载:28-token 的故事提示, +> 256 个 greedy tokens,`--prefill auto --vram-reserve-mib 512`,单请求串行。这里引用的每次运行都通过了 +> 下文的有效性判据。 + +**自然 greedy decode**——每个设置生成各自的续写: + +| 草稿模型 | Decode | 接受率 | 每轮 token 数 | +| --- | ---: | ---: | ---: | +| 无(`--spec 2`,仅 suffix 草稿) | 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 | + +**所有设置使用同一段文本**(`--spec-follow`,对上面 256 tokens 做 teacher-forced)。这才是公平比较: +上面各行不是同一段续写,更宽的窗口看起来更好或更差,部分原因是它恰好生成的文本更容易或更难预测。 + +| 草稿模型 | Decode | 接受率 | 每轮 token 数 | +| --- | ---: | ---: | ---: | +| 无(`--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 | + +两者一致:**`--spec 2` 是这张卡上的最佳窗口,比不开 MTP 快约 46%。**更宽的窗口每轮提议更多 token, +但接受的比例更小,而且在 12 GB 上额外的验证要从内存读取更多专家。`--spec-follow` 是诊断工具: +它在接受之前替换输出,所以测的是固定文本上的速度,不是模型本来会说的话。 + +社区在另一张卡上的运行对窗口结论一致:RTX 3090 24 GB、62 GiB 内存,同一份 UD-IQ4_XS 文件, +实测 `--spec 2` **相对 `--spec 4` 聊天 decode +27%、agent decode +17%** +([#7780](https://github.com/Niko1221/Strata/issues/7780))。那台机器 MTP `--spec 2` 聊天 decode 达到 179.6 tok/s, +这里是 155.32——差别在于它能留在显存里的专家。 + +同一负载下的提示读取:200 到 233 tok/s,首 token 时间 196 到 216 ms。短回答的每 token 速度更慢, +因为固定成本摊不开:不开 MTP 时,32-token 的英文回答 decode 为 79.6 tok/s,64-token 的中文回答为 94.2 tok/s。 + +**真实 agent 负载,不是基准提示。**一次通过服务 API 的较长会话(117 次请求,提示增长到约 78K tokens, +97% 提示复用)平均 **decode 192.9 tok/s、prefill 1,906 tok/s**,逐请求 decode 在 126.9 到 256.0 tok/s 之间, +专家显存命中率 73-81%。其中一轮产出 1,955 tokens,169.1 tok/s。监控面板显示显存 11.4/12 GB、3,305 个缓存专家、 +系统内存 39.5/47 GB。这就是这里出货的配置(131072 上下文,`--kv-grow`,MTP `--spec 2`), +它比上面的短提示数字更快,因为缓存前缀承担了大部分提示处理。 + +![该会话期间的服务监控面板:decode 192.9 tok/s,prefill 1,906 tok/s,117 次请求,3,305 个缓存专家](media/qwen4-35b-a3b-monitor.png) + +**MTP 层的代价。**它占 1,915 MiB 显存(816 个专家、580 个稠密,其余是 head 与 norm), +驻留专家数从 10,240 中的约 4,835 降到约 3,645。加速是付出这个代价之后剩下的收益: +在全部专家本来就放得下的卡上,权衡不同。 + +### MTP 草稿模型的 indexer(MTP QSA) + + +`mtp_qwen4_rt.py` 转换 sidecar 的 `blk.40.indexer.{q_proj,k_proj,q_norm,k_norm}`,引擎运行草稿层自己的 +indexer/top-k KV 选择(QSA)——与 trunk 运行的计算相同:投影 indexer 键,在每个块完成时池化并旋转, +给每个块打分,取 top-k,注意选中的单元。没有这些张量的 sidecar,或 `STRATA_MTP_INDEXER=0`, +保留原先对保留单元的**稠密注意力近似**。 + +- 无论哪条路径,目标模型都会校验每个草稿,所以被接受的 token 是目标模型自己的。这条路径改变的是草稿分布 + 与接受率,不是被接受 token 的正确性。 +- 有了 indexer,草稿模型读取一个有界选择(2,048 个单元加尾部),而不是每个保留单元, + 所以它的每轮成本不再随上下文增长。 +- 草稿模型没有轮次检查点,所以会话快照连同 K/V 携带它的整个 indexer 块。借用前缀会结束在某个块中间: + 尾部被清空,备用行接管失效的键,与检查点恢复的做法一样。于是那一个池化键最多有 `idx_block - 1` 个单元是近似的—— + 32K 前缀下是 8,192 中的一个块,2,048 单元以下则完全没有。trunk 在这里是精确的,因为它的检查点存在。 + +**长上下文:indexer 对比稠密近似。**64K 提示(65,570 tokens 的真实仓库文本,在半深处拼接一个 needle), +256 个 greedy tokens,`--spec 2`,2,000 个专家缓存槽位使驻留专家集合一致,`STRATA_PREFILL_CPU_SHARE=0`。 +每个组读取带宽 72.6-80.4 GB/s,都在下文有效性判据之内。 + +| 草稿模型 | Decode | 接受率 | ms/轮 | +| --- | ---: | ---: | ---: | +| 稠密近似 | 125.51 tok/s | 0.814 | 1.050 | +| **indexer** | **139.03 tok/s** | 0.697 | 0.983 | +| 编译进 indexer,`STRATA_MTP_INDEXER=0` | 125.01 tok/s | 0.814 | 1.049 | + +indexer 用接受率换更便宜的一轮,在 decode 上获胜(**+10.8%**)。`STRATA_MTP_INDEXER=0` 组精确复现稠密运行时 +发出的 ids,所以对保留近似的人来说,近似行为不变。 + +32K 与 128K 下,两条路径的接受率在本机重复运行波动范围内重叠,而且**每个组在 128K 下都正确检索到 needle**—— +在测试过的最长上下文下,选择仍能找到正确的块。那两批读取带宽为 52-72 GB/s,所以不引用其 decode 计时; +接受率计数与 needle 检查则照常引用。 + +这个波动是真实的,在读本文任何接受率数字之前值得先知道:*同一*配置的两次运行(`--mtp-q4 proj` 与 `--mtp-q4 all`, +在这个 pack 上二者相同,因为 head 子集不存在)测得接受率 0.733 与 0.826、135.5 与 127.1 tok/s。 +自然 greedy decode 在本引擎上不是逐位可复现的——自适应显存分层与 CPU 专家池的归约顺序随时间变化。 + +#### step 记录的宽度:随上下文增长的溢出 + +`qsa_block_topk` 读取 `step[kStepWidth]`,把 `n_kv <= width` 当作「全部选中」:然后写入 `n_kv` 个升序 ids 并返回。 +ids 缓冲区每个查询容纳 `cap` 个 ids。稠密路径填充 `n_kv`,而 `window_ids` 会用窗口自己的计数覆盖它 +(且其 `cap` 本来就按上下文尺寸分配);indexer 路径没有这种覆盖,其 `cap` 是固定的选择宽度, +所以在那里填充 `n_kv` 会让 kernel 走恒等分支,越界写入 `n_kv - cap` 个 ids。 + +这就是为什么最初的 indexer 运行在 32K 下看起来健康、在 64K 下崩溃:溢出随上下文增长。 +实测接受率 32K 下 0.715,**64K 下两次都是 0.217**,而同一运行时关闭 indexer 时为 0.76-0.89。 +现在全部五个主机端填充点都经过 `MtpDrafter::fill_step`:indexer 路径由它调用 `qsa_step_fill`——四元组的唯一写入者—— +稠密路径保留旧算术。修复后 64K 接受率为 0.697 / 0.660,128K 下 needle 能找到。 + +`mtp_step_test` 是对应的回归测试:无设备时检查算术,有设备时在带守卫的 ids 缓冲区上运行真实选择。 +对旧填充做 fail-first,**16 项检查失败**,32,802 单元的上下文测得越界 30,751 个 ids,65,570 单元测得 63,519 个。 + +### 两个默认值,实测 + + +**`--mtp-hnorm` 现在默认 `stream`。**它此前冻结在 `pooled`,等待同机 A/B;该测量已完成,结构性问题已有定论。 +`pre_fc_norm_hidden.weight` 宽 8192 = 4 x 2048,参考实现都**对每个 hyper-connection 流单独归一化**, +按该流对应的权重切片缩放: + +- 上游的 `q4_mtp_eh_concat_kernel` 每个 (token, stream) 启动一个 block,只在 `n_embd` 上求平方和, + 读取 `w_hnorm + c * n_embd`; +- llama.cpp 的 `qwen4exp` MTP 图做法相同; +- `tools/mtp_qwen4_rt.py` 把转换记录为「按 hc 流应用于 `hnorm(h)`」。 + +`pooled`——对全部四个流做一个 RMS——与它们都不符。本机 32K 下,各跑两次: + +| `--mtp-hnorm` | 接受率 | Decode | 每轮 token 数 | +| --- | ---: | ---: | ---: | +| `pooled`(旧默认) | 0.679, 0.679 | 138.73, 137.56 tok/s | 1.71 | +| **`stream`(新默认)** | **0.815, 0.852** | **142.30, 137.78 tok/s** | 1.90 | + +两次 `pooled` 运行逐位一致;两次 `stream` 运行都接受更多、所需轮数更少,而且尽管读取带宽*更低* +(60.0 / 52.1 GB/s 对 62.2 / 65.2),decode 都更快。DGX Spark 上的一次运行独立记录到 `stream` **+4.3% decode** +([DGX_SPARK_LINUX.md](DGX_SPARK_LINUX.md))。`pooled` 仍保留为 opt-out 选项。 + +**`--spec-min-p` 保持 `0.0`。**在 indexer 路径 32K 下扫描,每个取值跑一次:0.05 给出接受率 0.777、146.74 tok/s, +0.10 给出 0.678 / 139.01,0.20 给出 0.748 / 137.71,0.40 给出 0.837 / 134.22,对照 0.0 基线的 0.679 / ~138.1。 +排序不单调,差异落在上面测得的重复运行波动范围内,所以每个取值一次运行无法定论。0.40 呈现预期的权衡—— +接受率最高、decode 最低,因为低于阈值的草稿会终止链条。改这个默认值需要在无争用的机器上对每个取值多次重复。 + +**`--mtp-q4` 保持关闭,而且在这里并不省显存。**Q4_0 副本是*额外叠加*的:prompt 路径的批量 K/V 通路保留 Q8_0 原件。 +这张卡上 11 个投影转 Q4_0 花费 **+566 MiB**(1,989 -> 2,555 MiB),挤掉 26 个驻留专家(3,000 -> 2,974 槽位)。 +接受率上升(0.733 / 0.826),decode 没有(135.5 / 127.1 tok/s,基线 135.4)。没有草稿头子集 +(`rt/draft_vocab.bin` 或 `--mtp-draft-vocab`)时,`head` 以及 `all` 的 head 部分不起作用; +引擎会明说,而不是静默地在完整 head 上草稿。在专家已经放得下的卡上权衡不同——DGX Spark 上的一次运行记录到 +`--mtp-q4 all` **+3.5% decode**([DGX_SPARK_LINUX.md](DGX_SPARK_LINUX.md))。12 GB 上的结果是驻留结果, +不是对 Q4_0 草稿的定论。 + +### 有效性判据:盯住 CPU 专家池的带宽 + + +CPU 专家池必须从内存读取权重。当内存压力把这些页挤进 zram 交换区时,池改为解压它们,这次运行就没有意义—— +不是硬件慢,而是测量被污染。要检查的行在每次运行的统计里: + +``` +pool multi gate/up 0.930 quantize 0.016 down 0.498 ms/round; 66.3 GB/s over the rows phases +``` + +本机健康的运行读取 **60 到 70 GB/s**。同一 `--spec 4` 设置的两次运行,一次在 66.5 GB/s 下测得 126.87 tok/s, +另一次在 **1.2 GB/s** 下测得 23.74 tok/s;第二次有 8.9 GB zram 交换区在用,`allocstall_movable` 持续攀升。 +这不是 `--spec 4` 的性能悬崖。任何低于大约 50 GB/s 的数字都应在机器平静后重测, +而连续的大运行正是制造这种压力的原因。 + +## 分词器:`qwen4` 要开 `ignore_merges` + + +GGUF 的 `tokenizer.ggml.pre` 是 `qwen4`。它使用与 `qwen35` 相同的预分词模式,但**开启 `ignore_merges`**, +与上游 llama.cpp 一致(`src/llama-vocab.cpp` 的 `qwen4` 分支设置 +`pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN35; ignore_merges = true;`)。`qwen35` 分支不设置它。 + +这不是细枝末节。开启 `ignore_merges` 后,词表中存在的完整片段保持为一个 token,而不是由合并规则重建: +`俱乐部` 编码为单个 token 104328。该词表中约 201 个整词 CJK token 根本无法由合并路径复现, +这是支持该 flag 的证据,而不是反对它的。 + +仅用英文的 oracle 对照无法区分两者——英文文本不含这些片段——所以回归测试直接断言该 flag, +并增加一个在没有合并规则时区分两条规则的用例。 + +## 限制 + +- **CLI 不会在回合结束时停下。**`--max-new N` 会越过 `<|im_end|>` 与 `<|endoftext|>` 继续生成, + 所以短探测的尾部是垃圾。这是基准 harness 的行为,不是模型的:停止由服务端负责。 + 判断正确性看第一个结束标记之前的文本。 +- **`qsa_pattn` 现在支持这个几何,但这里的生产路径仍不使用它。**reduce-scatter 与 `px_head` 排列以 G(8 或 12) + 为模板参数,所以 16:2 不再触发头数检查。kernel 仍受 `STRATA_EXPERIMENTAL_SM60` 门控,出货的 `q4_lite` 构建 + 将其关闭:sm_86 上 prefill 仍像以前一样回退到 decode 循环,G=8 的工作在这张卡上不带来加速。 + 它通过任意架构 parity 入口来验证,该入口只绕过计算能力门控。见下文[分歧](#relationship-to-pr-7774)。 +- **12 GB 是混合模式。**出货的 131072 上下文下,10,240 个专家中 6,935 个不在显存(3,305 驻留,5.24 GiB); + 8192 下是 6,701 个。无论哪种,回答速度都取决于 PCIe 链路与内存带宽。prefill CPU 分担默认开启, + 可能轻微改变文本(引擎会打印它预期的平均 KL)。 +- **greedy 文本在不同投机宽度下不是逐位稳定的。**带 `--spec` 时验证窗口一次计算多个位置,改变归约顺序; + 接近平局的 argmax 于是以不同方式打破。同一提示的两次运行在第 52 个 token 处分歧,之后都继续为连贯文本。 + 用 `--spec-follow` 在同一段文本上比较设置,用 `--window-hashes` 加 `--adapt-every 0` 比较两个构建的算术。 +- 文件内嵌 MTP 块与 sidecar 是同一份权重。加载 sidecar(`--mtp`)才启用草稿;trunk 视图有意不携带 `blk.40`。 +- **草稿模型的 indexer 已实现;快照的一处角落仍是近似。**借用前缀结束在 indexer 块中间,所以那一个池化键 + 最多 `idx_block - 1` 个单元从续写位置重建(见上文)。其余都是模型自己的选择。本文每个数字都来自一张 RTX 3080 Ti。 + +## 测试 + +```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 tools.test_iq_pack \ + tools.test_mtp_qwen4_rt tools.test_qwen4_run +``` + +115 个测试,4 个跳过(跳过项需要不在场的分词器 fixture)。 + +| 测试 | 检查内容 | +| --- | --- | +| `test_qwen4_split_gguf.py` | 元数据截断与 F32 字节;**Q8_0 块字节经拆分后原样保留**;行数与元数据不符会被拒绝;失败或中断的写入保留先前输出,不留临时文件。 | +| `test_strata_tokenizer.py` | `qwen4` 是带 `ignore_merges` 的 `qwen35` 规则,含一个区分两条规则的用例;英文 oracle;真实 GGUF → `extract()` → `from_dir()` 往返,覆盖空合并集、CJK 整词、组合记号、emoji 与控制字符。 | +| `test_make_profile.py` | `--n-layer` 与不变的 48 层默认;完整 40 层 CLI 路径及其重读校验。 | +| `test_qwen4_intake.py` | `pre="qwen4"` 集合能构建并探测(用例 A);草稿模型报告对 Qwen4 指向 `tools/mtp_qwen4_rt.py`,对 Flash-Next 保留 `tools/mtp_pack.py`。 | +| `test_iq_pack.py` | `native_experts.txt` 最后发布:中断的运行不留完成标记,续跑不依赖它,完整的旧 pack 能在之后中断的索引写入中幸存。 | +| `test_mtp_qwen4_rt.py` | 四个草稿产物只在转换成功后发布,附带尺寸校验过的 `complete.json`;失败的运行保留先前产物集。indexer 张量按其真实 kind、行数与逐字节精确的载荷转换;`--plus-one-norms` 覆盖 indexer norm;没有 indexer 的旧 sidecar 仍能转换,且不携带任何此类张量;完成记录在两种情形下都如实写明 indexer 是否存在。 | +| `test_qwen4_run.py` | 启动器,用假硬件与工具离线运行:`--check` 什么都不改,空闲显存不足与端口被占在准备之前被拒绝,构建使用检测到的架构与完整 requirements,不完整的 pack/草稿模型被重建,早于 indexer 的草稿记录被重转而当前记录被复用,shared settings 合并不丢用户键。 | + +服务侧改动有自己的回归测试——`serve.test_effort_paths` 与 `serve.test_model_card_sampling` +(34 个测试:三条 API 路径上的 Qwen4 effort 方言,config/shared/settings,以及带显式覆盖的 Qwen4+MTP +模型卡默认值)——并与周围更大的服务套件一起重跑(19 个模块,覆盖前端、models、settings、安全、reasoning +与 thinking 路径):826 个测试,3 个跳过,全部通过。 +effort 方言把客户端的 `medium` 映射为 `high`(模板本身没有 `medium`,直接传会抛错):更新后的 `Qwen4EffortPaths` +回归先在旧代码上失败——19 个测试,13 个失败、2 个错误,全部落在 `medium` 路径——在前端词表与 shared settings +校验器加入映射后通过。 + +引擎侧工作有自己的回归测试,在 GPU 构建(`build-q4lite-tests`,sm_86)上运行: + +| 测试 | 检查内容 | +| --- | --- | +| `mtp_step_test` | step 四元组契约:算术填充在每个单元数下都与 `qsa_step_fill` 一致;32K/40K/64K/128K 下带守卫的真实选择只写入容量之内,选择宽度以下的单元保持恒等。对旧代码 fail-first:16 项失败,65570 KV 下最多 63519 个越界 ids。 | +| `conversation_snapshot_test` | 4639 项检查,含新增的 `draft_indexer_roundtrip`:block-span 布局逐字节精确往返,过期前缀重置,借用前缀让块粒度近似保持如实。 | +| CTest(GPU 构建) | 448 个中 426 个通过。22 个失败是既有集合加两个已归因的:`native_i8_parity` 在 indexer 改动 stash 后仍 3/3 失败(随机性 carved-tm parity 校验,既有问题),`poly_bell_test` 在机器空闲时通过(对负载敏感的计时偶发失败)。两者都不被本工作触及。 | + +## 与 PR #7774 的关系 + + +[Niko1221/Strata#7774](https://github.com/Niko1221/Strata/pull/7774) 是这个模型的参考实现。 +拆分器、MTP 运行时工具、`--n-layer`、`qwen4` 分词器规则与几何改动都遵循它。三处有意的差异: + +1. **`qsa_pattn.cu` 以 G(8 或 12)为模板参数,而不是不加检查地从几何推导。**PR 从几何推导 `G`, + 对 `q4_lite` 得到 8,但它的归约在 `s` 最大到 5 时读 `r[s + 6]`(8 元素数组的第 8 到 11 槽), + 并把 `h0` 最大到 11 的 `sp[h0]` 写进 `[G][CHUNK]`;PR 自己的评审线程指出了同样的越界读取与 `px_head` 排列问题。 + 这里排列推广为 `P_L(i) = HALF*((i/HALF)^b3) + ((i%HALF + QUARTER*b2)%HALF)`,其中 `HALF=G/2`、`QUARTER=G/4`, + 归约保留 `warp_sum_x` 的 xor 嵌套(16,8,4,2,1),使每个部分和以相同顺序相加,third-quarter 的 lane 折叠 + 只存在于 G=12(`if constexpr`)。parity 校验区分「未构建」与「几何拒绝」,并让两种头比例跑同一组 468 个用例: + G=8 **0 处差异**(19,644,888 个非零输出),G=12 **0 处差异**(29,724,792)——G=12 路径逐位保持不变。 + 对旧 kernel fail-first:468/468 差异。kernel 仍受 SM60 门控,所以生产 sm_86 服务不变。 +2. **`gguf_reader.hpp` 在读键前重置 `g.n_mtp_layers = 0`。**`read_geometry` 从 `g = core::kCompiledGeometry` 出发, + 而不是默认构造的几何,所以在 `q4_lite` 声明一个 MTP 层时,*没有* `nextn_predict_layers` 的文件继承了 1, + 按 41 层去对 40 项的 `compress_ratios` 计数。trunk 视图被拒绝。键缺失必须意味着没有 MTP 块。 + Flash-Next 不受影响(其编译值本来就是 0)。`compiled_geometry_mismatch` 也不再比较 `n_mtp_layers`, + 所以声明该层的构建与不携带它的 trunk 视图互相接受。 +3. **DFlash2 tap 工作没有移植。**`core/tap_plan.hpp`、`verify.*` 改动与 `generate.cpp` 里的 `--draft-tap` 选项 + 服务于 `--draft dflash2` 的块输入 tap,是另一种草稿模型。它们由 `STRATA_HAVE_DFLASH2` 守卫,默认保持旧行为。 + MTP 路径不需要它们,而且 PR 自己的说明写道:12 GB NVIDIA 卡上,除 code 外的每个上限下 DFlash2 都比 MTP 慢。 + +除上述之外从 PR 移植的:`qsa_prompt_attn.cu` 里的 WMMA wave pin(只有半个 wave 通过的 store 守卫不能把 WMMA +拉进该分支,这在 gfx11/gfx12 上 G <= 8 时很重要),以及 `qsa_prompt_attn_parity.cpp` 里的非有限输出计数 +(NaN 会静默地让后续所有比较失败)。 + +## 还没做的事(TODO) + +- **setup 菜单集成。**准备这个模型仍意味着运行上面四条命令(或 `qwen4-run.sh`);它还不是安装器里的选项。 + 这项工作是一个知道必须有 trunk 视图的 setup 入口——普通家族入口会提供出版分片 1 然后失败—— + 外加 pack 尺寸、内存与磁盘指引。先做服务是有意的;这是一块独立、边界清晰的工作。 +- **16:2 下 QSA 进生产。**G=8 归约树与 `px_head` 排列已完成并有 parity 门控(见上文),但 kernel 仍受 SM60 门控。 + 为 sm_86 prefill 启用它需要单独实测,不是拨一个 flag。 +- **`--spec-min-p`。**仍为 `0.0`:扫描差异落在本机重复运行波动范围内,改默认值前需要在无争用的机器上 + 对每个取值多次重复(见上文)。`--mtp-hnorm` 已定,现在默认 `stream`。 +- **IQ4_NL 草稿模型。**社区方向是 ~780 MiB 的 IQ4_NL sidecar,对比这份 Q8_0 的 2,194 MiB。尚未实现: + 本转换链要求 Q8_0,而且实测机器上既没有 IQ4_NL sidecar 也没有 Qwen4 MTP 的 HF 权重,所以这里没有任何对它的测量。 + `--mtp-q4` 是另一回事(Q8_0 投影的 Q4_0 副本),在这里花费显存而不是节省(见上文)。 +- **视觉没有接入。**模型目录附带 `mmproj-F16.gguf`;本适配只做文本。 +- **并发与其他卡没有实测。**所有数字都是一张 RTX 3080 Ti 上单请求串行。多槽位批处理、AMD/Intel 路径 + 与显存更大的卡,需要各自实测之后才能下任何结论。 \ No newline at end of file diff --git a/docs/QWEN4_ENGINE_PATHS.md b/docs/QWEN4_ENGINE_PATHS.md new file mode 100644 index 0000000000..279f41fac9 --- /dev/null +++ b/docs/QWEN4_ENGINE_PATHS.md @@ -0,0 +1,161 @@ +# Qwen4-35B-A3B: the strata and strata-poly engine routes, measured + +[中文版](QWEN4_ENGINE_PATHS.zh-CN.md) + +This page compares the two implementations that now exist for Qwen4-35B-A3B (`qwen4exp`): + +- **This branch** ([PR #430](https://github.com/simplexai-labs/PolyStrata/pull/430), `qwen4-35b` @ `52c562ff0`): + the model adapted to the existing **strata engine path** — the `strata` binary built with + `-DSTRATA_GEOMETRY=q4_lite`, a preprocessed trunk view and native pack, an external Q8_0 MTP drafter + runtime, and a fixed `--spec 2` verify window. The adaptation itself is described in [QWEN4.md](QWEN4.md). +- **Upstream main** (@ `df2c3ff30`): a native Qwen4 implementation on the **strata-poly engine** + (`engine/src/poly/qwen4.cpp`), reading the published two-shard GGUF directly, drafting with the MTP block + embedded in the file, and choosing the verify window per round with an adaptive policy. + +Both repositories contain both engine families; what differs is which one serves Qwen4 and how the model is +prepared for it. This page records the route differences and a same-box measurement snapshot. **It does not +claim that either route is better.** Upstream's implementation is evolving (for example +[#440](https://github.com/simplexai-labs/PolyStrata/pull/440), PLE row-by-row O_DIRECT reads, is open, and +BasinKV sparse KV offload has landed), so its numbers can move. All measurements here are one RTX 3080 Ti +12 GB (sm_86), 46 GB RAM, Linux, CUDA 12.8, one request at a time, Unsloth UD-IQ4_XS — the same published +GGUF files on both routes. + +## The two routes + +| Aspect | This branch (strata route) | Upstream main (strata-poly route) | +| --- | --- | --- | +| Engine binary | `strata` (`-DSTRATA_GEOMETRY=q4_lite`) | `strata-poly` | +| Qwen4 code | `engine/src/program/generate.cpp`, `engine/src/split/`, `engine/src/core/layer.cpp` adaptations | `engine/src/poly/qwen4.cpp` / `.cu`, native `qwen4exp` forward pass | +| Model loading | 40-layer trunk view (`tools/qwen4_split_gguf.py`) → native pack (`tools/iq_pack.py`), passed as `--pack` / `--native` | published 2-shard GGUF mmap'd directly (`--model`), no repack | +| Fused projections | split into separate tensors **by quantized byte rows** (no requantization) | read natively in fused form (`attn_qkv_gate`, `ssm_beta_alpha`, `*_down_inject`) | +| PLE n-gram table | published shard 2 passed separately as `--ple-gguf` | read by the poly engine from the published shard; [#440](https://github.com/simplexai-labs/PolyStrata/pull/440) (open) reworks this to row-by-row O_DIRECT reads | +| Expert profile | `tools/make_profile.py --n-layer 40` → `expert-profile.bin` | setup preparation → `expert-profile.txt` | +| MTP weights | separate Q8_0 sidecar (`MTP/mtp-Qwen4-35B-A3B-Q8_0.gguf`, 1.87 GiB) → drafter runtime (`tools/mtp_qwen4_rt.py`), passed as `--mtp`; costs 1,915 MiB VRAM | `blk.40` embedded in the published UD file: Q5_K matrices, F32 norms, BF16 indexer; loaded automatically, no flag | +| MTP attention | indexer/QSA path **implemented** — the sidecar's `blk.40.indexer.*` converted, block scores → top-k → selected cells; `STRATA_MTP_INDEXER=0` keeps the dense approximation ([details](QWEN4.md#the-mtp-drafters-indexer-mtp-qsa)) | indexer/QSA path retained (`blk.40.indexer.*` loaded like a trunk attention block) | +| Verify window | `--spec 2` fixed cap; `--spec-min-p` stays `0.0`; suffix drafter available | no `--window` → the engine resolves a default cap of **8** for this model (GDN recurrent state, `snaps_spread()` true because `full_snaps_` is only set on the DFlash2 path); the adaptive `DraftPolicy` then picks the size per round | +| KV / RAM | `--kv-grow`: KV allocated only for cells reached | `--conversation-cache-mib auto` (8 GiB, up to 4 parked conversations here); BasinKV offload available but not enabled in the measured config | +| Sampling default with MTP | Qwen4 (`pre="qwen4"`) requests that name no sampling use the **model card** (this branch's change) | #3354 rule: MTP requests that name no sampling stay **greedy** (`serve/server.py`, `mtp_greedy`) | +| Model aliases | the runner writes `aliases` into the run config | serve supports `aliases` (#297); the qwen4 setup writes none | + +What is shared: the published GGUF files, the serving surface (OpenAI and Anthropic APIs), and — byte for +byte — `engine/include/strata/spec/draft_policy.hpp`, the adaptive draft policy and its cost learner. The +routes differ in the cap they give that policy and in the drafter they feed it, not in the policy code. + +## Measurement 1: the window cap, within upstream (controlled) + +The same upstream stack and the same harness sweep (7 requests, 256 generated tokens each, prompts of +1,017 / 1,023 / 1,023 / 31,718 / 32,765 / 65,499 / 130,652 tokens, all cold reads) were run with the default +window and with a variant config adding `--window 2`. Two passes of the capped variant were recorded. +Acceptance is per draft token, from the serve log's `drafts accepted X of Y` lines. + +| Run | Acceptance | Mean decode | Tokens committed per round | Rounds per 256 tokens | +| --- | ---: | ---: | ---: | ---: | +| default (adaptive, cap 8) | 942/1281 = **73.5%** | **154.4 tok/s** | ~2.11 | ~121 | +| `--window 2`, pass 1 | 785/955 = **82.2%** | **152.4 tok/s** | ~1.78 | ~144 | +| `--window 2`, pass 2 | 786/923 = **85.2%** | **148.2 tok/s** | ~1.78 | ~144 | + +Per-request decode (tok/s): + +| Prompt tokens | default | w2 pass 1 | w2 pass 2 | +| ---: | ---: | ---: | ---: | +| 1,017 | 148.1 | 146.8 | 124.6 * | +| 1,023 | 170.1 | 167.1 | 170.6 | +| 1,023 | 172.0 | 173.9 | 162.3 | +| 31,718 | 159.7 | 150.4 | 154.6 | +| 32,765 | 165.4 | 160.9 | 161.1 | +| 65,499 | 150.6 | 146.5 | 144.6 | +| 130,652 | 114.9 | 121.4 | 119.6 | + +\* The pass-2 run at 1,017 tokens also prefilled 14× slower than usual (6,326 ms at 160.8 tok/s against +~450 ms at ~2,250 tok/s in every other run). That points to machine-level contention during that request, +not to the window setting; it is kept in the table and flagged, not silently dropped. + +What this shows: + +- **Capping the window at 2 raises acceptance from ~73.5% to ~82–85%.** The cap removes the deeper, + lower-confidence drafts from the denominator; the drafter is the same Q5_K embedded block in both runs. +- **Decode does not improve with the cap — it drops ~1–4% on average.** The adaptive policy commits ~2.11 + tokens per verification round against ~1.78 capped: ~18% more rounds, each ~16% cheaper (14.2 ms vs + 11.9 ms per round on the 1,017-token request). The two effects nearly cancel, with a small net loss. +- **At 130,652 tokens the capped window is ~6% faster** (114.9 → 121.4/119.6 tok/s): verifying a deep + window over a very long KV costs more, and the shallow window wins there. +- Acceptance rate and decode throughput are different objectives. The shared adaptive policy optimizes + learned per-round cost (tokens/s), not acceptance; a lower acceptance at a wider cap is the policy + spending draft tokens where they still pay off. + +## Measurement 2: across the two routes (observational, not a controlled A/B) + +The branch's own serve log on the same box and the same UD-IQ4_XS file, same harness prompt sizes +(128-token generations there, 256 above), cold reads on both sides: + +| Prompt tokens | This branch, prefill | Upstream, prefill | +| ---: | ---: | ---: | +| 1,017 | 2,262–2,329 tok/s | 2,181–2,290 tok/s | +| 31,718 | 3,884–3,905 tok/s | 2,357–2,385 tok/s | +| 65,499 | 3,704–3,731 tok/s | 2,094–2,169 tok/s | +| 130,652 | 3,466–3,516 tok/s | 1,819–1,887 tok/s | + +Decode: this branch measured 147.4–178.9 tok/s across those requests (acceptance 69.9–92.4% per request); +upstream's default-window sweep measured 114.9–172.0 tok/s. Expert residency at the shipped 131,072 +context: this branch keeps 3,305 of 10,240 trunk experts in VRAM plus the 1,915 MiB drafter +([QWEN4.md](QWEN4.md)); upstream's log reports 4,796 of 10,496 routed experts in 7.6 GiB (its count includes +the embedded drafter block) with 723 MiB free at the end. + +**These cross-route numbers carry real caveats:** + +1. **Different verification sampling by default.** This branch applies model-card sampling to Qwen4 MTP + requests that name no sampling; upstream keeps such requests greedy (#3354). Unless the harness pins + sampling explicitly, acceptance and decode on the two routes are measured under different verification + regimes. Prefill is unaffected by sampling. +2. **Different generation lengths** (128 vs 256 tokens) and different sessions; fixed costs amortize + differently. +3. **One card, one quantization, one request at a time.** Nothing here generalizes to other hardware. +4. **No ablation.** Attributing the prefill gap to the native pack layout and the CPU prefill share + (`--prefill auto`) versus the poly mmap path is static analysis of the two code paths, not a verified + cause. + +The prefill gap at long prompts (~1.5–1.9× at 31K–131K, cold on both sides) is the most robust of these +observations because it does not depend on the sampling regime. The decode and acceptance comparisons are +directional reference points, not a like-for-like verdict. + +## Analysis + +- **The acceptance gap between the routes is mostly window depth, not drafter precision.** At a matched + cap of 2, upstream's embedded Q5_K drafter accepts 82–85% (greedy verification) — in the same range as + this branch's Q8_0 sidecar at `--spec 2` (~82% in its own serve regime; 0.703 teacher-forced greedy in + [QWEN4.md](QWEN4.md#speed)). The 73.5% at the default cap is what the adaptive policy's deeper rounds + produce, and Measurement 1 shows it buys throughput rather than losing quality. This snapshot therefore + does **not** support a claim that the Q5_K embedded drafter is intrinsically worse than the Q8_0 sidecar. +- **Drafter precision trades against VRAM and residency.** The Q8_0 sidecar costs 1,915 MiB of VRAM; the + embedded Q5_K block is a fraction of that (its matrices are Q5_K in the published file). On a 12 GB card + that difference goes to trunk expert residency. On a card where everything fits, the trade is different. +- **This branch now runs the indexer too.** The sidecar's `blk.40.indexer.*` tensors are converted and the draft + layer runs the same block-score / top-k selection as the trunk, so the dense-attention approximation is no longer + this branch's limitation — it is the opt-out (`STRATA_MTP_INDEXER=0`, or a sidecar without the tensors). At a 64K + prompt the indexer decoded **10.8% faster** than the approximation on the same box + ([details](QWEN4.md#the-mtp-drafters-indexer-mtp-qsa)). The matched-cap acceptance above was measured with the + approximation and still stands as that configuration's number. +- **This analysis changed no defaults on either side.** The `--window 2` variant was a diagnostic config on the + upstream checkout; this branch ships `--spec 2` as before. Separate later work settled `--mtp-hnorm` to `stream` + on reference-implementation and same-box A/B evidence ([details](QWEN4.md#two-defaults-measured)); + `--spec-min-p` stays `0.0`. + +## What would verify the remaining questions + +- A cross-route run with the harness pinning sampling and generation length on both stacks, repeated to + bound variance, would turn Measurement 2 into a controlled comparison. +- A prefill-share ablation on the strata route (and the equivalent on poly) would test the static-analysis + attribution of the prefill gap. +- Upstream's in-flight work (#440's PLE reader, BasinKV configurations) should be re-measured when it + lands; the numbers above are a snapshot at `df2c3ff30`, not a moving target. + +## References + +- [QWEN4.md](QWEN4.md) — this branch's adaptation, conversion chain and speed measurements. +- [PR #430](https://github.com/simplexai-labs/PolyStrata/pull/430) — this branch's submission. +- [#440](https://github.com/simplexai-labs/PolyStrata/pull/440) — upstream's PLE O_DIRECT reader (open). +- [Niko1221/Strata#7774](https://github.com/Niko1221/Strata/pull/7774) — the reference implementation this + branch's conversion tools follow. +- Upstream sources at `df2c3ff30`: `engine/src/poly/qwen4.cpp` (embedded MTP, fused tensors, indexer), + `engine/src/poly/engine.cpp` (window default resolution), `terminal/setup.py` (`QWEN4_FAMILIES`), + `terminal/serve/server.py` (`mtp_greedy`, #3354). \ No newline at end of file diff --git a/docs/QWEN4_ENGINE_PATHS.zh-CN.md b/docs/QWEN4_ENGINE_PATHS.zh-CN.md new file mode 100644 index 0000000000..a9f63e250c --- /dev/null +++ b/docs/QWEN4_ENGINE_PATHS.zh-CN.md @@ -0,0 +1,108 @@ +# Qwen4-35B-A3B:strata 与 strata-poly 两条引擎路径及实测 + +[English version](QWEN4_ENGINE_PATHS.md) + +本页比较 Qwen4-35B-A3B(`qwen4exp`)目前存在的两套实现: + +- **本分支**([PR #430](https://github.com/simplexai-labs/PolyStrata/pull/430),`qwen4-35b` @ `52c562ff0`): + 将模型适配到既有的 **strata 引擎路径**——以 `-DSTRATA_GEOMETRY=q4_lite` 构建的 `strata` 二进制、 + 预处理的 trunk 视图与 native pack、外部 Q8_0 MTP 草稿运行时,以及固定的 `--spec 2` 验证窗口。 + 适配本身见 [QWEN4.md](QWEN4.md)。 +- **上游 main**(@ `df2c3ff30`):**strata-poly 引擎**上的原生 Qwen4 实现 + (`engine/src/poly/qwen4.cpp`),直接读取出版的双分片 GGUF,用文件内嵌的 MTP 块做草稿, + 并以自适应策略逐轮选择验证窗口。 + +两个仓库都包含两套引擎家族;差别在于哪一套服务 Qwen4,以及模型如何为其做准备。本页记录路径差异与同机测量快照,**不宣称任何一条路径更优**。上游实现仍在演进(例如 [#440](https://github.com/simplexai-labs/PolyStrata/pull/440) 的 PLE 逐行 O_DIRECT 读取仍 open,BasinKV 稀疏 KV 卸载已落地),其数字可能变化。本文全部测量均在同一台 RTX 3080 Ti 12 GB(sm_86)、46 GB 内存、Linux、CUDA 12.8 上完成,单请求串行,量化为 Unsloth UD-IQ4_XS——两条路径使用同一份出版 GGUF 文件。 + +## 两条路径 + +| 维度 | 本分支(strata 路径) | 上游 main(strata-poly 路径) | +| --- | --- | --- | +| 引擎二进制 | `strata`(`-DSTRATA_GEOMETRY=q4_lite`) | `strata-poly` | +| Qwen4 代码 | `engine/src/program/generate.cpp`、`engine/src/split/`、`engine/src/core/layer.cpp` 适配 | `engine/src/poly/qwen4.cpp` / `.cu`,原生 `qwen4exp` 前向 | +| 模型加载 | 40 层 trunk 视图(`tools/qwen4_split_gguf.py`)→ native pack(`tools/iq_pack.py`),以 `--pack` / `--native` 传入 | 出版双分片 GGUF 直接 mmap(`--model`),无需重打包 | +| 融合投影 | **按量化字节行**拆分为独立张量(不重量化) | 以融合形式原生读取(`attn_qkv_gate`、`ssm_beta_alpha`、`*_down_inject`) | +| PLE n-gram 表 | 出版第二分片单独作为 `--ple-gguf` 传入 | poly 引擎从出版分片读取;[#440](https://github.com/simplexai-labs/PolyStrata/pull/440)(open)将其改为逐行 O_DIRECT 读取 | +| 专家 profile | `tools/make_profile.py --n-layer 40` → `expert-profile.bin` | setup 准备 → `expert-profile.txt` | +| MTP 权重 | 独立 Q8_0 sidecar(`MTP/mtp-Qwen4-35B-A3B-Q8_0.gguf`,1.87 GiB)→ 草稿运行时(`tools/mtp_qwen4_rt.py`),以 `--mtp` 传入;占 1,915 MiB VRAM | 出版 UD 文件内嵌的 `blk.40`:Q5_K 矩阵、F32 norm、BF16 indexer;自动加载,无需开关 | +| MTP attention | indexer/QSA 路径**已实现**——转换 sidecar 的 `blk.40.indexer.*`,块打分 → top-k → 只注意选中单元;`STRATA_MTP_INDEXER=0` 保留稠密近似([详情](QWEN4.md#the-mtp-drafters-indexer-mtp-qsa)) | 保留 indexer/QSA 路径(`blk.40.indexer.*` 按 trunk attention 块方式加载) | +| 验证窗口 | `--spec 2` 固定上限;`--spec-min-p` 保持 `0.0`;可用 suffix drafter | 不传 `--window` 时引擎为该模型解析出默认上限 **8**(GDN 循环状态;`snaps_spread()` 为 true,因为 `full_snaps_` 只在 DFlash2 路径置位);自适应 `DraftPolicy` 随后逐轮选择窗口大小 | +| KV / 内存 | `--kv-grow`:仅为实际到达的 cell 分配 KV | `--conversation-cache-mib auto`(8 GiB,本测试最多 4 个驻留会话);BasinKV 卸载可用,但被测配置未启用 | +| MTP 默认采样 | Qwen4(`pre="qwen4"`)请求未显式指定采样时使用**模型卡**采样(本分支的改动) | #3354 规则:MTP 请求未显式指定采样时保持 **greedy**(`serve/server.py`,`mtp_greedy`) | +| 模型别名 | runner 将 `aliases` 写入运行配置 | serve 支持 `aliases`(#297);qwen4 setup 不写别名 | + +共享部分:出版 GGUF 文件、服务接口(OpenAI 与 Anthropic API),以及逐字节一致的 `engine/include/strata/spec/draft_policy.hpp`——自适应草稿策略及其成本学习器。两条路径的差别在于给该策略的上限、以及喂给它的草稿模型,而非策略代码本身。 + +## 测量 1:窗口上限(上游内部,受控实验) + +同一上游栈、同一 harness sweep(7 个请求,各生成 256 tokens,prompt 为 1,017 / 1,023 / 1,023 / 31,718 / 32,765 / 65,499 / 130,652 tokens,全部冷读),分别以默认窗口和添加 `--window 2` 的变体配置运行。限窗变体记录了两遍。接受率按草稿 token 计,来自 serve 日志的 `drafts accepted X of Y` 行。 + +| 运行 | 接受率 | 平均 decode | 每轮提交 token 数 | 每 256 token 的验证轮数 | +| --- | ---: | ---: | ---: | ---: | +| 默认(自适应,上限 8) | 942/1281 = **73.5%** | **154.4 tok/s** | ~2.11 | ~121 | +| `--window 2` 第一遍 | 785/955 = **82.2%** | **152.4 tok/s** | ~1.78 | ~144 | +| `--window 2` 第二遍 | 786/923 = **85.2%** | **148.2 tok/s** | ~1.78 | ~144 | + +逐请求 decode(tok/s): + +| Prompt tokens | 默认 | w2 第一遍 | w2 第二遍 | +| ---: | ---: | ---: | ---: | +| 1,017 | 148.1 | 146.8 | 124.6 * | +| 1,023 | 170.1 | 167.1 | 170.6 | +| 1,023 | 172.0 | 173.9 | 162.3 | +| 31,718 | 159.7 | 150.4 | 154.6 | +| 32,765 | 165.4 | 160.9 | 161.1 | +| 65,499 | 150.6 | 146.5 | 144.6 | +| 130,652 | 114.9 | 121.4 | 119.6 | + +\* 第二遍 1,017-token 请求的 prefill 也比平常慢 14 倍(6,326 ms @ 160.8 tok/s,其余各遍约 450 ms @ 约 2,250 tok/s)。这指向该请求期间的机器级争用,而非窗口设置;该点保留在表中并标注,不静默剔除。 + +这说明: + +- **把窗口上限压到 2,接受率从 ~73.5% 升至 ~82–85%。** 上限把更深、置信度更低的草稿从分母中去掉了;两遍运行的草稿模型是同一个 Q5_K 内嵌块。 +- **限窗没有改善 decode——平均反而下降 ~1–4%。** 自适应策略每验证轮提交 ~2.11 个 token,限窗后 ~1.78:轮数多 ~18%,每轮便宜 ~16%(在 1,017-token 请求上为 14.2 ms vs 11.9 ms 每轮)。两个效应几乎抵消,净小幅亏损。 +- **在 130,652 tokens 上限窗反而快 ~6%**(114.9 → 121.4/119.6 tok/s):在超长 KV 上验证深窗口的成本更高,浅窗口在那里获胜。 +- 接受率与 decode 吞吐是不同的目标。共享的自适应策略优化的是学习到的每轮成本(tokens/s),而非接受率;更宽上限下更低的接受率,是策略把草稿 token 花在仍然划算的地方。 + +## 测量 2:跨路径(观察性,非受控 A/B) + +本分支自己的 serve 日志,同机、同一份 UD-IQ4_XS 文件、同一 harness 的 prompt 尺寸(那边生成 128 tokens,上面是 256),两边均冷读: + +| Prompt tokens | 本分支 prefill | 上游 prefill | +| ---: | ---: | ---: | +| 1,017 | 2,262–2,329 tok/s | 2,181–2,290 tok/s | +| 31,718 | 3,884–3,905 tok/s | 2,357–2,385 tok/s | +| 65,499 | 3,704–3,731 tok/s | 2,094–2,169 tok/s | +| 130,652 | 3,466–3,516 tok/s | 1,819–1,887 tok/s | + +Decode:本分支在这些请求上测得 147.4–178.9 tok/s(逐请求接受率 69.9–92.4%);上游默认窗口 sweep 测得 114.9–172.0 tok/s。在出货的 131,072 上下文下的专家驻留:本分支将 10,240 个 trunk 专家中的 3,305 个保持在 VRAM,另加 1,915 MiB 草稿(见 [QWEN4.md](QWEN4.md));上游日志报告 10,496 个路由专家中的 4,796 个驻留在 7.6 GiB(其计数包含内嵌草稿块),结束时剩余 723 MiB 空闲。 + +**这些跨路径数字带有真实的 caveat:** + +1. **默认验证采样不同。** 本分支对未显式指定采样的 Qwen4 MTP 请求应用模型卡采样;上游让此类请求保持 greedy(#3354)。除非 harness 显式钉住采样,两条路径的接受率与 decode 是在不同验证制度下测得的。prefill 不受采样影响。 +2. **生成长度不同**(128 vs 256 tokens)、会话不同;固定成本的摊销方式不同。 +3. **单卡、单量化档、单请求串行。** 本文任何结论都不能外推到其他硬件。 +4. **没有消融实验。** 把 prefill 差距归因于 native pack 布局与 CPU prefill 分担(`--prefill auto`)对比 poly mmap 路径,是对两条代码路径的静态分析,不是已验证的原因。 + +长 prompt 下的 prefill 差距(31K–131K 约 1.5–1.9 倍,两边均冷读)是这些观察中最稳健的,因为它不依赖采样制度。decode 与接受率的比较只是方向性参考点,不是同等条件下的裁决。 + +## 分析 + +- **两条路径的接受率差距主因是窗口深度,而非草稿精度。** 在上限同为 2 时,上游内嵌 Q5_K 草稿接受率 82–85%(greedy 验证)——与本分支 Q8_0 sidecar 在 `--spec 2` 下的区间相同(其自身 serve 制度下 ~82%;[QWEN4.md](QWEN4.md#speed) 中 teacher-forced greedy 为 0.703)。默认上限下的 73.5% 是自适应策略更深轮次的产物,测量 1 表明它换来的是吞吐而非质量损失。因此本快照**不**支持"Q5_K 内嵌草稿本质上差于 Q8_0 sidecar"的说法。 +- **草稿精度与 VRAM 及驻留之间存在权衡。** Q8_0 sidecar 占 1,915 MiB VRAM;内嵌 Q5_K 块只占其一小部分(出版文件中其矩阵为 Q5_K)。在 12 GB 卡上,这个差额转化为 trunk 专家驻留。在一切都放得下的卡上,权衡不同。 +- **本分支现在也跑 indexer。** sidecar 的 `blk.40.indexer.*` 张量已转换,草稿层跑与 trunk 相同的块打分 / top-k 选择,因此 dense-attention 近似不再是本分支的限制,而是可选项(`STRATA_MTP_INDEXER=0`,或 sidecar 本身没有这些张量)。在同一台机器的 64K 提示下,indexer 写回答比近似**快 10.8%**([详情](QWEN4.md#the-mtp-drafters-indexer-mtp-qsa))。上面同上限的接受率是在近似路径下测的,仍作为该配置的数字成立。 +- **本分析没有改变任何一边的默认值。** `--window 2` 变体是上游检出上的诊断配置;本分支照旧出货 `--spec 2`。后续另一项工作依据参考实现与同机 A/B 证据把 `--mtp-hnorm` 定为 `stream`([详情](QWEN4.md#two-defaults-measured));`--spec-min-p` 仍为 `0.0`。 + +## 剩余问题需要什么来验证 + +- 跨路径运行中由 harness 在两边钉住采样与生成长度,并重复以约束方差,可把测量 2 变成受控比较。 +- 在 strata 路径上做 prefill 分担消融(及 poly 上的等价实验),可检验对 prefill 差距的静态分析归因。 +- 上游进行中的工作(#440 的 PLE 读取器、BasinKV 配置)落地后应重测;上面的数字是 `df2c3ff30` 处的快照,不是移动靶。 + +## 参考 + +- [QWEN4.md](QWEN4.md)——本分支的适配、转换链与速度测量。 +- [PR #430](https://github.com/simplexai-labs/PolyStrata/pull/430)——本分支的提交。 +- [#440](https://github.com/simplexai-labs/PolyStrata/pull/440)——上游 PLE O_DIRECT 读取器(open)。 +- [Niko1221/Strata#7774](https://github.com/Niko1221/Strata/pull/7774)——本分支转换工具所遵循的参考实现。 +- `df2c3ff30` 处的上游源码:`engine/src/poly/qwen4.cpp`(内嵌 MTP、融合张量、indexer)、`engine/src/poly/engine.cpp`(窗口默认解析)、`terminal/setup.py`(`QWEN4_FAMILIES`)、`terminal/serve/server.py`(`mtp_greedy`,#3354)。 \ No newline at end of file diff --git a/docs/media/qwen4-35b-a3b-monitor.png b/docs/media/qwen4-35b-a3b-monitor.png new file mode 100644 index 0000000000..b74ba28b2c Binary files /dev/null and b/docs/media/qwen4-35b-a3b-monitor.png differ diff --git a/docs/models/qwen4.md b/docs/models/qwen4.md new file mode 100644 index 0000000000..a0765ff90e --- /dev/null +++ b/docs/models/qwen4.md @@ -0,0 +1,209 @@ +# Qwen4-35B-A3B + +Back to [README.md](../../README.md) + +**Qwen4-35B-A3B**: a 35B mixture-of-experts model that uses only 3B of its weights per answer. It needs an NVIDIA +card with **12 GB of VRAM or more** and **32 GB of RAM or more**. The speeds on this page were measured on one +RTX 3080 Ti (12 GB). + +## Running it from a fresh clone + +One command from the repository root: + +```sh +git clone -b qwen4-35b https://github.com/skygunner/PolyStrata.git +cd PolyStrata +./qwen4-run.sh +``` + +The script preflights before it touches anything: GPU 0's **free** VRAM (other programs may already hold some), a +bindable serving port, system RAM and free disk space. Any failure is reported before a download or a build starts. +`--check` runs exactly these checks and changes nothing — no directories, no environment, no config. After the +preflight it builds the engine if needed (the CUDA architecture is detected from the card), installs the full +`terminal/requirements.txt`, prepares the four artifacts, writes the run config and starts the server. + +Artifacts are reused only when they are **complete**: the pack's completion marker `native_experts.txt` is written +last, and the drafter runtime carries a size-checked `complete.json` that also states whether the drafter's indexer is +present — a record without that field predates the indexer and is reconverted. A half-written artifact from an +interrupted run is rebuilt, never served. The config is written atomically, and an existing shared-settings file is +merged — your keys are kept, only missing defaults are filled in. + +If the model files are not on disk yet, use `./qwen4-run.sh --download` (about 32 GiB). Once running, the OpenAI-compatible +API is at `http://127.0.0.1:8080/v1` and the monitoring panel at `http://127.0.0.1:8080/`. + +## How this branch adapts the model + +The published GGUF is readable by llama.cpp but not by this engine as shipped. The branch resolves four independent +mismatches, in order: + +1. **The layer count.** The file's `block_count` is 41, but block 41 is the MTP drafter, not a trunk layer. Geometry + reading starts from the compiled shape and inherited `nextn_predict_layers = 1` when the key was absent, then + rejected 41 layers against a 40-entry compress-ratio array. The field is now reset before the key is read, the + array is validated over trunk + drafter, and `n_mtp_layers` no longer takes part in the kernel-shape guard — it + describes the file's layout, not the shapes the kernels execute. +2. **The tokenizer rule.** `qwen4` uses the qwen35 split **with `ignore_merges`**. Without the flag, about 201 + whole-piece tokens (mostly multi-character Chinese words such as 俱乐部) can never be reproduced by the merge path + and Chinese gets chopped up. Adapted the way llama.cpp master reads it, with regression tests. +3. **Four fused tensors, split without re-quantizing.** `attn_qkv_gate`, `ssm_beta_alpha` and the two + `*_down_inject` tensors concatenate several projections along output rows. Every block format here is + self-contained along the input dimension, so the splitter copies **quantized bytes row by row** — no + dequantize/requantize round trip, zero quality loss. The packer refuses an unsplit file. +4. **Speed and long context.** The model's own MTP block becomes a drafter runtime (`--mtp` + `--spec 2`), measured + about 46% faster than without it. The 128K context fits in 12 GB with `--kv-grow` (KV allocated on demand, not + reserved up front), at the cost of about 234 fewer cached experts. + +The serving layer needed no engine change: `terminal/models.json` supplies the registry facts the engine cannot +derive, and the runner writes the run config. The server also speaks Qwen4's own reasoning-effort words and applies +its model-card sampling with MTP (below). Two deliberate non-goals: the `qsa_pattn` fast path now handles the 16:2 +head ratio behind a parity gate (the reference PR's change would read and write out of bounds), but it stays +SM60-gated, so the production build for this geometry does not compile it; and the DFlash2 tap work is not +ported. The reasons: [the technical page](../QWEN4.md#relationship-to-pr-7774). + +> **The run config is not in the repository.** It names paths on one machine and is excluded by `.gitignore`; +> `qwen4-run.sh` generates it. To prepare the files by hand or write your own config, [QWEN4.md](../QWEN4.md) (the +> English technical page) has the four preparation commands and the full config template — replace `/path/to/` with +> your own directories. Starting the server by hand is one command: +> +> ```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 +> ``` +> +> Then talk to the OpenAI-compatible API (`http://127.0.0.1:8080/v1/chat/completions`) or the Anthropic API +> (`/v1/messages`). It binds loopback only and sets no API key; add `api_key` to the config before opening it to +> your LAN. + +## How fast is it? + +> **Measured on:** one NVIDIA RTX 3080 Ti (12 GB), 46 GB RAM, Linux, engine strata 0.1.66, Unsloth UD-IQ4_XS +> (~4-bit). Workload: a 256-token story from a 28-token prompt, one request at a time. + +| Setting | Writes answers | Reads your prompt | +| --- | ---: | ---: | +| **MTP on (recommended)** | **155 tokens/s** | about 200-230 tokens/s | +| MTP off | 106 tokens/s | about 200-230 tokens/s | + +MTP is **about 46% faster**. It is the model's own "drafter layer": it guesses a few tokens, the main model checks +them in one pass, and the correct guesses are kept together. + +**The drafter runs the model's own indexer (MTP QSA).** The conversion tool converts the sidecar's indexer tensors, and +the engine scores every block, takes the top-k and attends to the selected cells, as the main model does. A sidecar +without those tensors, or `STRATA_MTP_INDEXER=0`, keeps the previous dense-attention approximation over the retained +cells. Either way the target model verifies every draft, so accepted tokens are the target's own and the path does not +by itself make answers wrong. At a 64K prompt on the tested box the indexer decoded at **139.0 tokens/s against the +approximation's 125.5** (+10.8%), trading acceptance (0.697 against 0.814) for a cheaper round; its cost stops growing +with the context. The short-prompt acceptance and speed above were measured with the approximation and +`--mtp-hnorm pooled`, and stay as that configuration's numbers. + +`--mtp-hnorm` now defaults to **`stream`**: the reference implementations normalize each hyper-connection stream on its +own, and `pooled` (one RMS over all four) matches none of them. Two runs of each at 32K gave 0.815 / 0.852 acceptance +for `stream` against 0.679 / 0.679 for `pooled`. `--spec-min-p` stays **`0.0`**: its sweep's differences sit inside this +box's run-to-run spread and need repeats per value before the default changes. + +Through the serving API the same workload measured **154.5 tokens/s** (a short Chinese text, 344 tokens, normal +stop). With the context raised to 128K: **163.9 tokens/s** writing (450 tokens, 72% of drafts accepted), a Chinese +"explain the blue sky in three sentences" at **165.5 tokens/s** (360 tokens, normal stop, 2.47 s end to end), and a +long prompt read at **2,899 tokens/s** (24,282 tokens in one go). A highly predictable continuation reaches 98% +acceptance and 347 tokens/s — that is not a representative chat rate. + +**Faster in a real agent session.** One long session through the serving API (117 requests, prompts growing to about +78K tokens, 97% prompt reuse) averaged **192.9 tokens/s decode and 1,906 tokens/s prefill**, with per-request decode +between 126.9 and 256.0 tokens/s and a 73-81% expert VRAM hit rate. One turn wrote 1,955 tokens at 169.1 tokens/s. +The monitor showed 11.4 of 12 GB VRAM, 3,305 cached experts and 39.5 of 47 GB system RAM. It beats the short-prompt +numbers because the cached prefix does most of the prompt work. + +Short answers are slower per token because the fixed costs do not amortize: a 32-token English answer at about +80 tokens/s and a 64-token Chinese one at about 94 tokens/s (without MTP). + +**A card with more VRAM is faster.** 12 GB cannot hold every expert; about two thirds are read from RAM while +answering, so the speed depends on RAM and PCIe bandwidth. A community run on an RTX 3090 (24 GB, 62 GB RAM), same +UD-IQ4_XS file and MTP `--spec 2`, measured about 180 tokens/s +([#7780](https://github.com/Niko1221/Strata/issues/7780)). + +## What you need + +| | | +| --- | --- | +| **Graphics card** | NVIDIA GeForce RTX 20, 30, 40 or 50 series, **12 GB of VRAM or more**. This page's numbers come from an RTX 3080 Ti. | +| **RAM** | **32 GB or more**; the tested box has 46 GB. With less, experts are re-read from disk and it shows. | +| **Disk** | About **55 GB** free while preparing the files (30 GB originals + 19 GB trunk view + 2 GB drafter + 3 GB pack). Use an SSD if you can. | +| **System** | Linux, with a current NVIDIA driver. The one-command runner is a bash script; Windows was not measured here. | + +**Memory pressure distorts the measurement.** With many memory-hungry programs open, expert weights can be pushed +into swap and the answer rate drops to a fraction of normal. That is not the model or the card. The technical page +shows how to spot it at a glance ([the validity gate](../QWEN4.md#the-validity-gate-watch-the-cpu-pools-bandwidth)). + +## Chinese support + +The tokenizer treats Chinese specially: a word like 俱乐部 stays one whole token instead of being chopped into +pieces. The engine follows the model authors' reading (`ignore_merges`), so Chinese prompts are understood correctly. + +Measured: asked in Chinese "What is the capital of France? Answer with one word", the model thought, then answered +**巴黎** (Paris). Correct. + +## Reasoning effort and sampling + +**Reasoning effort uses Qwen4's own words:** `xhigh`, `high`, `low`, `off`, default `high` — the template itself +has no `medium`, so a client's `medium` maps to `high` instead of erroring; `max`/`maximum` mean `xhigh`, and +`none`/`minimal`/`disabled`/`false` mean `off`. Anthropic's `thinking.budget_tokens` maps to the official levels: +below 2048 → `low`, 2048-8191 → `high`, 8192 and above → `xhigh`. The dialect is selected from the tokenizer's +`pre="qwen4"`, not from the GGUF architecture name — Qwen3.8-Flash-Next shares `qwen4exp` and keeps the generic +Qwen words. + +**With MTP on, the defaults follow the model card.** Other models stay greedy when an MTP request names no +sampling; Qwen4 is the exception and uses the official recommendations: thinking `temperature 1.0, top_p 0.95, +top_k 20`; non-thinking `temperature 0.7, top_p 0.80, top_k 20, presence_penalty 1.5`. Sampling you set explicitly +in the request, in shared settings or in the config's sampling block still wins, and an explicit `temperature: 0` +is still greedy. + +**`preserve_thinking` is two different things.** Qwen4's chat template preserves reasoning that the *client* +already sends back in the history. Separately, the server can remember this session's reasoning and restore it when +the client returns only the answer text — that is the opt-in `preserve_thinking` run-config key, and **the runner +does not enable it**. The template's default behaviour is not server-side memory. + +## Known limits + +- **This is a think-first model; give it a budget.** The answer arrives in `content`, the reasoning in + `reasoning_content`. Asked for "exactly 200 words", it may count words inside the think block and spend the whole + budget there, ending with `length` instead of `stop` and an empty answer. That is not a fault. **The config sets a + 512-token thinking budget**: at the cap it wraps the thinking up politely and then answers — the same prompt then + wrote a 969-character story. For tasks that need longer deliberation, pass a larger `reasoning_budget_tokens` per + request (`0` means unlimited). +- **Under memory pressure, the first long answer after a start is slow.** The engine holds about 20 GB of expert + weights in RAM. With a browser and other programs open, the first long answer can run at a fraction of the normal + rate and then recover: the same request measured 24.7 tokens/s cold and 143.9 tokens/s warm. Close some programs, + or judge the speed after the first answer. +- **The CLI does not stop at the end of the turn.** With `--max-new` it keeps generating past the end markers. That + is the benchmark harness, not the model; **the serving API stops correctly** (measured). Judge correctness on the + text before the first end marker. +- **No pictures yet.** The model directory ships a vision encoder (`mmproj-F16.gguf`); this adaptation is text-only. +- **The drafter's indexer is implemented; one snapshot corner stays approximate** (above): a borrowed prefix ends + inside an indexer block, so at most three cells of that one pooled key are rebuilt from the resumed position. +- **One request at a time was measured.** There is no concurrency data. +- **The context is 128K (131072 tokens).** A 12 GB card cannot reserve that much KV up front, so the config uses + `--kv-grow`: KV occupies only the cells a request reaches, the rest of VRAM stays with the expert cache, and slots + are handed back as the context grows. The cost is about 234 fewer cached experts (3,539 → 3,305), not answer + quality. The mode needs a single GPU and an expert profile; this config has both. To save more VRAM you can change + the KV precision (`--kv int8` and friends) or stream KV from RAM (`--kv-resident`); neither is used here. + +## How does it work? + +The technical details, the full preparation commands, the measurement method, and the three deliberate differences +from the reference implementation: [QWEN4.md](../QWEN4.md). + +## Not done yet (TODO) + +- **Setup menu integration.** Preparing the files still means the four commands (or `qwen4-run.sh`); it is not an + installer option yet. The entry must know that the 40-layer trunk view comes first — a normal family entry would + offer the published shard 1 and fail — plus RAM and disk guidance. Serving was done first deliberately. +- **The QSA fast path at 16:2 in production.** The G=8 reduction tree and `px_head` permutation are done and + parity-gated; the kernel is still SM60-gated, so enabling it for sm_86 prefill is its own measurement. +- **`--spec-min-p`.** Still `0.0`: the sweep's differences sit inside this box's run-to-run spread and need repeats + per value. `--mtp-hnorm` is settled and now defaults to `stream`. +- **An IQ4_NL drafter.** Not implemented: this conversion chain requires Q8_0, and neither an IQ4_NL sidecar nor the + Qwen4 MTP HF weights exist on the tested box. `--mtp-q4` (Q4_0 copies) is a different thing and costs VRAM here + (+566 MiB for 11 projections). +- **Vision is not wired.** The model directory ships `mmproj-F16.gguf`; this adaptation is text-only. +- **Concurrency and other cards are unmeasured.** Every number here is one request at a time on one RTX 3080 Ti; + multi-slot batching, AMD/Intel paths and bigger cards need their own measurements before any claim. \ 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..436a541454 --- /dev/null +++ b/docs/models/qwen4.zh-CN.md @@ -0,0 +1,172 @@ +# 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)上实测的。 + +## 朋友拿到分支后怎么跑 + +克隆分支后,在仓库根目录执行一条命令即可: + +```sh +git clone -b qwen4-35b https://github.com/skygunner/PolyStrata.git +cd PolyStrata +./qwen4-run.sh +``` + +脚本会先做预检再动手:检查显卡 0 的**空闲**显存(别的程序可能正占着)、服务端口是否可绑定、内存和磁盘空间, +任何一项不过都在下载/编译之前报错。`--check` 只跑这些检查,不创建任何目录、环境或配置。 +预检通过后按需编译引擎(自动识别显卡架构),安装完整的 `terminal/requirements.txt` 依赖,依次准备四个产物, +生成运行配置并启动服务。产物只有**完整**才会被复用:打包以最后写入的 `native_experts.txt` 为完成标记, +草稿运行时以校验过尺寸的 `complete.json` 为准,该记录还写明是否携带草稿层 indexer——缺这个字段的记录早于 indexer, +会被重转;上次中断留下的半成品会被重建,不会被当成完成品。 +配置文件原子写入;已有的 shared settings 只补缺省值,不覆盖你自己设过的键。 +模型文件还没下载的话用 `./qwen4-run.sh --download`(约 32 GiB);只想检查机器是否满足条件用 `./qwen4-run.sh --check`。 +启动后在 `http://127.0.0.1:8080/v1` 提供 OpenAI 兼容接口,浏览器打开 `http://127.0.0.1:8080/` 可看监控面板。 + +## 这个分支是怎么适配的 + +原始 GGUF 能被 llama.cpp 读取,但不能直接被本引擎加载。分支按顺序解决了四个互不依赖的问题: + +1. **层数对不上。** 文件的 `block_count` 是 41,但第 41 层是 MTP 草稿层,不属于主干。几何读取从编译形状出发,会把缺失的 + `nextn_predict_layers` 继承成 1,于是按 41 层去校验只有 40 项的压缩比数组而拒绝。现在读键前先归零,并让该数组覆盖 + 「主干 + 草稿层」;同时把 `n_mtp_layers` 从内核形状守卫中移除——它是文件布局,不是内核执行的形状。 +2. **分词器规则不同。** `qwen4` 沿用 qwen35 的切分规则,但要开 `ignore_merges`。不开的话,约 201 个整词 token + (多为多字中文词,如「俱乐部」)永远无法被合并路径复现,中文会被切碎。已按 llama.cpp master 的读法适配并加了回归测试。 +3. **四个融合张量要拆开,而且不能重量化。** `attn_qkv_gate`、`ssm_beta_alpha` 和两处 `*_down_inject` 是把多个投影沿输出维度 + 拼起来的。这些量化格式沿输入维度自包含,所以拆分器**按量化字节逐行切分**,不反量化、不重量化,质量零损失。 + 打包工具会拒绝未拆分的文件,防止误用。 +4. **速度与长上下文。** 模型自带的 MTP 层被转成草稿运行时(`--mtp` + `--spec 2`),实测比不开快约 46%; + 128K 上下文靠 `--kv-grow`(KV 按需分配,不一次性预留)塞进 12 GB 显存,代价只是少缓存约 234 个专家。 + +服务层不需要改引擎:`terminal/models.json` 补齐引擎推导不出的注册信息,运行配置由脚本生成。 +服务端还说 Qwen4 自己的思考力度词表,并在开着 MTP 时按模型卡采样(见下文「思考力度与采样」)。 +有意没做的两件事:`qsa_pattn` 快速路径现在在 parity 门禁之后支持 16:2 头比例(沿用参考 PR 的改法会越界读写), +但仍受 SM60 守卫,本几何的生产构建不编译它;以及不移植 DFlash2 tap。 +原因见[技术页](../QWEN4.zh-CN.md#relationship-to-pr-7774)。 + +> **运行配置不在仓库里。** 它记录的是某一台机器上的路径,已被 `.gitignore` 排除;`qwen4-run.sh` 会自动生成。 +> 想手动准备文件或自己写配置的话,[QWEN4.zh-CN.md](../QWEN4.zh-CN.md)(中文技术页,[英文版](../QWEN4.md))给出了四条准备命令和完整配置模板, +> 把其中 `/path/to/` 换成你自己的目录即可。手动启动服务是一条命令: +> +> ```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 是模型自带的一个「草稿层」:它先猜几个词,主模型一次核对,猜对就一起收下。 + +**草稿层现在跑模型自己的 indexer(MTP QSA)。** 转换工具会转换 sidecar 的 indexer 张量,引擎像主模型那样给每个块 +打分、取 top-k、只注意被选中的单元。如果 sidecar 没有这些张量,或设置 `STRATA_MTP_INDEXER=0`,就退回原先对保留 +单元的「稠密注意力近似」。两种情况下主模型都会逐个校验草稿,被接受的 token 来自主模型自己,所以这条路径本身不会 +让答案变错。在实测机器的 64K 提示下,indexer 写回答 **139.0 tokens/s,稠密近似为 125.5**(快 10.8%):它用猜中率 +(0.697 对 0.814)换更便宜的一轮,而且开销不再随上下文增长。上面短提示的猜中率和速度是在稠密近似加 +`--mtp-hnorm pooled` 下测的,保留为该配置的数字。 + +`--mtp-hnorm` 默认值改为 **`stream`**:参考实现都是对每个 hyper-connection 流单独做归一化,而 `pooled`(四个流合起来 +做一个 RMS)与它们都不符。32K 下各跑两次,`stream` 猜中率 0.815 / 0.852,`pooled` 为 0.679 / 0.679。`--spec-min-p` +仍保持 **`0.0`**:扫描得到的差异落在本机重复运行的波动范围内,需要每个取值多次重复后才考虑改默认值。 + +通过服务接口对话时实测同样是 **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——那不是日常聊天的代表性数字。 + +**真实 agent 会话里更快。** 一次通过服务接口的长会话(117 次请求,提示逐渐增长到约 78K token,提示复用率 97%) +平均**写回答 192.9 tokens/s、读提示 1906 tokens/s**,单次回答速度在 126.9 到 256.0 tokens/s 之间,专家显存命中率 73-81%。 +其中一次回答写了 1955 token、169.1 tokens/s。监控面板同时显示显存 11.4/12 GB、缓存 3305 个专家、系统内存 39.5/47 GB。 +比上面短提示的数字快,是因为大部分提示直接命中了缓存。 + +短回答会慢一些,因为固定的启动开销摊不开: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,以及最新的 NVIDIA 显卡驱动。一键脚本是 bash 脚本;Windows 本次没有实测。 | + +**内存压力会让测速失真。** 如果电脑同时开着很多占内存的程序,专家权重可能被挤到交换区,回答速度会掉到正常值的几分之一。 +这不是模型或显卡的问题。技术页里说明了怎么一眼看出这种情况([有效性判据](../QWEN4.zh-CN.md#the-validity-gate-watch-the-cpu-pools-bandwidth))。 + +## 中文支持 + +这个模型的分词器对中文做了专门处理:像「俱乐部」这样的词会作为一个整词识别,而不是拆成几个碎片。 +引擎已经按模型作者的方式适配(`ignore_merges`),中文提示能被正确理解。 + +实测:用中文问「法国的首都是哪里?只回答一个词」,模型思考后回答**巴黎**,正确。 + +## 思考力度与采样 + +**思考力度(reasoning effort)用 Qwen4 自己的词:**`xhigh`、`high`、`low`、`off`,默认 `high`;模板本身**没有 `medium`**, +客户端传 `medium` 会映射为 `high` 而不是报错;`max`/`maximum` 等价于 `xhigh`,`none`/`minimal` 等等价于 `off`。 +Anthropic 接口的 `thinking.budget_tokens` 按官方档位映射:小于 2048 → `low`,2048–8191 → `high`,8192 及以上 → `xhigh`。 +这套词由分词器的 `pre="qwen4"` 识别,不看 GGUF 架构名——Qwen3.8-Flash-Next 与本模型共用 `qwen4exp`,仍用原来的通用词表。 + +**开着 MTP 时,默认采样按模型卡来。** 其它模型开 MTP 后不指定采样就保持 greedy;Qwen4 例外,默认用官方推荐: +思考模式 `temperature 1.0、top_p 0.95、top_k 20`;非思考模式 `temperature 0.7、top_p 0.80、top_k 20、presence_penalty 1.5`。 +你在请求里显式传的采样参数、shared settings 和配置里的采样块仍然优先;显式传 `temperature: 0` 仍是 greedy。 + +**`preserve_thinking` 要分清两件事。** Qwen4 的聊天模板会保留**客户端自己回传**的历史思考;而「服务端记住本轮 +思考、客户端下轮只回传正文时自动恢复」是运行配置里可选的 `preserve_thinking` 开关,**脚本没有开启它**。 +模板的默认行为不等于服务端记忆已打开。 + +## 已知限制 + +- **这是「先思考再回答」的模型,字数预算要给够。** 回答正文在 `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`),但本次适配没有接入,只做了文字。 +- **草稿层的 indexer 已实现,只剩快照的一处有界近似**(见上文):借用前缀可能落在某个 indexer 块中间,该块最多 + 3 个单元的池化键会从续写位置重建。 +- **一次只测了一个请求。** 多请求并发的表现没有实测数据。 +- **上下文开到 128K(131072 token)。** 12 GB 显存不可能一开始就为这么长的上下文预留空间,所以用了「按需增长」 + (`--kv-grow`):只给实际用到的部分分配显存,其余留给加速缓存,上下文变长时再逐步让出。代价是缓存里少放约 234 个 + 专家(3539 → 3305),回答质量不受影响。这个模式要求单显卡并且带专家画像文件,本配置都满足。 + 想再省显存还可以换 KV 精度(`--kv int8` 等)或把 KV 放到内存(`--kv-resident`),本次没有启用。 + +## 它是怎么工作的? + +技术细节、完整的准备命令、实测方法,以及和参考实现的三处有意差异:[QWEN4.zh-CN.md](../QWEN4.zh-CN.md)([英文版](../QWEN4.md))。 + +## 还没做的事(TODO) + +- **setup 安装菜单集成。** 目前文件准备仍需手动跑四条命令(或用 `qwen4-run.sh`),未进安装程序菜单。 + 菜单项必须知道「先拆分出 40 层主干视图」,否则会把原始 shard 1 直接给用户而加载失败,另外还要给出内存与硬盘提示。 + 之前先做了 serve,这是独立的一块工作。 +- **16:2 下 QSA 快速路径进生产。** G=8 的归约树与 `px_head` 排列已完成并通过 parity 校验;kernel 仍受 SM60 开关 + 限制,要在 sm_86 prefill 上启用需要单独实测。 +- **`--spec-min-p`。** 仍为 `0.0`:扫描差异落在本机重复运行的波动范围内,需要每个取值多次重复。`--mtp-hnorm` 已定, + 默认改为 `stream`。 +- **IQ4_NL 草稿层。** 未实现:本转换链要求 Q8_0,实测机器上也没有 IQ4_NL sidecar 或 Qwen4 MTP 的 HF 原始权重。 + `--mtp-q4`(Q4_0 副本)是另一回事,在本机反而多占显存(11 个投影 +566 MiB)。 +- **图片能力未接入。** 模型目录里有 `mmproj-F16.gguf`,本次只做文字。 +- **并发和其他显卡没有实测。** 本页所有数字都是单请求、单张 RTX 3080 Ti;多并发、AMD/Intel、显存更大的卡需要另行实测后才能下结论。 \ No newline at end of file diff --git a/engine/cmake/strata_gpu_engine.cmake b/engine/cmake/strata_gpu_engine.cmake index 8415f94cb4..531c0cf827 100644 --- a/engine/cmake/strata_gpu_engine.cmake +++ b/engine/cmake/strata_gpu_engine.cmake @@ -440,6 +440,13 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(expert_cache_slot_guard_test PRIVATE strata_engine) add_test(NAME expert_cache_slot_guard_test COMMAND expert_cache_slot_guard_test) set_tests_properties(expert_cache_slot_guard_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + # the MTP draft layer's step record: with the indexer its width is the selection's, so qsa_block_topk + # cannot take the "select everything" branch and write n_kv ids into a cap-sized buffer (needs a device + # for the guarded selection; the arithmetic part runs without) + add_executable(mtp_step_test tests/core/mtp_step_test.cpp) + target_link_libraries(mtp_step_test PRIVATE strata_engine) + add_test(NAME mtp_step_test COMMAND mtp_step_test) + set_tests_properties(mtp_step_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) endif() if(STRATA_BUILD_CONVERSATION_TESTS) add_executable(conversation_snapshot_test src/core/conversation_snapshot_test.cpp) 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/include/strata/core/layer.hpp b/engine/include/strata/core/layer.hpp index faee28a80a..e72d2fb8a8 100644 --- a/engine/include/strata/core/layer.hpp +++ b/engine/include/strata/core/layer.hpp @@ -255,6 +255,10 @@ struct QsaState { float* idx_pooled_allocation = nullptr; size_t idx_pooled_allocation_bytes = 0; int32_t* idx_block_pos = nullptr; + /// The drafter's indexer (MTP QSA): its tail/dead/pooled/block_pos are one contiguous arena block and a + /// conversation snapshot carries the whole block in its pooled part. A trunk layer leaves this false - its + /// tail/dead/block_pos ride in the turn checkpoint and only the pooled rows are in the K/V image. + bool idx_block_snapshot = false; float* cos_tab = nullptr; ///< (max_cells, n_rot/2), built on the HOST in float64 bool owns_rope = false; ///< built the table above (not borrowed with share_rope): it releases it diff --git a/engine/include/strata/core/mtp.hpp b/engine/include/strata/core/mtp.hpp index 0a6b0aaa59..fa624d1d84 100644 --- a/engine/include/strata/core/mtp.hpp +++ b/engine/include/strata/core/mtp.hpp @@ -65,13 +65,17 @@ class MtpDrafter { } /// At most this many drafts per round (below max_t - 1): a window longer than the MTP's comes from elsewhere. void set_max_drafts(int k) { max_drafts_ = k; } - /// --mtp-hnorm stream (opt-in; before the first draft or prefill): pre_fc_norm_hidden normalizes each - /// hyper-connection stream on its own, as llama.cpp's qwen4exp MTP graph does, instead of one RMS over all four. + /// --mtp-hnorm (default stream; before the first draft or prefill): pre_fc_norm_hidden normalizes each + /// hyper-connection stream on its own, as llama.cpp's qwen4exp MTP graph and upstream's q4_mtp_eh_concat_kernel + /// do (each stream's own 2048-wide RMS, scaled by its slice of the 8192-wide weight). pooled is one RMS over + /// all four and does not match the reference; it stays available as the opt-out. void set_hnorm_per_stream(bool on) { hnorm_stream_ = on; } bool hnorm_per_stream() const { return hnorm_stream_; } /// --mtp-q4 (opt-in; before load): the draft layer's Q8_0 projections and its draft head run from 4-bit (Q4_0) /// copies made at load/bind - fewer bytes per draft step; drafts only, the verify window decides every token. - /// (The prompt path's batched K/V pass keeps the Q8_0 originals.) head/all need the draft head's subset; + /// (The prompt path's batched K/V pass keeps the Q8_0 originals.) The copies are ADDITIVE: the Q8_0 originals + /// stay for that pass, so on a 12 GB card this costs VRAM (measured +566 MiB for 11 projections) and displaces + /// resident experts rather than saving room. head/all need the draft head's subset; /// bind() says so when there is none, instead of silently drafting over the full head. void set_q4(bool proj, bool head) { q4_ = proj; q4_head_ = head; } /// --mtp-draft-vocab FILE (opt-in; before bind): the draft head's token subset from FILE instead of @@ -245,6 +249,14 @@ class MtpDrafter { } /// The cells the draft layer attends to (0 = every cell), as load() settled it. int64_t window() const { return window_; } + /// MTP QSA: the sidecar's indexer is loaded and its selection replaces the dense window. + bool indexer_enabled() const { return indexer_; } + /// The drafter's per-row step record (pos, n_kv, n_bid, width), as the host upload fills it. + /// With the indexer the selection returns `qsa_selection_width(n_kv)` cells, so the width must be + /// the selection's own: `qsa_block_topk` takes `n_kv <= width` as "select everything" and writes + /// n_kv ids, which overruns the cap-sized ids buffer once the context passes the selection width. + /// The dense/window path keeps n_kv here and `window_ids` overwrites it with the window's count. + static void fill_step(int32_t* out, int64_t cell, const strata::kernels::QsaShapes& s, bool indexer); /// KVA: call before load(). The draft layer's attention then reads its cell range through a floor, which stays 0 /// (the plain window, cell for cell) until set_cell_floor() raises it. Off (the default): the code is 0.2.6's. void enable_cell_floor(bool on) { floor_on_ = on; } @@ -418,6 +430,19 @@ class MtpDrafter { float* dummy_inj_ = nullptr; int64_t cap_ = 0, attn_scratch_floats_ = 0; + // MTP QSA: the sidecar's own indexer (blk.40.indexer.*) replaces the dense window approximation. With it the + // drafter's K/V is planned like a trunk layer's (no ring, a full indexer pool) and its attention reads the + // blocks the indexer selects instead of the last `window` cells. STRATA_MTP_INDEXER=0 keeps the approximation. + bool indexer_ = false; + const uint16_t* w_idxq_ = nullptr; ///< indexer.q_proj.weight, BF16 + const uint16_t* w_idxk_ = nullptr; ///< indexer.k_proj.weight, BF16 + const float* w_iqn_ = nullptr; ///< indexer.q_norm.weight, F32 + const float* w_ikn_ = nullptr; ///< indexer.k_norm.weight, F32 + float* idx_raw_ = nullptr; ///< (T, idx_key_dim) the raw indexer key, before its norm and pooling + float* q_idx_ = nullptr; ///< (T, idx_q_heads * idx_key_dim) + float* cell_scores_ = nullptr; ///< (T, max_cells) block scores, sized as the trunk's QsaBuffers + int64_t max_blocks_ = 0; + // STRATA_BATCH_MTP_FUSED=1: lazily allocated only on first draft_slots() call (0 B when off) bool bm_ready_ = false; int bm_max_t_ = 0; diff --git a/engine/include/strata/kernels/qsa_pattn.hpp b/engine/include/strata/kernels/qsa_pattn.hpp index 3fd8de0ba8..9b9b68f11c 100644 --- a/engine/include/strata/kernels/qsa_pattn.hpp +++ b/engine/include/strata/kernels/qsa_pattn.hpp @@ -9,11 +9,13 @@ // warp_sum pairs), the ascending fmaf value fold, the merge's chunk order (fmaxf, __expf(m - M), fmaf(l, w, L), // fmaf(acc, w, acc), acc / L) - and change only where operands live and which thread does what: // - ps_score_x_kernel, one CTA per (chunk, KV head, query): q in registers (loaded once in a per-lane slot order), -// the chunk's K staged with 16-byte loads, two cells at a time through one reduce-scatter whose 24 sums are +// the chunk's K staged with 16-byte loads, two cells at a time through one reduce-scatter whose 2G sums are // warp_sum's tree without reduce12's selects; writes the chunk's probabilities, rows, m and l to the scratch; -// - ps_value_d4_kernel, one CTA per (KV head, query): four dims x 12 heads a thread, V four bytes a load, the chunks +// - ps_value_d4_kernel, one CTA per (KV head, query): four dims x G heads a thread, V four bytes a load, the chunks // in ascending order, each merged into the output as the merge kernel does (no partial accumulators, no merge // kernel). +// G is the geometry's query:KV ratio, n_head / n_head_kv: 12 (24:2, Flash-Next and q4_deep) or 8 (16:2, q4_lite). Any +// other ratio is refused and keeps the usual attention. // The caller's attention scratch holds the blocks of ~100 queries; a prompt chunk runs in batches of that size. // // Off unless STRATA_PATTN_SM60=1, and compiled only in the CUDA build with STRATA_EXPERIMENTAL_SM60 (every other build diff --git a/engine/src/core/conversation_snapshot.cpp b/engine/src/core/conversation_snapshot.cpp index 090623a3cc..e7f77d8b08 100644 --- a/engine/src/core/conversation_snapshot.cpp +++ b/engine/src/core/conversation_snapshot.cpp @@ -37,6 +37,22 @@ bool valid_extent(const QsaState& st, int64_t upto, std::string& error) { return true; } +// The drafter's indexer block: qsa_state_init takes tail, dead, pooled and block_pos in that order and every +// size but the last is a multiple of the cursor's 16, so the four are contiguous. The span is measured, not +// assumed: a state whose buffers came from anywhere else fails closed instead of copying the wrong bytes. +size_t indexer_block_bytes(const QsaState& st, const ModelGeometry& g) { + if (!st.idx_block_snapshot || !st.idx_tail || !st.idx_dead || !st.idx_pooled || !st.idx_block_pos) return 0; + const auto s = strata::kernels::qsa_real_shapes(); + const uint8_t* begin = reinterpret_cast(st.idx_tail); + const uint8_t* end = reinterpret_cast(st.idx_block_pos + 1); + if (end <= begin) return 0; + const size_t want = (size_t) (s.idx_block - 1) * g.idx_key_dim * sizeof(float) + + (size_t) g.idx_key_dim * sizeof(float) + + (size_t) st.idx_pooled_rows * g.idx_key_dim * sizeof(float) + sizeof(int32_t); + const size_t span = (size_t) (end - begin); + return span == want ? span : 0; +} + bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index, Layout& l, std::string& error) { if (!valid_extent(st, upto, error)) return false; if (st.kv_hybrid && (st.kv_mode == 2 || st.kv_q4 || st.kv_int8)) { // a streamed one reads its host copy @@ -55,7 +71,17 @@ bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index : (size_t) g.head_dim * (int8_keys ? 1 : 2); // Include the moving spare row, not only completed blocks. The checkpoint // restore reconstructs that row when rewinding to an earlier prefix. - const int64_t pooled = index && upto > 0 ? upto / s.idx_block + 1 : 0; + int64_t pooled = index && upto > 0 ? upto / s.idx_block + 1 : 0; + // A drafter with an indexer keeps no turn checkpoint: its whole indexer block rides with its K/V, at every + // extent (a borrowed prefix included - the rows past it are never read, selection being bounded by n_kv). + const size_t block = st.idx_block_snapshot ? indexer_block_bytes(st, g) : 0; + if (st.idx_block_snapshot) { + if (!block) { + error = "conversation snapshot: the drafter's indexer block is not contiguous"; + return false; + } + pooled = st.idx_pooled_rows; + } // Format 3 identifies snapshot K8V4 only; never pass it to the block movers. Rotated INT8 K/V (#293, // STRATA_KV_ROT=1) is another format too (+16): its bytes mean nothing to a state that does not rotate, so a // snapshot or prompt checkpoint taken with the rotation never restores into one without it, nor the reverse. @@ -66,10 +92,11 @@ bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index if (!product(l.data, {(uint64_t) cells, (uint64_t) g.n_head_kv, per}) || !product(l.scales, {(uint64_t) cells, (uint64_t) g.n_head_kv, int8_keys && !st.kv_q4 ? (uint64_t) (g.head_dim / 64) * 2 : 0}) || - !product(l.pooled, {(uint64_t) pooled, (uint64_t) g.idx_key_dim, sizeof(float)})) { + (!block && !product(l.pooled, {(uint64_t) pooled, (uint64_t) g.idx_key_dim, sizeof(float)}))) { error = "conversation snapshot: K/V byte count overflow"; return false; } + if (block) l.pooled = block; l.value_data = l.data; l.value_scales = l.scales; if (st.kv_hybrid) { @@ -85,22 +112,25 @@ bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index std::array pools(const QsaState& st, bool resident = false) { const bool host = st.kv_mode != 0 && !resident; + // part 4: the trunk's pooled rows, or the drafter's whole indexer block (its tail is the block's first byte) + void* index = st.idx_block_snapshot ? static_cast(st.idx_tail) : static_cast(st.idx_pooled); if (st.kv_hybrid) return {host ? st.host.k_q : st.k_q, host ? st.host.v_q4 : st.v_q4, host ? st.host.k_scale : st.k_scale, - nullptr, st.idx_pooled}; + nullptr, index}; if (st.kv_q4) - return {host ? st.host.k_q4 : st.k_q4, host ? st.host.v_q4 : st.v_q4, nullptr, nullptr, st.idx_pooled}; + return {host ? st.host.k_q4 : st.k_q4, host ? st.host.v_q4 : st.v_q4, nullptr, nullptr, index}; if (st.kv_int8) return {host ? st.host.k_q : st.k_q, host ? st.host.v_q : st.v_q, - host ? st.host.k_scale : st.k_scale, host ? st.host.v_scale : st.v_scale, st.idx_pooled}; - return {host ? st.host.k_pool : st.k_pool, host ? st.host.v_pool : st.v_pool, nullptr, nullptr, st.idx_pooled}; + host ? st.host.k_scale : st.k_scale, host ? st.host.v_scale : st.v_scale, index}; + return {host ? st.host.k_pool : st.k_pool, host ? st.host.v_pool : st.v_pool, nullptr, nullptr, index}; } bool valid(const QsaState& st, const Layout& l, int64_t upto, std::string& error) { if (upto < 0 || upto > st.max_cells || st.n_pages < 0 || l.cells / l.page_size > st.n_pages || st.kv_mode < 0 || st.kv_mode > 2 || st.n_slots <= 0 || (st.kv_mode == 0 && st.n_slots < st.n_pages) || - l.pooled_rows > st.idx_pooled_rows || (st.kv_mode != 0 && !st.host.present())) { + l.pooled_rows > st.idx_pooled_rows || (st.kv_mode != 0 && !st.host.present()) || + (st.idx_block_snapshot && (!st.idx_tail || !st.idx_dead || !st.idx_pooled || !st.idx_block_pos))) { error = "conversation snapshot: invalid K/V extent or missing authoritative host pool"; return false; } @@ -699,6 +729,23 @@ bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, co return refresh_residency(st, g, upto, error); } +// A borrowed prefix ends inside an indexer block. The completed rows below it are the donor's; the block being +// filled is not, and the raw tail the image carries belonged to the donor's LAST block. Reset it the way a turn +// checkpoint restore does - the spare row takes the constant dead key - and clear the tail. At most idx_block-1 +// cells of that one pooled key are then rebuilt from the resumed position; every row past the prefix is unread, +// selection being bounded by n_kv. The trunk is exact here because a checkpoint at the borrowed length exists. +bool reset_indexer_prefix(const QsaState& st, const ModelGeometry& g, int64_t upto, std::string& error) { + if (!st.idx_block_snapshot) return true; + const auto s = strata::kernels::qsa_real_shapes(); + const size_t tail = (size_t) (s.idx_block - 1) * g.idx_key_dim * sizeof(float); + if (cudaMemset(st.idx_tail, 0, tail) != cudaSuccess) { + error = "conversation snapshot: indexer tail reset failed"; + return false; + } + float* spare = st.idx_pooled + (size_t) (upto / s.idx_block) * g.idx_key_dim; + return transfer(spare, st.idx_dead, (size_t) g.idx_key_dim * sizeof(float), error); +} + bool conversation_kv_restore_prefix(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, int64_t captured, int64_t upto, bool index, std::string& error) { const VramKvSlot* slot = vram_kv_find(image.dev_tag); // (STRATA_PARK_VRAM_MIB, as in conversation_kv_restore) @@ -715,13 +762,16 @@ bool conversation_kv_restore_prefix(const ConversationKv& image, const QsaState& for (size_t i = 0; i < src.size(); ++i) if (sizes[i] > src[i]->size()) { error = "conversation snapshot: prefix beyond the K/V payload"; return false; } const auto dst = pools(st); + auto finish = [&] { + return reset_indexer_prefix(st, g, upto, error) && refresh_residency(st, g, upto, error); + }; // STRATA_PARK_VRAM_MIB: the prefix is the leading bytes of each part in the slot too std::array off{}; if (slot != nullptr && !vram_kv_locate(*slot, image.dev_tag, sizes, off)) { slot = nullptr; conversation_park_join(); } if (slot != nullptr) { for (size_t i = 0; i < src.size(); ++i) if (!transfer(dst[i], static_cast(slot->p) + off[i], sizes[i], error)) return false; - return refresh_residency(st, g, upto, error); + return finish(); } if (park_host_memcpy_on() && st.kv_mode != 0) { std::vector host_spans; @@ -736,13 +786,13 @@ bool conversation_kv_restore_prefix(const ConversationKv& image, const QsaState& if (!src[4]->visit(0, sizes[4], [&](const uint8_t* p, size_t n, size_t at) { return transfer(static_cast(dst[4]) + at, p, n, error); })) return false; - return refresh_residency(st, g, upto, error); + return finish(); } for (size_t i = 0; i < src.size(); ++i) if (!src[i]->visit(0, sizes[i], [&](const uint8_t* p, size_t n, size_t at) { return transfer(static_cast(dst[i]) + at, p, n, error); })) return false; - return refresh_residency(st, g, upto, error); + return finish(); } bool conversation_kv_part_sizes(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index, diff --git a/engine/src/core/conversation_snapshot_test.cpp b/engine/src/core/conversation_snapshot_test.cpp index 0fa6f3373e..c2d09fdda7 100644 --- a/engine/src/core/conversation_snapshot_test.cpp +++ b/engine/src/core/conversation_snapshot_test.cpp @@ -3,6 +3,7 @@ #include "strata/kernels/kv_q4.hpp" #include +#include #include #include #include @@ -579,11 +580,78 @@ void full_session(int fmt, int mode, int experts) { check(spare==a.checkpoints[0].dead,"checkpoint rebuilds spare row over a later completed block"); check(ss.ple_prev[0]==2 && ss.ple_prev[1]==3,"checkpoint PLE token window"); } + +// A drafter that carries an indexer keeps tail/dead/pooled/block_pos contiguous in its arena (qsa_state_init carves +// them in that order, each a multiple of 16 B but the trailing 4 B block_pos, so the span has no internal padding). +// Its K/V is saved with index=false (the draft is not a main layer), so the indexer state must ride part 4 whenever +// the draft has a FULL pool (idx_pooled_rows > 2, versus the ring's two-row spare). Without it a restored session +// drafts from a cold indexer: the selection scores zeroed blocks and the acceptance rate collapses (the trunk still +// verifies every token, so the output stays correct - a performance regression, not a wrong answer). This round-trip +// pins the persistence: save, wipe the device block, restore, and require every byte back. +void draft_indexer_roundtrip() { + for (int fmt : {kKvF16, kKvInt8}) { + Fixture f(fmt, 1, true); // mode 1: streaming, full host copy, full indexer pool + auto& st = f.state; + auto& g = f.g; + const auto s = qsa_real_shapes(); + const size_t tail_b = (size_t)(s.idx_block - 1) * g.idx_key_dim * 4; + const size_t dead_b = (size_t)g.idx_key_dim * 4; + const size_t pool_b = (size_t)st.idx_pooled_rows * g.idx_key_dim * 4; + const size_t block_b = tail_b + dead_b + pool_b + 4; + void* block = nullptr; + cuda_check(cudaMalloc(&block, block_b)); + f.device.push_back(block); // the fixture's separate pooled allocation stays owned but unused + st.idx_tail = static_cast(block); + st.idx_dead = reinterpret_cast(static_cast(block) + tail_b); + st.idx_pooled = reinterpret_cast(static_cast(block) + tail_b + dead_b); + st.idx_block_pos = reinterpret_cast(static_cast(block) + tail_b + dead_b + pool_b); + st.idx_pooled_allocation = st.idx_pooled; + st.idx_pooled_allocation_bytes = pool_b; + st.idx_block_snapshot = true; // the drafter's indexer rides with its K/V, not in a turn checkpoint + f.sources[4] = st.idx_tail; // fill() paints the whole contiguous indexer block + f.sizes[4] = block_b; + const int64_t upto = 64; + std::string err; + f.fill(91); + cuda_check(cudaDeviceSynchronize()); + std::vector want(block_b); + cuda_check(cudaMemcpy(want.data(), block, block_b, cudaMemcpyDeviceToHost)); + ConversationKv image; + check(conversation_kv_save(image, st, g, upto, false, err), "draft indexer: save with index=false"); + cuda_check(cudaMemset(block, 0, block_b)); + check(conversation_kv_restore(image, st, g, upto, false, err), "draft indexer: restore with index=false"); + cuda_check(cudaDeviceSynchronize()); + std::vector got(block_b); + cuda_check(cudaMemcpy(got.data(), block, block_b, cudaMemcpyDeviceToHost)); + check(got == want, "draft indexer: tail/dead/pooled/block_pos survive a save/restore"); + check(image.pooled.size() == block_b, "draft indexer: part 4 carries the whole indexer block"); + // A borrowed prefix ends inside a block: the completed rows below it are the donor's, the block being + // filled takes the constant dead key and the raw tail (the donor's last block) is cleared. + const int64_t prefix = 37; + check(conversation_kv_restore_prefix(image, st, g, upto, prefix, false, err), + "draft indexer: restore a borrowed prefix"); + cuda_check(cudaDeviceSynchronize()); + const size_t row_b = (size_t)g.idx_key_dim * 4; + const size_t kept = (size_t)(prefix / s.idx_block) * row_b; + std::vector head(kept), spare(row_b), tail(tail_b); + cuda_check(cudaMemcpy(head.data(), st.idx_pooled, kept, cudaMemcpyDeviceToHost)); + cuda_check(cudaMemcpy(spare.data(), st.idx_pooled + kept / 4, row_b, cudaMemcpyDeviceToHost)); + cuda_check(cudaMemcpy(tail.data(), st.idx_tail, tail_b, cudaMemcpyDeviceToHost)); + const size_t pool_at = tail_b + dead_b; + check(std::equal(head.begin(), head.end(), want.begin() + pool_at), + "draft indexer: completed pooled rows below the prefix are the donor's"); + check(std::equal(spare.begin(), spare.end(), want.begin() + tail_b), + "draft indexer: the block being filled takes the dead key"); + check(std::all_of(tail.begin(), tail.end(), [](uint8_t b) { return b == 0; }), + "draft indexer: the donor's raw tail is cleared"); + } +} } int main() { int devices=0; if (cudaGetDeviceCount(&devices)!=cudaSuccess || !devices) return 77; + draft_indexer_roundtrip(); for (int fmt : std::array{kKvF16,kKvInt8,kKvQ4,3}) for (int mode : {0,1,2}) { if (fmt==3 && mode!=0) continue; Fixture f(fmt,mode); diff --git a/engine/src/core/mtp.cpp b/engine/src/core/mtp.cpp index a2f3fe1e34..b5fb608e01 100644 --- a/engine/src/core/mtp.cpp +++ b/engine/src/core/mtp.cpp @@ -22,6 +22,8 @@ #include "strata/kernels/native_moe.hpp" #include "strata/kernels/native_mmvq.hpp" #include "strata/kernels/native_qsa.hpp" +#include "strata/kernels/native_qsa_indexer.hpp" +#include "strata/kernels/qsa_select.hpp" #include "strata/kernels/native_rope.hpp" #include "strata/kernels/native_router.hpp" #include "strata/kernels/qsa.hpp" @@ -508,13 +510,36 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session (double) packed_bytes / 1048576.0); } + // ---- the indexer: the sidecar's blk.40.indexer.* (all four tensors, or none of them) + w_idxq_ = bf16("indexer.q_proj.weight"); + w_idxk_ = bf16("indexer.k_proj.weight"); + w_iqn_ = f32("indexer.q_norm.weight"); + w_ikn_ = f32("indexer.k_norm.weight"); + const bool have_indexer = w_idxq_ != nullptr && w_idxk_ != nullptr && w_iqn_ != nullptr && w_ikn_ != nullptr; + const bool indexer_off = [] { const char* v = std::getenv("STRATA_MTP_INDEXER"); return v != nullptr && v[0] == '0'; }(); + indexer_ = have_indexer && !indexer_off; + if (have_indexer && indexer_off) + std::fprintf(stderr, "strata mtp: STRATA_MTP_INDEXER=0, the draft layer keeps its dense window attention\n"); + if (indexer_) { + if (g.idx_q_heads <= 0 || g.idx_key_dim <= 0 || g.idx_block <= 0) { + err = "mtp: the indexer weights need an indexer geometry"; return false; + } + std::fprintf(stderr, "strata mtp: the draft layer's indexer (%lld heads x %lld, block %lld, top-k %lld): " + "selection over every block, no attention window\n", + (long long) g.idx_q_heads, (long long) g.idx_key_dim, (long long) g.idx_block, + (long long) g.idx_top_k); + } + // ---- the layer's own K/V (dense attention: no indexer state is read) const strata::kernels::QsaShapes s = shapes_of(g); const int64_t max_cells = ss.qsa_states[ss.qsa_primary()].max_cells; // KV streaming: the drafter only reads its last `window` cells, so with streaming on its K/V is a ring of the // window (plus the cells a round writes ahead of its queries) over a host copy, refilled on a resume. The host copy // is pinned after the expert arena has pinned what it could: if it does not fit, the K/V stays whole in VRAM. - int64_t ring = (window > 0 && window < max_cells) ? window + 4 * (int64_t) max_t + 64 : 0; + // With an indexer the selection names blocks anywhere in the sequence, which a ring of the last `window` cells + // cannot serve: the drafter is planned like a trunk layer instead (ring 0 -> a resident window over the full host + // copy, and a full indexer pool). Its host copy is the same full-context one the ring already kept. + int64_t ring = (!indexer_ && window > 0 && window < max_cells) ? window + 4 * (int64_t) max_t + 64 : 0; // K8V4 never applies to the drafter: its own attention paths (below, and verify.cpp) handle whole formats // only, whatever ring shape it takes (0, a window, or the -1 fully-resident fallback). const bool kv_hybrid_was = qsa_kv_hybrid(); @@ -536,14 +561,20 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session } qsa_set_kv_int8(kv_int8_was); qsa_set_kv_hybrid(kv_hybrid_was); + // The drafter has no turn checkpoint: its indexer block rides with its K/V in a conversation snapshot. + st_.idx_block_snapshot = indexer_; qsa_state_zero(st_, g, nullptr); cudaDeviceSynchronize(); vram_ += sb; // ---- buffers - window_ = (window > 0 && window < max_cells) ? window : 0; + window_ = (!indexer_ && window > 0 && window < max_cells) ? window : 0; if (floor_on_ && !mapped(64, (void**) &h_floor_, (void**) &m_floor_)) { err = "mtp: the window floor does not fit"; return false; } - cap_ = (((window_ > 0 ? window_ : max_cells) + 63) / 64) * 64; + // With an indexer the attention reads the SELECTED cells, so the capacity is the selection width (a constant, + // as the trunk's), not the context: `ident_` holds the selected ids and the scratch is sized for them. + cap_ = indexer_ ? strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s) + : (((window_ > 0 ? window_ : max_cells) + 63) / 64) * 64; + max_blocks_ = (max_cells / s.idx_block) + 2; attn_scratch_floats_ = (int64_t) strata::kernels::qsa_decode_attn_scratch_floats(cap_, s); const uint64_t T = (uint64_t) max_t, N = (uint64_t) g.n_embd, HC = (uint64_t) g.hc, K = (uint64_t) ss.k; const uint64_t NH = (uint64_t) g.n_head, HD = (uint64_t) g.head_dim, NKV = (uint64_t) g.n_head_kv; @@ -590,6 +621,11 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session : strata::kernels::moe_hit_grouped_scratch_bytes((int64_t) (T * K), g.n_embd, g.n_ff)); sh_scratch_ = (float*) b.take(strata::kernels::shared_expert_scratch_bytes(g.n_ff)); x_bf16_ = b.take(N); + if (indexer_) { + idx_raw_ = b.take(T * (uint64_t) g.idx_key_dim); + q_idx_ = b.take(T * (uint64_t) g.idx_q_heads * (uint64_t) g.idx_key_dim); + cell_scores_ = b.take(T * (uint64_t) max_cells); + } out_ids_ = b.take(T + 4); probs_ = b.take(T + 4); arg_scratch_ = b.take(strata::kernels::argmax_rows_scratch_bytes((int) T)); @@ -1290,6 +1326,14 @@ bool MtpDrafter::record_front(int T, int row0, cudaStream_t cs, std::string& err kv_append_step(st_.k_pool, st_.v_pool, st_.page_table, step + t * 4, kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st_.host); } + if (indexer_) { + // The indexer's raw key, from the same mixed input the attention reads, then its norm/pool/rotate on + // each block completion - the trunk's step 5, over the T rows of this front pass in one launch. + bf16_gemv_fp32_mmvf_multi(mixed_, N, w_idxk_, idx_raw_, g.idx_key_dim, (int) N, (int) g.idx_key_dim, T, cs); + const QsaIndexerBuffers ib{st_.idx_tail, st_.idx_dead, st_.idx_pooled, st_.idx_block_pos}; + native_qsa_indexer_append_steps(idx_raw_, step, 4, T, 0, w_ikn_, EPS, ib, s, st_.max_cells, + rope_scaling(), cs); + } g_mp.stamp(4, cs); } catch (const std::exception& e) { err = std::string("mtp: ") + e.what(); @@ -1298,6 +1342,23 @@ bool MtpDrafter::record_front(int T, int row0, cudaStream_t cs, std::string& err return true; } +void MtpDrafter::fill_step(int32_t* out, int64_t cell, const strata::kernels::QsaShapes& s, bool indexer) { + using namespace strata::kernels; + if (indexer) { + // The selection returns qsa_selection_width(n_kv) cells, so the width is the selection's own. + // qsa_step_fill is the one writer of all four (qsa.hpp): filling them by hand is how the width + // came to be n_kv here, which sends qsa_block_topk down its "select everything" branch and + // writes n_kv ids into a cap-sized buffer. + qsa_step_fill(out, cell, s); + return; + } + // The dense/window path: n_kv, which window_ids / window_ids_floor overwrite with the window's count. + out[kStepPos] = (int32_t) cell; + out[kStepNKv] = (int32_t) (cell + 1); + out[kStepNBid] = (int32_t) ((cell + 1) / s.idx_block); + out[kStepWidth] = (int32_t) (cell + 1); +} + void MtpDrafter::norm_rope(float* data, const float* gamma, int rows, int cols, const int32_t* p, cudaStream_t cs) { using namespace strata::kernels; const QsaShapes s = shapes_of(*g_); @@ -1340,7 +1401,25 @@ bool MtpDrafter::record_rest(int step_row, cudaStream_t cs, std::string& err) { if (st_.kv_rot) fwht256_inplace_cuda(qcur_, (int64_t) T * NH, cs); g_mp.stamp(5, cs); const QsaAttnPools pools = qsa_attn_pools(st_); - if (floor_on_ && m_floor_ != nullptr) // KVA: the window (or every cell) from the first real draft cell on + if (indexer_) { + // MTP QSA: the indexer's query, then score / select / resolve / attend over the selected cells - + // the trunk's steps 7-8, replacing the dense window. `ident_` holds the selected ids. + bf16_gemv_fp32_mmvf_multi(mixed_, N, w_idxq_, q_idx_, (int64_t) g.idx_q_heads * g.idx_key_dim, + (int) N, (int) (g.idx_q_heads * g.idx_key_dim), T, cs); + native_qsa_rms_norm_weighted(q_idx_, w_iqn_, q_idx_, (int) g.idx_key_dim, (int) (T * g.idx_q_heads), EPS, cs); + for (int t = 0; t < T; ++t) { // one position per token, shared by its indexer heads + float* q = q_idx_ + (size_t) t * g.idx_q_heads * g.idx_key_dim; + if (native_rope_enabled()) + native_rope_apply(q, q, (int) g.idx_q_heads, (int) g.idx_key_dim, (int) s.n_rot, rope_scaling(), + pos + t * NH, cs); + else + rope_neox_apply(q, q, (int) g.idx_q_heads, (int) g.idx_key_dim, (int) s.n_rot, st_.cos_tab, + st_.sin_tab, pos + t * NH, cs); + } + qsa_block_scores(st_.idx_pooled, st_.idx_dead, q_idx_, step, T, max_blocks_, s, cell_scores_, cs); + qsa_block_topk(cell_scores_, step, T, max_blocks_, cap_, s, ident_, cs); + qsa_kv_resolve(st_, g, ident_, step, T, cap_, cs); + } else if (floor_on_ && m_floor_ != nullptr) // KVA: the window (or every cell) from the first real draft cell on window_ids_floor(const_cast(step), T, window_ > 0 ? (int) window_ : 0x7fffffff, ident_, cap_, m_floor_, cs); else if (window_ > 0) window_ids(const_cast(step), T, (int) window_, ident_, cap_, cs); // STRATA_QSA_SPLIT_ATTN=1: the draft layer's attention over its window, split the same way @@ -1765,10 +1844,7 @@ bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_ for (int64_t i = 0; i < n; ++i) { const int64_t cell = cell0 + i; tk[i] = next_tokens[i]; - stp[i * 4 + 0] = (int32_t) cell; - stp[i * 4 + 1] = (int32_t) (cell + 1); - stp[i * 4 + 2] = (int32_t) ((cell + 1) / 4); - stp[i * 4 + 3] = (int32_t) (cell + 1); + fill_step(stp + i * 4, cell, shapes_of(*g_), indexer_); for (int64_t h = 0; h < NHp; ++h) ps[i * NHp + h] = (int32_t) cell; } if (pf_ring_.h2d(pf_dev_, rec.data(), rec.size() * sizeof(int32_t), cs_) != cudaSuccess) { @@ -1811,10 +1887,7 @@ bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_ for (int t = 0; t < T; ++t) { const int64_t cell = cell0 + c + t; h_tok_[t] = next_tokens[c + t]; - h_step_[t * 4 + 0] = (int32_t) cell; - h_step_[t * 4 + 1] = (int32_t) (cell + 1); - h_step_[t * 4 + 2] = (int32_t) ((cell + 1) / 4); - h_step_[t * 4 + 3] = (int32_t) (cell + 1); + fill_step(h_step_ + t * 4, cell, shapes_of(*g_), indexer_); for (int64_t h = 0; h < g_->n_head; ++h) h_pos_[t * g_->n_head + h] = (int32_t) cell; } if (cudaMemcpyAsync(Rin_, R_rows + (size_t) c * HCN, (size_t) T * HCN * sizeof(float), cudaMemcpyDeviceToDevice, @@ -1897,10 +1970,7 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* const Clock::time_point t0 = Clock::now(); const int64_t NH = g_->n_head; auto put = [&](int row, int64_t cell) { - h_step_[row * 4 + 0] = (int32_t) cell; - h_step_[row * 4 + 1] = (int32_t) (cell + 1); - h_step_[row * 4 + 2] = (int32_t) ((cell + 1) / 4); - h_step_[row * 4 + 3] = (int32_t) (cell + 1); + fill_step(h_step_ + row * 4, cell, shapes_of(*g_), indexer_); for (int64_t h = 0; h < NH; ++h) h_pos_[row * NH + h] = (int32_t) cell; }; for (int t = 0; t < T; ++t) { @@ -2124,10 +2194,7 @@ bool MtpDrafter::chain_launch(int T, const int32_t* tokens, int64_t p, int a, co const Clock::time_point t0 = Clock::now(); const int64_t NH = g_->n_head; auto put = [&](int row, int64_t cell) { - h_step_[row * 4 + 0] = (int32_t) cell; - h_step_[row * 4 + 1] = (int32_t) (cell + 1); - h_step_[row * 4 + 2] = (int32_t) ((cell + 1) / 4); - h_step_[row * 4 + 3] = (int32_t) (cell + 1); + fill_step(h_step_ + row * 4, cell, shapes_of(*g_), indexer_); for (int64_t h = 0; h < NH; ++h) h_pos_[row * NH + h] = (int32_t) cell; }; for (int t = 0; t < T; ++t) { @@ -2257,6 +2324,11 @@ bool MtpDrafter::can_draft_slots(const BatchSlotDraft* items, int n_items) const for (int j = 0; j < i; ++j) if (items[j].slot == sl) return false; if (sl->device_ != device_ || sl->window_ != window_ || sl->cap_ != cap_ || sl->g_ != g_) return false; + // The batch pass scores every slot with this drafter's max_blocks_, which is max_cells/idx_block+2. + // cap_ does not imply it: with the indexer on, cap_ is the selection width (geometry only). A slot + // with fewer cells would be read past its own idx_pooled, so decline and draft it on its own. + if (sl->indexer_ != indexer_) return false; + if (indexer_ && sl->st_.max_cells != st_.max_cells) return false; if (sl->max_t_ < 2 || std::min(sl->max_t_ - 1, sl->max_drafts_) != 1) return false; if (sl->coupled_active_ || sl->cell_floor_enabled() || sl->chain_live_ || sl->experts_lent_) return false; if (sl->rr_res_ != nullptr) return false; @@ -2435,6 +2507,15 @@ bool MtpDrafter::record_front_slots(int T, const int32_t* tok_d, const int32_t* kv_append_step(st.k_pool, st.v_pool, st.page_table, step_d + t * 4, kcur_ + (size_t) t * NKV * HD, vcur_ + (size_t) t * NKV * HD, s, cs, &st.host); } + if (indexer_) { // each row's raw indexer key into its own slot's pool + bf16_gemv_fp32_mmvf_multi(mixed_, N, w_idxk_, idx_raw_, g.idx_key_dim, (int) N, (int) g.idx_key_dim, T, cs); + for (int t = 0; t < T; ++t) { + QsaState& st = *states[t]; + const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; + native_qsa_indexer_append(idx_raw_ + (size_t) t * g.idx_key_dim, step_d + t * 4, 0, w_ikn_, EPS, ib, s, + st.max_cells, rope_scaling(), cs); + } + } } catch (const std::exception& e) { err = std::string("mtp batch front: ") + e.what(); return false; @@ -2478,8 +2559,37 @@ bool MtpDrafter::record_rest_slots(int T, int32_t* step_d, const int32_t* pos_d, } if (st_.kv_rot) fwht256_inplace_cuda(qcur_, (int64_t) T * NH, cs); - // ---- per-slot dense attention (dual-track: fused qsa_decode_attn_slots when available, else sequential per-row on attn_scratch_) - if (window_ > 0) window_ids(step_d, T, (int) window_, ident_, cap_, cs); + // ---- per-slot attention (dual-track: fused qsa_decode_attn_slots when available, else sequential per-row on attn_scratch_) + if (indexer_) { + // MTP QSA per slot: each slot scores its OWN indexer keys and resolves its own residency. + bf16_gemv_fp32_mmvf_multi(mixed_, N, w_idxq_, q_idx_, (int64_t) g.idx_q_heads * g.idx_key_dim, + (int) N, (int) (g.idx_q_heads * g.idx_key_dim), T, cs); + native_qsa_rms_norm_weighted(q_idx_, w_iqn_, q_idx_, (int) g.idx_key_dim, (int) (T * g.idx_q_heads), EPS, cs); + for (int t = 0; t < T; ++t) { + float* q = q_idx_ + (size_t) t * g.idx_q_heads * g.idx_key_dim; + if (native_rope_enabled()) + native_rope_apply(q, q, (int) g.idx_q_heads, (int) g.idx_key_dim, (int) s.n_rot, rope_scaling(), + pos_d + t * NH, cs); + else + rope_neox_apply(q, q, (int) g.idx_q_heads, (int) g.idx_key_dim, (int) s.n_rot, states[t]->cos_tab, + states[t]->sin_tab, pos_d + t * NH, cs); + } + const float* pooled[8]; + const float* dead[8]; + bool scored = T <= 8; + if (scored) { + for (int t = 0; t < T; ++t) { pooled[t] = states[t]->idx_pooled; dead[t] = states[t]->idx_dead; } + scored = qsa_block_scores_slots(pooled, dead, q_idx_, step_d, T, max_blocks_, s, cell_scores_, cs); + } + if (!scored) + for (int t = 0; t < T; ++t) + qsa_block_scores(states[t]->idx_pooled, states[t]->idx_dead, + q_idx_ + (size_t) t * g.idx_q_heads * g.idx_key_dim, step_d + t * 4, 1, + max_blocks_, s, cell_scores_ + (size_t) t * max_blocks_, cs); + qsa_block_topk(cell_scores_, step_d, T, max_blocks_, cap_, s, ident_, cs); + for (int t = 0; t < T; ++t) + qsa_kv_resolve(*states[t], g, ident_ + (size_t) t * (size_t) cap_, step_d + t * 4, 1, cap_, cs); + } else if (window_ > 0) window_ids(step_d, T, (int) window_, ident_, cap_, cs); QsaAttnSlotPools sp{}; for (int t = 0; t < T; ++t) sp.p[t] = qsa_attn_pools(*states[t]); static const bool split_attn = [] { @@ -2755,10 +2865,7 @@ bool MtpDrafter::draft_slots(const BatchSlotDraft* items, int n_items, std::stri const int64_t HCN = g_->hc * g_->n_embd; const int M = bm_max_t_; auto put_step = [&](int row, int64_t cell) { - h_bm_step_[row * 4 + 0] = (int32_t) cell; - h_bm_step_[row * 4 + 1] = (int32_t) (cell + 1); - h_bm_step_[row * 4 + 2] = (int32_t) ((cell + 1) / 4); - h_bm_step_[row * 4 + 3] = (int32_t) (cell + 1); + fill_step(h_bm_step_ + row * 4, cell, shapes_of(*g_), indexer_); for (int64_t h = 0; h < NH; ++h) h_bm_pos_[row * NH + h] = (int32_t) cell; }; diff --git a/engine/src/kernels/cuda/qsa_pattn.cu b/engine/src/kernels/cuda/qsa_pattn.cu index 0b1174a798..540b88e35a 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; -constexpr int G = 12; -static_assert(HD == strata::core::kCompiledGeometry.head_dim && - G == strata::core::kCompiledGeometry.n_head / strata::core::kCompiledGeometry.n_head_kv, +// The reduce-scatter below is written for the query:KV ratios of the shipped geometries: G = 12 (24:2, Flash-Next and +// q4_deep) and G = 8 (16:2, q4_lite). px_head's permutation and the r[s + G/2] exchange need G slots, so a ratio the +// kernels are not written for would read past the end of r: qsa_pattn_batch_any_arch checks s.n_head / s.n_head_kv +// against {8, 12} and refuses anything else, which keeps the usual attention. +static_assert(HD == strata::core::kCompiledGeometry.head_dim, "qsa_pattn is compiled for core/geometry.hpp"); constexpr int CHUNK = 64; constexpr int THREADS = 256; @@ -112,33 +114,42 @@ __device__ __forceinline__ void stage_rows(const int8_t* __restrict__ codes, con sks[t >> 2][t & 3] = sc; } -constexpr int PS_BLK = G * CHUNK + 2 * CHUNK + 2 * G; // floats per (query, KV head, chunk): e, rows (int64), m, l +// floats per (query, KV head, chunk): e, rows (int64), m, l. Host and device both size their blocks with it. +__host__ __device__ constexpr int ps_blk(int g) { return g * CHUNK + 2 * CHUNK + 2 * g; } constexpr int NCM = 33; // chunks the value kernel keeps (cap <= 2112) // --------------------------------------------------------------------------------------------------------------------- // ps_score_x_kernel: the score phase two cells at a time with a select-free reduce-scatter. reduce12's selects exist // because the two lanes of an exchange send different slots; here every lane keeps the same slots and sends the same // slots, and the lane-dependent part is moved into which query head each register slot holds (q is loaded once, so the -// permutation costs nothing per cell) and which of the two cells is "first": -// slot i (0..11) of lane L holds head P_L(i) = 6 ((i / 6) ^ b3) + ((i % 6 + 3 b2) % 6) (b_k: bit k of L) +// permutation costs nothing per cell) and which of the two cells is "first". Write HALF = G/2, QUARTER = G/4: +// slot i (0..G-1) of lane L holds head P_L(i) = HALF ((i / HALF) ^ b3) + ((i % HALF + QUARTER b2) % HALF) (b_k: bit k of L) // first = cell B if b4 else cell A, second = the other one; part1[i] / part2[i] = lane partials of (first / second, // head P_L(i)) - the same expression as attn_chunk_kernel_pre75. -// level 16: r[i] = part1[i] + shfl(part2[i], 16) (partner: b4 flipped, so its second is my first, same P) -// level 8 : r6[i] = r[i] + shfl(r[i + 6], 8) (P_{L^8}(i) = P_L(i + 6)) -// level 4 : r3[i] = r6[i] + shfl(r6[i + 3], 4) (P_{L^4}(i) = P_L(i + 3), i < 3) -// level 2 / 1: reduce24's (heads 6 b3 + 3 b2 + {0, 1, 2}; o0 head +2 b1, o1 head +1 where b1 = 0) +// level 16: r[i] = part1[i] + shfl(part2[i], 16) (partner: b4 flipped, so its second is my first, same P) +// level 8 : rh[i] = r[i] + shfl(r[i + HALF], 8) (P_{L^8}(i) = P_L(i + HALF)) +// level 4 : rq[i] = rh[i] + shfl(rh[i + QUARTER], 4) (P_{L^4}(i) = P_L(i + QUARTER), i < QUARTER) +// level 2 / 1: the QUARTER heads left in the (b3, b2) group are hb + {0 .. QUARTER-1}, hb = HALF b3 + QUARTER b2. +// x0 = rq[b1 ? LAST : 0] + shfl(rq[b1 ? 0 : LAST], 2) sums head hb + LAST b1 over both b1 (LAST = QUARTER-1); +// o0 = x0 + shfl(x0, 1) finishes it over both b0. G = 12 (QUARTER 3) has a third head to finish: x1 = rq[1] + +// shfl(rq[1], 2), o1 = x1 + shfl(x1, 1), written by the b1 = 0 lanes. G = 8 (QUARTER 2) needs none: b1 already +// selects between the two slots, so every even lane writes exactly one head. +// Even lanes write G/2 heads per cell (G = 12: two, G = 8: one), so every (head, cell) of the chunk is written once. // At every level the value at lane L is its partial at L plus its partial at L ^ o, the same operands warp_sum adds, // so every score is reduce12's bit for bit. A pair with an absent / masked cell runs the same code on row 0's staged -// codes and that cell's outputs are not stored (it gets -FLT_MAX). 25 shuffles, 25 adds and 4 selects per pair -// instead of 2 x (15 + 15 + ~30). +// codes and that cell's outputs are not stored (it gets -FLT_MAX). Per pair: G = 12 costs 25 shuffles, 25 adds and 4 +// selects, G = 8 costs 16 shuffles, 16 adds and 2 selects - instead of 2 x (15 + 15 + ~30). +template __device__ __forceinline__ int px_head(int i, int lane) { + constexpr int HALF = G / 2, QUARTER = G / 4; const int b3 = (lane >> 3) & 1, b2 = (lane >> 2) & 1; - return 6 * ((i / 6) ^ b3) + ((i % 6 + 3 * b2) % 6); + return HALF * ((i / HALF) ^ b3) + ((i % HALF + QUARTER * b2) % HALF); } +template __device__ __forceinline__ void load_q_perm(const float* __restrict__ qh, int lane, float4 (&qa)[G], float4 (&qb)[G]) { #pragma unroll for (int i = 0; i < G; ++i) { - const float4* p4 = reinterpret_cast(qh + (size_t) px_head(i, lane) * HD + lane * 8); + const float4* p4 = reinterpret_cast(qh + (size_t) px_head(i, lane) * HD + lane * 8); qa[i] = __ldg(p4); qb[i] = __ldg(p4 + 1); } @@ -153,13 +164,15 @@ __device__ __forceinline__ float dot8(const float (&k8)[8], const float4& qa, co return k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w + k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w; } -template +template __device__ __forceinline__ void score_chunk_x(const float4 (&qa)[G], const float4 (&qb)[G], const int8_t (*sk)[HD], const float (*sks)[NSC], const long long* srow, float (*sp)[CHUNK], int n_here, float scale, int warp, int lane) { + constexpr int HALF = G / 2, QUARTER = G / 4, LAST = QUARTER - 1; + static_assert(G == 8 || G == 12, "qsa_pattn's reduce-scatter is written for G = 8 and G = 12"); const bool h16 = (lane & 16) != 0, h2 = (lane & 2) != 0, even = (lane & 1) == 0; - const int hb = 6 * ((lane >> 3) & 1) + 3 * ((lane >> 2) & 1); - const int h0 = hb + (h2 ? 2 : 0), h1 = hb + 1; + const int hb = HALF * ((lane >> 3) & 1) + QUARTER * ((lane >> 2) & 1); + const int h0 = hb + (h2 ? LAST : 0); #pragma unroll UNR for (int i = 0; i < CHUNK / WARPS; i += 2) { const int ca = warp + WARPS * i, cb = warp + WARPS * (i + 1); @@ -180,20 +193,21 @@ __device__ __forceinline__ void score_chunk_x(const float4 (&qa)[G], const float #pragma unroll for (int s = 0; s < G; ++s) r[s] = dot8(k8, qa[s], qb[s]) + __shfl_xor_sync(0xffffffffu, p2[s], 16); } - float r6[6]; + float rh[HALF]; #pragma unroll - for (int s = 0; s < 6; ++s) r6[s] = r[s] + __shfl_xor_sync(0xffffffffu, r[s + 6], 8); - float r3[3]; + for (int s = 0; s < HALF; ++s) rh[s] = r[s] + __shfl_xor_sync(0xffffffffu, r[s + HALF], 8); + float rq[QUARTER]; #pragma unroll - for (int s = 0; s < 3; ++s) r3[s] = r6[s] + __shfl_xor_sync(0xffffffffu, r6[s + 3], 4); - const float x0 = (h2 ? r3[2] : r3[0]) + __shfl_xor_sync(0xffffffffu, h2 ? r3[0] : r3[2], 2); - const float x1 = r3[1] + __shfl_xor_sync(0xffffffffu, r3[1], 2); + for (int s = 0; s < QUARTER; ++s) rq[s] = rh[s] + __shfl_xor_sync(0xffffffffu, rh[s + QUARTER], 4); + // every shuffle below is warp-uniform: only the shared-memory writes are guarded by the lane's bits + const float x0 = (h2 ? rq[LAST] : rq[0]) + __shfl_xor_sync(0xffffffffu, h2 ? rq[0] : rq[LAST], 2); const float o0 = x0 + __shfl_xor_sync(0xffffffffu, x0, 1); - const float o1 = x1 + __shfl_xor_sync(0xffffffffu, x1, 1); const bool vmine = h16 ? vb : va; - if (even && vmine) { - sp[h0][c1] = o0 * scale; - if (!h2) sp[h1][c1] = o1 * scale; + if (even && vmine) sp[h0][c1] = o0 * scale; + if constexpr (QUARTER == 3) { // G = 12: the third head of the group, written by the b1 = 0 lanes + const float x1 = rq[1] + __shfl_xor_sync(0xffffffffu, rq[1], 2); + const float o1 = x1 + __shfl_xor_sync(0xffffffffu, x1, 1); + if (even && vmine && !h2) sp[hb + 1][c1] = o1 * scale; } if (lane < G) { if (!va) sp[lane][ca] = -FLT_MAX; @@ -203,12 +217,13 @@ __device__ __forceinline__ void score_chunk_x(const float4 (&qa)[G], const float } // ps_score_kernel with score_chunk_x (q loaded in the permuted slot order) -template +template __global__ void __launch_bounds__(THREADS, 2) ps_score_x_kernel(const float* __restrict__ q, QsaAttnPools p, const int32_t* __restrict__ ids, const int32_t* __restrict__ step, int n_kv_heads, int page_size, float scale, float* __restrict__ blocks, int n_chunks, int cap) { + constexpr int PS_BLK = ps_blk(G); q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD; ids += (size_t) blockIdx.z * (size_t) cap; step += (size_t) blockIdx.z * kStepCount; @@ -232,11 +247,11 @@ __global__ void __launch_bounds__(THREADS, 2) ps_score_x_kernel(const float* __r reinterpret_cast(blk + G * CHUNK)[t] = r; } float4 qa[G], qb[G]; - load_q_perm(q + (size_t) (kvh * G) * HD, lane, qa, qb); + load_q_perm(q + (size_t) (kvh * G) * HD, lane, qa, qb); __syncthreads(); stage_rows(p.k_q, p.k_scale, srow, n_here, t, sk, sks); __syncthreads(); - score_chunk_x(qa, qb, sk, sks, srow, sp, n_here, scale, warp, lane); + score_chunk_x(qa, qb, sk, sks, srow, sp, n_here, scale, warp, lane); __syncthreads(); for (int h = warp; h < G; h += WARPS) { const float a = sp[h][lane], b = sp[h][lane + 32]; @@ -251,12 +266,13 @@ __global__ void __launch_bounds__(THREADS, 2) ps_score_x_kernel(const float* __r } // ps_value_d4_kernel: the value kernel with four dims a thread (64 threads, one CTA per (KV head, query)): a cell's four -// codes are one 32-bit load (a warp reads 128 contiguous bytes), its 12 weights three broadcast float4 reads for 48 +// codes are one 32-bit load (a warp reads 128 contiguous bytes), its G weights G/4 broadcast float4 reads for 4G // fmaf. V loads run four cells ahead. Per (dim, head) the fold and the merge are ps_value_kernel's. +template __global__ void __launch_bounds__(64) ps_value_d4_kernel(QsaAttnPools p, const int32_t* __restrict__ steps, const float* __restrict__ blocks, int n_kv_heads, int n_chunks, float* __restrict__ attn) { - constexpr int NT = 64; + constexpr int NT = 64, PS_BLK = ps_blk(G); const int kvh = blockIdx.x, z = blockIdx.y; const int t = threadIdx.x; const float* const blk0 = blocks + ((size_t) z * n_kv_heads + kvh) * n_chunks * PS_BLK; @@ -318,8 +334,12 @@ __global__ void __launch_bounds__(64) ps_value_d4_kernel(QsaAttnPools p, const i const float v0 = (float) (int8_t) (codes & 0xFF) * sc, v1 = (float) (int8_t) ((codes >> 8) & 0xFF) * sc; const float v2 = (float) (int8_t) ((codes >> 16) & 0xFF) * sc, v3 = (float) (int8_t) (codes >> 24) * sc; const float4* w4 = reinterpret_cast(spt[cl]); - const float4 w0 = w4[0], w1 = w4[1], w2 = w4[2]; - const float ww[G] = {w0.x, w0.y, w0.z, w0.w, w1.x, w1.y, w1.z, w1.w, w2.x, w2.y, w2.z, w2.w}; + float ww[G]; +#pragma unroll + for (int j = 0; j < G / 4; ++j) { + const float4 w = w4[j]; + ww[4 * j] = w.x; ww[4 * j + 1] = w.y; ww[4 * j + 2] = w.z; ww[4 * j + 3] = w.w; + } #pragma unroll for (int h = 0; h < G; ++h) { a[0][h] = fmaf(ww[h], v0, a[0][h]); @@ -397,6 +417,32 @@ bool sm6x_device() { return cc[dev] == 6; } +// One G's launches. The scratch holds the blocks of one batch of queries (probabilities, rows, m and l of every +// chunk), evenly split. False: it does not hold a single query, so the caller keeps the usual path. +template +bool pattn_run(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, + const QsaShapes& s, float* scratch, uint64_t scratch_floats, float* attn, int64_t n_q, int n_chunks, + float scale, cudaStream_t st) { + const uint64_t per_q = (uint64_t) s.n_head_kv * (uint64_t) n_chunks * ps_blk(G); + const int64_t max_batch = (int64_t) (scratch_floats / per_q); + if (max_batch < 1) return false; + const int64_t n_batches = (n_q + max_batch - 1) / max_batch; + const int64_t batch = (n_q + n_batches - 1) / n_batches; + for (int64_t t0 = 0; t0 < n_q; t0 += batch) { + const int64_t nb = n_q - t0 < batch ? n_q - t0 : batch; + const dim3 g1((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) nb); + const dim3 g2((unsigned) s.n_head_kv, (unsigned) nb); + const float* qb = q + (size_t) t0 * s.n_head * HD; + const int32_t* ib = ids + (size_t) t0 * cap; + const int32_t* sb = steps + (size_t) t0 * kStepCount; + ps_score_x_kernel<<>>(qb, pools, ib, sb, (int) s.n_head_kv, (int) s.page_size, scale, + scratch, n_chunks, (int) cap); + ps_value_d4_kernel<<>>(pools, sb, scratch, (int) s.n_head_kv, n_chunks, + attn + (size_t) t0 * s.n_head * HD); + } + return true; +} + } // namespace bool qsa_pattn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, @@ -409,32 +455,21 @@ bool qsa_pattn_batch_any_arch(const float* q, const QsaAttnPools& pools, const i int64_t cap, const QsaShapes& s, float* scratch, uint64_t scratch_floats, float* attn, int64_t n_q, void* stream) { if (n_q <= 0) return true; - if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !steps || - !pools.page_table || pools.k_q == nullptr || pools.v_q == nullptr || pools.k_q4 != nullptr || - pools.v_q4 != nullptr || !pools.k_scale || !pools.v_scale) + const int64_t g = s.n_head_kv > 0 ? s.n_head / s.n_head_kv : 0; // the query:KV ratio the kernels are written for + if (s.head_dim != HD || s.n_head_kv <= 0 || s.n_head != g * s.n_head_kv || (g != 8 && g != 12) || cap <= 0 || + !scratch || !ids || !steps || !pools.page_table || pools.k_q == nullptr || pools.v_q == nullptr || + pools.k_q4 != nullptr || pools.v_q4 != nullptr || !pools.k_scale || !pools.v_scale) return false; const cudaStream_t st = (cudaStream_t) stream; const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); const float scale = 1.0f / sqrtf((float) HD); if (n_chunks > NCM) return false; // a longer selection keeps the usual path - // the scratch holds the blocks of one batch of queries (probabilities, rows, m and l of every chunk), evenly split - const uint64_t per_q = (uint64_t) s.n_head_kv * (uint64_t) n_chunks * PS_BLK; - const int64_t max_batch = (int64_t) (scratch_floats / per_q); - if (max_batch < 1) return false; - const int64_t n_batches = (n_q + max_batch - 1) / max_batch; - const int64_t batch = (n_q + n_batches - 1) / n_batches; - for (int64_t t0 = 0; t0 < n_q; t0 += batch) { - const int64_t nb = n_q - t0 < batch ? n_q - t0 : batch; - const dim3 g1((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) nb); - const dim3 g2((unsigned) s.n_head_kv, (unsigned) nb); - const float* qb = q + (size_t) t0 * s.n_head * HD; - const int32_t* ib = ids + (size_t) t0 * cap; - const int32_t* sb = steps + (size_t) t0 * kStepCount; - ps_score_x_kernel<1><<>>(qb, pools, ib, sb, (int) s.n_head_kv, (int) s.page_size, scale, - scratch, n_chunks, (int) cap); - ps_value_d4_kernel<<>>(pools, sb, scratch, (int) s.n_head_kv, n_chunks, - attn + (size_t) t0 * s.n_head * HD); - } + const bool ran = g == 12 + ? pattn_run<12>(q, pools, ids, steps, cap, s, scratch, scratch_floats, attn, n_q, n_chunks, + scale, st) + : pattn_run<8>(q, pools, ids, steps, cap, s, scratch, scratch_floats, attn, n_q, n_chunks, + scale, st); + if (!ran) return false; const cudaError_t e = cudaGetLastError(); if (e != cudaSuccess) { // a launch that did not start: say so once, and let the caller run the usual attention over the whole chunk 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_pattn_parity.cpp b/engine/src/kernels/qsa_pattn_parity.cpp index ab67038d80..bad3f8ef62 100644 --- a/engine/src/kernels/qsa_pattn_parity.cpp +++ b/engine/src/kernels/qsa_pattn_parity.cpp @@ -16,7 +16,9 @@ // decode layout (so qsa_pattn_batch runs several batches). The pattn scratch and the output are filled with // junk before each call, so a read of a block that was not written shows up as a difference. // -// qsa_pattn_parity [--device N] exit 0: every case is bit-identical; 77: no GPU or a build without the kernels +// qsa_pattn_parity [--device N] exit 0: every case is bit-identical; 1: a case differs, or the candidate declined +// a shape it is written for; 77: no GPU, a build without the kernels, or a query:KV +// ratio outside the kernels' {8, 12} #include "strata/kernels/qsa.hpp" #include "strata/kernels/qsa_decode_attn.hpp" #include "strata/kernels/qsa_pattn.hpp" @@ -34,6 +36,17 @@ namespace k = strata::kernels; +// qsa_pattn.cu compiles its kernels only in the CUDA build with STRATA_EXPERIMENTAL_SM60; every other build links stubs +// that answer false. The same condition here, so a decline can be told apart from a build that has no kernels. +#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60) +constexpr bool kPattnBuilt = true; +#else +constexpr bool kPattnBuilt = false; +#endif +// The query:KV ratios the score / value kernels are written for (qsa_pattn.cu's G). Declining one of them is a defect, +// not a skip: reporting every decline as "no sm_6x kernels" hid that a 16:2 build (q4_lite, G = 8) ran no case at all. +constexpr int kPattnRatios[] = {8, 12}; + namespace { void ck(cudaError_t e, const char* what) { if (e != cudaSuccess) { @@ -83,6 +96,8 @@ struct Harness { float *q = nullptr, *scratch_ref = nullptr, *scratch_new = nullptr, *attn_ref = nullptr, *attn_new = nullptr; int32_t *ids = nullptr, *steps = nullptr; int64_t max_q = 0, max_cap = 0; + int64_t ratio = 0; // n_head / n_head_kv: the kernels' G + bool ratio_supported = false; std::vector to_free; template T* keep(T* p) { to_free.push_back(p); return p; } @@ -90,6 +105,9 @@ struct Harness { void init(std::mt19937& rng, int64_t max_q_, int64_t max_cap_) { max_q = max_q_; max_cap = max_cap_; + ratio = s.n_head_kv > 0 && s.n_head % s.n_head_kv == 0 ? s.n_head / s.n_head_kv : 0; + for (int r : kPattnRatios) + if (r == ratio) ratio_supported = true; const int64_t PS = s.page_size, pages = kCells / PS, H = s.n_head_kv, D = s.head_dim; std::vector tab((size_t) pages); // logical page -> physical page: a permutation, with holes for (int64_t i = 0; i < pages; ++i) tab[(size_t) i] = (int32_t) i; @@ -123,7 +141,8 @@ struct Harness { for (void* p : to_free) cudaFree(p); } - // returns 0 identical, 1 differs, -1 the candidate declined (build without the kernels) + // returns 0 identical, 1 differs (or declined a supported shape), -1 no kernels in this build, -2 a ratio the + // kernels are not written for int run(int64_t cap, int n_q, int scr_q, const std::vector& widths, std::mt19937& rng, bool on_pascal, long long& nonzero) { const int64_t D = s.head_dim, NH = s.n_head; @@ -162,7 +181,14 @@ struct Harness { const uint64_t scratch_floats = (uint64_t) scr_q * k::qsa_decode_attn_scratch_floats(cap, s); const bool took = k::qsa_pattn_batch_any_arch(q, pools, ids, steps, cap, s, scratch_new, scratch_floats, attn_new, n_q, nullptr); - if (!took) return -1; + if (!took) { + if (!kPattnBuilt) return -1; + if (!ratio_supported) return -2; + std::printf("FAIL: qsa_pattn_batch_any_arch declined G %lld (cap %lld, n_q %d, scratch %d queries), a ratio " + "the kernels are written for\n", + (long long) ratio, (long long) cap, n_q, scr_q); + return 1; + } ck(cudaDeviceSynchronize(), "candidate"); ck(cudaMemcpy(b.data(), attn_new, n * 4, cudaMemcpyDeviceToHost), "read candidate"); bool same = std::memcmp(a.data(), b.data(), n * 4) == 0; @@ -243,10 +269,15 @@ int main(int argc, char** argv) { widths.push_back(std::min((int32_t) cap, wc < n_base ? base_widths[wc] : base_widths[rng() % (uint32_t) n_base])); long long nz = 0; const int r = hx.run(cap, n_q, scr_q, widths, rng, on_pascal, nz); - if (r < 0) { + if (r == -1) { std::puts("SKIP: this build has no sm_6x kernels (CUDA with STRATA_EXPERIMENTAL_SM60)"); return 77; } + if (r == -2) { + std::printf("SKIP: query:KV ratio %lld is outside the pattn kernels' {8, 12}\n", + (long long) hx.ratio); + return 77; + } nonzero_total += nz; ++cases; if (r != 0) ++failed; 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/engine/src/prefill/prefill.cpp b/engine/src/prefill/prefill.cpp index a98636f87c..5b6e480d8d 100644 --- a/engine/src/prefill/prefill.cpp +++ b/engine/src/prefill/prefill.cpp @@ -3007,7 +3007,7 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t core::QsaState& st = mtp.kv_state_rw(); if (off) return decline("STRATA_MTP_BATCH=0"); if (n <= 0 || m.g == nullptr || m.region == nullptr) return decline("no prompt scratch region on this path"); - if (st.kv_mode != 0 && !(st.kv_mode == 2 && ring_ok)) + if (st.kv_mode != 0 && st.kv_mode != 1 && !(st.kv_mode == 2 && ring_ok)) return decline(st.kv_mode == 2 ? "the drafter's K/V is a ring and STRATA_MTP_BATCH_RING=0" : "the drafter's K/V mode is not paged/ring"); if (st.kv_hybrid) return decline("the drafter's K/V is hybrid (kv_hybrid)"); if (mtp.device() != m.device) return decline("the drafter is on another device than this prefill path"); @@ -3025,6 +3025,11 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t const void* w_k = mtp.tensor_q8("self_attn.k_proj.weight"); const void* w_v = mtp.tensor_q8("self_attn.v_proj.weight"); const float* w_kn = mtp.tensor_f32("self_attn.k_norm.weight"); + // MTP QSA: the drafter's own indexer key projection and norm (the prompt path appends its pooled blocks here) + const bool indexer = mtp.indexer_enabled(); + const uint16_t* w_ik = indexer ? mtp.tensor_bf16("indexer.k_proj.weight") : nullptr; + const float* w_ikn = indexer ? mtp.tensor_f32("indexer.k_norm.weight") : nullptr; + if (indexer && (!w_ik || !w_ikn)) return decline("the drafter's indexer tensors are missing"); if (!w_ne || !w_fe || !w_nh || !w_fh || !w_hn || !w_dn || !w_up || !w_k || !w_v || !w_kn) return decline("a drafter tensor is missing (Q8_0 projections / norms)"); const core::NativeEmbed* nemb = core::native_embed(); @@ -3045,6 +3050,7 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t static const bool f16_only = [] { const char* v = std::getenv("STRATA_MTP_BATCH_F16"); return v == nullptr || v[0] != '0'; }(); const bool q8 = !f16_only && mmq::built() && mmq::fits(kQ8_0, Nn) && mmq::fits(kQ8_0, KV); // #420 const uint64_t per_row = 4 * (2 * Nn + 4 * HCN + LR + HC + Nn + 2 * KV + 1) + 2 * (Nn + 2 * HCN + LR + Nn) + 64 + + (indexer ? (uint64_t) g.idx_key_dim * 4 : 0) + (q8 ? (uint64_t) mmq::q8_bytes(g.hc, Nn) + 8 * g.hc : 0); // (8 * hc: the row table twice, see its margin below) int64_t B = std::min(n - r0, (int64_t) (m.region_bytes / per_row) & ~(int64_t) 63); if (st.kv_mode == 2) // a ring: one batch's cells must not share a slot (a batch can straddle one page more) @@ -3069,6 +3075,7 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t float* Kc = (float*) carve((size_t) B * KV * 4); float* Vc = (float*) carve((size_t) B * KV * 4); int32_t* tok = (int32_t*) carve((size_t) B * 4); + float* idx_raw = indexer ? (float*) carve((size_t) B * g.idx_key_dim * 4) : nullptr; void* xq = q8 ? carve(mmq::q8_bytes(B * g.hc, Nn)) : nullptr; // The row table is read past its end by llama.cpp's MMQ (a whole J-column tile from the start of each tile; the stream-k fixup up to roundup(max_rows, J) // from the expert's first row; J up to 128): rows + the margin of mmq_ids_margin.hpp, max_rows <= B * hc (one expert, p.n = 1), the identity over all of it. @@ -3157,6 +3164,12 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t kv_append(Kc, Vc, nb, c0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool, st.kv_int8 ? nullptr : st.v_pool, st.k_q, st.v_q, st.k_scale, st.v_scale, m.cs, &st.host); } + if (indexer) { // the pooled indexer keys of these cells, as the trunk's prompt path appends its own + m.gemm.bf16(mixed_h, w_ik, idx_raw, nb, g.idx_key_dim, Nn); + const strata::kernels::QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; + strata::kernels::native_qsa_indexer_append_batch(idx_raw, nb, c0, 0, w_ikn, EPS, ib, s, st.max_cells, + strata::kernels::rope_scaling(), m.cs); + } } if (cudaStreamSynchronize(m.cs) != cudaSuccess) { err = std::string("prefill: the draft layer's K/V: ") + cudaGetErrorString(cudaGetLastError()); diff --git a/engine/src/program/generate.cpp b/engine/src/program/generate.cpp index 977fa6c981..4b955e0194 100644 --- a/engine/src/program/generate.cpp +++ b/engine/src/program/generate.cpp @@ -1173,9 +1173,12 @@ struct Options { int lookup_max_t = -1; /// --lookup-sizes A,B,.. : the lookup window sizes above the MTP's (default with --lookup-max-t N: MTP+1, MTP+2, N) std::string lookup_sizes; - /// --mtp-hnorm stream (opt-in): the draft layer's pre_fc_norm_hidden normalizes each hyper-connection stream on - /// its own (llama.cpp's qwen4exp MTP graph) instead of one RMS over all four (the default, tools/mtp_probe.py). - bool mtp_hnorm_stream = false; + /// --mtp-hnorm pooled|stream: the draft layer's pre_fc_norm_hidden normalizes each hyper-connection stream on + /// its own (the default: llama.cpp's qwen4exp MTP graph, upstream's q4_mtp_eh_concat_kernel, and what + /// tools/mtp_qwen4_rt.py documents - "applied per hc stream to hnorm(h)"). pooled is one RMS over all four + /// (tools/mtp_probe.py's reading), kept as an opt-out: it does not match the reference and measured lower + /// acceptance on two cards. + bool mtp_hnorm_stream = true; /// --mtp-q4 (opt-in): the draft layer's projections and draft head from 4-bit copies (fewer bytes per draft /// step); head/all need the draft head's subset (--mtp-draft-vocab FILE or rt/draft_vocab.bin) and say so without one std::string mtp_q4; ///< "" (off), all, proj (the projections only) or head (the draft head only) @@ -1353,8 +1356,8 @@ void usage() { " --lookup-chain K opt-in: after the MTP's drafts, add up to K prompt-lookup drafts that continue\n" " them (the window grows to at most 8; default 0 = off)\n" " --lookup-chain-min M the shortest context match --lookup-chain extends on (default 3)\n" - " --mtp-hnorm pooled|stream the draft layer's hidden-input norm: one RMS over all four streams\n" - " (default) or one per stream (llama.cpp's MTP graph)\n" + " --mtp-hnorm pooled|stream the draft layer's hidden-input norm: one RMS per stream (default,\n" + " llama.cpp's MTP graph) or one over all four streams (pooled, opt-out)\n" " --mtp-q4 all|proj|head opt-in: the draft layer's projections and/or draft head as 4-bit copies\n" " (head/all need the draft head's subset: --mtp-draft-vocab / rt/draft_vocab.bin)\n" " --mtp-draft-vocab FILE opt-in: the draft head's token subset (default /draft_vocab.bin)\n" @@ -8182,7 +8185,7 @@ int main(int argc, char** argv) { } if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size()); if (!o.mtp.empty()) { - mtp.set_hnorm_per_stream(o.mtp_hnorm_stream); // --mtp-hnorm stream (opt-in), before any capture + mtp.set_hnorm_per_stream(o.mtp_hnorm_stream); // --mtp-hnorm (default stream), before any capture mtp.set_q4(o.mtp_q4 == "all" || o.mtp_q4 == "proj", o.mtp_q4 == "all" || o.mtp_q4 == "head"); // before load if (!o.mtp_draft_vocab.empty()) mtp.set_draft_vocab(o.mtp_draft_vocab); } diff --git a/engine/tests/core/mtp_step_test.cpp b/engine/tests/core/mtp_step_test.cpp new file mode 100644 index 0000000000..e60b63ca7a --- /dev/null +++ b/engine/tests/core/mtp_step_test.cpp @@ -0,0 +1,138 @@ +// The MTP draft layer's step record (MtpDrafter::fill_step) against the QSA selection's contract. +// +// `qsa_block_topk` reads the per-query width from step[kStepWidth] and takes `n_kv <= width` as +// "everything is selected": it then writes n_kv ids, ascending, and returns. The ids buffer is +// `cap = qsa_selection_width(kTopkMaxCells, s)` per query, so a width of n_kv is only legal while +// n_kv <= cap. The draft layer's dense/window path fills n_kv and `window_ids` overwrites it with +// the window's own count; the indexer path has no such overwrite, so it must fill the selection's +// width itself (qsa_step_fill's rule) or the kernel writes past the buffer. +// +// Measured on an RTX 3080 Ti before the fix: the drafter's acceptance was 0.715 at a 32K prompt and +// 0.217 at 64K (twice, greedy, matched expert cache), while the same runtime with the indexer off +// kept 0.76-0.89. The overflow grows with the context, which is why the short runs looked healthy. +// +// Part 1 needs no device (the arithmetic). Part 2 runs the real selection over a guarded ids +// buffer and exits 77 without a device. +#include "strata/core/mtp.hpp" +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_select.hpp" + +#include + +#include +#include +#include + +namespace k = strata::kernels; +using strata::core::MtpDrafter; + +static int failed = 0; +#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #x); ++failed; } } while (0) + +namespace { +// the contexts the defect was measured at, plus one below and one far above the selection width +const int64_t kCells[] = {1023, 2050, 32801, 40994, 65569, 131106}; +constexpr int64_t kMaxCells = 133120; +constexpr int32_t kSentinel = 0x5A5A5A5A; +constexpr int64_t kGuard = 140000; // ids past cap: enough for the longest context's identity write + +void arithmetic(const k::QsaShapes& s) { + const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s); + for (int64_t cell : kCells) { + int32_t st[k::kStepCount] = {0, 0, 0, 0}; + MtpDrafter::fill_step(st, cell, s, /*indexer=*/true); + const int64_t n_kv = cell + 1; + CHECK(st[k::kStepPos] == (int32_t) cell); + CHECK(st[k::kStepNKv] == (int32_t) n_kv); + CHECK(st[k::kStepNBid] == (int32_t) (n_kv / s.idx_block)); + // the contract: the indexer's width is the selection's, never the whole context + CHECK(st[k::kStepWidth] == (int32_t) k::qsa_selection_width(n_kv, s)); + CHECK(st[k::kStepWidth] <= cap); + // the dense/window path is unchanged: n_kv, for window_ids to overwrite + int32_t dense[k::kStepCount] = {0, 0, 0, 0}; + MtpDrafter::fill_step(dense, cell, s, /*indexer=*/false); + CHECK(dense[k::kStepWidth] == (int32_t) n_kv); + CHECK(dense[k::kStepPos] == st[k::kStepPos]); + CHECK(dense[k::kStepNKv] == st[k::kStepNKv]); + CHECK(dense[k::kStepNBid] == st[k::kStepNBid]); + } +} + +bool selection(const k::QsaShapes& s) { + int n = 0; + if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { + (void) cudaGetLastError(); + std::printf("mtp_step_test: no device, the selection part skipped\n"); + return false; + } + const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s); + const int64_t max_blocks = kMaxCells / s.idx_block + 2; + const int64_t nq = 1; + std::vector scores((size_t) (nq * max_blocks)); + for (int64_t b = 0; b < max_blocks; ++b) + scores[(size_t) b] = (float) ((b * 2654435761u) % 1000) / 1000.0f - 0.5f; + float* d_scores = nullptr; + int32_t* d_steps = nullptr; + int32_t* d_ids = nullptr; // cap ids, then the guard + const int64_t ids_ints = cap + kGuard; + if (cudaMalloc(&d_scores, scores.size() * 4) != cudaSuccess || + cudaMalloc(&d_steps, (size_t) (nq * k::kStepCount) * 4) != cudaSuccess || + cudaMalloc(&d_ids, (size_t) ids_ints * 4) != cudaSuccess) { + (void) cudaGetLastError(); + std::printf("mtp_step_test: no room for the selection buffers, skipped\n"); + cudaFree(d_scores); cudaFree(d_steps); cudaFree(d_ids); + return false; + } + cudaMemcpy(d_scores, scores.data(), scores.size() * 4, cudaMemcpyHostToDevice); + std::vector back((size_t) ids_ints); + for (int64_t cell : kCells) { + int32_t st[k::kStepCount] = {0, 0, 0, 0}; + MtpDrafter::fill_step(st, cell, s, /*indexer=*/true); + const int64_t n_kv = cell + 1, width = st[k::kStepWidth]; + // the tail block scores the dead key far above the rest when it holds cells, as the scorer leaves it + std::vector sc = scores; + if (n_kv % s.idx_block != 0) sc[(size_t) st[k::kStepNBid]] += 1e9f; + cudaMemcpy(d_scores, sc.data(), sc.size() * 4, cudaMemcpyHostToDevice); + cudaMemcpy(d_steps, st, sizeof st, cudaMemcpyHostToDevice); + cudaMemset(d_ids, 0x5A, (size_t) ids_ints * 4); + k::qsa_block_topk(d_scores, d_steps, nq, max_blocks, cap, s, d_ids, nullptr); + if (cudaDeviceSynchronize() != cudaSuccess) { + std::fprintf(stderr, "FAIL cell %lld: the selection launch: %s\n", (long long) cell, + cudaGetErrorString(cudaGetLastError())); + ++failed; + continue; + } + cudaMemcpy(back.data(), d_ids, back.size() * 4, cudaMemcpyDeviceToHost); + int64_t over = 0; + for (int64_t i = cap; i < ids_ints; ++i) if (back[(size_t) i] != kSentinel) ++over; + CHECK(over == 0); // nothing written past the ids buffer + if (over != 0) + std::fprintf(stderr, " cell %lld (n_kv %lld, width %lld, cap %lld): %lld ids past the buffer\n", + (long long) cell, (long long) n_kv, (long long) width, (long long) cap, (long long) over); + // exactly `width` cells, ascending, inside the sequence + int64_t written = 0; + bool ascending = true, in_range = true; + for (int64_t i = 0; i < cap; ++i) { + const int32_t v = back[(size_t) i]; + if (v == kSentinel) break; + ++written; + if (written > 1 && v <= back[(size_t) (i - 1)]) ascending = false; + if (v < 0 || v >= n_kv) in_range = false; + } + CHECK(written == width); + CHECK(ascending); + CHECK(in_range); + } + cudaFree(d_scores); cudaFree(d_steps); cudaFree(d_ids); + return true; +} +} // namespace + +int main() { + const k::QsaShapes s = k::qsa_real_shapes(); + arithmetic(s); + const bool ran = selection(s); + if (failed) { std::fprintf(stderr, "mtp_step_test: %d failed\n", failed); return 1; } + std::printf("mtp_step_test: ok%s\n", ran ? "" : " (arithmetic only)"); + return 0; +} \ No newline at end of file diff --git a/qwen4-run.sh b/qwen4-run.sh new file mode 100755 index 0000000000..3d2c92ef90 --- /dev/null +++ b/qwen4-run.sh @@ -0,0 +1,380 @@ +#!/usr/bin/env bash +# qwen4-run.sh - one command from a fresh clone of the qwen4-35b branch to a running +# Qwen4-35B-A3B server. Idempotent: existing artifacts are reused, so re-running is safe. +# +# ./qwen4-run.sh prepare whatever is missing, then serve +# ./qwen4-run.sh --download also fetch the Unsloth GGUF files (~32 GiB) +# ./qwen4-run.sh --check preflight only; change nothing +# ./qwen4-run.sh --build-only prepare everything, do not start the server +# ./qwen4-run.sh --rebuild force a rebuild of the engine +# ./qwen4-run.sh --update fast-forward this checkout, rebuild, then ask whether to start/restart +# ./qwen4-run.sh --stop stop the instance this launcher started (identity-checked) +# +# Overrides: QWEN4_MODEL_DIR, QWEN4_PACK_DIR, QWEN4_PORT, QWEN4_HOST, QWEN4_CUDA_ARCH. +set -euo pipefail + +ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +MODEL_DIR="${QWEN4_MODEL_DIR:-$HOME/PolyStrata-data/models/Qwen4-35B-A3B-GGUF}" +PACK_DIR="${QWEN4_PACK_DIR:-$HOME/PolyStrata-data/packs/qwen4-35b-ud-iq4_xs-trunk40}" +HOST="${QWEN4_HOST:-127.0.0.1}" +PORT="${QWEN4_PORT:-8080}" +SHARD1="UD-IQ4_XS/Qwen4-35B-A3B-UD-IQ4_XS-00001-of-00002.gguf" +SHARD2="UD-IQ4_XS/Qwen4-35B-A3B-UD-IQ4_XS-00002-of-00002.gguf" +MTP="MTP/mtp-Qwen4-35B-A3B-Q8_0.gguf" +TRUNK="trunk40/Qwen4-35B-A3B-UD-IQ4_XS-trunk40.gguf" +ENGINE="$ROOT/build-q4lite/strata" +VENV="$ROOT/terminal/.venv" +CONFIG="$ROOT/terminal/strata-qwen4-35b-ud-iq4_xs.json" +SHARED="$ROOT/terminal/strata-qwen4-35b-ud-iq4_xs.shared-settings.json" +DOWNLOAD=0; CHECK=0; SERVE=1; REBUILD=0; UPDATE=0; STOP=0 + +# Only the leading comment block is the help text; printing a fixed line range leaked shell code. +usage() { awk 'NR>1 && /^#/ {print; next} NR>1 {exit}' "${BASH_SOURCE[0]}"; } +while [ $# -gt 0 ]; do + case "$1" in + --download) DOWNLOAD=1 ;; + --check) CHECK=1 ;; + --build-only) SERVE=0 ;; + --rebuild) REBUILD=1 ;; + --update) UPDATE=1; REBUILD=1; SERVE=0 ;; + --stop) STOP=1 ;; + -h|--help) usage; exit 0 ;; + *) echo "unknown option: $1" >&2; usage >&2; exit 2 ;; + esac + shift +done + +say() { printf '\n== %s\n' "$*"; } +die() { printf '\nERROR: %s\n' "$*" >&2; exit 1; } +need() { command -v "$1" >/dev/null 2>&1 || die "$1 not found. $2"; } + +# Stop the instance this launcher starts. The server is identified by its working directory AND its command line +# (this repo's terminal/, this config), never by the port alone: a bare PID is never signalled, and another +# checkout's server is left alone. Engine children are captured before the signal, so a leftover is still verified +# against its own start time and executable rather than assumed. +stop_instance() { + python3 - "$ROOT" "$(basename "$CONFIG")" "$ENGINE" <<'PY' +import os, signal, sys, time +from pathlib import Path +root, config, engine = sys.argv[1], sys.argv[2], str(Path(sys.argv[3]).resolve()) +want_cwd = str(Path(root) / "terminal") + +def text(pid, name): + try: + return Path("/proc/%d/%s" % (pid, name)).read_text() + except OSError: + return None + +def argv(pid): + t = text(pid, "cmdline") + return [p for p in t.split("\0") if p] if t else [] + +def link(pid, name): + try: + return os.readlink("/proc/%d/%s" % (pid, name)) + except OSError: + return None + +def fields(pid): + t = text(pid, "stat") + return t.rsplit(")", 1)[1].split() if t and ")" in t else None + +def token(pid): + f = fields(pid) + return f[19] if f and len(f) > 19 else None + +def same(pid, tok): + f = fields(pid) + # a zombie is already gone; its parent has not reaped it yet + return tok is not None and f is not None and len(f) > 19 and f[19] == tok and f[0] != "Z" + +def pids(): + return [int(p) for p in os.listdir("/proc") if p.isdigit()] + +servers = [] +for pid in pids(): + a = argv(pid) + if "serve.server" not in a or "--config" not in a: + continue + i = a.index("--config") + if i + 1 < len(a) and a[i + 1] == config and link(pid, "cwd") == want_cwd: + servers.append(pid) + +if not servers: + print("no running instance of %s in %s" % (config, want_cwd)) + sys.exit(0) + +def end(pid, tok, grace): + os.kill(pid, signal.SIGTERM) + for _ in range(grace * 10): + if not same(pid, tok): + return True + time.sleep(0.1) + if same(pid, tok): + os.kill(pid, signal.SIGKILL) + for _ in range(50): + if not same(pid, tok): + return True + time.sleep(0.1) + return not same(pid, tok) + +failed = [] +for pid in servers: + tok = token(pid) + if tok is None: + print("pid %d: identity unreadable, left alone" % pid) + failed.append(pid) + continue + kids = [] + for c in pids(): + f = fields(c) + if f and f[1] == str(pid) and link(c, "exe") == engine: + kids.append((c, token(c))) + print("stopping server pid %d (%s)" % (pid, config)) + if not end(pid, tok, 20): + print("pid %d did not exit" % pid) + failed.append(pid) + continue + for c, ct in kids: + if same(c, ct): + print("stopping leftover engine pid %d" % c) + if not end(c, ct, 10): + failed.append(c) +print("stopped" if not failed else "could not stop: %s" % failed) +sys.exit(1 if failed else 0) +PY +} + +if [ "$STOP" -eq 1 ]; then + need python3 "Install Python 3.10 or newer." + stop_instance + exit $? +fi + +say "Preflight" +need python3 "Install Python 3.10 or newer." +need nvidia-smi "This model needs an NVIDIA card with 12 GB or more of VRAM." +need cmake "Install cmake." +need ninja "Install ninja-build." +need gcc-14 "Install gcc-14/g++-14 (the engine is built with them)." +need g++-14 "Install gcc-14/g++-14." +command -v nvcc >/dev/null 2>&1 || die "nvcc not found. Install the CUDA toolkit (12.x) first." +# GPU 0: total, free and compute capability in one query. The tested card is a 12 GB (12288 MiB) +# RTX 3080 Ti; what matters is the FREE memory, because other workloads may already hold some. +GPU_CSV="$(nvidia-smi -i 0 --query-gpu=memory.total,memory.free,compute_cap --format=csv,noheader,nounits)" +IFS=', ' read -r VRAM_MIB VRAM_FREE_MIB COMPUTE_CAP <<< "$GPU_CSV" +if [ "$SERVE" -eq 1 ]; then + [ "${VRAM_FREE_MIB:-0}" -ge 11264 ] || die "GPU 0 has only ${VRAM_FREE_MIB:-0} MiB free; this model needs about 11264 MiB free (tested on a 12 GB / 12288 MiB card). Free the GPU or use a bigger card." +else + # Building needs no VRAM, and a running service holds most of it: --build-only and --update must still work. + echo "note: GPU 0 has ${VRAM_FREE_MIB:-0} MiB free; serving needs about 11264 MiB (re-checked before a start)." +fi +CUDA_ARCH="${QWEN4_CUDA_ARCH:-${COMPUTE_CAP//./}}" +CUDA_ARCH="${CUDA_ARCH}-real;${CUDA_ARCH}-virtual" +RAM_GIB=$(( $(awk '/MemTotal/{print $2}' /proc/meminfo) / 1048576 )) +[ "$RAM_GIB" -ge 30 ] || die "System RAM is ${RAM_GIB} GiB; 32 GB or more is required (46 GiB tested)." +RAM_AVAIL_GIB=$(( $(awk '/MemAvailable/{print $2}' /proc/meminfo) / 1048576 )) +echo "GPU ${VRAM_MIB} MiB (${VRAM_FREE_MIB} MiB free), RAM ${RAM_GIB} GiB (${RAM_AVAIL_GIB} GiB available), CUDA $(nvcc --version | awk '/release/{print $6}')" +echo "models: $MODEL_DIR" +echo "pack: $PACK_DIR" + +# The serving port must be bindable before anything is downloaded or built. +if [ "$SERVE" -eq 1 ]; then + python3 - "$HOST" "$PORT" <<'PY' || die "cannot bind $HOST:$PORT - the port is already in use (or the host is not local). Pick another QWEN4_PORT." +import socket, sys +with socket.socket() as s: + s.bind((sys.argv[1], int(sys.argv[2]))) +PY +fi + +# Disk: check the filesystems that would hold the model and the pack, without creating anything. +# df needs an existing path, so walk up to the nearest existing parent of a missing directory. +existing_parent() { local p="$1"; while [ ! -e "$p" ]; do p="$(dirname -- "$p")"; done; printf '%s\n' "$p"; } +free_gib() { df -Pk "$(existing_parent "$1")" | awk 'NR==2{print int($4/1048576)}'; } +fs_dev() { df -Pk "$(existing_parent "$1")" | awk 'NR==2{print $1}'; } + +pack_complete() { + local f + for f in index.txt dense.bin conversions.json native_experts.txt tokenizer/vocab.json tokenizer/chat_template.jinja; do + [ -f "$PACK_DIR/$f" ] || return 1 + done +} +mtp_complete() { + [ -f "$MODEL_DIR/$MTP" ] || return 1 + python3 - "$PACK_DIR/mtp-rt" "$MODEL_DIR/$MTP" <<'PY' +import json, sys +from pathlib import Path +rt, src = Path(sys.argv[1]), Path(sys.argv[2]) +try: + m = json.loads((rt / "complete.json").read_text(encoding="utf-8")) + assert m["schema"] == 1 + assert m["source"]["name"] == src.name and m["source"]["size"] == src.stat().st_size + # A record without the indexer marker was written before the drafter's QSA selection existed. Its artifact sizes + # are self-consistent, so only the missing marker reveals it: reconvert instead of serving dense attention. + assert "indexer" in m + for name in ("dense.bin", "dense.txt", "experts.bin", "experts.txt"): + assert m["artifacts"][name] == (rt / name).stat().st_size +except Exception: + sys.exit(1) +PY +} + +TRUNK_OK=0; [ -f "$MODEL_DIR/$TRUNK" ] && TRUNK_OK=1 +PACK_OK=0; if pack_complete; then PACK_OK=1; fi +MTP_OK=0; if mtp_complete; then MTP_OK=1; fi +if [ "$TRUNK_OK" -eq 0 ] || [ "$PACK_OK" -eq 0 ]; then + FREE_GIB="$(free_gib "$MODEL_DIR")" + [ "$FREE_GIB" -ge 60 ] || die "Only ${FREE_GIB} GiB free under $MODEL_DIR; about 60 GiB is needed for the first run." + if [ "$(fs_dev "$PACK_DIR")" != "$(fs_dev "$MODEL_DIR")" ]; then + PACK_FREE_GIB="$(free_gib "$PACK_DIR")" + [ "$PACK_FREE_GIB" -ge 60 ] || die "Only ${PACK_FREE_GIB} GiB free under $PACK_DIR; about 60 GiB is needed for the first run." + fi +fi +[ "$CHECK" -eq 0 ] || { say "Preflight passed (--check: nothing was changed)"; exit 0; } + +mkdir -p "$MODEL_DIR" "$PACK_DIR" + +if [ "$DOWNLOAD" -eq 1 ]; then + say "Downloading the Unsloth files (about 32 GiB)" + python3 -m venv "$VENV" + "$VENV/bin/python" -m pip install -q --upgrade pip huggingface_hub + HF_HUB_ENABLE_HF_TRANSFER=0 "$VENV/bin/python" - "$MODEL_DIR" <<'PY' +import sys +from huggingface_hub import hf_hub_download +dest = sys.argv[1] +for rel in ("UD-IQ4_XS/Qwen4-35B-A3B-UD-IQ4_XS-00001-of-00002.gguf", + "UD-IQ4_XS/Qwen4-35B-A3B-UD-IQ4_XS-00002-of-00002.gguf", + "MTP/mtp-Qwen4-35B-A3B-Q8_0.gguf"): + p = hf_hub_download(repo_id="unsloth/Qwen4-35B-A3B-GGUF", filename=rel, local_dir=dest) + print("downloaded:", p) +PY +fi +[ -f "$MODEL_DIR/$SHARD1" ] || die "Missing $MODEL_DIR/$SHARD1 +Download it from https://huggingface.co/unsloth/Qwen4-35B-A3B-GGUF or re-run with --download." +[ -f "$MODEL_DIR/$SHARD2" ] || die "Missing $MODEL_DIR/$SHARD2 (the PLE table)." +[ -f "$MODEL_DIR/$MTP" ] || die "Missing $MODEL_DIR/$MTP (the drafter)." + +if [ ! -x "$VENV/bin/python" ]; then + say "Creating the Python environment" + python3 -m venv "$VENV" +fi +# The conversion tools need the full runtime requirements (regex, jinja2, ...), not just numpy. +"$VENV/bin/python" -c 'import numpy, regex, jinja2' 2>/dev/null || \ + "$VENV/bin/python" -m pip install -q -r "$ROOT/terminal/requirements.txt" +PY="$VENV/bin/python" + +if [ "$UPDATE" -eq 1 ]; then + say "Updating this checkout (fast-forward only)" + git -C "$ROOT" rev-parse --git-dir >/dev/null 2>&1 || die "--update needs a git checkout; $ROOT is not one." + BRANCH="$(git -C "$ROOT" symbolic-ref --quiet --short HEAD || true)" + [ -n "$BRANCH" ] || die "--update needs a branch, but HEAD is detached. Check out the branch you follow, then re-run." + UPSTREAM="$(git -C "$ROOT" rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null || true)" + [ -n "$UPSTREAM" ] || die "branch '$BRANCH' has no upstream. Set it once: git branch --set-upstream-to=/ $BRANCH" + if ! git -C "$ROOT" diff --quiet || ! git -C "$ROOT" diff --cached --quiet; then + die "tracked files have local changes; --update will not pull over them. Commit or stash them first (git status --short)." + fi + git -C "$ROOT" fetch --quiet "${UPSTREAM%%/*}" || die "git fetch failed; nothing was changed." + BEFORE="$(git -C "$ROOT" rev-parse --short HEAD)" + git -C "$ROOT" merge --ff-only --quiet "$UPSTREAM" || die "'$BRANCH' cannot fast-forward to '$UPSTREAM' (rebased, force-pushed, or local commits). Nothing was merged; reconcile it yourself, then re-run." + AFTER="$(git -C "$ROOT" rev-parse --short HEAD)" + if [ "$BEFORE" = "$AFTER" ]; then echo "already up to date ($AFTER)"; else echo "$BEFORE -> $AFTER"; fi +fi + +if [ "$REBUILD" -eq 1 ] || [ ! -x "$ENGINE" ]; then + say "Building the engine (geometry q4_lite)" + cmake -G Ninja -S "$ROOT/engine" -B "$ROOT/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=$CUDA_ARCH" \ + -DCMAKE_C_COMPILER=gcc-14 -DCMAKE_CXX_COMPILER=g++-14 -DCMAKE_CUDA_HOST_COMPILER=g++-14 + cmake --build "$ROOT/build-q4lite" --target strata -j"$(nproc)" +fi + +if [ ! -f "$MODEL_DIR/$TRUNK" ]; then + say "1/4 Writing the 40-layer trunk view (quantized bytes are copied, not requantized)" + "$PY" "$ROOT/terminal/tools/qwen4_split_gguf.py" --gguf "$MODEL_DIR/$SHARD1" --out "$MODEL_DIR/$TRUNK" +fi +if [ "$PACK_OK" -eq 0 ]; then + say "2/4 Building the native pack" + "$PY" "$ROOT/terminal/tools/iq_pack.py" --gguf "$MODEL_DIR/$TRUNK" --out "$PACK_DIR" --compat-bf16 + pack_complete || die "iq_pack.py did not leave a complete pack in $PACK_DIR (native_experts.txt is the completion marker)." +fi +if [ ! -f "$PACK_DIR/expert-profile.bin" ]; then + say "3/4 Writing the even expert profile (40 layers x 256 experts)" + "$PY" "$ROOT/terminal/tools/make_profile.py" --no-base --n-layer 40 --n-expert 256 \ + --out "$PACK_DIR/expert-profile.bin" + [ -f "$PACK_DIR/expert-profile.bin" ] || die "make_profile.py did not write $PACK_DIR/expert-profile.bin." +fi +if [ "$MTP_OK" -eq 0 ]; then + say "4/4 Turning the MTP sidecar into a drafter runtime" + "$PY" "$ROOT/terminal/tools/mtp_qwen4_rt.py" --gguf "$MODEL_DIR/$MTP" --out "$PACK_DIR/mtp-rt" + mtp_complete || die "mtp_qwen4_rt.py did not leave a complete drafter runtime in $PACK_DIR/mtp-rt (complete.json is the completion record)." +fi + +say "Writing the run config" +"$PY" - "$ROOT" "$MODEL_DIR" "$PACK_DIR" "$CONFIG" "$SHARED" "$HOST" "$PORT" <<'PY' +import json, sys +from pathlib import Path +root, m, p, cfg_path, shared_path, host, port = sys.argv[1:] +cfg = { + "exe": str(Path(root) / "build-q4lite/strata"), + "args": [ + "--pack", str(Path(p)), + "--native", str(Path(m) / "trunk40/Qwen4-35B-A3B-UD-IQ4_XS-trunk40.gguf"), + "--native-dense-gguf", str(Path(m) / "trunk40/Qwen4-35B-A3B-UD-IQ4_XS-trunk40.gguf"), + "--ple-gguf", str(Path(m) / "UD-IQ4_XS/Qwen4-35B-A3B-UD-IQ4_XS-00002-of-00002.gguf"), + "--expert-profile", str(Path(p) / "expert-profile.bin"), + "--mtp", str(Path(p) / "mtp-rt"), + "--spec", "2", "--prefill", "auto", + "--max-context", "131072", "--kv-grow", "--vram-reserve-mib", "512", + ], + "cwd": str(Path(root)), + "tokenizer": str(Path(p) / "tokenizer"), + "model_name": "qwen4-35b-a3b-ud-iq4_xs", + "aliases": ["qwen4", "qwen4-35b", "Qwen4-35B-A3B"], + "display_name": "Qwen4-35B-A3B UD-IQ4_XS (MTP)", + "log": str(Path(root) / "terminal/strata-qwen4-35b-ud-iq4_xs.log"), + "port": int(port), "gpu": 0, "host": host, + "open_browser": False, "answer_room": True, "reasoning_budget_tokens": 512, +} +def publish(path, obj): + # Write beside the target, then rename: a crash never leaves a half-written config. + path = Path(path) + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(json.dumps(obj, indent=2) + "\n", encoding="utf-8") + tmp.replace(path) + +publish(cfg_path, cfg) +# Shared settings belong to the user: keep every existing key, only fill in missing defaults. +shared = {} +if Path(shared_path).exists(): + shared = json.loads(Path(shared_path).read_text(encoding="utf-8")) +shared.setdefault("max_tokens", 65536) +publish(shared_path, shared) +print("wrote", cfg_path) +print("wrote", shared_path) +PY + +if [ "$UPDATE" -eq 1 ]; then + say "Updated and rebuilt" + printf 'Start or restart the service now? [y/N] ' + read -r ANSWER || ANSWER="" + case "$ANSWER" in + y|Y|yes|YES) ;; + *) say "Not started. Start later with: $0"; exit 0 ;; + esac + # The old instance holds the port and the VRAM: stop it (identity-checked) before starting the new one. + stop_instance + VRAM_FREE_MIB="$(nvidia-smi -i 0 --query-gpu=memory.free --format=csv,noheader,nounits)" + [ "${VRAM_FREE_MIB:-0}" -ge 11264 ] || die "GPU 0 has only ${VRAM_FREE_MIB:-0} MiB free after stopping; serving needs about 11264 MiB." + SERVE=1 +fi + +if [ "$SERVE" -eq 0 ]; then + say "Ready (--build-only). Start with: cd terminal && .venv/bin/python -m serve.server --engine strata --config $(basename "$CONFIG") --host $HOST --port $PORT" + exit 0 +fi + +say "Serving on http://$HOST:$PORT/v1 (Ctrl-C stops; the first load takes 1-3 minutes)" +cd "$ROOT/terminal" +exec "$PY" -m serve.server --engine strata --config "$(basename "$CONFIG")" --host "$HOST" --port "$PORT" 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/serve/frontend.py b/terminal/serve/frontend.py index e6e5ec9826..bbc585f5d6 100644 --- a/terminal/serve/frontend.py +++ b/terminal/serve/frontend.py @@ -181,6 +181,12 @@ def _text_of(content) -> str: _EFFORT_QWEN = dict(EFFORT) +# Qwen4's own template has xhigh/high/low/off, defaults to high, and has no medium: the template raises on +# 'medium', so client 'medium' maps to the default 'high' instead of erroring; 'high' stays 'high' (not 'xhigh' +# as on Qwen3.8). It shares the GGUF architecture qwen4exp with Qwen3.8, so Service selects this table only +# from the tokenizer's pre="qwen4". +_EFFORT_QWEN4 = {"none": None, "off": None, "minimal": None, "disabled": None, "false": None, + "low": "low", "medium": "high", "high": "high", "xhigh": "xhigh", "max": "xhigh", "maximum": "xhigh"} _EFFORT_INKLING = {"none": None, "off": None, "disabled": None, "false": None, "minimal": "minimal", "low": "low", "medium": 0.4, "high": "high", "xhigh": "xhigh", "max": "max", "maximum": "max"} @@ -188,8 +194,8 @@ def _text_of(content) -> str: def use_family(family: str | None) -> None: - """The reasoning-effort words of the model family this server runs (module state, like ENV_TO_USER): the Qwen table, Hy4-Flash's - (its template knows no_think, high and max: serve/hy4_dialect.py), or Inkling 2's (minimal, low, medium, high, xhigh, max, or 0..0.99).""" + """The reasoning-effort words of the model family this server runs (module state, like ENV_TO_USER): the Qwen table, + Qwen4's own xhigh/high/low/off table, Hy4-Flash's (serve/hy4_dialect.py), or Inkling 2's.""" global _FAMILY _FAMILY = family EFFORT.clear() @@ -200,6 +206,9 @@ def use_family(family: str | None) -> None: if family == "inkling": EFFORT.update(_EFFORT_INKLING) return + if family == "qwen4": + EFFORT.update(_EFFORT_QWEN4) + return EFFORT.update(_EFFORT_QWEN) @@ -232,18 +241,23 @@ def effort_kwargs(value) -> dict: raise ValueError(f"unknown reasoning effort {value!r}: use none, minimal, low, medium, high, xhigh, max or 0..0.99") key = str(value).strip().lower() if key not in EFFORT: - raise ValueError(f"unknown reasoning effort {value!r}: use none, low, medium or high") + choices = "none, off, low, medium, high or xhigh" if _FAMILY == "qwen4" else "none, low, medium or high" + raise ValueError(f"unknown reasoning effort {value!r}: use {choices}") level = EFFORT[key] return {"enable_thinking": False} if level is None else {"reasoning_effort": level} def budget_effort(tokens) -> dict: - """Anthropic's thinking budget (budget_tokens) -> a level: under 2K low, under 8K medium, else high (clamped through EFFORT for Hy4-Flash).""" + """Anthropic's thinking budget -> low below 2K; Qwen4 uses high below 8K and xhigh above it, + while the generic Qwen dialect uses medium below 8K and its high (xhigh) above it.""" try: n = int(tokens) except (TypeError, ValueError): return {} - level = EFFORT.get("low", "low") if n < 2048 else EFFORT.get("medium", "medium") if n < 8192 else EFFORT["high"] + if _FAMILY == "qwen4": + level = EFFORT["low"] if n < 2048 else EFFORT["high"] if n < 8192 else EFFORT["xhigh"] + else: + level = EFFORT.get("low", "low") if n < 2048 else EFFORT.get("medium", "medium") if n < 8192 else EFFORT["high"] return {"reasoning_effort": level} diff --git a/terminal/serve/server.py b/terminal/serve/server.py index 6e2e3acbf6..95d4f6d5c5 100644 --- a/terminal/serve/server.py +++ b/terminal/serve/server.py @@ -4961,6 +4961,9 @@ def _read_tokenizer(self, tokenizer) -> None: if key in special} # how the model writes a tool call (serve/frontend.py's OutputParser) pre = getattr(tokenizer, "pre", "") + # Qwen4 and Qwen3.8 share qwen4exp in GGUF; only the tokenizer distinguishes Qwen4's effort dialect and + # its model-card sampling with MTP. Keep family=None: output parsing and tool markup use that structural value. + self.qwen4 = pre == "qwen4" self.call_format = "glm" if pre in ("glm4", "glm5", "flint", "laguna") else "gemma" if pre == "gemma4" else \ "dsml" if pre in ("joyai-llm", "deepseek-v3") else "lfm2" if pre == "lfm2" else \ "inkling" if pre == "inkling2" else "function" @@ -5019,10 +5022,10 @@ def _read_tokenizer(self, tokenizer) -> None: else PromptEncoder(tokenizer) def set_family(self, family: str | None) -> None: - """The model family (None: the Qwen form this server was written for).""" + """The structural model family (None: the Qwen form), with Qwen4's effort dialect selected separately.""" self.family = family import serve.frontend as _frontend - _frontend.use_family(family) + _frontend.use_family("qwen4" if family is None and getattr(self, "qwen4", False) else family) _force_text = None @@ -5256,14 +5259,15 @@ def model_config(self, target: dict) -> tuple[dict, dict, object, ChatTemplate]: cfg = apply_saved_tuning(run_config(target["config"], self.cfg_overrides)) except SystemExit as e: # read_config()'s word for a JSON mistake, with its place raise ValueError(f"{target['id']} cannot be loaded: {str(e).removeprefix('[strata] ')}") from None - try: - settings = model_settings(cfg, self.overrides) - except ValueError as e: - raise ValueError(f"{target['id']} cannot be loaded: its config: {e}") from None tpath = Path(cfg.get("tokenizer") or "") tok = load_tokenizer(tpath) if tok is None: raise ValueError(f"{target['id']} cannot be loaded: its tokenizer is missing ({tpath})") + try: + # The tokenizer identifies Qwen4 before its xhigh/high/low/off config is validated. + settings = model_settings(cfg, self.overrides, qwen4=getattr(tok, "pre", "") == "qwen4") + except ValueError as e: + raise ValueError(f"{target['id']} cannot be loaded: its config: {e}") from None tpl = tpath / "chat_template.jinja" return cfg, settings, tok, ChatTemplate(tpl if tpl.exists() else ROOT / "serve/chat_template.jinja") @@ -5644,7 +5648,7 @@ def read_shared(self, config_path) -> None: try: self.shared = clean_shared_defaults( json.loads(Path(self.shared_path).read_text(encoding="utf-8")), - hy4=self.hy4, inkling=self.call_format == "inkling") + hy4=self.hy4, inkling=self.call_format == "inkling", qwen4=self.qwen4) if self.shared: print("[strata] other apps use the settings: " + ", ".join(f"{k}={v}" for k, v in self.shared.items()), flush=True) @@ -6206,7 +6210,7 @@ def loop(): def set_shared(self, defaults) -> dict: """The settings every client gets for what it leaves out; {} / None = clients use their own again.""" - self.shared = clean_shared_defaults(defaults, hy4=self.hy4, inkling=self.call_format == "inkling") + self.shared = clean_shared_defaults(defaults, hy4=self.hy4, inkling=self.call_format == "inkling", qwen4=self.qwen4) if self.shared_path: try: if self.shared: @@ -7387,9 +7391,10 @@ def _run(self, ids, thinking, tools, max_new, sampling, cancel, force=None, `force` (forced_call): the opening of the call the reply must make - see prepare().""" # the model card's sampling for this thinking state, then the config's block, then the settings shared with # apps; the request's own fields win over all of them - # #3354: when MTP drafting is active (has_mtp) and the request does not explicitly ask for sampling, - # omitted sampling parameters remain greedy so MTP drafts are not silently disabled by model card defaults. - mtp_greedy = self.has_mtp and not request_asks_sampling(sampling, self.shared, self.sampling_defaults) + # #3354: MTP requests that specify no sampling stay greedy, except Qwen4: its official sampled defaults + # also apply with the MTP sidecar. Request/shared/config sampling still wins, and explicit zero stays greedy. + mtp_greedy = (self.has_mtp and not getattr(self, "qwen4", False) + and not request_asks_sampling(sampling, self.shared, self.sampling_defaults)) card = {} if mtp_greedy else model_card_sampling( self.model_arch, thinking, greedy=asks_greedy(sampling, self.shared, self.sampling_defaults), @@ -9590,7 +9595,8 @@ def _props(self): if not svc.loaded() and not getattr(svc.engine, "unloaded", False): self._json(503, {"error": {"message": "the engine is not running"}}) return - card_defaults = {} if (svc.has_mtp and not request_asks_sampling(svc.shared, svc.sampling_defaults)) else \ + card_defaults = {} if (svc.has_mtp and not getattr(svc, "qwen4", False) + and not request_asks_sampling(svc.shared, svc.sampling_defaults)) else \ model_card_sampling(svc.model_arch, True, greedy=asks_greedy(svc.shared, svc.sampling_defaults)) defaults = {**card_defaults, **svc.sampling_defaults, **svc.shared} @@ -10662,7 +10668,7 @@ def run_config(path, overrides: dict | None = None) -> dict: return cfg -def model_settings(cfg: dict, overrides: dict | None = None) -> dict: +def model_settings(cfg: dict, overrides: dict | None = None, qwen4: bool = False) -> dict: """#37: what a model's own run config sets on the Service ({attribute: value}), read at the start and again at every switch to that model (Service.apply_settings). `overrides` are the command line's --(no-)fit-max-tokens, --idle-unload, --min-free-vram-mib and --before-load, which win for every model. ValueError names a bad value; nothing is set @@ -10687,7 +10693,7 @@ def number(key, kind, words): is_ink = ("inkling" in str(cfg.get("model_name") or "").lower() or any("inkling" in str(x).lower() for x in (cfg.get("args") or ()))) effort = clean_shared_defaults({"reasoning_effort": cfg["reasoning_effort"]}, - hy4=hy4_kind.is_hy4(cfg), inkling=is_ink).get("reasoning_effort") + hy4=hy4_kind.is_hy4(cfg), inkling=is_ink, qwen4=qwen4).get("reasoning_effort") mode = str(cfg.get("anthropic_thinking") or "model") # #278: "on_request" = only when the request asks if mode not in ("model", "on_request"): raise ValueError(f"anthropic_thinking must be \"model\" or \"on_request\", not {mode!r}") @@ -11273,7 +11279,7 @@ def request_stop(reason: str): if a.pin_cache_mib is not None: overrides["pin_cache_mib"] = a.pin_cache_mib try: - settings = model_settings(cfg, overrides) # #37: the model's own settings, read again at every switch + settings = model_settings(cfg, overrides, qwen4=getattr(tok, "pre", "") == "qwen4") # #37: the model's own settings except ValueError as e: raise SystemExit(f"[strata] config {e}") if a.engine == "strata": @@ -11466,7 +11472,7 @@ def request_stop(reason: str): svc.models_root = Path(a.config).resolve().parent # the other models' configs are beside this one if a.config: # the settings shared with other apps, from last time svc.shared_path = str(Path(a.config).with_suffix("")) + ".shared-settings.json" - svc.shared = load_shared_settings(svc.shared_path) # #4933: one unknown key no longer clears the rest + svc.shared = load_shared_settings(svc.shared_path, qwen4=svc.qwen4) # #4933: one unknown key no longer clears the rest if svc.shared: print("[strata] other apps use the settings: " + ", ".join(f"{k}={v}" for k, v in svc.shared.items()), flush=True) diff --git a/terminal/serve/server_parts/http_api.py b/terminal/serve/server_parts/http_api.py index a767382769..7dc9688463 100644 --- a/terminal/serve/server_parts/http_api.py +++ b/terminal/serve/server_parts/http_api.py @@ -327,7 +327,7 @@ def origins_of(value, key: str, wildcard: bool) -> list[str]: "experimental_speed_projection") -def load_shared_settings(path, warn=print) -> dict: +def load_shared_settings(path, warn=print, qwen4: bool = False) -> dict: """The settings kept next to a config between starts, read so that one bad key cannot erase the others. The strict reader below belongs to POST /settings, where a client is there to be told which key is wrong and can @@ -352,13 +352,13 @@ def load_shared_settings(path, warn=print) -> dict: out = {} for key, value in doc.items(): try: - out.update(clean_shared_defaults({key: value})) + out.update(clean_shared_defaults({key: value}, qwen4=qwen4)) except ValueError as e: warn(f"[strata] one Chat setting in {path} is skipped ({e}); the others still apply") return out -def clean_shared_defaults(d, hy4: bool = False, inkling: bool = False) -> dict: +def clean_shared_defaults(d, hy4: bool = False, inkling: bool = False, qwen4: bool = False) -> dict: """The settings other apps get (POST /settings): only known keys, each checked; ValueError names a bad one.""" if d is None: return {} @@ -376,6 +376,9 @@ def clean_shared_defaults(d, hy4: bool = False, inkling: bool = False) -> dict: raise ValueError("reasoning_effort: none, minimal, low, medium, high, xhigh, max or 0..0.99") elif value not in ("none", "minimal", "low", "medium", "high", "xhigh", "max"): raise ValueError("reasoning_effort: none, minimal, low, medium, high, xhigh, max or 0..0.99") + elif qwen4: + if value not in ("none", "off", "low", "medium", "high", "xhigh"): + raise ValueError("reasoning_effort: none, off, low, medium, high or xhigh") elif value not in ("none", "low", "medium", "high") + (("max",) if hy4 else ()): # Hy4's template also has max raise ValueError("reasoning_effort: none, low, medium, high or max" if hy4 else "reasoning_effort: none, low, medium or high") diff --git a/terminal/serve/test_effort_paths.py b/terminal/serve/test_effort_paths.py index 78ac23c900..5efae7ac2e 100644 --- a/terminal/serve/test_effort_paths.py +++ b/terminal/serve/test_effort_paths.py @@ -11,14 +11,18 @@ import json import sys +import tempfile import unittest import urllib.error import urllib.request from pathlib import Path +from unittest import mock sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from serve.frontend import ChatTemplate # noqa: E402 -from serve.server import ByteTokenizer, MockEngine, Service, serve # noqa: E402 +from serve import frontend # noqa: E402 +from serve.server import ByteTokenizer, MockEngine, Service, model_settings, serve # noqa: E402 +from serve.server_parts.http_api import clean_shared_defaults, load_shared_settings # noqa: E402 ROOT = Path(__file__).resolve().parents[1] MSG = [{"role": "user", "content": "hello"}] @@ -190,5 +194,155 @@ def test_the_agents_request_shape_with_thinking_off(self): self.assertEqual(self.level("/v1/chat/completions", {"messages": MSG, "chat_template_kwargs": {"enable_thinking": False}, "reasoning_effort": "none"}), "none") +class Qwen4EffortPaths(unittest.TestCase): + """Qwen4's own template dialect: high stays high, client medium maps to high (the template itself has no + medium and would raise), and MTP is irrelevant here. + + A minimal template is deliberate. The generic Qwen template maps high to xhigh itself, which would hide + a frontend that made the same mistake before the model's template ever saw the value. + """ + + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory() + cls.template_path = Path(cls.tmp.name) / "chat_template.jinja" + cls.template_path.write_text( + "{{ 'off' if enable_thinking is false else (reasoning_effort | default('high', true)) }}", + encoding="utf-8") + cls.tok = ByteTokenizer() + cls.tok.pre = "qwen4" + cls.engine = MockEngine(cls.tok, "\nhm\n\n\nok", max_context=8192) + cls.svc = Service(cls.engine, cls.tok, ChatTemplate(cls.template_path)) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + cls.tmp.cleanup() + frontend.use_family(None) # EFFORT is module state; do not leak Qwen4 into other test modules + + def setUp(self): + self.svc.config_effort = None + self.svc.shared = {} + self.svc.shared_path = None + self.svc.set_family(None) + + def post(self, path, body): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + self.engine.last_prompt = [] + try: + with urllib.request.urlopen(req, timeout=30) as r: + status = r.status + r.read() + except urllib.error.HTTPError as e: + with e: + status = e.code + e.read() + return status + + def level(self, path, body): + status = self.post(path, body) + self.assertEqual(status, 200, (path, body)) + return self.tok.decode(self.engine.last_prompt) + + def test_tokenizer_selects_qwen4_without_changing_the_structural_family(self): + self.assertTrue(self.svc.qwen4) + self.assertIsNone(self.svc.family) + self.svc.set_family(None) # _main() repeats this after Service._read_tokenizer() + self.assertIsNone(self.svc.family) + self.assertEqual(frontend.effort_kwargs("high"), {"reasoning_effort": "high"}) + self.assertEqual(frontend.effort_kwargs("xhigh"), {"reasoning_effort": "xhigh"}) + self.assertEqual(frontend.effort_kwargs("medium"), {"reasoning_effort": "high"}) + with self.assertRaises(ValueError): + frontend.effort_kwargs("huge") + + def test_openai_effort_levels(self): + cases = ((None, "high"), ("none", "off"), ("off", "off"), ("minimal", "off"), + ("low", "low"), ("medium", "high"), ("high", "high"), ("xhigh", "xhigh"), ("max", "xhigh"), + ("HIGH", "high"), (False, "off")) + for given, want in cases: + body = {"messages": MSG, **({} if given is None else {"reasoning_effort": given})} + with self.subTest(given=given): + self.assertEqual(self.level("/v1/chat/completions", body), want) + for body in ({"messages": MSG, "reasoning": {"effort": "high"}}, + {"messages": MSG, "chat_template_kwargs": {"reasoning_effort": "xhigh"}}, + {"messages": MSG, "chat_template_kwargs": {"enable_thinking": False}}): + want = "off" if (body.get("chat_template_kwargs") or {}).get("enable_thinking") is False else \ + (body.get("reasoning") or body.get("chat_template_kwargs"))["effort" if "reasoning" in body else "reasoning_effort"] + self.assertEqual(self.level("/v1/chat/completions", body), want) + self.assertEqual(self.level("/v1/chat/completions", {"messages": MSG, "reasoning_effort": "medium"}), "high") + self.assertEqual(self.post("/v1/chat/completions", {"messages": MSG, "reasoning_effort": "huge"}), 400) + + def test_anthropic_effort_and_budget(self): + for given, want in (("low", "low"), ("medium", "high"), ("high", "high"), ("xhigh", "xhigh")): + with self.subTest(effort=given): + self.assertEqual(self.level("/v1/messages", {"messages": MSG, "max_tokens": 50, + "output_config": {"effort": given}}), want) + for budget, want in ((500, "low"), (2047, "low"), (2048, "high"), (8191, "high"), + (8192, "xhigh"), (31999, "xhigh")): + with self.subTest(budget=budget): + self.assertEqual(self.level("/v1/messages", {"messages": MSG, "max_tokens": 50, + "thinking": {"type": "enabled", "budget_tokens": budget}}), want) + self.assertEqual(self.level("/v1/messages", {"messages": MSG, "max_tokens": 50, + "thinking": {"type": "disabled"}}), "off") + self.assertEqual(self.level("/v1/messages", {"messages": MSG, "max_tokens": 50}), "high") + self.assertEqual(self.level("/v1/messages", {"messages": MSG, "max_tokens": 50, + "output_config": {"effort": "medium"}}), "high") + self.assertEqual(self.post("/v1/messages", {"messages": MSG, "max_tokens": 50, + "output_config": {"effort": "huge"}}), 400) + + def test_responses_effort_levels(self): + for given, want in (("low", "low"), ("medium", "high"), ("high", "high"), ("xhigh", "xhigh"), + ("none", "off"), ("minimal", "off")): + with self.subTest(given=given): + self.assertEqual(self.level("/v1/responses", {"input": "hello", "reasoning": {"effort": given}}), want) + self.assertEqual(self.level("/v1/responses", {"input": "hello"}), "high") + self.assertEqual(self.level("/v1/responses", {"input": "hello", "reasoning": {"effort": "medium"}}), "high") + self.assertEqual(self.post("/v1/responses", {"input": "hello", "reasoning": {"effort": "huge"}}), 400) + + def test_config_and_shared_levels_reach_every_api(self): + for source in ("config", "shared"): + for given, want in (("low", "low"), ("medium", "high"), ("high", "high"), ("xhigh", "xhigh"), ("off", "off")): + self.svc.config_effort = given if source == "config" else None + self.svc.shared = {"reasoning_effort": given} if source == "shared" else {} + for path, body in (("/v1/chat/completions", {"messages": MSG}), + ("/v1/messages", {"messages": MSG, "max_tokens": 50}), + ("/v1/responses", {"input": "hello"})): + with self.subTest(source=source, given=given, path=path): + self.assertEqual(self.level(path, body), want) + + def test_shared_settings_and_config_validate_qwen4_levels(self): + for given in ("none", "off", "low", "medium", "high", "xhigh"): + with self.subTest(given=given): + self.assertEqual(clean_shared_defaults({"reasoning_effort": given}, qwen4=True), + {"reasoning_effort": given}) + self.assertEqual(model_settings({"reasoning_effort": given}, qwen4=True)["config_effort"], given) + for given in ("huge",): + with self.subTest(invalid=given): + with self.assertRaises(ValueError): + clean_shared_defaults({"reasoning_effort": given}, qwen4=True) + with self.assertRaises(ValueError): + model_settings({"reasoning_effort": given}, qwen4=True) + self.assertEqual(self.post("/settings", {"defaults": {"reasoning_effort": "xhigh"}}), 200) + self.assertEqual(self.post("/settings", {"defaults": {"reasoning_effort": "medium"}}), 200) + self.assertEqual(self.post("/settings", {"defaults": {"reasoning_effort": "huge"}}), 400) + path = Path(self.tmp.name) / "shared.json" + path.write_text(json.dumps({"reasoning_effort": "xhigh", "max_tokens": 32}), encoding="utf-8") + self.assertEqual(load_shared_settings(path, qwen4=True), {"reasoning_effort": "xhigh", "max_tokens": 32}) + + def test_model_switch_config_reads_the_tokenizer_before_validating_effort(self): + cfg = {"tokenizer": self.tmp.name, "reasoning_effort": "xhigh", "args": []} + target = {"id": "qwen4-test", "config": str(Path(self.tmp.name) / "model.json")} + with mock.patch("serve.server.run_config", return_value=cfg), \ + mock.patch("serve.server.apply_saved_tuning", side_effect=lambda value: value), \ + mock.patch("serve.server.load_tokenizer", return_value=self.tok): + _, settings, tok, _ = self.svc.model_config(target) + self.assertIs(tok, self.tok) + self.assertEqual(settings["config_effort"], "xhigh") + + if __name__ == "__main__": unittest.main() diff --git a/terminal/serve/test_model_card_sampling.py b/terminal/serve/test_model_card_sampling.py index 5474038dcb..e44be33ad0 100644 --- a/terminal/serve/test_model_card_sampling.py +++ b/terminal/serve/test_model_card_sampling.py @@ -55,10 +55,15 @@ def setUp(self): self.svc.sampling_defaults = {} self.svc.shared = {} self.svc.config_effort = None + self.svc.qwen4 = False + self.svc.has_mtp = False + self.svc.set_family(None) def tearDown(self): self.svc.model_arch = None + self.svc.qwen4 = False self.svc.has_mtp = False + self.svc.set_family(None) def keys(self, **body): body = {"model": "m", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 8, **body} @@ -68,6 +73,10 @@ def keys(self, **body): urllib.request.urlopen(req, timeout=10).read() return StrataEngine.sampling_keys(self.engine.sampling) + def props(self): + with urllib.request.urlopen(self.base + "/props", timeout=10) as response: + return json.load(response)["default_generation_settings"]["params"] + def test_tables(self): self.assertEqual(model_card_sampling("qwen4exp", True), {"temperature": 1.0, "top_p": 0.95, "top_k": 20}) self.assertEqual(model_card_sampling("qwen4exp", False), @@ -165,6 +174,47 @@ def test_mtp_explicit_zero_stays_greedy(self): self.assertNotIn("temperature", k) self.assertNotIn("penalty_present", k) + def test_qwen4_mtp_uses_the_model_card_by_default(self): + # Qwen4 and Qwen3.8 share the qwen4exp GGUF architecture. Only pre=qwen4 opts out of #3354's + # MTP greedy default: Qwen4's official sampled settings are the default even with its MTP sidecar. + self.svc.qwen4 = True + self.svc.has_mtp = True + self.svc.set_family(None) + k = self.keys() + self.assertIn("temperature=1.0", k) + self.assertIn("top_p=0.95", k) + self.assertIn("top_k=20", k) + k = self.keys(reasoning_effort="none") + self.assertIn("temperature=0.7", k) + self.assertIn("top_p=0.8", k) + self.assertIn("top_k=20", k) + self.assertIn("penalty_present=1.5", k) + props = self.props() + self.assertEqual(props["temperature"], 1.0) + self.assertEqual(props["top_p"], 0.95) + self.assertEqual(props["top_k"], 20) + + def test_qwen4_mtp_explicit_zero_and_overrides_still_win(self): + self.svc.qwen4 = True + self.svc.has_mtp = True + self.svc.set_family(None) + k = self.keys(temperature=0, reasoning_effort="none") + self.assertNotIn("temperature", k) + self.assertNotIn("penalty_present", k) + self.svc.sampling_defaults = {"temperature": 0.6, "top_k": 40} + self.assertIn("temperature=0.6", self.keys()) + self.assertIn("top_k=40", self.keys()) + self.svc.shared = {"temperature": 0.2} + self.assertIn("temperature=0.2", self.keys()) + self.assertIn("temperature=0.3", self.keys(temperature=0.3)) + + def test_other_qwen4exp_mtp_default_stays_greedy(self): + # pre is not qwen4: Qwen3.8-Flash-Next keeps the existing MTP behaviour. + self.svc.qwen4 = False + self.svc.has_mtp = True + self.assertEqual(self.keys(), "") + self.assertNotIn("temperature", self.props()) + def test_request_asks_sampling(self): self.assertFalse(request_asks_sampling()) self.assertFalse(request_asks_sampling({})) diff --git a/terminal/tools/iq_pack.py b/terminal/tools/iq_pack.py index d62801664d..67e8552533 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): @@ -724,16 +762,21 @@ def layer_blobs(l, blob, ts): htmp.replace(out / "hadamard.txt") else: (out / "hadamard.txt").unlink(missing_ok=True) # a previous Hadamard model's, packed into this folder - 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") + def publish_native_experts(): + # This is the pack's completion marker: publish it only after every selected expert artifact is complete. + 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) + publish_native_experts() return 0 if reuse: print("experts.bin was cut from this model's shards (%s); not rewritten" % sidecar.name) + publish_native_experts() 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 @@ -784,6 +827,7 @@ def layer_blobs(l, blob, ts): 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) + publish_native_experts() print("experts.bin: %d layers, %.2f GiB" % (len(layout), offset / 2**30)) return 0 diff --git a/terminal/tools/make_profile.py b/terminal/tools/make_profile.py index cf8599c09a..3e45616374 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,58 @@ 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("