Skip to content

[Engine] support Qwen4-35B-A3B (qwen4exp) with MTP and 128K serving - #430

Closed
skygunner wants to merge 18 commits into
simplexai-labs:mainfrom
skygunner:qwen4-35b
Closed

skygunner wants to merge 18 commits into
simplexai-labs:mainfrom
skygunner:qwen4-35b

Conversation

@skygunner

@skygunner skygunner commented Dec 4, 2026 •

Copy link
Copy Markdown

Problem and result

PolyStrata refuses the published Qwen4-35B-A3B GGUF (qwen4exp), while mainline llama.cpp can run it. This branch makes Unsloth's UD-IQ4_XS file usable on the existing Strata engine path, including the model's own MTP drafter and the serving APIs.

On one RTX 3080 Ti 12 GB with 46 GB RAM, the same teacher-forced 256-token workload decodes at 155.32 tok/s with MTP --spec 2 versus 106.12 tok/s without it (+46%). The server runs at 131072 tokens of context with --kv-grow. A real 117-request agent session, with prompts growing to about 78K tokens and 97% prompt reuse, averaged 192.9 tok/s decode and 1,906 tok/s prefill.

Addresses #425, and the serving effort bug reported in #437 (see below). The related Strata implementation is Niko1221/Strata#7774; the differences are listed below.

Serving monitor during the 117-request session: 192.9 tok/s decode, 1,906 tok/s prefill, 3,305 cached experts

Why the published file cannot simply be loaded

The file has four independent mismatches with this engine, and the branch handles each separately:

  1. block_count includes the drafter. The published file has 41 blocks: 40 trunk layers plus one in-file nextn/MTP block. read_geometry starts from the compiled shape, so a trunk view without nextn_predict_layers inherited n_mtp_layers = 1 from q4_lite and was rejected: 41 layers against a 40-entry attention.compress_ratios array. The reader now resets that field before reading the key, validates the array over trunk + MTP (the MTP block is full attention), and treats it as file layout rather than a kernel shape. compiled_geometry_mismatch no longer compares it, so builds and trunk views with either declaration accept each other.

  2. tokenizer.ggml.pre = qwen4 needs ignore_merges. It uses the qwen35 split pattern and vocabulary, but llama.cpp master sets ignore_merges = true for qwen4 and not for qwen35. About 201 single-piece vocabulary entries, mostly multi-character CJK such as 俱乐部, cannot be produced by any merge chain. Accepting qwen4 without that flag would silently split Chinese incorrectly. The tokenizer therefore aliases the split rule but adds qwen4 to IGNORE_MERGES, with a regression test that distinguishes the two rules even when no merges are present.

  3. Four projections are fused. attn_qkv_gate, ssm_beta_alpha, hc_attn_down_inject and hc_ffn_down_inject each contain two projections concatenated along output rows. qwen4_split_gguf.py writes a 40-layer trunk view and separates them by copying quantized byte rows: every format involved (Q8_0, Q5_K, Q4_K, IQ4_XS) is self-contained along the input dimension, so no dequantize/requantize round trip and no quantization loss is involved. It also truncates the per-layer metadata and drops blk.40 and the PLE table. iq_pack.py refuses a file that still carries fused names and points to the splitter, preventing an accidental pack from the unsplit shard. The second published shard is passed separately as --ple-gguf; it contains only per_layer_token_embd.weight.

  4. The MTP block is a drafter, not trunk layer 40. mtp_qwen4_rt.py repackages the Q8_0 sidecar as the drafter runtime used by --mtp. --spec 2 is the measured optimum on this card; wider windows propose more tokens but accept fewer and read more experts from RAM. The drafter costs 1,915 MiB of VRAM, which is why the speedup is reported against a no-MTP run rather than assumed.

Serving needs no separate engine protocol work. terminal/models.json supplies registry facts that cannot be derived from this config (it names its GGUF with --native; --model is only read by the qwen35moe pre-scan). The documented run config uses --max-context 131072 --kv-grow, which allocates KV only for cells actually reached instead of reserving the whole context up front, and reasoning_budget_tokens: 512 to close the think block politely and leave room for the answer.

Serving correctness (new in 52c562f)

