Skip to content

dflash: fix draft-feature capture on hyper-connection models - #113

Merged
Vasyl-Trefilov merged 1 commit into
RustingStudio:mainfrom
SSA1911:dflash-hc-mean
Nov 26, 2026
Merged

Vasyl-Trefilov merged 1 commit into
RustingStudio:mainfrom
SSA1911:dflash-hc-mean

Conversation

@SSA1911

@SSA1911 SSA1911 commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

dflash: fix draft-feature capture on hyper-connection models

What's broken

Some Qwen-family models (Qwen3.8-Flash-Next among them) carry each token's hidden state as several parallel variants — the model's "hyper-connection streams" — which are summed later in the layer. When you run a standalone DFlash2 draft model (--draft-model), RustingStrata feeds the drafter snapshots of the big model's hidden state at the layers the head was trained on. On these models v1.3.1 reads only one of the streams instead of the average of all of them, so the drafter gets inputs it was never trained on and its guesses rarely match the big model's.

The drafter is trained to consume the average of the streams; llama.cpp fixed the identical bug the same way for this architecture (ggml-org/llama.cpp#30927, merged 2026-10-22).

Evidence (deterministic)

Measured on an 8k-context bench run, stock v1.3.1 release binary: the big model accepted 74 of 168 drafts (44%). With this patch: 96/96 (100%). Draft acceptance under greedy decoding is deterministic, so acceptance is the primary claim of this PR.

The fix

Average the streams before the capture, in both places it happens: per-token decoding (src/gpu_model.rs) and prompt prefill (src/gpu_model/prefill.rs). Diff +18/−1 and +22/−2, no API or format changes. Models without hyper-connections take the unchanged code path, and the averaging scratch buffer is allocated only when the model actually has streams.

Notes for reviewers

  • Prefill cost of the patch itself: at 8k (reps 1) prefill went 125.8 → 109.9 tok/s (≈ −13%). The prefill copy is tiled to the verify-row block size because hc_mix's gate buffer indexes per position; the patch reuses existing kernels on all three backends rather than adding a new mean kernel.
  • The EAGLE3 capture paths have the same defect: the same single-stream copy with no hyper-connection guard (src/gpu_model.rs:1975, src/gpu_model/prefill.rs:376). Not touched by this patch — we had no EAGLE3 head for a hyper-connection target to test a fix against. Flagging for a follow-up.
  • Tested on: CUDA (Windows 11 Pro 26H2, RTX 4070 SUPER 12 GB, driver 617.14; MSVC x86-64-v3 build, rustc 1.100.0). One confounded Vulkan run; HIP untested.
  • No serving speedup is claimed. In chat-style generation at depth on a 12 GB card, the drafter's VRAM cost made generation slower than no-draft in the one deep run we measured. This PR makes the DFlash2 path correct; whether it helps a given workload is separate.

Repro

  1. Build with the MSVC target (release).
  2. Point --draft-model at the Hugging Face head directory (safetensors + config.json) — the engine converts it to GGUF itself on first load. Set STRATA_DFLASH_Q8=1 to get the Q8_0 head we tested. (Heads we tested were converted by the engine, not by hand.)
  3. Run:
rustingstrata bench --gpu --backend cuda --model <model.gguf> --draft-model <head-dir> \
  --ctx 8192 --pp 4096 --tg 128 --reps 1 --kv q8 --chunk 4096 --json-out out.json
  1. Check drafts {made, accepted} in the JSON: unpatched v1.3.1 ≈ 74/168 (44%); with this patch 96/96 (100%).

cargo test --release: 112 passed, 1 failed. The failure (standalone_external_draft_model_spec_step_matches_greedy, Windows error 1224 "user-mapped section open") reproduces identically on unpatched v1.3.1 — pre-existing Windows flake, not this patch.

Built from commit 32bde88 (rebased onto upstream v1.3.4, a02a259), MSVC x86-64-v3; exe SHA-256 aa1dc5f6e7a072c93c847455d9ea0751d515dbe8bed98945655d40eb092facfa. On the same 8k bench run, unpatched stock v1.3.4 accepts 72/168 (42.9%).

The draft-feature capture read one hyper-connection stream instead of
the average of all of them, so standalone DFlash2 drafters were fed
inputs they were never trained on (44% draft acceptance on an
8k-context bench; 100% after this fix). Average the streams before the
capture, in both the per-token and prefill paths.
Comment thread src/gpu_model.rs
// (mirrors llama.cpp's hc_stream_mean); hc_mix with a constant large gate
// yields sum * sigmoid(g) / hc = mean.
let src = if self.m.cfg.hc_n > 0 {
g.hc_mix(self.x.addr(), df.dfg.addr(), df.dfm.addr(), ne, self.m.cfg.hc_n, nt)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Correctness · 1 of 6

The 12.0 gate gives sigmoid(12) ≈ 0.999994, so the drafter feature is only approximately the hc mean, not exactly the mean the comment claims. The feature is scaled by about 0.999994 on every hc target. The error is small but systematic, so drafter outputs can drift from the llama.cpp reference that the comment says it mirrors, and a numerical comparison test would fail on tight tolerances.

Prompt for your AI agent
File: src/gpu_model.rs
Line: 2015
Symbol: forward
Issue: The 12.0 gate gives sigmoid(12) ≈ 0.999994, so the drafter feature is only approximately the hc mean, not exactly the mean the comment claims. The feature is scaled by about 0.999994 on every hc target. The error is small but systematic, so drafter outputs can drift from the llama.cpp reference that the comment says it mirrors, and a numerical comparison test would fail on tight tolerances.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/gpu_model/prefill.rs
g.dtod(&pf.slab, 4 * r * ne, dff, 4 * (r * n_ids + idx) * ne, 4 * ne)?;
// hc targets (qwen4exp): collapse the hc streams to their plain mean first
// (mirrors llama.cpp's hc_stream_mean); see the step-side note. hc_mix's gate
// buffer holds TMAX rows, so tile over TMAX-position blocks.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Correctness · 2 of 6

Prefill tests c.hc_n but the surrounding code uses self.m.cfg; if c is not the model config, this does not compile or reads the wrong value. If c is a different struct (for example the DFlash config or a scratch descriptor) without an hc_n field, the build breaks. If it is a different config, hc targets take the wrong branch and the drafter reads unmixed streams.

Prompt for your AI agent
File: src/gpu_model/prefill.rs
Line: 784
Symbol: prefill_chunk
Issue: Prefill tests `c.hc_n` but the surrounding code uses `self.m.cfg`; if `c` is not the model config, this does not compile or reads the wrong value. If `c` is a different struct (for example the DFlash config or a scratch descriptor) without an hc_n field, the build breaks. If it is a different config, hc targets take the wrong branch and the drafter reads unmixed streams.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/gpu_model.rs
layers: dl_layers,
feat: gpu.zeros::<f32>(TMAX * dc.target_layer_ids.len() * c.n_embd)?,
// hc_mix indexes its gate buffer per position (g[t*hc*n + c*n + i]), so it needs
// TMAX rows; 12.0 => sigmoid ~ 1 => plain stream mean.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Performance · 3 of 6

dfg is allocated and filled from the host with 12.0 for every DFlash model, and dfm is allocated, even when hc_n is 0 and neither is used. Non-hc DFlash models pay TMAX*n_embd extra device memory for dfm plus a host-built vector upload at construction for dfg, with no effect on output. Allocation should be gated on hc_n > 0, as Scratch::dflash_mean already is.

Prompt for your AI agent
File: src/gpu_model.rs
Line: 884
Symbol: load_part
Issue: dfg is allocated and filled from the host with 12.0 for every DFlash model, and dfm is allocated, even when hc_n is 0 and neither is used. Non-hc DFlash models pay TMAX*n_embd extra device memory for dfm plus a host-built vector upload at construction for dfg, with no effect on output. Allocation should be gated on hc_n > 0, as Scratch::dflash_mean already is.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/gpu_model.rs
// (mirrors llama.cpp's hc_stream_mean); hc_mix with a constant large gate
// yields sum * sigmoid(g) / hc = mean.
let src = if self.m.cfg.hc_n > 0 {
g.hc_mix(self.x.addr(), df.dfg.addr(), df.dfm.addr(), ne, self.m.cfg.hc_n, nt)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Maintainability · 4 of 6

A constant gate buffer is used to fake a plain mean, instead of a mean kernel or a flag on the mixing path. Correctness now depends on hc_mix's undocumented gate semantics (sigmoid and division by hc) staying fixed. Any change to that kernel silently breaks the feature. A direct mean operation would be simpler and independent of the gate.

Prompt for your AI agent
File: src/gpu_model.rs
Line: 2015
Symbol: forward
Issue: A constant gate buffer is used to fake a plain mean, instead of a mean kernel or a flag on the mixing path. Correctness now depends on hc_mix's undocumented gate semantics (sigmoid and division by hc) staying fixed. Any change to that kernel silently breaks the feature. A direct mean operation would be simpler and independent of the gate.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/gpu_model/prefill.rs
@@ -775,8 +779,24 @@ impl GpuModel<'_> {
if let (Some(dff), Some(df)) = (&pf.dflash_feat, self.dflash.as_ref()) {
if let Some(idx) = df.cfg.target_layer_ids.iter().position(|&tl| tl == il) {
let n_ids = df.cfg.target_layer_ids.len();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Maintainability · 5 of 6

The DFlash capture loop (hc_mix tiling and per-row dtod copies) is duplicated between prefill and the step path with near-identical logic. A future fix to the row-copy or tiling logic must be made in two places, and they can drift apart. A shared helper taking the source buffer and row count would remove the duplication.

Prompt for your AI agent
File: src/gpu_model/prefill.rs
Line: 781
Symbol: prefill_chunk
Issue: The DFlash capture loop (hc_mix tiling and per-row dtod copies) is duplicated between prefill and the step path with near-identical logic. A future fix to the row-copy or tiling logic must be made in two places, and they can drift apart. A shared helper taking the source buffer and row count would remove the duplication.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/gpu_model.rs
let n_ids = df.cfg.target_layer_ids.len();
// hc targets (qwen4exp): the drafter reads the plain mean of the hc streams
// (mirrors llama.cpp's hc_stream_mean); hc_mix with a constant large gate
// yields sum * sigmoid(g) / hc = mean.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Low · Performance · 6 of 6

The step path issues one dtod per row inside the batch, with the hc mean now computed as a separate kernel launch each step, rather than producing the feature in a single pass. Each decode step launches hc_mix and nt separate copy operations for every captured layer. With many layers and drafts, launch overhead grows, even though a fused or strided copy could move the rows in one operation.

Prompt for your AI agent
File: src/gpu_model.rs
Line: 2013
Symbol: forward
Issue: The step path issues one dtod per row inside the batch, with the hc mean now computed as a separate kernel launch each step, rather than producing the feature in a single pass. Each decode step launches hc_mix and nt separate copy operations for every captured layer. With many layers and drafts, launch overhead grows, even though a fused or strided copy could move the rows in one operation.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

@aletheore

aletheore Bot commented Nov 26, 2026

Copy link
Copy Markdown

Aletheore Flash Lite review

What this PR does. This PR fixes the DFlash draft-feature capture for hyper-connection (hc) target models such as qwen4exp, where the drafter now reads the plain mean of the hc residual streams instead of a single stream, matching llama.cpp's hc_stream_mean. It adds a gate buffer preset to a large constant so the existing hc_mix kernel reduces to a plain mean, and tiles prefill over TMAX-sized blocks. The change affects the GPU DFlash speculative-decoding path (src/gpu_model.rs and src/gpu_model/prefill.rs) and only runs when the target model has hc_n > 0; non-hc models take the unchanged code path.

Merge confidence Review effort Merge risk
3 / 5 1 / 5 Medium
Area Files Lines
src 1 +18 −1
src/gpu_model 1 +22 −2

6 finding(s) posted as inline review comment(s).

# Severity Category Where
1 🟠 High Correctness gpu_model.rs:2015 The 12.0 gate gives sigmoid(12) ≈ 0.999994, so the drafter feature is only approximately the hc mean, not…
2 🟠 High Correctness prefill.rs:784 Prefill tests c.hc_n but the surrounding code uses self.m.cfg; if c is not the model config, this does…
3 🔵 Low Performance gpu_model.rs:884 dfg is allocated and filled from the host with 12.0 for every DFlash model, and dfm is allocated, even when…
4 🔵 Low Maintainability gpu_model.rs:2015 A constant gate buffer is used to fake a plain mean, instead of a mean kernel or a flag on the mixing path…
5 🔵 Low Maintainability prefill.rs:781 The DFlash capture loop (hc_mix tiling and per-row dtod copies) is duplicated between prefill and the step…
6 🔵 Low Performance gpu_model.rs:2013 The step path issues one dtod per row inside the batch, with the hc mean now computed as a separate kernel…
Review details

Reviewed 2 file(s); skipped 0. Dismissed 0; outside PR diff 0. Grounding: 6 of 6 proposed finding(s).

Fix all with your agent
File: src/gpu_model.rs
Line: 2015
Symbol: forward
Issue: The 12.0 gate gives sigmoid(12) ≈ 0.999994, so the drafter feature is only approximately the hc mean, not exactly the mean the comment claims. The feature is scaled by about 0.999994 on every hc target. The error is small but systematic, so drafter outputs can drift from the llama.cpp reference that the comment says it mirrors, and a numerical comparison test would fail on tight tolerances.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/gpu_model/prefill.rs
Line: 784
Symbol: prefill_chunk
Issue: Prefill tests `c.hc_n` but the surrounding code uses `self.m.cfg`; if `c` is not the model config, this does not compile or reads the wrong value. If `c` is a different struct (for example the DFlash config or a scratch descriptor) without an hc_n field, the build breaks. If it is a different config, hc targets take the wrong branch and the drafter reads unmixed streams.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/gpu_model.rs
Line: 884
Symbol: load_part
Issue: dfg is allocated and filled from the host with 12.0 for every DFlash model, and dfm is allocated, even when hc_n is 0 and neither is used. Non-hc DFlash models pay TMAX*n_embd extra device memory for dfm plus a host-built vector upload at construction for dfg, with no effect on output. Allocation should be gated on hc_n > 0, as Scratch::dflash_mean already is.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/gpu_model.rs
Line: 2015
Symbol: forward
Issue: A constant gate buffer is used to fake a plain mean, instead of a mean kernel or a flag on the mixing path. Correctness now depends on hc_mix's undocumented gate semantics (sigmoid and division by hc) staying fixed. Any change to that kernel silently breaks the feature. A direct mean operation would be simpler and independent of the gate.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/gpu_model/prefill.rs
Line: 781
Symbol: prefill_chunk
Issue: The DFlash capture loop (hc_mix tiling and per-row dtod copies) is duplicated between prefill and the step path with near-identical logic. A future fix to the row-copy or tiling logic must be made in two places, and they can drift apart. A shared helper taking the source buffer and row count would remove the duplication.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/gpu_model.rs
Line: 2013
Symbol: forward
Issue: The step path issues one dtod per row inside the batch, with the hc mean now computed as a separate kernel launch each step, rather than producing the feature in a single pass. Each decode step launches hc_mix and nt separate copy operations for every captured layer. With many layers and drafts, launch overhead grows, even though a fused or strided copy could move the rows in one operation.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

The pull request description says: "One confounded Vulkan run; HIP untested.". This review read the diff only: it did not compile or run the code, so it cannot confirm that part works.

@aletheore

aletheore Bot commented Nov 26, 2026

Copy link
Copy Markdown

🔍 Aletheore evidence diff

graph LR
    n0["gpu_model.rs"]
    n1["lib.rs"]
    n2["main.rs"]
    n3["model.rs"]
    n4["mod.rs"]
    n5["backend.rs"]
    n6["vision.rs"]
    n0 --> n1
    n0 --> n2
    n0 --> n3
    n0 --> n4
    n0 --> n5
    n0 --> n6
    classDef changed fill:#d9772c,color:#fff,stroke:#b85f1c;
    classDef changedFinding fill:#c0392b,color:#fff,stroke:#922b21;
    classDef dependent fill:#f2f0ec,color:#18140f,stroke:#d6d0c5;
    class n0 changed
    class n1 dependent
    class n2 dependent
    class n3 dependent
    class n4 dependent
    class n5 dependent
    class n6 dependent
Loading

What changed
Deterministic, computed from this commit's real scan and import graph - posted on every run, whether or not Flash Review found anything.

  • src/gpu_model.rs · modified · +18/-1 · 6 other dependents
  • src/gpu_model/prefill.rs · modified · +22/-2

Aggregate deltas

  • Modules: -2
  • Dependency graph edges: -34
  • Commits: -17

@Vasyl-Trefilov
Vasyl-Trefilov merged commit 1bcbd16 into RustingStudio:main Nov 26, 2026
4 checks passed
@Vasyl-Trefilov

Copy link
Copy Markdown
Member

Big ty @SSA1911, this is a really nice catch and a clean fix, the drafter now gets the stream mean like it was trained on. Merged, it will be in the next release. I also noted the EAGLE3 capture has the same thing, I will look at it

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.

2 participants