Skip to content

perf(deepseek4): stage long text prompts through sparse prefill in paged serving - #781

Merged
davide221 merged 5 commits into
mainfrom
perf/ds4-paged-staged-text-prefill
Sep 28, 2026
Merged

davide221 merged 5 commits into
mainfrom
perf/ds4-paged-staged-text-prefill

Conversation

@davide221

@davide221 davide221 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Paged (multi-user) DeepSeek4 serving requires --ds4-prefill exact and prefills every prompt row in the gathered decode graph. On the R9700 + Strix Halo deployment that is one row per lane per step, so a 1843-token prompt took 85.2 s to its first token, against 8.2 s in single-request serving.

Change

--ds4-prefill sparse is now accepted with --paged-attention (dense is still rejected; exact is unchanged). With sparse, text prompts of at least 64 tokens take the path image prompts already use (#763):

  1. prefill the prompt minus its last token into the slot's staging cache on the single-request sparse layer-major path;
  2. copy it into the paged slot (import_deepseek4_paged_slot);
  3. prefill the last token and decode in the gathered graph as before.
  • Monolithic Strix Halo: text prompts join the shared layer-sliced staged pass.
  • R9700 + Strix Halo: the shared pass needs the whole model on one GPU, so a staged text prompt runs one chunk of the regular heterogeneous sparse prefill per scheduler step: 2048 rows while no request decodes, 1024 while others decode. Each chunk pays a large fixed cost (every cold expert is read once per call; measured 306 rows in 3.2 s against 1842 rows in 7.7 s), so chunks stay wide.
  • Staged requests are identified by request id instead of their image handle, so a text request that retires mid-pass cannot be confused with the next request in its slot.
  • Without vision, staging caches (about 72 MB per slot at 8K context) are optional: if they do not fit, text prompts keep the gathered prefill.

Results (lucebox7, R9700 + Strix Halo, DeepSeek-V4-Flash MIX-STRIX, top-k 6, --max-concurrency 4 --max-ctx 8192)

Before (exact) After (sparse, staged)
1843-token prompt, time to first token 85.2 s 8.3 s (single-request serving: 8.2 s)
Two 1843-token prompts at once not measured (one row per lane per step) 18.9 s each
Short prompts (< 64 tokens), 4 users, aggregate tok/s 42.5 42.9

Sparse prefill is approximate, as in single-request serving. Outputs were checked for coherence on every request (for example, "## Summary of the Code … a GGUF model loader for the Qwen3.5-27B …"); they differ from exact, as single-request sparse output does.

Test plan

  • test_server_unit 614/614 and test_deepseek4_unit 0 failures on gfx1201 (gate test updated: sparse accepted, dense rejected with paged serving)
  • End-to-end on R9700 + Strix Halo: single long prompt, two concurrent long prompts, four concurrent short prompts
  • Monolithic Strix Halo paged serving with sparse (shared staged pass) not yet measured

🤖 Generated with Claude Code

Review in cubic

…ged serving

Paged DeepSeek4 serving prefilled every prompt row in the gathered graph,
one row per lane per step on the R9700 + Strix Halo deployment: a
1843-token prompt took 85 s to its first token.

With --ds4-prefill sparse (now accepted with --paged-attention), text
prompts of at least 64 tokens take the path image prompts already use:
prefill into the slot's staging cache on the single-request sparse
layer-major path, copy into the paged slot, then prefill the last token
and decode in the gathered graph. The monolithic deployment shares the
layer-sliced staged pass. The heterogeneous one runs one chunk of the
regular hybrid prefill per step (2048 rows idle, 1024 while others
decode), since the shared pass needs the whole model on one GPU. Staged
requests are identified by request id, not by image handle. Without
vision the staging caches are optional: if they do not fit, text prompts
keep the gathered prefill. --ds4-prefill exact is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 7 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="server/src/deepseek4/deepseek4_seq_engine.cpp">

<violation number="1" location="server/src/deepseek4/deepseek4_seq_engine.cpp:229">
P1: This hardcodes a 2048-row no-decode chunk for every hybrid placement. Non-qualified placements can therefore use the unqualified 2K sparse-prefill arena and hit the fragmentation risk that the 1K cap is meant to prevent; pass the placement-aware long-context cap into staged text chunks.

(Based on your team's feedback about hybrid prefill placement caps.)</violation>
</file>

<file name="server/src/deepseek4/deepseek4_backend.cpp">

<violation number="1" location="server/src/deepseek4/deepseek4_backend.cpp:1305">
P2: Text prompts admitted before an image request consume the entire shared-pass row budget in `begin_staged_pass`, so the image's items are skipped (`budget < min_rows`) for every pass while the long text prompt stages. That serializes image staging behind the text prompt's whole prefill instead of letting image blocks take the budget first as before. Process image items before text rows (or reserve budget for whole image blocks) so a long text prompt cannot indefinitely starve co-pending image staging.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

// expert's weights are read once per call), so chunks stay wide:
// measured 306 rows in 3.2 s against 1842 rows in 7.7 s.
if (!b_.run_staged_text_chunk(
staged, decoding ? kHybridStagedRowsWithDecode

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: This hardcodes a 2048-row no-decode chunk for every hybrid placement. Non-qualified placements can therefore use the unqualified 2K sparse-prefill arena and hit the fragmentation risk that the 1K cap is meant to prevent; pass the placement-aware long-context cap into staged text chunks.

(Based on your team's feedback about hybrid prefill placement caps.)

View Feedback

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At server/src/deepseek4/deepseek4_seq_engine.cpp, line 229:

<comment>This hardcodes a 2048-row no-decode chunk for every hybrid placement. Non-qualified placements can therefore use the unqualified 2K sparse-prefill arena and hit the fragmentation risk that the 1K cap is meant to prevent; pass the placement-aware long-context cap into staged text chunks.

(Based on your team's feedback about hybrid prefill placement caps.) </comment>

<file context>
@@ -159,23 +206,56 @@ bool DeepSeek4SeqEngine::staging_in_flight(int slot) const {
+            // expert's weights are read once per call), so chunks stay wide:
+            // measured 306 rows in 3.2 s against 1842 rows in 7.7 s.
+            if (!b_.run_staged_text_chunk(
+                    staged, decoding ? kHybridStagedRowsWithDecode
+                                     : kHybridStagedRowsWithoutDecode, error)) {
+                staged.error = error.empty() ? "staged text prefill failed" : error;
</file context>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 87816bf: staged chunks use the same placement-aware long-context cap as single-request sparse prefill.

// Text: the budget's worth of rows, never leaving a tail below the
// layer-major minimum for the next pass.
const int remaining = item->prefix - item->done;
n = std::min(remaining, budget);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Text prompts admitted before an image request consume the entire shared-pass row budget in begin_staged_pass, so the image's items are skipped (budget < min_rows) for every pass while the long text prompt stages. That serializes image staging behind the text prompt's whole prefill instead of letting image blocks take the budget first as before. Process image items before text rows (or reserve budget for whole image blocks) so a long text prompt cannot indefinitely starve co-pending image staging.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At server/src/deepseek4/deepseek4_backend.cpp, line 1305:

<comment>Text prompts admitted before an image request consume the entire shared-pass row budget in `begin_staged_pass`, so the image's items are skipped (`budget < min_rows`) for every pass while the long text prompt stages. That serializes image staging behind the text prompt's whole prefill instead of letting image blocks take the budget first as before. Process image items before text rows (or reserve budget for whole image blocks) so a long text prompt cannot indefinitely starve co-pending image staging.</comment>

<file context>
@@ -1246,19 +1285,32 @@ bool DeepSeek4Backend::begin_staged_pass(const std::vector<StagedPrefill *> & it
+            // Text: the budget's worth of rows, never leaving a tail below the
+            // layer-major minimum for the next pass.
+            const int remaining = item->prefix - item->done;
+            n = std::min(remaining, budget);
+            if (n < remaining && remaining - n < min_rows) n = remaining - min_rows;
+            if (n < min_rows) continue;
</file context>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 87816bf: image items take the shared pass budget before text prompts.

- Keep the image handle in in-flight staged-pass members so a request
  retired mid-pass cannot free image rows the pass still reads; the
  request id stays the identity check.
- Image blocks take the shared pass budget before text prompts.
- Heterogeneous staged chunks use the same placement-aware long-context
  cap as single-request sparse prefill.
- Free the slot-0 cache too when text staging does not fit.
- The 64-token threshold counts the whole prompt.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@davide221

Copy link
Copy Markdown
Contributor Author

Review of c5a9bea: all five points fixed in 87816bf.

  • P1, image lifetime: in-flight staged-pass members keep a strong ImagePromptHandle again, so a request retiring mid-pass cannot free image rows the pass still reads. The request id stays the identity check (text requests have no handle).
  • P1, hybrid chunk cap: heterogeneous staged chunks go through deepseek4_hybrid_prefill_chunk_tokens with the backend's placement-aware long-context cap, the same as single-request sparse prefill. Only the qualified R9700 + Strix Halo placement takes 2K chunks.
  • Image starvation: image items take the shared pass budget before text prompts.
  • Fallback memory: when text staging does not fit, the slot-0 cache is freed too.
  • Threshold: the 64-token threshold counts the whole prompt.

Re-verified on lucebox7 (R9700 + Strix Halo): 1843-token prompt 8.2 s to first token, two concurrent long prompts 18.7 s each, 4 short users 43.1 tok/s. Output hashes are unchanged from the previous head. test_server_unit and test_deepseek4_unit pass.

@cubic-dev-ai review the current head

@cubic-dev-ai

cubic-dev-ai Bot commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

Review of c5a9bea: all five points fixed in 87816bf.

  • P1, image lifetime: in-flight staged-pass members keep a strong ImagePromptHandle again, so a request retiring mid-pass cannot free image rows the pass still reads. The request id stays the identity check (text requests have no handle).
  • P1, hybrid chunk cap: heterogeneous staged chunks go through deepseek4_hybrid_prefill_chunk_tokens with the backend's placement-aware long-context cap, the same as single-request sparse prefill. Only the qualified R9700 + Strix Halo placement takes 2K chunks.
  • Image starvation: image items take the shared pass budget before text prompts.
    ...

@davide221 I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 7 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="server/src/deepseek4/deepseek4_backend.cpp">

<violation number="1" location="server/src/deepseek4/deepseek4_backend.cpp:2095">
P2: Text-only sparse paged startup still aborts if slot 0's staging cache does not fit. Route this failure through the existing `!staged` fallback; image serving still needs to fail when its staging cache cannot be allocated.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment on lines +2095 to +2099
if (!create_deepseek4_cache(backend_, w_, max_ctx, cache_)) {
std::fprintf(stderr, "[deepseek4] failed to allocate KV cache (ctx=%d)\n", max_ctx);
return false;
}
bool staged = true;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Text-only sparse paged startup still aborts if slot 0's staging cache does not fit. Route this failure through the existing !staged fallback; image serving still needs to fail when its staging cache cannot be allocated.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At server/src/deepseek4/deepseek4_backend.cpp, line 2095:

<comment>Text-only sparse paged startup still aborts if slot 0's staging cache does not fit. Route this failure through the existing `!staged` fallback; image serving still needs to fail when its staging cache cannot be allocated.</comment>

<file context>
@@ -2027,28 +2085,47 @@ bool DeepSeek4Backend::init() {
+            // staging cache (slot 0 uses cache_), then copy it into the paged
+            // slot. All of them are allocated now, so memory is committed at
+            // startup rather than in the middle of a request.
+            if (!create_deepseek4_cache(backend_, w_, max_ctx, cache_)) {
+                std::fprintf(stderr, "[deepseek4] failed to allocate KV cache (ctx=%d)\n", max_ctx);
+                return false;
</file context>
Suggested change
if (!create_deepseek4_cache(backend_, w_, max_ctx, cache_)) {
std::fprintf(stderr, "[deepseek4] failed to allocate KV cache (ctx=%d)\n", max_ctx);
return false;
}
bool staged = true;
bool staged = create_deepseek4_cache(backend_, w_, max_ctx, cache_);
if (!staged && (!stage_text || vision_)) {
std::fprintf(stderr, "[deepseek4] failed to allocate KV cache (ctx=%d)\n", max_ctx);
return false;
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 796f086: a failed slot-0 staging cache takes the same fallback when vision is off.

…s not fit

Text-only sparse paged serving now treats a failed slot-0 staging cache
like the other slots: text prompts keep the gathered prefill. Image
serving still fails startup, since it needs the staging caches.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@davide221

Copy link
Copy Markdown
Contributor Author

Review of 87816bf: fixed in 796f086. A failed slot-0 staging cache now takes the same fallback as the other slots: without vision, text prompts keep the gathered prefill and startup continues. With vision, startup still fails, since image serving needs the staging caches. free_deepseek4_cache is safe on the never-allocated cache. Build, test_server_unit and test_deepseek4_unit pass on gfx1201.

@cubic-dev-ai review the current head

@cubic-dev-ai

cubic-dev-ai Bot commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

Review of 87816bf: fixed in 796f086. A failed slot-0 staging cache now takes the same fallback as the other slots: without vision, text prompts keep the gathered prefill and startup continues. With vision, startup still fails, since image serving needs the staging caches. free_deepseek4_cache is safe on the never-allocated cache. Build, test_server_unit and test_deepseek4_unit pass on gfx1201.

@cubic-dev-ai review the current head

@davide221 I have started the AI code review. It will take a few minutes to complete.

…cess expert path

run_staged_text_chunk() drives the heterogeneous prefill through the
in-process expert backend or expert runtime. A hybrid placement without
either now keeps the gathered prefill instead of staging text prompts
that would then fail.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found and verified against the latest diff

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="server/src/deepseek4/deepseek4_backend.cpp">

<violation number="1" location="server/src/deepseek4/deepseek4_backend.cpp:1270">
P2: A runtime failure inside `run_staged_text_chunk` permanently fails the already-admitted request instead of falling back to gathered prefill. The chunked path is only entered when `staged_text_uses_chunks()` (hybrid placement), and once the slot is seeded and `staged.error` is set here, `DeepSeek4SeqEngine::step` reports `fail_prefill` for the slot with no fallback (see `deepseek4_seq_engine.cpp` step: `failed -> fail_prefill(slice.slot, ...)`). This change deliberately added a resilient fallback for init-time staging-cache allocation failure (“text prompts prefill in the batch”), so a transient chunk failure (embedding error, scratch allocation) hitting this path will reject a request that could still have run gathered prefill. Consider voicing the batch-pre-fill fallback here (e.g., retire the staged admit and re-admit the request as gathered) or at least documenting that the failure is intentional.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

/*allow_decode_graph_reuse=*/true, nullptr, moe_hybrid_.get(),
expert_runtime_.compute ? &expert_runtime_ : nullptr,
routing_stats_.get(), vision::ImageSpanView{})) {
error = "staged text prefill failed";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: A runtime failure inside run_staged_text_chunk permanently fails the already-admitted request instead of falling back to gathered prefill. The chunked path is only entered when staged_text_uses_chunks() (hybrid placement), and once the slot is seeded and staged.error is set here, DeepSeek4SeqEngine::step reports fail_prefill for the slot with no fallback (see deepseek4_seq_engine.cpp step: failed -> fail_prefill(slice.slot, ...)). This change deliberately added a resilient fallback for init-time staging-cache allocation failure (“text prompts prefill in the batch”), so a transient chunk failure (embedding error, scratch allocation) hitting this path will reject a request that could still have run gathered prefill. Consider voicing the batch-pre-fill fallback here (e.g., retire the staged admit and re-admit the request as gathered) or at least documenting that the failure is intentional.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At server/src/deepseek4/deepseek4_backend.cpp, line 1270:

<comment>A runtime failure inside `run_staged_text_chunk` permanently fails the already-admitted request instead of falling back to gathered prefill. The chunked path is only entered when `staged_text_uses_chunks()` (hybrid placement), and once the slot is seeded and `staged.error` is set here, `DeepSeek4SeqEngine::step` reports `fail_prefill` for the slot with no fallback (see `deepseek4_seq_engine.cpp` step: `failed -> fail_prefill(slice.slot, ...)`). This change deliberately added a resilient fallback for init-time staging-cache allocation failure (“text prompts prefill in the batch”), so a transient chunk failure (embedding error, scratch allocation) hitting this path will reject a request that could still have run gathered prefill. Consider voicing the batch-pre-fill fallback here (e.g., retire the staged admit and re-admit the request as gathered) or at least documenting that the failure is intentional.</comment>

<file context>
@@ -1230,6 +1233,47 @@ bool DeepSeek4Backend::begin_staged_prefill(StagedPrefill & item) {
+            /*allow_decode_graph_reuse=*/true, nullptr, moe_hybrid_.get(),
+            expert_runtime_.compute ? &expert_runtime_ : nullptr,
+            routing_stats_.get(), vision::ImageSpanView{})) {
+        error = "staged text prefill failed";
+        return false;
+    }
</file context>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kept terminal on purpose and documented in 27b459b: the slot already holds the prompt as seeded rows, and a failure of this path would most likely recur in gathered prefill. Init-time failures still fall back.

…ilure

- In the shared pass, a text tail below twice the layer-major minimum
  goes in whole when it fits the remaining budget instead of waiting for
  a later pass.
- A heterogeneous staged chunk failure stays terminal for the request,
  now with the reason in the code.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@davide221

Copy link
Copy Markdown
Contributor Author

Review of 26595ea:

  • P3, short tail stall: fixed in 27b459b. In the shared pass, a text tail below twice the layer-major minimum goes in whole when it fits the remaining budget, as run_staged_text_chunk already does.
  • P2, chunk failure is terminal: kept intentionally, now documented in the code. By the time a chunk runs, the slot holds the prompt as seeded rows, and falling back would mean unwinding that slot. A failure of this path (scratch or expert allocation) would most likely recur in the gathered prefill of the same rows, so the request fails cleanly and its slot is released. Init-time failures still fall back to gathered prefill.

Build, test_server_unit and test_deepseek4_unit pass on gfx1201.

@cubic-dev-ai review the current head

@cubic-dev-ai

cubic-dev-ai Bot commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

Review of 26595ea:

  • P3, short tail stall: fixed in 27b459b. In the shared pass, a text tail below twice the layer-major minimum goes in whole when it fits the remaining budget, as run_staged_text_chunk already does.
  • P2, chunk failure is terminal: kept intentionally, now documented in the code. By the time a chunk runs, the slot holds the prompt as seeded rows, and falling back would mean unwinding that slot. A failure of this path (scratch or expert allocation) would most likely recur in the gathered prefill of the same rows, so the request fails cleanly and its slot is released. Init-time failures still fall back to gathered prefill.

Build, test_server_unit and test_deepseek4_unit pass on gfx1201.
...

@davide221 I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 7 files

Re-trigger cubic

@davide221
davide221 merged commit 82f0a04 into main Sep 28, 2026
19 of 21 checks passed
dusterbloom pushed a commit to dusterbloom/lucebox-hub that referenced this pull request Sep 29, 2026
…ged serving (Luce-Org#781)

* perf(deepseek4): stage long text prompts through sparse prefill in paged serving

Paged DeepSeek4 serving prefilled every prompt row in the gathered graph,
one row per lane per step on the R9700 + Strix Halo deployment: a
1843-token prompt took 85 s to its first token.

With --ds4-prefill sparse (now accepted with --paged-attention), text
prompts of at least 64 tokens take the path image prompts already use:
prefill into the slot's staging cache on the single-request sparse
layer-major path, copy into the paged slot, then prefill the last token
and decode in the gathered graph. The monolithic deployment shares the
layer-sliced staged pass. The heterogeneous one runs one chunk of the
regular hybrid prefill per step (2048 rows idle, 1024 while others
decode), since the shared pass needs the whole model on one GPU. Staged
requests are identified by request id, not by image handle. Without
vision the staging caches are optional: if they do not fit, text prompts
keep the gathered prefill. --ds4-prefill exact is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(deepseek4): review fixes for staged text prefill

- Keep the image handle in in-flight staged-pass members so a request
  retired mid-pass cannot free image rows the pass still reads; the
  request id stays the identity check.
- Image blocks take the shared pass budget before text prompts.
- Heterogeneous staged chunks use the same placement-aware long-context
  cap as single-request sparse prefill.
- Free the slot-0 cache too when text staging does not fit.
- The 64-token threshold counts the whole prompt.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(deepseek4): fall back to gathered prefill when slot 0 staging does not fit

Text-only sparse paged serving now treats a failed slot-0 staging cache
like the other slots: text prompts keep the gathered prefill. Image
serving still fails startup, since it needs the staging caches.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(deepseek4): stage text on a hybrid placement only with the in-process expert path

run_staged_text_chunk() drives the heterogeneous prefill through the
in-process expert backend or expert runtime. A hybrid placement without
either now keeps the gathered prefill instead of staging text prompts
that would then fail.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(deepseek4): take short staged text tails whole; document chunk failure

- In the shared pass, a text tail below twice the layer-major minimum
  goes in whole when it fits the remaining budget instead of waiting for
  a later pass.
- A heterogeneous staged chunk failure stays terminal for the request,
  now with the reason in the code.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

---------

Co-authored-by: mrciffa <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
davide221 added a commit that referenced this pull request Oct 7, 2026
…erf (#774)

* feat(ggml-cuda): add Qwen3.8-Flash-Next kernel suite (QSA, MMB, HC/GDN/PLE fusion)

* feat(qwen4exp): hand-written Qwen3.8-Flash-Next backend

* test(qwen4exp): forward smoke and mmb/cuBLAS differentials

* fix(harness): score GSM/Math answers correctly and add the planted-recall suite

* perf(qwen4exp): measured dense-GEMM dispatch table and 16-row HC tile

- QWEN4EXP_DENSE_TABLE: per-shape measured dense-GEMM dispatch (gfx1151,
  T=16366), routing by measured winner (mostly MMQ over MMB/cuBLAS).
- QWEN4EXP_HC_TILE16: 16-row HC gate/mix tile on RDNA3.5, byte-exact.
- expert-major MoE pipeline implemented but neutral; rejected, kept
  default-off behind QWEN4EXP_MOE_PIPELINE.
- harness BENCH_MAX_TOKENS / BENCH_THINKING / BENCH_EFFORT experiment knobs.
- delivered @16366 tokens: 1063.1 t/s median / 1065.5 best (control 994.0 /
  1002.2), min-of-8 all >1000; quality HE 10/10, GSM 10/10, Math 9/10,
  recall 2/2; GSQ + IQ4_NL reference profiles byte-exact.
- evidence under docs/performance/qwen4exp-1100/.

* perf(qwen4exp): enable dense table, 16-row HC tile, and last-token FFN by default

These three were validated wins in 52a40e52 but shipped default-off, so the
released binary ran the slow path. Now on by default (opt out with =0).

- QWEN4EXP_DENSE_TABLE=1, QWEN4EXP_HC_TILE16=1, QWEN4EXP_LAST_TOKEN_FFN=1
- QWEN4EXP_UPSTREAM=1 still excludes the two dispatch candidates, so the
  reference profile is unchanged.

Verified on IQ4_NL with no candidate flags:
- quality HE 10/10, GSM 10/10, Math 9/10, recall 2/2
- prefill min-of-8 @16366 tokens: TTFT 15.27 s -> ~1072 t/s
- reference differential (GSQ, QWEN4EXP_UPSTREAM=1): byte-exact, 0/160
  expert-ID mismatches, no onset.

* perf(qwen4exp): reuse the T=1 decode workspace by default

QWEN4EXP_DECODE_REUSE retains a T=1 decode metadata context and graph
allocator in Qwen4ExpCache: each token resets the metadata arena, rebuilds
the graph, remeasures allocator assignments, and reuses the allocator
backing buffers. Default-on; opt out with =0; excluded under
QWEN4EXP_UPSTREAM=1.

Decode min-of-N (IQ4_NL, 1 warm-up + 8):
- ~2k:  27.87 -> 28.55 t/s (+2.43%)
- ~16k: 24.62 -> 25.34 t/s (+2.93%)

Gates: exact constrained greedy output/token count at both depths;
reference differential byte-exact (ratios 1.0000, 0/48 expert-ID
mismatches); quality HE 10/10, GSM 10/10, Math 9/10, recall 2/2;
prefill min-of-8 unchanged (15.30 s @16366).

* perf(qwen4exp): capture/replay a stable T=1 decode graph by default

The T=1 decode step now runs a stable, per-KV-bucket cgraph (fixed views,
bucketed kv_len, single input buffer) that HIP captures once and replays:
~2,236 replays / 2,240 calls, one hipGraphLaunch per steady-state token
carrying all ~2,800 kernels. Build/allocation per token drops from
0.95->0.011 ms (2k) and 1.21->0.010 ms (16k).

Decode min-of-N (IQ4_NL, 1 warm-up + 8):
- ~2k:  28.58 -> 29.89 t/s (+4.58%)
- ~16k: 25.32 -> 28.06 t/s (+10.85%)

Default-on: QWEN4EXP_DECODE_STABLEGRAPH (opt out =0) and the HIP graph
replay build option (server/CMakeLists.txt now defaults GGML_HIP_GRAPHS=ON;
-DGGML_HIP_GRAPHS=OFF to disable). Excluded under QWEN4EXP_UPSTREAM=1.

Gates: exact greedy token stream; quality HE 10/10, GSM 10/10, Math 9/10,
recall 2/2; reference differential byte-exact (no onset); prefill min-of-8
unchanged (~1068 t/s @16366).

* perf(qwen4exp): route GSQ (IQ3_XXS) dense GEMMs off MMB

Adds 22 measured GSQ tuples to the default-on QWEN4EXP_DENSE_TABLE, selecting
MMQ (instead of the slow MMB path) for exact-16366-token, gfx1151 qwen4exp
runs. Excluded under QWEN4EXP_UPSTREAM=1.

GSQ prefill min-of-N @16,366: 579.63 [579.33-583.97] -> 757.99
[754.33-764.33] t/s (+30.77%). Gates: exact planted recall, greedy "Paris",
GSQ quality HE10/GSM8/Math10/recall2, GSQ+IQ4 upstream differentials no onset
0/ID mismatches, IQ4 prefill 1073.69 t/s and decode thermally matched.
A BF16 rocBLAS extension reached 857.93 t/s but corrupted long-context
output and was rejected (rocBLAS/f16-fallback risk; see log E26).

* revert(qwen4exp): hold HIP graph replay default pending quality triage

T12 (all-arch regression) found that with HIP graphs on, qwen4exp missed one
standard 13k recall fact (7/8 matched cases vs 8/8 with graphs off) and the
first greedy response was not byte-stable on first capture; fresh repeats
passed 6/6 but the signal blocks an unconditional ship.

Restore GGML_HIP_GRAPHS=OFF (server/CMakeLists.txt) and make the stable T=1
graph opt-in (QWEN4EXP_DECODE_STABLEGRAPH=1). No throughput regressions were
seen on qwen35/deepseek4/qwen4exp, but correctness gates win. The E23/E24
code stays for triage (T14).

* perf(qwen4exp): default the stable T=1 decode graph on, HIP replay off

T14 root-caused the E30 quality variance to pre-existing prefill numerics
(full-vocab logit hashes already differ at step 0 even with HIP graphs OFF,
QSA/MMB/tiled-GDN off, and the upstream profile) rather than the stable graph,
and showed HIP capture/replay is throughput-neutral in a matched stable-path
A/B. So re-enable only the stable T=1 graph (cached cgraph + allocator, which
carries the decode win) while keeping GGML_HIP_GRAPHS=OFF.

QWEN4EXP_DECODE_STABLEGRAPH is default-on (opt out =0); excluded under
QWEN4EXP_UPSTREAM=1.

Decode min-of-N (IQ4_NL, 1 warm-up + 8), same graphs-off build, paired:
- ~2k:  27.85 -> 29.70 t/s
- ~16k: 22.40 -> 26.60 t/s   (E23 order-controlled: 25.32 -> 28.06, +10.85%)

Gates: HE 10/10, GSM 10/10, Math 9/10, recall 2/2; prefill min-of-8 15.31 s
@16366; reference differential no onset; T14 graph-on recall 16/16.

* fix(qwen4exp): final backend pass — safety, contract, and hygiene fixes

- fattn: move the sparse-mask assertion after the DeepSeek4 maskless dispatch
  (the qwen4exp guard was aborting DS4 maskless prefill).
- backend: drop the process-global GGML_CUDA_MMB setenv; implement real
  park/unpark (release + reload weights/cache, propagate errors).
- graph: require every full-attention layer to pass qsa_layer_ok before
  eliding the dense mask; parse QWEN4EXP_QSA by value (=0 now disables).
- loader/cache: free buffer + close PLE reader on failure; clear the PLE
  n-gram window on reset/free; reject malformed GDN metadata.
- hip_compat: add cudaErrorNoDevice; drop a self-referential __launch_bounds__.
- remove rejected/diagnostic-only paths (QWEN4EXP_MOE_PIPELINE + check,
  QWEN4EXP_KQ_MASK_DEV); CUDA_CHECK HIP calls; exhaustive CLAMP rejection list.
- tools/docs/tests: derive repo paths (no hardcoded /home/duster); full flag
  inventory in docs/qwen4exp.md + ENVIRONMENT.md; qwen4exp capability
  regression tests; fix two stale tests.

Validated: ROCm build PASS; ctest 730/730 (13 expected skips); quality HE 10/10,
GSM 10/10, Math 9/10, recall 2/2; upstream differential no onset; prefill N=8
1065.84 [1063.42-1066.88] t/s (+0.79%).

* fix(qwen4exp): lifetime-safe fast PLE/GDN conv fusion

Replaces the previous approach (b4bdf73a), which fixed a read-after-free by
dropping the CONCAT-time interception. That forced full materialization of the
conv-input concat (37 tensors ~[16369,10240], about 24.8 GB at T=16,366) and
cost +2.4 s prefill (IQ4_NL 17.10 vs 14.49 s; GSQ 23.46 vs 20.95 s).

This restores the fast interception and makes the dependency explicit to the
allocator through unused input slots, so the fused kernel reads tensors whose
lifetime is graph-encoded at the node where it runs:
- GDN: ordinary SSM_CONV ignores src[3]; it is set to the transpose input.
- PLE: CONT ignores src[1]; it is set to the normalized input for the first shift.

Gates: 16,366 prefill at/above the pre-fix parent (IQ4_NL 14.340 s / 1141 t/s,
GSQ 20.715 s / 790 t/s); C=1024 N=3 fresh-process snapshots byte-identical
(1f34fa...926c, matching the correct output); quality HE10/GSM10/Math9/recall2;
QWEN4EXP_UPSTREAM=1 differential no onset, 0 expert-ID mismatches; build OK.

* fix(qwen4exp): PLE gather serial fallback must cover every row

Qwen4ExpPleReader::gather() partitioned the serial-fallback range by the
configured thread-pool size, so a T=1 gather (fewer rows than workers) filled
only the first worker's slice and left the remaining per-layer-embedding rows
zero. Partition by the actual worker count (1 on the serial path).

Found via the batched-decode layer-by-layer diff; after the fix, solo quality
(HE 10/10, GSM 10/10, Math 9/10, recall 2/2) and the QWEN4EXP_UPSTREAM=1
differential (no onset, 0 expert-ID mismatches) are unchanged.

* feat(qwen4exp): batched independent-slot decode entry point (opt-in)

Adds qwen4exp_forward_batched(): one graph with T=active_slots independent
one-token rows, running the shared embedding/projection/MoE/HC ops batched
(weights read once) and the per-slot full-attention, GDN recurrence and PLE
against each slot's own Qwen4ExpCache, emitting one logits row per slot.

Gated by QWEN4EXP_BATCHED_DECODE=1 (default off; excluded under
QWEN4EXP_UPSTREAM=1). The serving scheduler does not call it yet. Uses one
shared caller-owned workspace; N=1 delegates to the single-sequence path.

Validated: N=1 bit-identical to the existing path; 4 identical slots mutually
bit-identical; untouched-slot isolation, row permutation and cancel/reset/reuse
pass; batched-vs-solo residual logit deltas ~1e-3 at boundaries growing to
~2 through routing (margin policy). N=4 @32768 fits the 96 GiB GTT pool with
~12 GiB headroom.

* feat(qwen4exp): opt-in concurrent sequence engine (per-slot full caches)

Adds Qwen4ExpSeqEngine implementing the shared SeqEngine contract: one
full-context Qwen4ExpCache per slot (F16, no paging), one shared batched-decode
workspace, a single FIFO prefill owner with 512-token slices, per-slot reset,
and bounded-progress plan handling. Decode batch runs via
qwen4exp_forward_batched(). Fixed the engine to advance the per-slot
Qwen4ExpCache::cur_pos after each successful prefill/decode (the single-sequence
forward leaves it at zero).

Gated behind LUCE_QWEN4EXP_SEQ_ENGINE=1 + QWEN4EXP_BATCHED_DECODE=1 (both default
off; excluded under QWEN4EXP_UPSTREAM=1). When enabled, the feature gate permits
--max-concurrency 2..4 at --max-ctx 32768 with one local device and no
--kv-pool-tokens; otherwise the existing --paged-attention requirement is
unchanged. Wired through ModelBackend::seq_engine().

Validated at N=2/N=4: real-engine SeqEngine contract PASS, randomized
admit/retire soak PASS (peak GTT 75.4 GB -> 18.6 MB teardown), and 4 concurrent
distinct requests all coherent (distinct-concurrent=PASS); only slot 0 diverged
from solo at step 7 (epsilon 0.509 vs solo margin 0.021, within the margin
allowance). The decisive quality-under-batch gate is P3.

* fix(qwen4exp): don't force paged attention for the opt-in full-cache engine

server_main.cpp auto-enabled --paged-attention whenever --max-concurrency > 1,
which conflicts with the qwen4exp full-cache sequence engine that requires
paging off. Add a narrow exception: skip the auto-enable only when
LUCE_QWEN4EXP_SEQ_ENGINE=1 and QWEN4EXP_BATCHED_DECODE=1 (and not
QWEN4EXP_UPSTREAM); every other path is unchanged.

Validated end-to-end (N=4, --max-ctx 32768): the server starts in concurrent
mode, 4 simultaneous distinct requests return correct independent answers (no
cross-talk), and the sequential quality suite still passes (HE 10/10, GSM 10/10,
Math 9/10, recall 2/2). Goodput N=1 vs N=4: per-request decode 27.9 -> 7.5 t/s,
aggregate ~1.08x -- MoE expert streams do not amortize across rows.

* fix(ggml-cuda): make the qwen4exp kernels portable to CUDA and RDNA4

The Qwen3.8-Flash-Next kernel suite used AMD-specific intrinsics that broke
non-gfx1151 targets:
- CUDA/NVIDIA: ggml-cuda.cu/fattn.cu referenced the HIP-only MMB/HC/QSA symbols
  unconditionally, but the CUDA build excludes those TUs -> link failure. All 65
  references are now behind #if defined(GGML_USE_HIP) with the generic
  matmul/attention path restored for CUDA.
- gfx1201 (RDNA4 / ROCm 7.2.2): mmb.cu and qsa.cu failed to compile ('Cannot
  select intrinsic llvm.amdgcn.wmma.f32.16x16x16.f16', plus the BF16 WMMA
  builtin). The real MMB/QSA implementations are now compiled only for gfx1151,
  other targets get link-compatible unsupported stubs so the supported_* checks
  fall back to generic kernels, and MMB runtime enablement is restricted to
  RDNA3.5.

Verified: gfx1151 build (luce_server + smoke), IQ4_NL forward smoke (T=16
prefill + decode, finite logits), HTTP greedy smoke (Paris), and compile-only
checks for mmb.cu/qsa.cu at gfx1201. CUDA and full gfx1201 link are validated by
CI.

* perf(qwen4exp): pack concurrent prefill rows into one ragged graph

The concurrent engine pinned a single FIFO prefill owner and capped the
whole cohort at 512 prefill tokens, so prompts never shared a weight read
with each other or with the live decode rows. Decode was already
width-batched (all dense and routed matmuls ran at T = live rows).

Packed ragged prefill gives each slot its own 512-token chunk, up to the
graph's 2048-row budget minus live decode rows, so independent sequences
share one traversal for dense projections, HC, router and MoE, while
attention KV, GDN recurrence and PLE history stay per-slot.

Whole-wave aggregate goodput (Halo, 3 fresh servers per width): N=1 11.45,
N=2 14.22, N=3 15.86 (1.39x), N=4 15.42 tok/s, +22% at N=4 over 12.64.
Quality, contract, soak, HTTP edge gates and QWEN4EXP_UPSTREAM parity all
pass. Opt-in via LUCE_QWEN4EXP_SEQ_ENGINE=1 + QWEN4EXP_BATCHED_DECODE=1.

* feat(props): report where the model's memory goes (#777)

Issue #675 asked how to see what is responsible for growing host RAM:
KV-cache size in tokens and bytes, device versus host allocations,
whether memory is released after compaction, and DFlash host buffers.
None of it was visible without reading the code.

/props gains a `memory` section:
- `cache`: the live cache the model decodes from, allocated once for
  --max-ctx: location (device or host), capacity and live tokens, and
  bytes split into attention K/V, recurrent state, DFlash target
  features and the rest of the allocation, plus live host-side decode
  state (DeepSeek4 logits and DSpark feature window).
- `snapshots`: every saved snapshot with its slot, role (prefix,
  agent_turn, prefill_cache, disk_staging), tokens, bytes and location,
  with host and device totals. On discrete GPUs this is where RAM grows
  when an agent conversation keeps one snapshot per turn.
- `process`: resident and peak RSS, read when /props is served.

ModelBackend::memory_report() builds the numbers from the real buffers
(Qwen and DeepSeek4; other backends report nothing). In DeepSeek4
concurrent serving the cache is the paged cache plus the per-slot image
staging caches, and host vectors count by capacity, since trimming them
keeps their allocation. The generation
thread publishes the report at startup and after every request, in the
classic worker and in the concurrent scheduler, and /props serves the
stored copy, so it never touches backend state from the client thread.
The OpenAPI spec and props-endpoint.md describe the new section; the
change is additive, so props_schema stays 2.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>

* perf(qwen35): adaptive DFlash2 verify width in the concurrent engine (#779)

* perf(qwen35): adaptive DFlash2 verify width in the concurrent engine

The concurrent engine verified every chain at the full draft block. With
several lanes the batched verify is compute-bound, so a round of 8 lanes x
16 rows mostly verifies drafts that are rejected early.

Each batch bucket now keeps an AdaptiveSpecWidth and picks the verify width
per round from {4, 8, block}: expected committed tokens from per-depth
conditional acceptance (a depth counts only when offered with every
shallower candidate accepted, so narrow rounds do not bias deeper
estimates) divided by the measured round cost. Each width is offered three
times per bucket first; the cold first offer is not a cost sample. The
drafter still proposes the full block and a round verifies its prefix.

On by default for batched serving; LUCE_ADAPTIVE_SPEC_WIDTH=0 restores
the fixed block width. Single-request speculative decoding is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(qwen35): review fixes for the adaptive verify width

- Key the width controllers by the exact speculative lane count instead
  of the graph bucket, which spans several lane counts.
- Take cost samples only from rounds without AR peers and without a
  graph rebuild, so build time and mixed loads do not bias the costs.
- Scope the default-on note to DFlash2 chain speculation.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(qwen35): calibrate widths on clean samples; learn from verified prefixes

- Calibration offers a width until it has two clean cost samples (capped
  at eight offers), so the cost model is active after calibration even
  when rounds often carry AR peers or graph rebuilds.
- Acceptance statistics use the target-verified prefix before the room
  and min-token clamps, which are serving policy, not rejections.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(qwen35): saturate width calibration counters; reuse per-round buffers

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(qwen35): observe the round's majority lane last

The controller's clean-draft flag comes from its last observe(); the
lane whose outcome matches the round majority now goes last, carrying
the round's cost sample.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(qwen35): key adaptive width by the verify graph bucket

The verify graph is built for tree_bucket lanes, with missing lanes as
padding, so a round's cost is set by the bucket and width rather than
the number of real lanes. Keying by bucket keeps each cost model
consistent and calibrates each bucket once.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

---------

Co-authored-by: mrciffa <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>

* perf(deepseek4): stage long text prompts through sparse prefill in paged serving (#781)

* perf(deepseek4): stage long text prompts through sparse prefill in paged serving

Paged DeepSeek4 serving prefilled every prompt row in the gathered graph,
one row per lane per step on the R9700 + Strix Halo deployment: a
1843-token prompt took 85 s to its first token.

With --ds4-prefill sparse (now accepted with --paged-attention), text
prompts of at least 64 tokens take the path image prompts already use:
prefill into the slot's staging cache on the single-request sparse
layer-major path, copy into the paged slot, then prefill the last token
and decode in the gathered graph. The monolithic deployment shares the
layer-sliced staged pass. The heterogeneous one runs one chunk of the
regular hybrid prefill per step (2048 rows idle, 1024 while others
decode), since the shared pass needs the whole model on one GPU. Staged
requests are identified by request id, not by image handle. Without
vision the staging caches are optional: if they do not fit, text prompts
keep the gathered prefill. --ds4-prefill exact is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(deepseek4): review fixes for staged text prefill

- Keep the image handle in in-flight staged-pass members so a request
  retired mid-pass cannot free image rows the pass still reads; the
  request id stays the identity check.
- Image blocks take the shared pass budget before text prompts.
- Heterogeneous staged chunks use the same placement-aware long-context
  cap as single-request sparse prefill.
- Free the slot-0 cache too when text staging does not fit.
- The 64-token threshold counts the whole prompt.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(deepseek4): fall back to gathered prefill when slot 0 staging does not fit

Text-only sparse paged serving now treats a failed slot-0 staging cache
like the other slots: text prompts keep the gathered prefill. Image
serving still fails startup, since it needs the staging caches.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(deepseek4): stage text on a hybrid placement only with the in-process expert path

run_staged_text_chunk() drives the heterogeneous prefill through the
in-process expert backend or expert runtime. A hybrid placement without
either now keeps the gathered prefill instead of staging text prompts
that would then fail.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(deepseek4): take short staged text tails whole; document chunk failure

- In the shared pass, a text tail below twice the layer-major minimum
  goes in whole when it fits the remaining budget instead of waiting for
  a later pass.
- A heterogeneous staged chunk failure stays terminal for the request,
  now with the reason in the code.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

---------

Co-authored-by: mrciffa <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>

* fix(ggml-cuda): compile qwen4exp MMB/QSA host dispatch on every HIP target

The portability guard used #if defined(__gfx1151__), but the HIP host pass
defines no arch macro, so in every HIP build since then MMB's host dispatch
compiled to the stub and QSA reported "unsupported". Guard the device code with
defined(__gfx1151__) || !defined(__HIP_DEVICE_COMPILE__) and gate the host
decision on the runtime cc (GGML_CUDA_CC_IS_RDNA3_5).

Restores pre-regression behaviour on gfx1151 single-arch and fat builds: MMB
live at T>=512 (routed MoE per first chunk 1474 -> 391 ms), QSA=1 runs, quality
HE10/GSM10/Math9/recall2, QWEN4EXP_UPSTREAM clean with 0 expert-id mismatches.

* feat(ggml-cuda): opt-in Q8_0->F16 WMMA dense GEMM for MMB prefill

Adds mmb-q8f16.cuh: a Q8_0 dense GEMM for MMB prefill (T>=512, gfx1151) that
dequantizes weights while staging LDS into an F16 WMMA 256-row tile with whole-K
F32 accumulation, ported from gufo's MIT design. Opt-in via LUCE_MMB_Q8F16=1;
changes numerics vs the bf16 tile, so it stays default-off.

UD-Q4_K_XL: dense MUL_MAT per d0 chunk 2299 -> 841 ms, 16,366 TTFT 25.69 -> 17.28 s
(637 -> 947 tok/s), decode unchanged. Microbench 32.9-35.9 TFLOPS on qkv/gate/q/
ssm_out (gufo F16 route ~36-37). Quality HE10/GSM10/Math10/recall2 with it on.

* chore(gitignore): keep local qwen4exp performance evidence out of git

* fix(qwen4exp): drop head-offload declarations that leaked into the committed header

f6b4dfec declared Qwen4ExpHeadOffload and an eight-argument qwen4exp_forward
with a defaulted head parameter, but the implementation lives only in the
unshipped layer-split work. The committed .cpp defines the seven-argument
overload, so every seven-argument call was ambiguous and luce_common failed to
compile on Linux, Windows and GB10.

* fix(ggml-cuda): add the mmb-small-m.cuh header that mmb.cu includes

mmb.cu includes mmb-small-m.cuh for the opt-in LUCE_MMB_SMALL_M bandwidth
kernel, but the header was never committed, so both ROCm builds stopped at the
missing include. This is the same file the gfx1151 measurements were built with.

* refactor(ggml-cuda): remove the QWEN4EXP_DENSE_PROBE route sweep from dense matmul

The probe timed every dense route inline in ggml_cuda_mul_mat and forced
routes through a global MMB tile override. It was an offline capture tool for
building the frozen QWEN4EXP_DENSE_TABLE, which stays. With the flag unset the
route and the tile override were always zero, so default dispatch is unchanged.

* refactor(qwen4exp): remove the QWEN4EXP_LAYER_TRACE tensor trace

The trace wrote selected activations to /tmp from all three forward paths and
duplicated QWEN4EXP_DUMP, which the upstream differential harness uses. Every
trace call acted only when the flag was set, so the graphs are unchanged. The
batched smoke test's trace-prefix and first-decode hooks go with it.

* chore(test): drop test_quant_probe, a manual GGUF probe with no assertions

It was a diagnostic executable, never registered with ctest, that printed
dequantized tensor bytes for manual comparison.

* perf(ggml-cuda): split routed dequant and 64-token small routed tiles

Q4_K GLU rows and Q5_1 down blocks are decoded by all threads instead of one row per
thread, and experts under 128 rows use 64-token tiles, so each expert's weights stream
once. Per-output K order is unchanged: bit-exact (E372, E376). UD chunk@0 about -50 ms;
IQ4 long-prompt flat (session 15).

* perf(ggml-cuda): 16-channel HC gate-mix tile for Q8_0 weights

The CH=16 tile already served IQ4_NL; UD's Q8_0 HC-up weights stayed on CH=32 at ~7 TF.
Byte-identical output (855/855 tile checks), greedy 3/3 at d0/4k/16k, quality unchanged
(E386, formerly dense E376). UD d0 chunk 2,131.75 -> 2,077.26 ms. Off under QWEN4EXP_UPSTREAM
via QWEN4EXP_HC_TILE16.

* perf(qwen4exp): read PLE n-gram rows with 32 threads

A fresh 2K-token prompt gathers ~49k random PLE rows from disk; with 4
reader threads that host phase took 500-650 ms and dominated the gap
between our forward span and TTFT. 32 readers bring it to ~100 ms:
fresh-prompt TTFT 2.25 -> 1.83 s on UD-Q4_K_XL (gfx1151). Rows are
identical, so outputs are bit-exact; decode gathers stay serial.

* perf(qwen4exp): F16 activation dataflow and int8 HC down for gfx1151 MMB prefill, default-on

Prefill on gfx1151 moved activations as F32 or bf16 and converted them per
consumer. Producers now emit what their consumers read:

- GGML_OP_GATED_RMS_NORM_F16: rms * ssm_norm * sigmoid(z) written as F16
  for ssm_out's Q8_0 -> F16 GEMM; the attention gate uses the same op
  without the norm. Both bit-exact vs the unfused chain.
- The MoE weighted combine and shared-expert gate fold into the next
  HC_COMBINE_NORM (MoE mode); routed down writes F16 rows read only by
  that combine. Prefill only (at T=1 the fold cost ~1.7% decode).
- The HC combine emits Q8 tiles of xn when it feeds a Q8_0 HC down, which
  then runs W8A8 on int8 WMMA (mmb-w8a8.cuh, derived from gufo's
  W8A8BlockedWmmaGEMMKernel, MIT notice included).
- Q8F16 (Q8_0 dense on F16 WMMA) and the small-M bandwidth kernel are now
  default-on; the GLU output is marked bf16-only when every consumer is an
  MMB MUL_MAT_ID.

Kill switches (=0): LUCE_MMB_Q8F16, LUCE_MMB_SMALL_M, QWEN4EXP_F16,
LUCE_MMB_HCDOWN_I8; all four off reproduces the previous default byte for
byte. Excluded under QWEN4EXP_UPSTREAM and QWEN4EXP_DUMP; the upstream
differential stays byte-exact on IQ4_NL and UD.

Median of per-server minimum, 2048-token chunk: UD-Q4_K_XL 1958 -> 1827 ms
(vs the previous opt-in best; 3401 ms previous default), IQ4_NL (QSA=1)
2364 -> 2093 ms. Long-prompt quality gate passes on both quants (recall
3/3, HE/GSM/Math unchanged or better); decode unchanged.

* perf(ggml-cuda): stop unrolling the HC gate-mix k16 loop and epilogue

The fully unrolled k16 loop and epilogue token loop held LDS fragments and
xn loads for every step at once: 256 VGPRs with spills in 37 of 44
instantiations (production Q8_0 CH16: 7 spilled, occupancy 5). Without the
unroll the kernel uses 111 VGPRs, occupancy 8, and runs 1.17 -> 0.81 ms
per call. The WMMA accumulation order is unchanged, so output is
bit-identical.

2048-token chunk: UD-Q4_K_XL 1827 -> 1779 ms, IQ4_NL 2093 -> 2041 ms.

* perf(ggml-cuda): 128x256 Q8F16 tiles for GEMMs with at most 1024 output rows

The 256-row tile left M=640 GEMMs (qwen4exp shared-expert gate/up) with
three row blocks per token tile. A 128-row x 256-token tile runs the M=640,
K=2560, T=2048 shape in 0.216 ms instead of 0.327 ms. The per-output K
order is unchanged, so results are bit-identical (all 11 swept configs
matched at six prefill shapes); larger M keeps the 256x128 tile, which was
best or tied everywhere else.

* perf(ggml-cuda): per-token multi-section RoPE fused with PERMUTE + CONT

rope_multi launches one 256-thread block per row, half of it idle, and
recomputes the FP64 angle for every head; qwen4exp's Q (24 heads x 2048
tokens) then goes through a separate PERMUTE + CONT pass before flash
attention. For prefill batches (>= 64 tokens) a per-token kernel computes
each pair's angle once, applies it to every head, and writes through
arbitrary destination strides, so ROPE -> PERMUTE -> CONT runs as one
kernel straight into the attention layout.

The angle code is shared with rope_multi (refactor verified bit-identical)
and the rotation is written as the explicit FMA form rope_multi compiles
to, so outputs match bit for bit (0 of 12.6M elements differ; greedy text
identical). Decode and QWEN4EXP_UPSTREAM keep the original kernel and
graph.

UD-Q4_K_XL 2048-token chunk, with the Q8F16 tile change: 1779 -> 1746 ms.

* chore(ggml-cuda): carry gufo's MIT notice in the Q8F16 kernel

mmb-q8f16.cuh follows gufo's DenseF16GEMMKernel closely (the same fetch and
commit stages and the magic-number F16 dequant), so it is a substantial
portion of MIT-licensed code, and MIT asks for its copyright and permission
notice to travel with it. Include the notice in the same form as
mmb-w8a8.cuh instead of the one-line design credit.

* fix(ggml-cuda): limit the per-token MRoPE kernel to HIP builds

The per-token kernel writes its rotation as the explicit FMA form that HIP
compiles rope_multi's expression to, which makes it bit-identical on AMD.
nvcc may contract the same expression differently, so on CUDA the kernel
could move other MRoPE models' prefill by an ulp. CUDA builds keep
rope_multi; the ROPE -> PERMUTE -> CONT fusion still applies there, since it
only changes where rope_multi writes.

* chore(qwen4exp): drop internal experiment IDs from code comments

Several comments cited IDs from a local experiment log that is not part of
the repository. State the evidence in words instead.

* chore(harness): ruff-format client_test_runner.py

* fix(ggml-cuda): use fmaf in the per-token MRoPE rotation

MSVC-hosted nvcc has no __builtin_fmaf, so the Windows CUDA build of rope.cu
failed. fmaf rounds once like the builtin, so HIP results stay bit-identical
to rope_multi (0 of 12.6M elements differ on gfx1151).

* refactor(qwen4exp): default the gfx1151 profile and drop 26 env variables

On gfx1151 the backend sets the qualified prefill profile (GGML_CUDA_MMB=1,
QWEN4EXP_MMB_CUBLAS=5, LUCE_MMB_SHADOW=1, LLAMA_MMB_HC16=2, QWEN4EXP_QSA=1,
LUCE_HIP_NO_AUTO_UMA=1) before loading, so no environment is needed.
Explicit values win and QWEN4EXP_UPSTREAM keeps the reference path.

Diagnostics are deleted, burn-in kill switches retired to their default
path, QWEN4EXP_ROPE_F32 and QWEN4EXP_FA_PAD256 folded into
QWEN4EXP_UPSTREAM, and the batch/step telemetry into QWEN4EXP_PROF. The
scheduler UMA ring in ggml-backend.cpp goes back to main: qwen4exp never
uses ggml_backend_sched.

Verified on gfx1151: defaults reproduce the explicit recipe byte for byte
on UD-Q4_K_XL, IQ4_NL and GSQ at equal prefill speed, and the upstream
differential passes on all three.

* fix(qwen4exp): honour the thinking reply budget

The server hands every backend a BudgetHook that force-closes thinking
once the remaining budget reaches the reply reserve. The qwen4exp decode
loop ignored it, so thinking could consume max_tokens and leave no answer.

Add a small BudgetHookState next to BudgetHook, with the same semantics
as the scheduler's per-slot hook, and apply it in the qwen4exp decode
loop. The unit test covers a forced close, the multi-token close
sequence, a model that closes itself, and no hook.

* fix(ggml-cuda): keep the LUCE_FA256_MMA opt-in on RDNA3.5

The env diet dropped LUCE_FA256_MMA from the RDNA3.5 head-256 route
check along with QWEN4EXP_FA_PAD256, but test_fattn_mma256 sets it to
pin that route on gfx1151 and failed on the Strix Halo runner. Restore
the opt-in; QWEN4EXP_UPSTREAM still enables the route on its own.

* feat(qwen4exp): ship model cards for Qwen3.8-Flash-Next

Without a card the server fell back to the qwen family table: greedy
sampling when the client sends none, and a bare </think> as the forced
close, after which the model kept reasoning in the visible reply.

Add cards for the supported GGUFs (general.name "Qwen3.8 Flash Next" for
the Unsloth UD and bartowski quants, "Qwen3.8-Flash-Next GSQ-RCO" for
ISTA-DASLab): the model card's thinking sampling (temperature 1.0,
top_p 0.95, top_k 20, min_p 0, no penalties), Qwen's budget-forcing text
as the thinking terminator, and an 8,192-token reply reserve.

* fix(qwen4exp): use Qwen's exact early-stopping text in the model cards

Qwen's budget-forcing text starts with a blank line ("\n\nConsidering the
limited time by the user, ..."). Without it the forced text was glued to
the last reasoning word ("...DELConsidering the limited time").

* fix(qwen4exp): run QSA at decode and pool consecutive block tokens

Checked against the reference Qwen4Exp QSA indexer (transformers qwen4_exp):

- Pooling averaged tokens j, j+nb, j+2nb, j+3nb of a chunk for block j
  instead of the block's own consecutive tokens 4j..4j+3, so block scores
  mixed in later tokens and depended on the chunk size.
- Decode and chunks under 128 tokens always attended densely. The reference
  selects the top 512 blocks plus the partial tail for every query once
  more than 512 complete blocks are visible (2,052 tokens); dense attention
  past that point gives a very different distribution (KL 5.8 vs the
  prefill on 6,000 tokens of real text).

Every token's raw indexer key is now cached and blocks are pooled from that
cache when QSA first needs them, so pooling no longer depends on where a
chunk starts. Past the block budget, chunks of 128 or more tokens use the
packed prefill kernel and shorter ones the per-query kernel (now up to 127
queries), reading K/V through cache strides. Below the budget QSA equals
dense attention and decode keeps the stable graph; past it the graph is
rebuilt per step on the reused workspace.

On UD-Q4_K_XL, one-token decode now matches a single prefill (KL 0.08, same
argmax), chunks of 512 or more are bit-identical to it, 16K recall passes,
and tg128 runs at 21.5 tok/s at 4K and 16K (dense: 23.2 / 22.8).

Adds test_qwen4exp_indexer_score (GPU vs CPU indexer scores for every
token-count specialization), a pooling unit test, and a prefill-vs-split
mode to smoke_qwen4exp_forward (QWEN4EXP_SMOKE_SPLIT=N[:chunk]).

* fix(qwen4exp): render with the GGUF chat template and think by default

Qwen3.8-Flash-Next's official template thinks by default and opens the
system turn with a reasoning-effort instruction (xhigh unless low or
medium is requested). The hardcoded Qwen3 renderer never wrote that line,
and the server's thinking-off default meant clients that send nothing got
non-thinking mode.

For qwen4exp the server now renders through the existing Jinja path with
the GGUF's tokenizer.chat_template (as llama.cpp does; --chat-template-file
still wins), passes the request's reasoning effort to it (high, x-high and
max map to xhigh), and keeps thinking and its budget envelope on unless the
request disables them. On lucebox4 the server's prompt token counts equal
the reference Jinja rendering for thinking on, effort medium and thinking
off.

* perf(ggml): fuse QSA block sorting and cell expansion

* perf(qwen4exp): use fused QSA cell IDs after top-k

* docs(qwen4exp): QSA also runs at decode

The QWEN4EXP_QSA row still said decode stays dense, which stopped being true in 1bb96427.

* fix(harness): read the result of an equation after a GSM answer marker

"Total: $2 + 1 = 3$" was scored as 2: the marker rule took the first number after "total:" and the bold "**3**" fallback never ran. When the marked number starts an arithmetic chain ending in "= N", take N. Found on Qwen3.8-Flash-Next gsm_02, which answers 3.

* fix(ggml-cuda): pass write_inverse to the mm-ids helper from the MIX WMMA path

main's ROCmFP MIX WMMA MoE path (#794) calls ggml_cuda_launch_mm_ids_helper with the old signature; this branch added write_inverse. Pass false, as the upstream mmq/mmf callers do, so the path behaves as on main. Fixes the build after merging main.

* fix(server): replay assistant reasoning_content and honour preserve_thinking in Jinja templates

Request history never carried an assistant turn's reasoning_content to the Jinja renderer, and chat_template_kwargs.preserve_thinking was ignored, so Qwen3.8-Flash-Next's official template rendered every earlier turn with an empty <think></think> block, neither of its two modes. Read reasoning_content (or reasoning) on assistant messages, pass it as message.reasoning_content, and pass preserve_thinking through when the client sets it (undefined otherwise, so the template default applies). Built-in templates are unchanged.

* feat(server): model-card sampling defaults for non-thinking requests

Qwen3.8-Flash-Next recommends different sampling with thinking off (temperature 0.7, top_p 0.80, top_k 20, presence_penalty 1.5) than with thinking on, but cards held one set, so thinking-off requests got the thinking defaults. An optional card field sampling_no_thinking now fills the sampling fields a request omits once its thinking state resolves to off; explicit fields still win and cards without it behave as before. Both Flash-Next cards carry Qwen's instruct set.

* fix(harness): preserve fraction grouping in math_scoring equivalence

_expand_frac() flattened \frac{A}{B} to a bare "A/B" string inside
_normalize_math(), which both discarded nesting (so the two different
groupings of \frac{1}{\frac{2}{3}} and \frac{\frac{1}{2}}{3} collapsed
to the identical string "1/2/3") and broke the pre-existing numeric
\frac{A}{B}-vs-decimal comparison (\frac{1}{2} no longer matched
"0.5") since the flattened form never reaches the frac_pat/mixed_pat
regexes in _math_equiv().

Keep _normalize_math() frac-preserving like upstream, and only flatten
(now with parenthesized grouping) as a later string-equality fallback
in _math_equiv(), after the exact/numeric fraction checks have had a
chance to run.

* refactor(ggml-cuda): delete the uncalled moe-weighted-reduction kernel

ggml_cuda_op_moe_weighted_reduction() has no caller anywhere in the
tree (only its own declaration and definition), and its header is
included only by itself. Remove the module and the CUDA CMake
exclusion/comment that mentioned it (it was only ever reachable
through the HIP backend's blanket *.cu glob, never from CUDA).

Also drop the now-orphaned ggml_cuda_mmb_down16() wrapper (declared in
mmb.cuh, defined in both mmb.cu arch branches), whose only caller was
the deleted module. mmb_down16_flag(), which it wrapped, still has a
live caller in mmb.cu and is untouched.

* refactor(ggml-cuda): delete unused dequantize.cuh converter templates

dequantize_iq4_nl<dst_t, dst_ptr_t> and dequantize_mxfp4<dst_t, dst_ptr_t>
have no callers anywhere in the tree: the IQ4_NL/MXFP4 cases in
mmb-quant.cuh compute inline instead of calling these templates.

The 15 single-template-param pointer-forwarding overloads
(dequantize_q2_K/q3_K/q4_K/q5_K/q6_K/iq2_xxs/iq2_xs/iq2_s/iq3_xxs/
iq3_s/iq1_s/iq1_m/iq4_nl/iq4_xs/mxfp4) are likewise unreachable: every
call site in mmb-quant.cuh passes an mmb_quant_slice (not a raw
pointer) as the output argument, which only the generic two-param
template can deduce against, so overload resolution never selects the
single-param forwarders.

Keep dequantize_iq4_xs<dst_t, dst_ptr_t> (531-544 pre-change), which
mmb-quant.cuh's IQ4_XS case still calls through that generic overload.

* refactor(qwen4exp): drop QWEN4EXP_PROF timing from the single-sequence path

Remove the per-call phase-timing (t0/t_emb/t_ple/t_alloc/t_upload/
t_compute), the forward-call timestamp log, and the trace_batch_widths()
call from qwen4exp_forward() -- the single-sequence path these fire
profiling fprintf statements in a hot loop for no functional purpose.

QWEN4EXP_DUMP activation dumps (used by the differential harness) are
untouched. The prof_now_ms/prof_enabled/mono_now_s/trace_batch_widths
helpers and the QWEN4EXP_PROF ENVIRONMENT.md entry stay for now: they
still have live callers in qwen4exp_forward_batched/_packed and
qwen4exp_seq_engine.cpp, which are retired as a unit in the
concurrency-removal change.

* refactor(qwen4exp): drop unused loader fields and the dead f32-array parser

get_f32_array() has no caller (a separate, unrelated get_f32_array()
in bailingmoe3_loader.cpp has its own callers and is untouched).

Qwen4ExpLayer's six *_s NVFP4-style scale fields (attn_qkv_s, wq_s,
wk_s, wv_s, wo_s, ssm_out_s) are never read or written anywhere
outside their own default-member-initializer.

attn_norm, attn_post_norm, ffn_norm and ffn_exp_probs_b are resolved
from the GGUF tensor table and added to the upload set, but the
forward graph never reads them (it only consumes the hc_*-prefixed
hyper-connection norms). Remove the fields together with their loader
assignments and upload registrations; keep the HC tensor validation
and everything the graph actually consumes.

* refactor(ggml-cuda): inline mmb.cu's constant-return mode helpers

mmb_f32split(), mmb_bf16w(), mmb_hc16(), mmb_tall_mode()/mmb_tall(),
mmb_gatemix_flag(), mmb_down16_flag() and mmb_glu() all unconditionally
return a fixed value (true, or 2 for mmb_tall_mode); mmb_f32split_mode()
had no caller at all. Inline each flag's constant at its call site and
delete the wrapper, and drop the two dispatch arms they gated that can
now never execute:

- ggml_cuda_mul_mat_mmb's F32 GEMM always took the `two=true` tile
  (mmb_f32split_kernel<128,128,32,64,true,...>); the `two=false` arm
  is removed.
- The tall-M IQ4_NL path always took `wide=true`
  (mmb_dense_kernel<384,64,96,32,0>); the narrow (32-row) arm is
  removed.

No arithmetic changes and the same kernel instantiations run as
before -- this only removes dead branches and the indirection to
reach them. mmb.cu is excluded from the CUDA build (HIP-only, see
ggml-cuda/CMakeLists.txt) and this environment has no ROCm/HIP
toolchain, so this change could not be compiled locally; it needs a
build + the existing qwen4exp/mmb differential checks on the gfx1151
box before merge.

* refactor(qwen4exp): retire the experimental independent-slot concurrency

Remove the default-off qwen4exp SeqEngine path (gated behind
LUCE_QWEN4EXP_SEQ_ENGINE=1 + QWEN4EXP_BATCHED_DECODE=1 +
--max-concurrency=2..4 + --max-ctx=32768, and still excluded under
QWEN4EXP_UPSTREAM) before it ships:

- Delete qwen4exp_seq_engine.{cpp,h}, the smoke/unit tests built only
  for it (smoke_qwen4exp_batched.cpp, test_qwen4exp_seq_engine.cpp)
  and their CMake targets.
- Delete qwen4exp_forward_batched()/qwen4exp_forward_packed() from
  qwen4exp_graph.{cpp,h} and the GDN/PLE graph builders that existed
  only to feed them (build_linear_attn_projected[_sequence],
  build_full_attn_projected, build_ple_row, build_ple_projected,
  column[_span], token_span_3d) -- each had zero remaining callers
  once the two entry points were gone. The now-fully-dead
  QWEN4EXP_PROF telemetry helpers (prof_now_ms/prof_enabled/
  mono_now_s/trace_batch_widths), whose last callers were these
  functions and qwen4exp_seq_engine.cpp, go with them; QWEN4EXP_DUMP
  activation dumps are untouched.
- Delete Qwen4ExpBatchedDecodeWorkspace and
  clear_qwen4exp_batched_decode_workspace() (qwen4exp_cache.{cpp,h});
  Qwen4ExpDecodeWorkspace (the single-sequence T=1 reuse workspace)
  is untouched.
- Drop the multi-slot cache vector, SeqEngine member and seq_engine()
  override from Qwen4ExpBackend, and the max_concurrency field from
  Qwen4ExpBackendConfig (backend_factory.cpp never set anything else
  on it, matching bailingmoe3's single-sequence config).
- Remove the qwen4exp exceptions in feature_gate.cpp's
  --max-concurrency rule and server_main.cpp's auto-enable of
  --paged-attention. qwen4exp's capability row already marks
  paged_attn = kNever, so --max-concurrency > 1 now falls through to
  the same "--max-concurrency requires --paged-attention" ->
  "architecture 'qwen4exp' has no paged decode path" rejection every
  other unsupported architecture (bailingmoe3, qwen3, ...) gets --
  with or without the old opt-in environment variables set. Added a
  regression case to test_feature_gate.cpp covering both.
- Move the single-sequence "reset/reuse must match a freshly
  allocated cache" assertions out of the deleted
  smoke_qwen4exp_batched.cpp into smoke_qwen4exp_forward.cpp, the
  retained smoke test; it exercises only qwen4exp_forward() and never
  touched the batched path.
- Drop the QWEN4EXP_BATCHED_DECODE, LUCE_QWEN4EXP_SEQ_ENGINE and (now
  fully dead) QWEN4EXP_PROF entries from ENVIRONMENT.md.

Single-sequence generation is unchanged: qwen4exp_forward(),
Qwen4ExpCache, and Qwen4ExpBackend::generate_impl() never called any
of the removed code.

* fix(ggml-cuda): range-check the RoPE->PERMUTE->CONT fusion against its inputs

The fused M-RoPE/permute/copy writes its output while still reading the
position leaf, and the allocator may place CONT's output over the positions
after ROPE's last unfused read. The overlap check skipped GGML_OP_NONE leaves
and this fusion never ran it. Range-check leaf inputs too and run the check
for this fusion; aliased instances run unfused. Found through four-slot
decode, where it corrupted one row. test_rope_tail reproduces the alias on CPU
and GPU (fails before, passes after on gfx1151); split KLs and decode/prefill
speed are unchanged.

* fix(qwen4exp): default to 2048-token prefill chunks

The generic --chunk default (512) overrode Qwen4ExpBackendConfig's 2048, so
serving with default flags prefilled at ~720 tok/s instead of ~1,000 on
gfx1151 (UD-Q4_K_XL, 16K / 64K prompts: 720 -> 992, 661 -> 1000 tok/s). The
plan now resolves qwen4exp to 2048 unless --chunk is given explicitly; other
architectures keep 512.

* docs(qwen4exp): add the Qwen3.8-Flash-Next guide

Model files, running on the Strix Halo, thinking budget for hard problems, measured speed and quality, support table and layout, matching the DS41 guide.

* refactor(qwen4exp): drop the qwen4exp environment variables

The backend applied its gfx1151 profile by writing six environment
variables into the process, and the branch added four kill switches and
reference/dump switches on top. The profile is now a calling-thread setting
in ggml-cuda (ggml_backend_cuda_set_qwen4exp_profile) that the qwen4exp
graph scopes around its own work, with device support resolved once at
load; other models keep the generic dispatch and the process environment
is untouched. The kill switches and the paths behind them are gone, and the
reference path, activation dumps, token files and split checks are test
and script arguments. Outputs are byte-identical (UD-Q4_K_XL and IQ4_NL
greedy, split KLs, no onset against upstream) and prefill/decode speed is
unchanged on gfx1151.

* perf(qwen4exp): overlap prefill input prep and trim the GDN tail

Prepare the next chunk's embeddings and PLE rows on the host while the
current chunk's graph computes, evaluate the GDN decay exp once per token
instead of once per column, and skip the dense causal mask for short-tail
QSA, which derives its own visibility. Reduction and FMA order are
unchanged: greedy output, teacher-forced KL and the split references are
identical. gfx1151, UD-Q4_K_XL, 2048-token chunks: GDN 132.6 -> 128.9 ms
per 2048 rows, cold prefill +5.1% at 32K and +3.2% at 64K.

* perf(ggml-cuda): keep routed Q4_K blocks in registers in the MMB GLU

The routed Q4_K GLU reloaded each compressed block's scales and quants per
use, requesting 384 bytes per block. Load the block once into registers
(160 bytes); WMMA tiles and the route-order reduction are unchanged, so
outputs are bit-identical. gfx1151, UD-Q4_K_XL: routed GLU microbench
8.24 -> 7.61 ms at T=2048 (8.84 -> 8.15 with skewed routing), prefill
+2.1-2.3% on cold 32K/64K prompts, greedy output byte-identical.

* fix(qwen4exp): accumulate prompt attention in F32 below the QSA budget

While every key fit the QSA selection budget, a prompt chunk took the dense
flash-attention path (known-answer error 0.028 vs 3e-8 for the packed QSA
kernel), so the logits depended on the chunk size: an 18K prompt prefilled
in 2048-token chunks drifted from one-pass prefill (initial KL 1.81, 0/128
rows equal). Route multi-row prompt chunks through packed QSA with F32
accumulation at any context; single-token decode keeps dense attention below
the budget. Pad the KV capacity to the packed kernel's 4-key groups.

gfx1151, UD-Q4_K_XL: 18K prefill in 2048- and 7424-token chunks is bitwise
equal to one-pass (128/128 rows); split references unchanged; HumanEval,
GSM8K and Math 10/10 each, recall 3/3; short decode unchanged (23.3-23.4).

* perf(qwen4exp): size prefill chunks to the memory that is free

Without --chunk, pick the largest 256-row multiple whose measured graph,
ring and scratch plan fits the memory left after weights and the configured
caches, keeping 10% headroom (7424 rows at 262K context with one slot).
Larger chunks amortize the per-chunk MoE and QSA setup; with F32 prompt
attention the logits do not depend on the chunk size. --chunk N is still
exact, and the server banner and /props report the chosen size.

gfx1151, UD-Q4_K_XL, 262K context, medians of 3 vs 2048-row chunks:
prefill 16K 1,116 -> 1,196 tok/s, 64K 1,038 -> 1,231; short decode
unchanged; quality gate 10/10/10, recall 3/3, split references unchanged.

* refactor(ggml-cuda): drop the exact-16,366-row dense dispatch table

The gfx1151 table routed 28 dense GEMM shapes to MMQ only when a matmul had
exactly 16,366 rows, the length of the captures it was trained on. Chunked
prefill never produces that row count (2048 rows, or at most 7424 at 262K),
so in serving it only changed the activation quantization of one-pass
prompts of that exact length. Remove it; every other shape already takes
the same MMB/BLAS route.

* docs(qwen4exp): state the measured chunk-invariance result

The guide said the logits do not depend on the chunk size. What was
measured is an 18K UD prompt in 2048- and 7424-row chunks matching one-pass
prefill bitwise; say that.

* fix(qwen4exp): keep device reporting and the GDN kernel choice unchanged for other models

#774 reported HIP iGPUs as integrated and as GGML_BACKEND_DEVICE_TYPE_IGPU
(and every integrated CUDA device as IGPU, GB10 included). The Qwen3
drafter loader only accepts GPU devices, so PFlash/KVFlash compress drafters
for qwen35, laguna and gemma4 failed to load on Strix and GB10, and the
integrated flag changed supports_buft and the DS4 fused-verify keep size for
every model. Device reporting is back to main's; the qwen4exp input ring asks
ggml_backend_cuda_qwen4exp_supported() instead, and the debug input assert
admits pinned host buffers under the qwen4exp profile.

The tiled gated-delta-net recurrence was keyed on RDNA3.5 + H == 48 +
S_v == 128, which is also the Qwen3.5/3.6 27B shape, so their Strix prefill
switched kernel. It now also requires the qwen4exp profile.

test_mul_mat_host_input runs under the qwen4exp profile on gfx1151 and
skips elsewhere.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* chore(harness): leave the benchmark harness as on main

The harness rewrite (recall suite, a new GSM scorer, \frac handling and
BENCH_MAX_TOKENS / BENCH_THINKING / BENCH_EFFORT knobs, most of it ruff
reformatting) is the tool behind the PR's quality numbers; nothing under
server/ uses it. It belongs in its own PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(qwen4exp): drop the reference profile from the CUDA/HIP backend

GGML_CUDA_QWEN4EXP_REFERENCE only served the byte-exact upstream
differential kit (smoke_qwen4exp_forward --reference). Its kernel branches
never ran in the shipped server:

- rope.cu: the upstream_f32 angle variant of rope_multi;
- ggml-cuda.cu: the vector-times-matrix MMVF swap for F32 weights;
- fattn.cu: the RDNA3.5 head-256 MMA selection (also opened by a second
  LUCE_FA256_MMA read that defaulted to 0 on RDNA3.5 while the RDNA4 read
  defaults to 1), plus the ncols1/ncols2 changes that only it reached;
- fattn-mma-f16.cuh: the RDNA3 head-256 backport, which compiled the MMA
  kernel for every RDNA3 target; nothing else selects MMA on RDNA3.

fattn-mma-f16.cuh and test_fattn_mma256.cpp are back to main. The
ROPE->PERMUTE->CONT fusion now requires the qwen4exp profile instead of
"not reference", and the per-token rope_multi_heads prefill kernel runs
only under it, so other MROPE models keep rope_multi on HIP.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(loaders): share the GGUF fallback reads between bailingmoe3 and qwen4exp

The qwen4exp loader copied get_u32_or, get_f32_or and align_up verbatim from
the bailingmoe3 loader. Both now include common/gguf_kv.h. TensorAllocation
stays per loader: qwen4exp's carries the shard index.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(qwen4exp): keep shared fusions and graph checks as on main for other models

#774 changed paths every model reaches:

- ggml_cuda_check_fusion_memory_ranges now also checked leaf inputs, so
  fusions other graphs got on main could be refused. Leaves are checked only
  under the qwen4exp profile.
- The RDNA3.5 PLE/GDN conv matchers, the HC gate-mix/mix-reduce matcher and
  the RMS_NORM+SCALE fusion ran on every RDNA3.5 graph (scanning every
  CONCAT/CONT/SSM_CONV and every node for the HC pattern). They now need the
  qwen4exp profile too.
- ggml_can_fuse_subgraph_ext admitted views of any weight-usage buffer for
  every backend and model. The only fusion that needed it is the PLE conv
  matcher, whose tap views of the conv weight are no-ops: it now leaves them
  out of the subgraph check and ggml.c is back to main.

Also undoes a reflow of the DS4_MOE_COMBINE supports_op condition.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(ggml): drop ggml_flash_attn_ext_set_n_kv_max

The setter wrote FLASH_ATTN_EXT op_params[4] and no CUDA, HIP or CPU kernel
reads it back (the QSA kernels read scale, max_bias and softcap only). The
same slot is DS4's raw_rows, so a reader added later would have misread one
of the two. Its only caller, qwen4exp_graph.cpp, goes in the server change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(cuda): drop the mul_mat_id inverse-map mode

ggml_cuda_launch_mm_ids_helper gained a write_inverse flag (token slot ->
compact row) and ggml_cuda_launch_mm_ids_bounded an inverse one, for a
quant-dedup path that was never wired: every production caller passes false
and only the new regression test set it. Both flags, the "fast path only when
not inverse" condition and the unused chunk count of mm_ids_route_sort are
gone, and mmq.cu/mmf.cu/mix-wmma-moe.cu are back to main's calls (mmq.cu
keeps its Q2_0 cases).

Kept: the ten-expert specialisation (padded to 16 lanes per token), the
__syncwarp race fix and the RDNA3.5 512x10 route-bounded sort MMB uses.

test_ds4_mmid_regression covers that helper rather than DS4, so it is now
test_mmid_regression and checks the forward contract only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(qwen4exp): drop the test-only modes, unreachable planning and dead state

Nothing the server runs reaches any of this:

- Upstream reference mode and its kit: the reference/upstream parameters of
  the loader, cache, forward and Qwen4ExpCudaScope, the 256-row KV padding,
  the unfused MoE aggregate and the unfused HC combine/mix branches, and
  scripts/qwen4exp_upstream_diff.py + qwen4exp_upstream_nodes.cpp (which
  hardcoded a GPU index and a local llama.cpp tree). GGML_CUDA_QWEN4EXP_REFERENCE
  goes away on the kernel side.
- Activation-dump mode: the dump argument of qwen4exp_forward, the dump_mark
  calls in every builder and the stderr printer. Dumping also switched off the
  F16 path, so it never showed the graph that ships.
- Multi-slot memory planning: --max-concurrency > 1 needs paged attention,
  which qwen4exp refuses, so slots was always 1. Also the smoke binary's
  --plan-ctx / --slots.
- Fields written and never read: Qwen4ExpWeights backend, n_ff_shexp,
  ssm_dt_rank, linear_key_heads, ple_image_token_id, shard2_path and
  output_norm (it was uploaded to the GPU), cache cur_pos and kv_type (the
  cache is F16, the only type any caller passed), Qwen4ExpForwardResult
  n_tokens/pos0, Qwen4ExpBackendConfig stream_fd, Qwen4ExpPleReader::head_dim,
  build_qsa_attn's kv_pad/kv_len, the ggml_flash_attn_ext_set_n_kv_max call
  (no kernel reads it) and an unused include.
- The float fallback for QSA cell ids. It only ran for block ratios other
  than 4 or contexts past 16M tokens; the loader now refuses other ratios and
  the cache refuses contexts of 2^24 tokens or more, so the exact integer
  kernel always applies. test_qwen4exp_qsa_ids keeps its own float reference.
- scripts/qwen4exp_forward_diff.py duplicated the smoke binary's
  --compare-chunk check; the smoke binary stays.

The PLE conv state is now indexed per PLE layer; every PLE layer used
state 0, which was only right because published models have one.

The chunk planner prints the plan of the chosen chunk once instead of one
line per binary-search probe.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* chore(qwen4exp): drop unrelated edits and give the chunk test the cpu label

- .gitignore no longer lists the author's local docs/performance and
  docs/qwen4exp.md (qwen4exp_internal.h pointed readers at the latter).
- feature_gate.cpp, a comment-only rewrite, the server_main.cpp re-wrap of
  an unchanged line and the seq_engine_contract.h message tweak are back to
  main.
- The GGML_HIP_GRAPHS description no longer cites a private experiment log.
- smoke_qwen4exp_forward is built without an if(EXISTS) guard around a file
  this PR adds.
- test_qwen4exp_chunk carries the cpu label, so check-cpu builds and runs it
  in the hosted job.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* ci(rocm): build and run the qwen4exp kernel tests on the R9700 and the Strix Halo

The new GPU tests (QSA cell ids, indexer score, M-RoPE tail, MMB vs library
GEMM, vectorized convert, scalar get_rows, RMS_NORM+SCALE, pinned host
inputs, the mmid regression) were built by nothing in CI. They join the
ROCm job's build list and ctest filter on both devices; the gfx1151-only
ones skip on the R9700.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(qwen4exp): drop dead MMB API, knobs and the row-concat weight shadow

- ggml_cuda_mmb_cache_reserve (the only user of producer slot 0) and
  ggml_cuda_mmb_marks_clear had no callers.
- ggml_cuda_mmb_gatemix/blk16/res16 always returned the arch check (res16
  had no caller); the HC gate-mix and bf16-dst conditions no longer ask.
- The concat(w0, w1) BF16 shadow keyed on an IQ4_NL CONCAT of two resident
  weights: every qwen4exp ggml_concat is on activations, so it never matched.
- mmb_small_n_bf16_kernel served M <= 8 BF16 weights after mmb_small_m,
  which already takes every such weight here (K = 2560 or 10240, K % 512 == 0);
  other shapes fall through to the generic BF16 tile.
- The nested gfx1151 guards repeated the file-level one, and the
  mmb-small-m.cuh header pointed at a microbench that is not in the repo.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(qwen4exp): one entry point for HC_COMBINE_NORM

- ggml_cuda_hc_combine_norm_supported had no caller.
- The res_in_bf16 / blk_in_bf16 / res_out_bf16 args were never set, so the
  kernel's BF16 residual and block-output branches (and hc_lo/hc_hi) were
  dead.
- ggml_cuda_hc_combine_norm_ptrs repeated the args launch for the unmarked
  case. compute_forward now builds one args struct for all three cases
  (MoE, marked bf16-only xn, plain) and calls ggml_cuda_op_hc_combine_norm.

The plain path now asserts n_embd <= HC_CN_MAX_EMB like the MoE path, since
the kernel keeps one row of that many columns in registers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(qwen4exp): drop the scalar QSA decode kernel

qsa_decode_partial only ran when the WMMA decode kernel's conditions failed:
GQA != 12 or a K cache view not 16-byte aligned. qwen4exp_graph.cpp builds
QSA only for n_head == 12 * n_head_kv, and its K/V are offset-0 views of the
F16 cache tensors (512-byte rows), so the WMMA kernel always took the call.
Those conditions now sit in ggml_cuda_flash_attn_ext_qsa_decode_supported;
anything else falls to the generic path, which refuses maskless sparse
attention with an assert instead of computing it on a second, unvalidated
kernel.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(qwen4exp): drop template switches and knobs with one value

- mmb_routed_kernel / mmb_routed_glu_kernel: EXPERT_MAJOR was always false.
- mmb_f32split_kernel: TWO was always true, so the w_lo * x_hi product never
  ran; the weight's lo split, its LDS tile and its fragment loads go too, and
  the comment now says what the kernel computes (w rounded to F16, x as
  hi + lo).
- mmb_decode_slice<IQ4_NL> was never instantiated (IQ4_NL maps to WTYPE 0,
  which decodes through mmb_dq_row36).
- gdn_conv_enabled(), ple_conv_enabled() and hc16 were constant true.
- gdn_conv_direct_kernel: apply_silu was always true and the bias b always
  0 (now the same accumulation as ssm_conv); the match's silu field is gone.
- ggml_backend_cuda_get_gdn_tiled_launch_count had no declaration and no
  caller.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(qwen4exp): one header for the fused kernels' shared device helpers

The non-contracting F32 multiply/add pair existed four times (hc-cn, hc-mix,
MMB's gm_*, ple-conv), the unary.cu sigmoid four times (hc-cn, hc-mix, MMB,
gated-norm), the BF16 widen/narrow/pack helpers three times (hc_*, mmb_*,
mq_f2bf), and gdn_concat_tail was ple_concat_tail with H = 3. They now live
in qwen4exp-common.cuh as q4x_* (the concat tail as a template on H); the
expressions are unchanged.

hc-cn.cu, hc-mix.cu and mmb.cu are HIP-only (ggml-cuda/CMakeLists.txt drops
them from CUDA builds), so their copies' CUDA branches were dead; the header
keeps the __fmul_rn/__fadd_rn branch for ple-conv.cu, which CUDA compiles.
mmb-q8f16.cuh no longer claims to be self-contained for a microbench that is
not in the repo.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(qwen4exp): run the fusion tests under the qwen4exp profile

The ROPE->PERMUTE->CONT and RMS_NORM->SCALE fusions now need the qwen4exp
profile, so test_rope_tail's GPU position-alias case and
test_rms_norm_scale set it around their graphs; without it both sides of
the comparison took the unfused path and the tests passed vacuously.

The if(EXISTS) guards around test_mmb_cublas_diff, test_convert_vec and
test_getrows_scalar wrapped files this change adds, so they are gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* perf(qwen4exp): skip the MMB weight-shadow scan outside qwen4exp graphs

ggml_backend_cuda_graph_compute walked every node of every HIP graph to find
dense weights for the BF16 shadow, though ggml_cuda_mmb_supported_mm refuses
them without the qwen4exp profile. The loop now stops at once for other
models, as their graphs ran on main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* ci(rocm): test_mmid_regression is the renamed mmid test

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(qwen4exp): cap prompt chunks at the 32768 tokens the MoE route sort serves

With plenty of free memory the chunk planner picked 84K-92K rows, so a 55K
prompt went through as one chunk. The gfx1151 MoE route sort only serves
4097-32768 tokens; past that MUL_MAT_ID falls back to the generic id helper,
whose shared memory holds 4 bytes per token, and the server aborted at
mmid.cu (GGML_ASSERT(nbytes_shared <= smpbo)). On a busy box the planner had
picked ~28K rows, which hid it. qwen4exp_fit_chunk now stops at 32768.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* revert(ggml): drop the Q2_0 type and keep TQ3_0 at id 42

No Qwen3.8-Flash-Next GGUF uses Q2_0 (UD-Q4_K_XL, IQ4_NL and IQ3_XXS do
not), and adding it renumbered the existing TQ3_0 KV cache type from 42
to 43, which needed a disk prefix cache version bump. Remove the type,
its CPU and CUDA/HIP kernels, the MMB decode branch and the test entry,
and restore TQ3_0 = 42 and DISK_CACHE_VERSION = 2 as on main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(qwen4exp): free the MMB weight shadows when the target parks

park() freed the weights but kept the backend, so the bf16 shadows (up
to 6 GiB) stayed allocated while parked. They are keyed by weight
address, and unpark() reloads the weights: a weight landing at an
address that held another one would read that one's shadow.
ggml_backend_cuda_trim_pool now also releases the MMB caches and
shadows (allocated from the pools it trims), and park() trims.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(cuda): release MMB state in trim_pool on HIP builds only

The MMB sources are built for HIP only, so a CUDA build has no
ggml_cuda_mmb_release_all and test_server_unit failed to link on the
DGX runner. Guard the call the way ggml_backend_cuda_free does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(ggml): restore Q2_0 at id 42; the G…
@davide221
davide221 deleted the perf/ds4-paged-staged-text-prefill branch November 9, 2026 10:25
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.

1 participant