Qwen4's reasoning-effort dialect — fixes #437. Qwen4's official levels are xhigh/high/low/off, default high; the template itself has no medium and raises on it. The generic Qwen table was translating high to xhigh and passing medium through, which the template rejects with an HTTP 400. The server now selects Qwen4's own table from the tokenizer's pre="qwen4" — not from the GGUF architecture, which Qwen3.8-Flash-Next shares — on all three API paths, in the run config, in shared settings and in POST /settings. A client's medium maps to the template's default high instead of erroring (a742ed0, the same mapping upstream's table carries), so clients that only know the generic words — polystrata.py --think defaults to medium — keep working; truly unknown words still 400. Anthropic's thinking.budget_tokens maps to low below 2048, high from 2048 to 8191 and xhigh from 8192. Service.family keeps its structural None, so output parsing and tool markup are unchanged. The tokenizer is read before the config's effort value is validated, so a Qwen4 config with xhigh loads.

Model-card sampling with MTP. For other models, an MTP request that names no sampling stays greedy (#3354). Qwen4 was silently losing its official sampled defaults the same way. A Qwen4 request with MTP now uses the model card when it names no sampling — thinking temperature 1.0, top_p 0.95, top_k 20; non-thinking 0.7 / 0.80 / 20 / presence_penalty 1.5. Explicit request fields, shared settings and the config's sampling block still win, an explicit temperature: 0 is still greedy, and GET /props reports the same defaults the generation path uses. Non-Qwen4 qwen4exp models keep the old behaviour.

The drafter now runs the model's own indexer (updated in aecfe3c). mtp_qwen4_rt.py converts the indexer tensors and the engine runs the MTP QSA selection; STRATA_MTP_INDEXER=0, or a sidecar without them, keeps the earlier dense-attention approximation. The target still verifies every draft either way, so an accepted token is the target's own. The quoted acceptance (0.703 at --spec 2) and the speeds in this section remain the approximation's numbers on the tested box, and are still valid for that configuration. The indexer section below has the long-context A/B and an out-of-bounds write the work exposed. --mtp-hnorm now defaults to stream on reference-implementation and same-box A/B evidence; --spec-min-p stays 0.0 because its sweep landed inside this box's run-to-run noise.

preserve_thinking is documented as two different things: the template preserves reasoning the client sends back in history; the server-side memory that restores reasoning when the client returns only answer text is the opt-in run-config key, which the runner does not enable.

Conversion integrity and the runner (new in 52c562f)

The preparation chain is now crash-safe, with a fail-first regression for each change:

  • iq_pack.py publishes native_experts.txt — the pack's completion marker — last, after every selected expert artifact. An interrupted run leaves no marker; a resume does not depend on it; a complete old pack survives a later interrupted index write.
  • qwen4_split_gguf.py and mtp_qwen4_rt.py write beside the target and rename only on success. A failed or interrupted conversion keeps the previous output and leaves no temporary file; the quantized-byte-split assertions are unchanged. The MTP set carries a size-checked complete.json published last.
  • make_profile.py writes atomically. Tokenizer.from_dir() reads an empty merge set as [] (a Qwen4 export previously became unloadable), extract() records the correct qwen4 provenance, and qwen4_intake.py points the Qwen4 drafter at mtp_qwen4_rt.py (Flash-Next keeps mtp_pack.py) and classifies a pre="qwen4" set as case A.
  • qwen4-run.sh preflights before any download or build: GPU 0's free VRAM, a bindable serving port, RAM, and free disk on the filesystems that would hold the model and the pack. --check changes nothing. It installs the full terminal/requirements.txt (a fresh clone previously missed regex/jinja2), detects the CUDA architecture instead of hard-coding sm_86, reuses artifacts only when complete, writes the config atomically, merges shared settings without overwriting user keys, and carries the models.json aliases into the config. The download path is unchanged — this is a correctness pass, not a new download mechanism.
  • complete.json now also states whether the runtime carries the drafter's indexer (cc5faef). The launcher previously reused any mtp-rt whose four artifact sizes matched its own record — and a runtime converted before the indexer existed is exactly that: self-consistent, 28 tensors, no indexer. ./qwen4-run.sh therefore kept serving the dense-attention approximation and never reconverted; the only way out was to run mtp_qwen4_rt.py by hand, which defeats a one-command launcher. Sizes cannot distinguish the two, so the record says which one it is: the converter writes an indexer boolean read back from the dense.txt it just published, and mtp_complete() requires the field — a record without it predates the indexer and is reconverted (fail-closed). A current record is still reused, so the steady state costs nothing. Fail-first on the old code: KeyError: 'indexer' in both converter tests, and the launcher assertion that a stale runtime is rebuilt got returncode 0 because it was accepted.
  • --update and --stop (54d2e10) are fork-local convenience and may be dropped from this PR in full. qwen4-run.sh builds a source checkout, whereas upstream's update path installs signed prebuilt engines (strata update) and does not rebuild a checkout, so this fills a gap only this fork has. --update requires a git checkout on a branch with an upstream, refuses to pull over tracked local changes, fetches and merges --ff-only (a rebased, force-pushed or locally-committed branch is refused with nothing merged), rebuilds, then asks before starting or restarting; the default answer is no. --stop selects a process by command line, working directory and start-time token, leaves an unreadable identity alone and reports it, re-checks the token before escalating from SIGTERM to SIGKILL so a recycled PID is not killed, and matches the engine child by parent PID and executable path. Two changes in that commit are defect fixes rather than convenience, and are worth keeping if the flags are dropped: --help used a fixed line range and leaked shell code from the script body (set -euo pipefail, ROOT=, MODEL_DIR=, PACK_DIR=), and the free-VRAM gate ran unconditionally, so it refused --build-only and --update whenever a running server already held the card. The gate now applies only when serving and is re-checked after a stop.
  • The three test_qwen4_split_gguf.py tests that hit PermissionError [WinError 32] on Windows (reported by @qron88 below) now use ignore_cleanup_errors=True, the convention already used in test_iq_pack.py. Assertions are unchanged; the mmap cleanup race is a test-harness issue, not a conversion issue.

MTP indexer (MTP QSA) and a context-dependent overflow (new in aecfe3c)

The sidecar's blk.40.indexer.{q_proj,k_proj,q_norm,k_norm} are converted and loaded, and the draft layer runs the
trunk's own selection: project the indexer key, pool and rotate it on block completion, score every block, take the
top-k, attend to the selected cells. 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.

A real out-of-bounds write, exposed by the long-context runs. qsa_block_topk treats n_kv <= step[kStepWidth] as
"everything is selected" and then writes n_kv ascending ids into a buffer holding cap ids per query. The dense path
is safe: its cap is sized to the context and window_ids overwrites the width. The indexer's cap is the constant
selection width (2,051) and nothing overwrites the 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. All five host fill sites now go through
MtpDrafter::fill_step, which calls qsa_step_fill (the quadruple's one writer) for the indexer and keeps the old
arithmetic for the dense path. can_draft_slots also declines a batch whose slots disagree on indexer_ or, with the
indexer on, on max_cells, because the batch pass scores every slot with this drafter's max_blocks_.

mtp_step_test is the fail-first regression: 16 checks failed on the old filling, 30,751 ids past the buffer at a
32,802-cell context and 63,519 at 65,570. It passes after the fix.

64K prompt (65,570 tokens of real repository prose with a needle 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:

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
. Those two batches read 52-72 GB/s under accumulated swap pressure, so their decode timings are
deliberately not quoted; the acceptance counts and the needle check are.

The conversation snapshot carries the drafter's whole indexer block with its K/V, because the drafter has no turn
checkpoint. 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 there because its checkpoint exists.

--mtp-hnorm defaults to stream (new in 96025b9)

pre_fc_norm_hidden.weight is 8192 = 4 x 2048 wide, and every reference reading normalizes each hyper-connection
stream on its own
, scaled by its slice of that weight: upstream's q4_mtp_eh_concat_kernel (one block per
token/stream, sums squares over n_embd only, reads w_hnorm + c * n_embd), llama.cpp's qwen4exp MTP graph, and
mtp_qwen4_rt.py's own docstring ("applied per hc stream to hnorm(h)"). pooled — one RMS over all four — matches
none of them. It was the default only because it was frozen pending a same-box A/B. That measurement is done.

32K prompt, two runs of each, same box and settings as above:

--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). After the flip, two runs with no flag
measured 0.789 / 0.838 acceptance at 143.98 / 141.55 tok/s. pooled stays available as the opt-out, and the setup paths
that already passed --mtp-hnorm stream are unchanged. The DGX Spark data point below independently recorded stream
at +4.3% decode.

--spec-min-p stays 0.0. Swept at 0.05 / 0.10 / 0.20 / 0.40 on the indexer path, one run per value:
non-monotonic and inside this box's run-to-run spread. The spread is worth knowing before reading any acceptance number
here — two runs of an identical configuration (--mtp-q4 proj and all, the same on this pack because the draft head's
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. One run per
value cannot settle the flag.

--mtp-q4 stays opt-in. Its 4-bit copies are additive, not a replacement: the prompt path's batched K/V pass keeps
the Q8_0 originals. On this 12 GB card 11 projections cost +566 MiB and displaced resident experts (3000 -> 2974), so
acceptance rose while decode did not. That is a residency result, not a verdict on Q4_0 drafting; the DGX Spark
measurement of --mtp-q4 all was +3.5%.

Run it

From a fresh clone of this branch:

git clone -b qwen4-35b https://github.com/skygunner/PolyStrata.git
cd PolyStrata
./qwen4-run.sh --download   # omit --download if the three Unsloth files are already present

--check performs only the preflight; --build-only prepares without serving. The equivalent manual commands and the complete config are in docs/QWEN4.md (English) and docs/QWEN4.zh-CN.md (Chinese); the user guide is docs/models/qwen4.md (English) and docs/models/qwen4.zh-CN.md (Chinese). Each pair is kept fact-for-fact consistent.

Validation

Revision: f6b10a4 (supersedes 54d2e10, 848286c, 9353f58, 52c562f and 99376fc). Linux, RTX 3080 Ti 12288 MiB (sm_86), 46 GB RAM, CUDA 12.8, gcc/g++ 14, engine 0.1.66, Unsloth UD-IQ4_XS.

Every new regression was run against the old code first and failed there (16 failures + 9 errors in the effort paths, 1 failure in the MTP sampling default, the tokenizer round-trip error, the drafter-advice failure, the completion-marker and atomic-output failures, 5 of 6 launcher behaviour failures), then passed after the minimal fix. No existing test was removed or weakened. The later engine work added two more fail-first regressions: mtp_step_test failed 16 checks on the old step filling (up to 63,519 ids written past the ids buffer), and the G=8 parity gate failed 468/468 cases on the old qsa_pattn kernel. Both pass after the fix. The launcher staleness fix added three more: two KeyError: 'indexer' errors in the converter tests, and one launcher assertion that got returncode 0 on the old code because the pre-indexer runtime was accepted as complete. The ten --update/--stop regressions also failed on the old launcher (unknown option: --update; --help printing shell code). Two of them first failed for a fixture reason — the bare test remote's HEAD named a branch that did not exist, so the clone checked out nothing — and once the fixture was corrected they were re-run against the committed old script and failed there as well. The medium→high mapping rewrote the Qwen4EffortPaths assertions that had pinned the old rejection: on the old code the updated class ran 19 tests with 13 failures and 2 errors, all on the medium paths, and passes after the mapping was added to the frontend table and the shared-settings validator (the 19-module serving suite re-ran at 826 tests, 3 skipped, all passing).

Passed at the new revision:

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
# Ran 125 tests — OK (skipped=4; the skips need a tokenizer fixture that is not present)

.venv/bin/python -m unittest serve.test_effort_paths serve.test_model_card_sampling \
    serve.test_frontend serve.test_models serve.test_model_check serve.test_model_gate \
    serve.test_preserve_thinking serve.test_hy4_dialect serve.test_inkling serve.test_server \
    serve.test_security serve.test_chunked_body serve.test_reasoning_tools \
    serve.test_reasoning_rescue serve.test_reasoning_loop_recovery \
    serve.test_parser_bare_reasoning_call serve.test_parser_think_end_quotes \
    serve.test_thinking_hold serve.test_thinking_hold_batch
# Ran 826 tests — OK (skipped=3)

Engine-side regressions at this revision (GPU build, sm_86, -DSTRATA_GEOMETRY=q4_lite):

./build-q4lite-tests/mtp_step_test                 # ok  (fail-first on the old code: 16 failed)
./build-q4lite-tests/conversation_snapshot_test    # 4639 checks passed
ctest --test-dir build-q4lite-tests                # 426 of 448 pass

The 22 CTest failures are the pre-existing set plus two attributed ones, neither touched by this PR:

  • native_i8_parity — filed upstream as #490. It fails 3/3 with this PR's engine changes stashed, and then 3/3 on a clean upstream main checkout at df2c3ff30 built from the identical sources. It is not tolerance noise: the test seeds its RNG with a constant (rng(20261112)), yet 3 of its 90 configurations flip between runs while 87 stay bit-stable, the relative RMS against native_expert_grouped reaches 1.80 against a 5e-3 tolerance (healthy runs: 1.7–2.3e-03), and the kernel sometimes disagrees with itself between two passes inside one process. Every failing assertion is in check_carved at H=512, FF=256; the plain check() path never failed in six runs. native_expert_i8 is a research kernel that is off by default on this card class, so default serving is unaffected. Not fixed here — a separate PR will reference native_i8_parity fails intermittently on main: carved-layout output is non-deterministic under a fixed seed, relative RMS up to 1.8 vs 5e-3 #490.
  • poly_bell_test — passes when the machine is idle (16 checks, 0 failed); a load-sensitive timing flake under parallel build/test load.

The test count rose from 430 to 448 because STRATA_BUILD_CONVERSATION_TESTS was enabled and mtp_step_test added.

The launcher tests run offline with fake hardware and tools: no download, compilation, GPU or server. A real ./qwen4-run.sh --check on the measurement box correctly refused to proceed while another workload held the GPU (250 MiB free), before creating anything.

The engine was built with -DSTRATA_GEOMETRY=q4_lite and executed on the GPU, not merely compiled. Both serving protocols were exercised at 99376fc: /v1/chat/completions and /v1/messages, including correct end-of-turn stops and Chinese answers. At the shipped 128K configuration, a Chinese answer decoded at 165.5 tok/s and a 24,282-token prompt read at 2,899 tok/s. Those two serving numbers remain the earlier runs on this box; no running service was restarted for the later revisions. The indexer, --mtp-hnorm and --spec-min-p work was measured with strata generate on the GPU at the revisions named in their sections above, not through the serving APIs.

MTP was compared both with natural decode and with --spec-follow on identical text:

Drafter Same-text decode Acceptance
none (--spec 2, suffix drafts) 106.12 tok/s 0.056
MTP --spec 2 155.32 tok/s 0.703
MTP --spec 3 146.99 tok/s 0.516
MTP --spec 4 128.33 tok/s 0.383

Every quoted run passed the CPU-pool bandwidth validity gate documented in the page (healthy: 60–70 GB/s).

Failed / discarded measurements

One --spec 4 run measured 23.74 tok/s while the CPU pool read only 1.2 GB/s with 8.9 GB of zram in use. It was discarded as memory-pressure contamination, not reported as a performance cliff. The same setting measured 126.87 tok/s at 66.5 GB/s. No test failures remain.

Not run

  • HIP and SYCL builds, AMD/Intel execution, and Windows execution by this PR's author. The WMMA change is inside the existing HIP-only path but has not been executed on AMD here; @Keoian's HIP data point below covers gfx1010 (no WMMA there).
  • Any quantization other than UD-IQ4_XS, or cards below 12 GB, by this PR's author (community data points below cover UD-Q4_K_XL on 2x8 GB AMD and IQ3_XS on 8 GB Windows).
  • Concurrent requests, vision (mmproj-F16.gguf is not wired), and the DFlash2 drafter.
  • Installer/setup-menu execution: this model is not in the menu yet.
  • --spec-min-p: swept once per value, non-monotonic and inside the run-to-run spread, so the default stays 0.0; it needs repeated runs per value. (--mtp-hnorm was A/B'd twice per value and its default changed — see above.)
  • IQ4_NL drafting: no such file on this box and no HF source weights, so it is neither implemented nor measured. It stays a direction, not a result.
  • The G=8 qsa_pattn kernel's end-to-end effect: it is SM60-gated and this geometry's production sm_86 build does not compile it, so serving behaviour here is unchanged. Its evidence is the parity gate, not a speed measurement.

This is submitted as a draft for those missing backend/hardware checks.

Deliberate differences from Niko1221/Strata#7774

  1. qsa_pattn.cu is templated on G (8 or 12), not derived from the geometry unchecked (updated in 5f75cb7). Deriving G = 8 for q4_lite with the PR's reduce-scatter is unsafe: r[s + 6] reads beyond an eight-element array and sp[h0] can index beyond its storage; 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. The geometry reader explicitly treats an absent nextn key as zero, because it starts from the compiled geometry rather than a default-constructed one.
  3. DFlash2 tap changes are not ported. They belong to a different drafter and are unnecessary for this MTP path.

The AMD WMMA wave pin and the parity test's non-finite-output count are ported from that PR. Flash-Next defaults remain unchanged: make_profile.py still defaults to 48 layers, the new pack guards are inert for files without nextn or fused tensors, and the non-Qwen4 MTP greedy default (#3354) is preserved.

Engine route: this PR (strata) vs current upstream main (strata-poly)

Upstream main now also carries a native Qwen4 implementation on the strata-poly engine (engine/src/poly/qwen4.cpp, measured at df2c3ff30), while this PR adapts the model to the existing strata engine path (-DSTRATA_GEOMETRY=q4_lite). Both engine families exist in both repositories; the routes differ in which one serves Qwen4 and how the model is prepared for it. This section records the differences neutrally — it does not claim that either route is better. Upstream's implementation is evolving (#440's PLE row-by-row O_DIRECT reader is open; BasinKV sparse KV offload has landed), so the numbers below are a snapshot, not a ranking. Added in 23e8cc4 (docs-only; no code or default changes).

Route differences — full table, measurements and caveats in docs/QWEN4_ENGINE_PATHS.md (中文版):

Aspect This PR (strata route) Upstream main (strata-poly route)
Model input preprocessed trunk view + native pack, shard 2 as --ple-gguf published 2-shard GGUF mmap'd directly, fused tensors read natively
MTP drafter external Q8_0 sidecar → drafter runtime (--mtp, 1,915 MiB VRAM); indexer/QSA path implemented — STRATA_MTP_INDEXER=0 keeps the dense approximation in-file blk.40 (Q5_K matrices, F32 norms, BF16 indexer); indexer/QSA path retained
Verify window fixed --spec 2 adaptive DraftPolicy; with no --window the default cap resolves to 8 for this model
MTP sampling default model card for Qwen4 requests that name no sampling (this PR's change) greedy (#3354)

The adaptive draft policy itself (engine/include/strata/spec/draft_policy.hpp) is byte-for-byte identical in both repositories; the routes differ in the cap they give it and the drafter they feed it.

Same-box measurement snapshot (one RTX 3080 Ti 12 GB, 46 GB RAM, UD-IQ4_XS, single request; methodology and caveats in the doc):

  • Within upstream (controlled A/B): capping the window at 2 raises acceptance from 73.5% to 82–85% but lowers mean decode ~1–4% (154.4 → 152.4/148.2 tok/s over a 7-request cold sweep); at 130,652 prompt tokens the capped window is ~6% faster. Acceptance and throughput are different objectives: the acceptance gap between the routes is mostly window depth, not drafter precision — at a matched cap of 2 the embedded Q5_K drafter accepts in the same range as this branch's Q8_0 sidecar.
  • Across routes (observational, not a controlled A/B): cold prefill at 31K–131K prompts measured ~1.5–1.9× higher on this branch (e.g. 3,466–3,516 vs 1,819–1,887 tok/s at 130,652 tokens). Decode and acceptance are not like-for-like: the routes default to different verification sampling (model card vs greedy) and the runs used different generation lengths (128 vs 256 tokens). No ablation was run; attributing the prefill gap to the pack layout and CPU prefill share is static analysis, not a verified cause.

No defaults were changed on either side by that analysis; the --window 2 variant was a diagnostic config on a separate upstream checkout. Separate later work in this PR settled --mtp-hnorm to stream on reference-implementation and same-box A/B evidence (see above); --spec-min-p stays 0.0. The matched-cap acceptance quoted here was measured with the dense approximation and still stands as that configuration's number.

Remaining work

  • Setup-menu integration needs a dedicated entry that knows the trunk-view step; a normal family entry would offer the unsplit shard and fail.
  • --spec-min-p: repeated runs per value before its default can move; the single-run sweep was inside this box's noise floor.
  • The smaller IQ4_NL drafter in @Keoian's data point (780 MiB vs 2,194 MiB) is a promising direction for 8 GB cards, but it is a different conversion, is not implemented here, and is not claimed.
  • Vision, and additional hardware/concurrency measurements.

Done since the last revision: the G=8 QSA kernel with its parity gate (5f75cb7), the MTP indexer path and its conversation snapshot (42fe3c4, aecfe3c), the --mtp-hnorm default (96025b9), the Chinese mirror of the technical page (9353f58), and the launcher's pre-indexer drafter detection with its bilingual documentation (cc5faef, 848286c), and the fork-local --update/--stop flags with two launcher defect fixes (54d2e10), and the client medium→high mapping with its fail-first regressions and bilingual documentation (a742ed0, f6b10a4).

These are recorded in the documentation's TODO section rather than claimed here.

… 128K serving

The published qwen4exp file was refused: block_count 41 counts an in-file nextn MTP
block, and read_geometry starts from the compiled shape, so a trunk view carrying no
nextn_predict_layers key inherited n_mtp_layers=1 and then failed the 40-entry
compress_ratios check. Reset it to 0 before reading the key, let that array cover
trunk + MTP (an MTP block is full attention), and drop n_mtp_layers from the
kernel-shape guard: it is file layout, not a shape the kernels run.

qsa_pattn keeps G=12 instead of deriving it from the geometry. Its reduce-scatter is
written for 24:2 - r[s+6], sp[h0] and px_head all need 12 slots - so deriving G=8 for
q4_lite's 16:2 would read and write out of bounds. The existing runtime head-count
check refuses it and the QSA layers keep the usual attention path; supporting G=8
needs a new reduction tree. Also pin the WMMA wave for G<=8 and count non-finite
parity outputs, which otherwise pass every comparison silently (NaN > x is false).

Tools: qwen4_split_gguf.py writes the 40-layer trunk view, splitting the four fused
tensors byte for byte along their quantized rows, so nothing is requantized;
iq_pack.py refuses a fused file with the split command and skips the MTP block;
make_profile.py takes --n-layer; mtp_qwen4_rt.py turns the MTP sidecar into a drafter
runtime. The tokenizer accepts qwen4 as an alias of the qwen35 split but with
ignore_merges, as llama.cpp master reads it - 201 single-piece vocabulary entries,
mostly multi-character CJK, are unreachable by any chain of merges without it.

Measured on one RTX 3080 Ti 12 GB, 46 GB RAM: MTP --spec 2 decodes at 155.32 tok/s
against 106.12 without (+46%), and beats --spec 3 (146.99) and --spec 4 (128.33) on
the same teacher-forced text. Serving at 131072 with --kv-grow: 165.5 tok/s on a
Chinese answer, 2899 tok/s reading a 24282-token prompt, 3305 resident experts.
reasoning_budget_tokens closes the think block politely instead of cutting it off.

Flash-Next defaults are unchanged: make_profile still defaults to 48 layers, and the
new iq_pack guards are inert at nextn=0 with no fused tensors. 114 tests pass.
…it out of the repo

The serving section told the reader to launch with --config
strata-qwen4-35b-ud-iq4_xs.json, but .gitignore excludes /terminal/strata-*.json:
the file names one machine's paths, so it is not in the repository and the page
never showed its contents. Anyone cloning the fork could not follow the section.

Embed the config as JSON with /path/to/ placeholders, as UNSLOTH_Q4.md already does
for its own run config, and say where to save it. Verified against the config the
measurements were taken with: same keys, and the same arguments once the machine
prefixes are normalised. lib_dirs is the one deliberate omission - it is optional
(the server only prepends those directories to the library search path), so it is
documented in prose with the value used here rather than baked into the template.

The Chinese page points at the same file, so it now says the config has to be saved
from the technical page too.
…r and TODOs

The page said what to run but not why the published file needs four changes, so
add the pipeline and the reasoning for each one: the 41-block geometry, the
qwen4 tokenizer's ignore_merges, the byte-exact fused-tensor split, and how the
MTP drafter plus --kv-grow deliver speed and 128K. Correct the MTP sidecar size
(1.87 GiB, not 2.0 GB) and add the measured agent session: 117 requests growing
to about 78K tokens, 192.9 tok/s decode and 1906 tok/s prefill on average.

qwen4-run.sh takes a fresh clone to a running server: preflight, optional
download, engine build, the four idempotent preparation steps, config generation,
then serve. --check changes nothing; --build-only stops before serving. Verified
here with bash -n, a real --check, and a --build-only run against the existing
artifacts, which skipped every preparation step and wrote a working config.
The name deliberately avoids the root /run-*.sh ignore rule for local scripts.

Record what is deliberately left: setup menu integration (a normal family entry
would hand out the unsplit shard and fail), qwen4_intake's geometry knowledge,
the G=8 QSA kernel, vision, and unmeasured concurrency/other cards.
@Keoian

Keoian commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

An AMD data point for the "Not run" list (HIP build, AMD execution, cards below 12 GB). I built this PR's revision 99376fc85 unchanged for HIP and ran it on two RX 5700 XT.

Environment. 2x Radeon RX 5700 XT 8 GB (gfx1010), Core i7-3770 (AVX, no AVX2), 32 GB DDR3, SATA SSD, Ubuntu Server (Linux 7.0), ROCm 7.14 (gfx101X-dgpu wheels).

Build. -DSTRATA_ENABLE_HIP=ON -DCMAKE_HIP_ARCHITECTURES=gfx1010 -DSTRATA_GEOMETRY=q4_lite -DSTRATA_ISA_FLOOR=avx -DSTRATA_BUILD_TESTS=OFF -DSTRATA_BUILD_POLY=OFF, target strata: 154 of 154 steps, no errors. gfx1010 has no WMMA (STRATA_PA_WMMA is 0 there), so this says nothing about the wave pin in qsa_prompt_attn.cu.

Model. Unsloth UD-Q4_K_XL (not UD-IQ4_XS). Pack, profile and drafter were made with this branch's iq_pack.py --compat-bf16, make_profile.py --no-base --n-layer 40 --n-expert 256 and mtp_qwen4_rt.py. The trunk view was written earlier with the splitter of Niko1221/Strata#7774; this branch's copy differs from it in comment lines only.

Measured. terminal/tools/strata_bench.py, 3 runs, thinking off, medians with the range of the runs. Both columns: --max-context 131072 --kv-grow --prefill auto --vram-reserve-mib 512, "gpu": [0, 1], "layer_split": "auto", one request at a time.

This PR's documented settings A smaller drafter
Drafter mtp_qwen4_rt.py, --spec 2 qwen4_mtp_rt.py --experts iq4_nl (Niko1221/Strata#7786), --mtp-hnorm stream --spec 4 --spec-min-p 0.5
Draft layer VRAM (engine log) 2,194 MiB 780 MiB
Experts on the two cards at start 3,161 of 10,240 3,883 of 10,240
Chat decode 46.3 tok/s (44.3 to 55.4) 51.0 tok/s (50.0 to 59.0)
Chat, time to first token 1.02 s 0.86 s
4K prompt 415 tok/s (410 to 416) 415 tok/s (409 to 415)
16K prompt 575 tok/s (572 to 580) 541 tok/s (539 to 544)
Agent turn, decode 57.9 tok/s (47.2 to 63.0) 58.7 tok/s (47.5 to 65.8)
Five fixed prompts, 500 new tokens each, thinking on, temperature 0 53.0 tok/s, 80.6% of drafts accepted 53.4 tok/s, 72.2% of drafts accepted
  • With the documented settings, a sentence planted at 60% of a 25,858-token prompt came back correctly (prompt read at 601 tok/s).
  • One card alone ("gpu": 0, 8 GB, --max-context 32768 --kv int8, the IQ4_NL drafter): it starts, with 1,659 of 10,240 experts on the card. The five prompts ran at 38.6 tok/s (75.6% of drafts accepted), and a sentence in an 11,570-token prompt came back correctly (read at 416 tok/s). About 23 of the 32 GB of RAM were in use.

Three things I noticed.

  1. On a layer split --kv-grow does nothing. The engine logs --kv-grow is off (one GPU, a profile, the whole K/V in VRAM, every expert in RAM, no --batch, --vram-elastic or --peer-device), so two cards allocate the 131072 context up front.
  2. On 8 GB cards the drafter's size shows. mtp_qwen4_rt.py writes a 1.15 GB dense.bin (28 tensors); qwen4_mtp_rt.py writes 68 MB (26 tensors) and its IQ4_NL experts are half the size. That was 722 more experts on the cards and about 10% more chat decode here. A data point, not a request to change this PR.
  3. With this model's chat template a request with "reasoning_effort": "medium" is an HTTP 400 (Unexpected reasoning effort medium), and high reaches the model as xhigh. That is server-side and separate from this port: [Engine] serve: Qwen4-35B-A3B thinking levels (reasoning_effort "medium" was an HTTP 400) #437.

Run with another engine build, not this revision (main plus the engine commits 89561aaaf to 8edd10483 of Niko1221/Strata#7774, same cards, same files):

  • Pictures work with strata-vision built from terminal/tools/vision of the current tree (CPU reader) and Unsloth's mmproj-BF16.gguf in a "vision" section: the model read a number in a line of code and named the shape in a generated 1280x800 picture. A strata-vision binary from an older release stopped with unknown pre-tokenizer type: 'qwen4'.
  • Against llama.cpp (72a780e, CPU) on the same GGUF, twelve short questions at temperature 0: every prompt has the same token count in both, and counted up to the first difference the two pick the same next token at 612 of 625 positions.
  • A 137,674-token prompt at --max-context 262144 --kv int8 was read at 671 tok/s and its planted sentence came back correctly.

Not run: qwen4-run.sh (it asks for nvidia-smi), UD-IQ4_XS, Windows, any RDNA2/3/4 card, parallel requests.

🤖 Generated with Claude Code

@qron88

qron88 commented Dec 4, 2026

Copy link
Copy Markdown

Windows / 8 GB data point for this PR.

Setup. Windows 11, RTX A2000 Laptop 8 GB (sm_86), 31.7 GB RAM, MSVC 14.44, CUDA 13.4, Ninja, -DSTRATA_GEOMETRY=q4_lite (branch qwen4-35b at 99376fc85). CUDA 13.5 failed at CMake's compiler-ID step with this MSVC (nvcc could not find CMakeCUDACompilerId.cu); 13.4 builds fine.

File. OpenUncensored_Qwen4-35B-A3B-Uncensored-IQ3_XS, a single-file GGUF (the PLE table is inside, so --ple-gguf points at the same file). It carries the same fused tensors (30 attn_qkv_gate, 30 ssm_beta_alpha, 41 each of hc_attn_down_inject / hc_ffn_down_inject) and blk.40.nextn.*. qwen4_split_gguf.py split it (1021 tensors, 320 splits), iq_pack.py + make_profile.py built the pack. No MTP.

Results (GPU and RAM otherwise idle, --spec 2):

  • Correct answers on two chat prompts (capital of France; a Fibonacci function).
  • ~26-28 tok/s decode.
  • ~620 tok/s prefill on a 2048-token prompt with --prefill auto (it picks a 2048 chunk); --prefill 1024 gave ~430.
  • With other processes holding the GPU and most of the RAM (about 8 GiB left), decode dropped to ~4.6 tok/s.

Unit tests on Windows: 59 + 41 + 14 = 114 run, all pass (4 skipped: no tokenizer fixture, no llama.cpp vectors, no live HF). One caveat: three tests in tools/test_qwen4_split_gguf.py (test_trunk_metadata_and_splits, test_a_quantized_merged_tensor_keeps_its_blocks, test_a_row_count_that_disagrees_with_the_geometry_is_refused) fail with PermissionError: [WinError 32] when leaving with tempfile.TemporaryDirectory(), because the GGUF reader still has trunk.gguf / model-00001-of-00002.gguf memory-mapped and Windows will not delete it. The assertions themselves pass: with ignore_cleanup_errors=True all 59 are OK. Closing the reader before leaving the with block (or that flag) would fix it.

Not tested: MTP (--mtp), HTTP serving, long context. qwen4-run.sh is Linux-only (gcc-14, /proc/meminfo, nproc); the manual steps (split, pack, profile, run) worked on Windows.

…nd make the conversion chain crash-safe

Serving: Qwen4's template knows xhigh/high/low/off and no medium, so select that
dialect from the tokenizer's pre="qwen4" - qwen4exp is shared with Flash-Next,
and Service.family keeps its structural None. Anthropic budgets map 2048/8192 to
high/xhigh, config/shared/settings use the same table, and the tokenizer is read
before the config's effort is validated. With MTP, a Qwen4 request that names no
sampling now uses the model card (thinking 1.0/0.95/20) instead of greedy;
explicit request fields, shared settings and temperature=0 still win, and /props
reports the same defaults. This is the effort bug reported in simplexai-labs#437.

Tools: Tokenizer.from_dir reads an empty merge set as [] (splitlines, not
split("\n")), extract() records the qwen4 provenance (QWEN35 + ignore_merges),
and intake points the Qwen4 drafter at mtp_qwen4_rt.py while Flash-Next keeps
mtp_pack.py. iq_pack publishes native_experts.txt last, after every selected
expert artifact; the splitter and the MTP runtime write beside the target and
rename only on success; the MTP set carries a size-checked complete.json;
make_profile writes atomically. The split tests ignore Windows mmap cleanup
errors, as reported on the PR (assertions unchanged).

Runner: preflight GPU 0's free VRAM, a bindable port, RAM and per-filesystem disk
before any download or build; --check changes nothing. Install the full
requirements.txt, detect the CUDA architecture, reuse artifacts only when
complete, write the config atomically, merge shared settings without overwriting
user keys, and carry the models.json aliases into the config.

Docs: QWEN4.md and both model pages describe the effort dialect, the MTP sampling
exception, the drafter's dense-attention approximation (indexer tensors are not
converted), the two meanings of preserve_thinking, and the deliberately unchanged
--mtp-hnorm/--spec-min-p defaults; add the English model page.

Every new regression failed on the old code first. Final runs: 110 tool tests
(4 skipped) and 826 serving tests (3 skipped), all passing. No engine default that
shapes the draft distribution was changed, and no new real-inference measurement
was taken; the quoted speeds remain the earlier RTX 3080 Ti runs.
…poly)

Record the route differences between this branch's strata (q4_lite)
adaptation and upstream main's native strata-poly implementation, plus a
same-box measurement snapshot: a controlled --window 2 A/B within the
upstream stack and an observational cross-route prefill/decode comparison
with explicit sampling-regime caveats. No defaults changed; no claim that
either route is better. Link the new page from QWEN4.md.
…ill path

a69e611 left qsa_pattn at G=12: its reduce-scatter, px_head permutation and
shared-memory layout were written for 24:2, so the runtime head-count check
refused q4_lite's 16:2 and the parity gate skipped with a misleading "no sm_6x
kernels" message even though the SM60 kernels were built.

Template the score and value kernels on G (8 or 12). 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 only exists
for G=12 (if constexpr). G=8 costs 16 shuffles + 16 adds per warp against 25+25
for G=12. ps_blk becomes __host__ __device__ constexpr so nvcc can call it from
the kernels without --expt-relaxed-constexpr.

The parity harness now separates "not built" from "geometry refused", runs both
ratios through the same 468 cases, and reports the real reason on a skip.

Verified on one RTX 3080 Ti (sm_86; the kernels exercised through the any-arch
entry, which bypasses only the cc gate): fail-first 468/468 differ on the old
kernel; after the change q4_lite (G=8) 468 cases 0 differ (19,644,888 nonzero
outputs, the same count as the fail-first run) and q4_deep (G=12) 468 cases
0 differ (29,724,792 nonzero) - the G=12 path stays bit for bit. The q4_lite
CTest sweep passes 410/430; all 20 failures reproduce identically with this
change stashed (geometry-guard, GDN/GR/HC/PLE parity, CPU pool and prefill IQ
tests that assume the flash_next geometry). The sweep excludes
pinned_shared_test, whose link failure (expert_layout() undefined in
strata_core, also breaking strata-concurrent/load/overlap) predates this
change. Production sm_86 serving is unchanged: the kernel remains SM60-gated
and prefill falls back to the decode loop. On the rebuilt binary the
teacher-forced spec-2 run reproduces the P0 acceptance exactly (109/155 =
0.703); natural-run acceptance and decode move within the documented CPU-share
prefill nondeterminism and machine-state noise (spec-2 acceptance 0.644-0.703,
decode 148-160 tok/s across repeats).
…ata elsewhere

test_polystrata_names (tools/polystrata_names.py --check) was failing. Three of
the flagged lines came from 23e8cc4: the engine-route bullets said "Strata
engine path" / "Strata 引擎路径" and the QWEN4.md link said "Strata-engine
adaptation", while the page's own title and the parallel bullet use the
lowercase binary names (strata / strata-poly). Lowercase them to match; the
route contrast stays symmetric in both languages.

Two flagged lines predate that commit (QWEN4.md's serving note and
qwen4_split_gguf.py's docstring): run the repo's own rename tool, which writes
PolyStrata there. --check now reports 0 files would change. The mtp_qwen4_rt.py
docstring fix rides with the indexer-conversion commit that touches the same
file.
… drafter runtime

The published Q8_0 sidecar carries blk.40's four indexer tensors (the QSA
selection's own q/k projections in BF16 and their norms in F32), but the
converter dropped them, so the drafter runtime could only ever run its
dense-attention approximation. Convert all four - or refuse a partial set -
under the names the trunk's native pack uses (indexer.{q,k}_proj.weight,
indexer.{q,k}_norm.weight), with the same shape checks as the other
projections (key width from k_proj, q rows a multiple of it, norms sized to
the key) and --plus-one-norms support. A sidecar without indexer tensors
converts exactly as before; the runtime keeps its dense path until the engine
side lands, and the new entries are inert until then.

Tests: three new IndexerConversionTests (projections and norms reach the
runtime, plus-one norms apply, an indexer-less sidecar is unchanged),
fail-first on the old converter (2 of 5 failing). Full tools suite from
terminal/: 2183 tests OK. The module docstring also takes the repo's rename
tool (polystrata_names gate).
…rsation snapshot

The Qwen4 MTP sidecar carries blk.40.indexer.{q_proj,k_proj,q_norm,k_norm}. Until now the
drafter ignored them and approximated its attention with a dense window over the last cells,
which is what the fork's 82% acceptance was measured against. This loads the four tensors and
runs the trunk's selection on the draft layer: score every completed block, take the top-k, and
attend to the selected cells instead of a window.

  - load(): the indexer tensors, a full indexer pool planned like a trunk layer's (no ring),
    window_ = 0, and cap_ = the selection width (a constant) rather than the context.
    STRATA_MTP_INDEXER=0 keeps the dense approximation, and a sidecar without the tensors
    loads exactly as before.
  - record_front / record_rest and the batch-slots passes: the indexer key projection, its
    norm/pool/rotate on block completion, then block scores -> top-k -> residency resolve,
    the trunk's chain over the draft layer's own state.
  - Prefill::draft_kv accepts kv_mode 1 and appends the prompt's pooled indexer keys in
    chunks, declining if the tensors are missing.
  - conversation snapshot: the drafter has no turn checkpoint, so its whole indexer block
    (tail, dead, pooled, block_pos) rides with its K/V. QsaState::idx_block_snapshot marks
    that; the span is measured against the four sizes and fails closed if they are not
    contiguous. A borrowed prefix ends inside a block: the tail is cleared and the spare
    takes the dead key, as a checkpoint restore does. At most idx_block-1 cells of that one
    pooled key are approximate; the trunk is exact there because its checkpoint exists.

The step record's width, and a regression test for it
----------------------------------------------------
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 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 sends the kernel down the identity branch
and writes past the buffer, by n_kv - cap ids.

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.

mtp_step_test 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 30751 ids past the buffer for a 32802-cell context and 63519 for 65570.

Measured on an RTX 3080 Ti (12 GB), UD-IQ4_XS trunk40 + Q8_0 sidecar, greedy, --spec 2,
matched expert cache, STRATA_PREFILL_CPU_SHARE=0, real repository prose with a needle at
half depth:

  64K prompt (65570 tokens, 2000 cache slots)
    dense approximation   acceptance 0.814   125.5 tok/s   1.050 ms/round
    indexer, before fix   acceptance 0.217    87.9 tok/s   0.942 ms/round
    indexer, after fix    acceptance 0.697   139.0 tok/s   0.983 ms/round
    indexer off           acceptance 0.814   125.0 tok/s   1.049 ms/round

The before-fix row is the repeat arm, the one whose log survived; both arms measured 0.217.
The indexer-off arm reproduces the dense runtime's emitted ids exactly, so the approximation
is unchanged for anyone who keeps it.

can_draft_slots also declines a batch whose slots disagree on indexer_ or, with the indexer
on, on max_cells: the batch pass scores every slot with this drafter's max_blocks_, and cap_
does not imply it (with the indexer, cap_ is geometry only). A smaller slot would be read
past its own idx_pooled. Declining drafts it on its own instead.

Not changed here: --spec-min-p stays 0.0 (its sweep is inside this box's run-to-run noise).
The --mtp-hnorm default is settled in a separate commit. The SM60 qsa_pattn G=8 path is a
separate commit and is not compiled into this geometry's production build.
…ence uses

pre_fc_norm_hidden.weight is 8192 = 4 x 2048 wide. The reference implementations normalize
each hyper-connection stream on its own, scaled by its slice of that 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. It was the default only
because it was frozen pending a same-box A/B. That measurement is done.

RTX 3080 Ti (12 GB), UD-IQ4_XS trunk40 + Q8_0 sidecar, 32K prompt, greedy, --spec 2, matched
expert cache, STRATA_PREFILL_CPU_SHARE=0, two runs of each:

  pooled   acceptance 0.679, 0.679   138.73, 137.56 tok/s   1.71 tokens/round
  stream   acceptance 0.815, 0.852   142.30, 137.78 tok/s   1.90 tokens/round

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. After the flip,
two runs with no flag measured 0.789 / 0.838 acceptance at 143.98 / 141.55 tok/s.

pooled stays available as the opt-out; the help text and the header comments now say which
one is the default. The setup paths that already passed --mtp-hnorm stream are unchanged.

Also documented here, from the same measurement pass: --mtp-q4's 4-bit copies are ADDITIVE,
not a replacement -- the prompt path's batched K/V pass keeps the Q8_0 originals. On this
12 GB card 11 projections cost +566 MiB and displaced resident experts (3000 -> 2974), so
acceptance rose while decode did not. That is a residency result, not a verdict on Q4_0
drafting; the DGX Spark measurement of --mtp-q4 all was +3.5%. The flag stays opt-in.

--spec-min-p stays 0.0: its sweep (0.05 / 0.10 / 0.20 / 0.40) was non-monotonic and inside
this box's run-to-run spread. Two runs of an identical configuration measured 0.733 and
0.826 acceptance, so a single run per value cannot settle it.
…asured defaults

The MTP indexer work and the --mtp-hnorm default change landed in the engine. This brings
the documentation in line with them, in both languages where a pair exists.

QWEN4.md
  - "The MTP drafter is a dense-attention approximation" becomes "The MTP drafter's indexer
    (MTP QSA)": what the path now does, what STRATA_MTP_INDEXER=0 and an older sidecar keep,
    and the snapshot's block-granular approximation stated as a bounded cost (at most
    idx_block-1 cells of one pooled key; nothing below 2048 cells).
  - the 64K A/B against the approximation, with the bandwidth validity gate, and the 32K /
    128K acceptance and needle results. The 32K and 128K decode timings are deliberately not
    quoted: those batches read 52-72 GB/s under accumulated swap pressure.
  - a new subsection on the step record's width overflow: why it looked healthy at 32K and
    collapsed at 64K, the five fill sites, and mtp_step_test's fail-first evidence.
  - "Two defaults, measured": --mtp-hnorm to stream with the reference readings and the A/B;
    --spec-min-p staying 0.0 with the sweep and the noise floor that makes it unsettled;
    --mtp-q4's additive VRAM cost on a 12 GB card.
  - the run-to-run spread is documented before any acceptance number is read: two runs of an
    identical configuration measured 0.733 and 0.826.
  - Limits, the PR #7774 difference list and the TODO updated; Testing now names the engine
    regressions (mtp_step_test, conversation_snapshot_test at 4639 checks, CTest 426/448 with
    the two new failures attributed) and the tool subset at 113 tests.

models/qwen4.md and .zh-CN.md, QWEN4_ENGINE_PATHS.md and .zh-CN.md
  - the route table's MTP attention row now reads "implemented" on this branch, with the
    approximation as the opt-out; the analysis keeps the earlier matched-cap acceptance as
    that configuration's number rather than rewriting it.
  - anchors updated to the renamed sections; no stale anchor remains.

DETAILS.md and DGX_SPARK_LINUX.md
  - the flag tables say which hnorm reading is the default, and that the Spark measurement is
    now the engine's default on every card.

IQ4_NL drafting is recorded as not implemented: no such file on this box and no HF source
weights, so it stays a direction rather than a result.
QWEN4.md was the only Qwen4 document without a Chinese version. This adds
docs/QWEN4.zh-CN.md, a full translation: same 19 headings, same 9 tables, same 8 code
blocks, every measurement and identifier unchanged. The shell commands are byte-identical
to the English page; only the comments and the ASCII diagram's box labels are translated.

Chinese headings get an explicit <a id="..."></a> carrying the English slug, so the anchors
that other documents link to (#speed, #relationship-to-pr-7774,
#the-validity-gate-watch-the-cpu-pools-bandwidth, #the-tokenizer-qwen4-takes-ignore_merges,
#serving-it, #the-mtp-drafters-indexer-mtp-qsa, #two-defaults-measured) still resolve from
the Chinese page.

Cross-links follow the language: the English page gains a 中文版 link, and
models/qwen4.zh-CN.md now points at the Chinese technical page instead of the English one.

Also corrected in all three pages: the "deliberate non-goals" paragraph still said the
qsa_pattn fast path "stays disabled at 16:2". It now handles G=8 behind a parity gate; what
keeps it off this geometry's production build is the SM60 guard, not an unsafe derivation.
The Limits section already said so -- the introduction contradicted it.
…exer

The launcher reused any mtp-rt whose four artifact sizes matched its own
complete.json. A runtime converted before the indexer existed is exactly
that: self-consistent, 28 tensors, no indexer. So ./qwen4-run.sh kept
serving the dense-attention approximation and never reconverted, and the
only way out was to run mtp_qwen4_rt.py by hand -- which defeats the point
of a one-command launcher.

Sizes cannot distinguish the two, so the record now says which one it is.
mtp_qwen4_rt.py writes an `indexer` boolean, read back from the dense.txt
it just published so it cannot disagree with the artifacts. mtp_complete()
requires the field: a record without it predates the indexer and is
reconverted (fail-closed). A current record is still reused, so the steady
state costs nothing.

Fail-first on the unfixed code: 3 failures -- KeyError: 'indexer' in both
converter tests, and the launcher test that asserts a rebuild got
returncode 0 because the stale runtime was accepted. After the fix the two
modules pass 13 tests, and the documented tool subset runs 115 tests,
OK (skipped=4).
…xer is present

Both language versions describe the reuse rule, the tool subset (113 ->
115 tests) and the two regression rows. The reuse paragraph now says why a
record without the indexer field is reconverted: its artifact sizes are
self-consistent, so they alone cannot reveal the missing tensors, and
serving it would silently keep the dense-attention approximation.

The launcher row also records the positive control -- a current record is
reused, not reconverted on every run.
Updating a source checkout meant doing git, the rebuild and the restart by
hand. --update fast-forwards the checkout, rebuilds, prepares the artifacts
and then asks whether to start or restart; --stop ends the instance this
launcher started. This is convenience for our own fork: upstream has its own
signed-feed update path and does not need these.

The order is build-before-stop. A running service holds the port and most of
the VRAM, and a failed build must not leave the user without a service, so
the free-VRAM gate now applies only when actually serving (--update and
--build-only work while a service is up) and is re-checked after the stop.

--stop never signals a bare PID. The server is matched by working directory
(this repo's terminal/) and command line (this config); engine children are
captured before the signal and re-verified against their own start time and
executable, so another checkout's server is left alone.

--update refuses rather than guesses: not a git checkout, detached HEAD, no
upstream, tracked local changes, or a non-fast-forward (a rebased or
force-pushed branch). It fetches and merges --ff-only and never creates a
merge commit.

Also fixes --help, which printed a fixed line range and leaked five lines of
shell code, and the header's stale run-qwen4.sh name.

Fail-first: 10 new tests failed on the old launcher. The two git tests were
re-proved against the committed script after fixing a fixture whose bare
remote HEAD named a nonexistent branch, which had made its push fail
silently. After the change: 18 launcher tests pass and the documented tool
subset runs 125 tests, OK (skipped=4). The stop path was also exercised
against the live instance with os.kill intercepted: it targeted exactly that
server and no other process, and delivered nothing.
Qwen4's template has no medium and raises on it, so a client sending the
generic medium (polystrata.py --think defaults to it) had its request
interrupted. Follow upstream: the frontend effort table and the shared
settings/config validator accept medium and map it to the template's
default high; truly unknown words still 400.

Fail-first: the rewritten Qwen4EffortPaths regressions on the old code ran
19 tests with 13 failures and 2 errors, all on the medium paths; after the
mapping 19/19 pass, and the 19-module serving suite is 826 tests, 3 skipped,
all passing.
Both language versions of the technical page and the model page now state
that the template itself has no medium and the server maps a client's
medium to the default high instead of erroring. The validation section
records the fail-first run (19 tests, 13 failures, 2 errors on the old
code) and the passing reruns.
@VecSzn

VecSzn commented Dec 5, 2026

Copy link
Copy Markdown
Collaborator

Thank you for the effort on this draft! Native strata-poly Qwen4-35B-A3B support (with MTP and long-context serving) has already shipped in �0.2.20-poly.10, and this branch touches 17 upstream strata core files (q4_lite) that belong in Niko1221/Strata#7774. Closing as superseded.

@VecSzn VecSzn closed this Dec 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants