Repository navigation
Conversation
… 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.
|
An AMD data point for the "Not run" list (HIP build, AMD execution, cards below 12 GB). I built this PR's revision Environment. 2x Radeon RX 5700 XT 8 GB ( Build. Model. Unsloth UD-Q4_K_XL (not UD-IQ4_XS). Pack, profile and drafter were made with this branch's Measured.
Three things I noticed.
Run with another engine build, not this revision (
Not run: 🤖 Generated with Claude Code |
|
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, File. Results (GPU and RAM otherwise idle,
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 Not tested: MTP ( |
…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.
|
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. |
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 2versus 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.
Why the published file cannot simply be loaded
The file has four independent mismatches with this engine, and the branch handles each separately:
block_countincludes the drafter. The published file has 41 blocks: 40 trunk layers plus one in-file nextn/MTP block.read_geometrystarts from the compiled shape, so a trunk view withoutnextn_predict_layersinheritedn_mtp_layers = 1fromq4_liteand was rejected: 41 layers against a 40-entryattention.compress_ratiosarray. 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_mismatchno longer compares it, so builds and trunk views with either declaration accept each other.tokenizer.ggml.pre = qwen4needsignore_merges. It uses the qwen35 split pattern and vocabulary, but llama.cpp master setsignore_merges = trueforqwen4and not forqwen35. About 201 single-piece vocabulary entries, mostly multi-character CJK such as 俱乐部, cannot be produced by any merge chain. Acceptingqwen4without that flag would silently split Chinese incorrectly. The tokenizer therefore aliases the split rule but addsqwen4toIGNORE_MERGES, with a regression test that distinguishes the two rules even when no merges are present.Four projections are fused.
attn_qkv_gate,ssm_beta_alpha,hc_attn_down_injectandhc_ffn_down_injecteach contain two projections concatenated along output rows.qwen4_split_gguf.pywrites 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 dropsblk.40and the PLE table.iq_pack.pyrefuses 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 onlyper_layer_token_embd.weight.The MTP block is a drafter, not trunk layer 40.
mtp_qwen4_rt.pyrepackages the Q8_0 sidecar as the drafter runtime used by--mtp.--spec 2is 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.jsonsupplies registry facts that cannot be derived from this config (it names its GGUF with--native;--modelis 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, andreasoning_budget_tokens: 512to 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, defaulthigh; the template itself has nomediumand raises on it. The generic Qwen table was translatinghightoxhighand passingmediumthrough, which the template rejects with an HTTP 400. The server now selects Qwen4's own table from the tokenizer'spre="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 inPOST /settings. A client'smediummaps to the template's defaulthighinstead of erroring (a742ed0, the same mapping upstream's table carries), so clients that only know the generic words —polystrata.py --thinkdefaults tomedium— keep working; truly unknown words still 400. Anthropic'sthinking.budget_tokensmaps tolowbelow 2048,highfrom 2048 to 8191 andxhighfrom 8192.Service.familykeeps its structuralNone, so output parsing and tool markup are unchanged. The tokenizer is read before the config's effort value is validated, so a Qwen4 config withxhighloads.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-thinking0.7 / 0.80 / 20 / presence_penalty 1.5. Explicit request fields, shared settings and the config's sampling block still win, an explicittemperature: 0is still greedy, andGET /propsreports the same defaults the generation path uses. Non-Qwen4qwen4expmodels keep the old behaviour.The drafter now runs the model's own indexer (updated in aecfe3c).
mtp_qwen4_rt.pyconverts 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-hnormnow defaults tostreamon reference-implementation and same-box A/B evidence;--spec-min-pstays0.0because its sweep landed inside this box's run-to-run noise.preserve_thinkingis 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.pypublishesnative_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.pyandmtp_qwen4_rt.pywrite 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-checkedcomplete.jsonpublished last.make_profile.pywrites atomically.Tokenizer.from_dir()reads an empty merge set as[](a Qwen4 export previously became unloadable),extract()records the correctqwen4provenance, andqwen4_intake.pypoints the Qwen4 drafter atmtp_qwen4_rt.py(Flash-Next keepsmtp_pack.py) and classifies apre="qwen4"set as case A.qwen4-run.shpreflights 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.--checkchanges nothing. It installs the fullterminal/requirements.txt(a fresh clone previously missedregex/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 themodels.jsonaliases into the config. The download path is unchanged — this is a correctness pass, not a new download mechanism.complete.jsonnow also states whether the runtime carries the drafter's indexer (cc5faef). The launcher previously reused anymtp-rtwhose 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.shtherefore kept serving the dense-attention approximation and never reconverted; the only way out was to runmtp_qwen4_rt.pyby hand, which defeats a one-command launcher. Sizes cannot distinguish the two, so the record says which one it is: the converter writes anindexerboolean read back from thedense.txtit just published, andmtp_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.--updateand--stop(54d2e10) are fork-local convenience and may be dropped from this PR in full.qwen4-run.shbuilds 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.--updaterequires 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.--stopselects 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:--helpused 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-onlyand--updatewhenever a running server already held the card. The gate now applies only when serving and is re-checked after a stop.test_qwen4_split_gguf.pytests that hitPermissionError [WinError 32]on Windows (reported by @qron88 below) now useignore_cleanup_errors=True, the convention already used intest_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 thetrunk'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_topktreatsn_kv <= step[kStepWidth]as"everything is selected" and then writes
n_kvascending ids into a buffer holdingcapids per query. The dense pathis safe: its
capis sized to the context andwindow_idsoverwrites the width. The indexer'scapis the constantselection width (2,051) and nothing overwrites the width, so filling
n_kvthere sent the kernel down the identitybranch and wrote past the buffer by
n_kv - capids. That is why the first indexer runs looked healthy at 32K andcollapsed at 64K — the overflow grows with the context. All five host fill sites now go through
MtpDrafter::fill_step, which callsqsa_step_fill(the quadruple's one writer) for the indexer and keeps the oldarithmetic for the dense path.
can_draft_slotsalso declines a batch whose slots disagree onindexer_or, with theindexer on, on
max_cells, because the batch pass scores every slot with this drafter'smax_blocks_.mtp_step_testis the fail-first regression: 16 checks failed on the old filling, 30,751 ids past the buffer at a32,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,000expert 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:
STRATA_MTP_INDEXER=0The indexer trades acceptance for a cheaper round and wins on decode (+10.8%). The
STRATA_MTP_INDEXER=0armreproduces 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 - 1cells of that one pooled key are then approximate — one block of 8,192at a 32K prefix, and nothing at all below 2,048 cells. The trunk is exact there because its checkpoint exists.
--mtp-hnormdefaults tostream(new in 96025b9)pre_fc_norm_hidden.weightis 8192 = 4 x 2048 wide, and every reference reading normalizes each hyper-connectionstream on its own, scaled by its slice of that weight: upstream's
q4_mtp_eh_concat_kernel(one block pertoken/stream, sums squares over
n_embdonly, readsw_hnorm + c * n_embd), llama.cpp'sqwen4expMTP graph, andmtp_qwen4_rt.py's own docstring ("applied per hc stream tohnorm(h)").pooled— one RMS over all four — matchesnone 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-hnormpooled(the old default)stream(the new default)The two
pooledruns were bit-identical. Bothstreamruns accepted more and needed fewer rounds, and both decodedfaster 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.
pooledstays available as the opt-out, and the setup pathsthat already passed
--mtp-hnorm streamare unchanged. The DGX Spark data point below independently recordedstreamat +4.3% decode.
--spec-min-pstays0.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 projandall, the same on this pack because the draft head'ssubset 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-q4stays opt-in. Its 4-bit copies are additive, not a replacement: the prompt path's batched K/V pass keepsthe 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 allwas +3.5%.Run it
From a fresh clone of this branch:
--checkperforms only the preflight;--build-onlyprepares without serving. The equivalent manual commands and the complete config are indocs/QWEN4.md(English) anddocs/QWEN4.zh-CN.md(Chinese); the user guide isdocs/models/qwen4.md(English) anddocs/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_testfailed 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 oldqsa_pattnkernel. Both pass after the fix. The launcher staleness fix added three more: twoKeyError: '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/--stopregressions also failed on the old launcher (unknown option: --update;--helpprinting 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. Themedium→highmapping rewrote theQwen4EffortPathsassertions that had pinned the old rejection: on the old code the updated class ran 19 tests with 13 failures and 2 errors, all on themediumpaths, 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:
Engine-side regressions at this revision (GPU build, sm_86,
-DSTRATA_GEOMETRY=q4_lite):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 upstreammaincheckout atdf2c3ff30built 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 againstnative_expert_groupedreaches 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 incheck_carvedatH=512, FF=256; the plaincheck()path never failed in six runs.native_expert_i8is 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_TESTSwas enabled andmtp_step_testadded.The launcher tests run offline with fake hardware and tools: no download, compilation, GPU or server. A real
./qwen4-run.sh --checkon 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_liteand executed on the GPU, not merely compiled. Both serving protocols were exercised at 99376fc:/v1/chat/completionsand/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-hnormand--spec-min-pwork was measured withstrata generateon 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-followon identical text:--spec 2, suffix drafts)--spec 2--spec 3--spec 4Every quoted run passed the CPU-pool bandwidth validity gate documented in the page (healthy: 60–70 GB/s).
Failed / discarded measurements
One
--spec 4run 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
mmproj-F16.ggufis not wired), and the DFlash2 drafter.--spec-min-p: swept once per value, non-monotonic and inside the run-to-run spread, so the default stays0.0; it needs repeated runs per value. (--mtp-hnormwas A/B'd twice per value and its default changed — see above.)qsa_pattnkernel'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
qsa_pattn.cuis templated on G (8 or 12), not derived from the geometry unchecked (updated in 5f75cb7). DerivingG = 8forq4_litewith the PR's reduce-scatter is unsafe:r[s + 6]reads beyond an eight-element array andsp[h0]can index beyond its storage; the PR's own review thread flags the same out-of-bounds read and thepx_headpermutation. Here the permutation generalises toP_L(i) = HALF*((i/HALF)^b3) + ((i%HALF + QUARTER*b2)%HALF)withHALF=G/2andQUARTER=G/4, the reduction keepswarp_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.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.pystill 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 atdf2c3ff30), 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 (中文版):
--ple-gguf--mtp, 1,915 MiB VRAM); indexer/QSA path implemented —STRATA_MTP_INDEXER=0keeps the dense approximationblk.40(Q5_K matrices, F32 norms, BF16 indexer); indexer/QSA path retained--spec 2--windowthe default cap resolves to 8 for this modelThe 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):
No defaults were changed on either side by that analysis; the
--window 2variant was a diagnostic config on a separate upstream checkout. Separate later work in this PR settled--mtp-hnormtostreamon reference-implementation and same-box A/B evidence (see above);--spec-min-pstays0.0. The matched-cap acceptance quoted here was measured with the dense approximation and still stands as that configuration's number.Remaining work
--spec-min-p: repeated runs per value before its default can move; the single-run sweep was inside this box's noise floor.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-hnormdefault (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/--stopflags with two launcher defect fixes (54d2e10), and the clientmedium→highmapping with its fail-first regressions and bilingual documentation (a742ed0, f6b10a4).These are recorded in the documentation's TODO section rather than claimed here.