ds4 icon indicating copy to clipboard operation
ds4 copied to clipboard

DSpark under --temp > 0: a decode/verify consistency bug, a working stochastic-verify implementation with no net win on M5 Max, and an unresolved kernel issue

Open Flor1an-B opened this issue 3 months ago • 6 comments

Hi, I spent some time (with Claude Code as pair-programmer) investigating why DSpark's speculative decoding currently does nothing under real sampling (--temp > 0), and whether the batched-verify infrastructure could be made to pay off if fixed. Sharing what came out of it in case any of it is useful. I ended up reverting all the code changes locally (didn't want to ship something I couldn't fully validate), so this is a text report, no PR/diff attached — happy to share the actual commits (currently only on a local, un-pushed branch) if useful.

Setup: M5 Max, Metal backend, DeepSeek-V4-Flash (43 layers, 256 experts / 6 active, MLA+SWA), --warm-weights, single GPU, --batched-session off.

1. A real correctness bug: indexer sparse-threshold inconsistency between decode and batched verify

metal_graph_encode_decode_layer (single-token decode) gates the indexer query chain behind metal_graph_decode_indexer_sparse_threshold() (1024 compressed rows by default) before falling back to dense mixed attention -- the comment there explains this is a genuine perf tradeoff (indexer setup dominates below ~2K context).

The batched path (metal_graph_encode_layer_attention_batch, used by both real prompt prefill and DSpark's metal_graph_verify_suffix_tops) instead gates purely on n_comp > DS4_N_INDEXER_TOP_K (512). So for n_comp in (512, 1024], ordinary decode attends densely over all compressed rows, but DSpark's verifier attends over the indexed top-512 -- a different candidate set than what decode would actually produce for the same position. Not just a perf discrepancy: the verifier isn't exactly reproducing what decode does in that window.

I only fixed this for small (n_tokens <= 8, i.e. actual verify-shaped) batches, gated so real large prefill chunks keep the original threshold -- decode's amortization argument for going sparse earlier doesn't obviously transfer to genuine multi-thousand-token prefill, and I didn't want to touch that without separately validating it.

2. Stochastic (temp>0) verify: implemented, correct, but no net win on this hardware

ds4_session_eval_dspark_speculative_argmax only ever worked for greedy decoding -- it compares drafted tokens to the target's argmax via exact match, and the CLI/server call sites gate the whole speculative path to --temp <= 0 accordingly. Under real production sampling this path is currently dead code.

I implemented the standard Leviathan/Chen stochastic accept/reject (accept a drafted token with probability min(1, p(x)/q(x)), residual-resample from max(0, p-q)/Z on rejection) and validated the residual-resample math with a 300k-trial statistical test confirming the marginal distribution of the emitted token matches the target distribution exactly, not just approximately -- happy to share that test file.

Three concrete perf fixes along the way (each verified by direct measurement, not assumed):

  • reused the existing spec_frontier_commit_prefix fast-commit path for stochastic partial-accepts instead of falling back to a full sequential replay on every rejection
  • routed draft_n==1 cycles through a plain decode instead of the batched verifier -- same required output (post-token logits), ~1/3 the measured cost, since the batched verifier pays for a full 43-layer batch dispatch even at n_tokens==1
  • the indexer threshold fix above

Net effect at the shipped default config (--dspark-confidence 0.6, scheduler on): went from ~35-45% slower than not using DSpark at all, down to ~4-6% slower. Tested across confidence 0.01/0.3/0.4/0.5/0.6/0.7/0.8 and scheduler on/off; 0.6 + scheduler-on (today's default) remained the best configuration found. Did not reach a net positive gain on this specific hardware/model combination.

3. Attempted fusion kernel: correct in isolation, broken live, root cause not found

Decode has ~8 hand-fused kernels (e.g. kernel_dsv4_qkv_pair_quad_compressor_store_q8_0, doing attn_q_a + attn_kv + attn/indexer-compressor kv+gate in one dispatch) that the generic batch path lacks, presumably because decode is always exactly one row and never needed batching. I wrote a row-batched sibling (attn_q_a + attn_kv + indexer-compressor kv/gate only -- DSpark's batch path never needs attn_compressor, that's zero_prefix-only) and validated it against the currently-shipped unfused reference on real model weights under MTL_SHADER_VALIDATION=1 MTL_DEBUG_LAYER=1: 126/126 exact matches across all compressed layers for n_tokens in {1,2,5,6,8} (found and fixed one real bug this way -- a missing per-branch output-stride override, invisible in the original single-row kernel since its row index is always 0).

Wired into metal_graph_encode_layer_attention_batch behind an explicit opt-in flag (set only by the DSpark verify call site, cleared right after), it produces wrong generated text -- and does so reproducibly differently depending on whether MTL_SHADER_VALIDATION is enabled: correct without it, garbled with it, same seed, deterministic either way. That's consistent with a synchronization/integration issue somewhere in how the shared per-layer command buffer/encoder is used, but I wasn't able to pin it down (ruled out an insufficient trigger heuristic, and g_batch_encoder_concurrent's FFN-overlap window, as causes). Left it disabled by default. If anyone wants to pick this up, an Xcode GPU Frame Capture on the verify call would probably show the actual dispatch ordering directly and make this fast to root-cause.


Happy to answer questions or share the actual commits/diffs if that would help anyone dig into any of this further.

Flor1an-B avatar Aug 30 '26 20:08 Flor1an-B

For anyone who wants to look at the actual code: the full diff (all three parts described above) is here, against the same base commit it was developed on:

https://github.com/Flor1an-B/ds4/compare/304bff9...dspark-stochastic-verify-investigation

Everything risky is off by default:

  • --dspark-stochastic opts into the new verify path (the two safe, measured perf fixes + the indexer threshold fix are inside it).
  • The experimental fusion kernel described in part 3 additionally requires DS4_METAL_ENABLE_QKV_COMPRESSOR_BATCH_FUSE=1 -- it's dead code otherwise, and the comment right above the gate in metal_graph_encode_layer_attention_batch documents exactly what's broken and what's been ruled out.

tests/test_dspark_stochastic.c (pure math, runs anywhere) and tests/test_qkv_compressor_batch.c (model-backed GPU oracle, needs DS4_TEST_MODEL) are the two new test files, wired into make test / make test-qkv-compressor-batch.

Not opening this as a PR since part of it (the fusion kernel) is known-broken and part of it (the stochastic verify path) doesn't pay for itself yet on my hardware -- wanted the actual code available in case any piece of it is useful as a starting point, without implying it's ready to merge as-is.

Flor1an-B avatar Aug 30 '26 20:08 Flor1an-B

Correction: I should have checked main more carefully before opening this. Working from an internal branch that turned out to be 19 commits behind main, I missed that stochastic DSpark support was already merged (769a8ba "dspark: support exact stochastic speculative decoding" and 8d683d6 "dspark: add opportunistic temperature sampling", both 2026-08-09). Went back and diffed against current main directly. Revised status:

Part 1 (indexer sparse-threshold inconsistency) -- still stands. Confirmed by reading current main directly: metal_graph_encode_layer_attention_batch's !zero_prefix branch still gates the indexer query/score/top-k chain purely on n_comp > DS4_N_INDEXER_TOP_K (512), while metal_graph_encode_decode_layer gates the same decision on metal_graph_decode_indexer_sparse_threshold() (1024) for ordinary decode. This is exercised by the now-shipped stochastic path too (ds4_session_eval_dspark_speculative_stochastic calls the same metal_graph_verify_suffix_tops), so it currently affects real, already-released sampled DSpark decoding whenever compressed context lands in (512, 1024].

Part 2 (stochastic verify itself) -- superseded, and yours is the better design for this drafter. dspark_stochastic_accept/dspark_stochastic_replacement treat each drafted token as a deterministic single candidate (accept with probability exactly target_p(x), reject -> resample with x's mass zeroed and renormalized) rather than the general Leviathan/Chen p(x)/q(x) ratio I implemented against a materialized draft distribution. Since the markov-corrected walk here really does produce one specific candidate per position rather than a calibrated draw from a normalized q, your formulation is the correct minimal special case (it's algebraically identical to the general one when q is a point mass) and is cheaper -- no need to retain/recompute the drafter's own softmax at all. The spec_frontier_commit_prefix reuse for partial accepts that I described as a fix is also already there in your stochastic path.

One piece of the perf finding still holds, narrower than originally stated: in ds4_session_eval_dspark_speculative_stochastic, a position-0 rejection already replaces cheaply via ds4_session_eval_probe_tp (ordinary decode). But a position-0 acceptance with draft_n == 1 still falls through to the full metal_graph_verify_suffix_tops batched path unconditionally, paying for a 43-layer batch dispatch at n_tokens == 1 to get logits a plain decode would give at a fraction of the cost -- the same case I originally measured at ~60ms vs ~23ms. Worth an early-out for that specific case.

Part 3 (experimental fusion kernel) is unaffected by any of this -- still an open, unfinished lead, reported as-is.

Sorry for the noise on part 2 -- should have checked upstream first. Part 1 (and the narrower part of the perf note) are the pieces I'd still stand behind.

Flor1an-B avatar Aug 30 '26 20:08 Flor1an-B

Opened a PR for the two confirmed-still-open items above: #915 (indexer sparse-threshold fix + a narrow draft_n==1 fast path, both verified on real weights). The fusion-kernel lead from part 3 is unrelated and still unresolved.

Flor1an-B avatar Aug 30 '26 21:08 Flor1an-B

Hi all — following this thread with interest, since I'm running the same hardware and hit the same question from a different angle. Some numbers in case they're useful.

M5 Max 128 GB, Metal, DeepSeek-V4-Flash 0731, --warm-weights, single GPU, --batched-session off — the same setup described in the issue. Measured this morning on two heads, at --temp 0, so this is the greedy regime rather than the temp > 0 path the correctness bug covers.

--dspark is a modest win here, not a loss.

model baseline --dspark d1 gain
IQ2XXS-w2Q2K-AProjQ8 43.39 t/s 46.64 +7.5%
Layers37-42Q4K…imatrix-fixed 45.71 t/s 47.44 +3.8%

Heads: main @ 8db89fe, PR #915 @ 88bd78a. Support model DeepSeek-V4-Flash-DSpark-support-0731.gguf. Three prompts per configuration, 512 tokens each, --temp 0.

Draft depth makes no difference. d1 through d4 land within ~1% of each other on both models, so whatever is being gained comes from first-token acceptance rather than from speculating deeper.

PR #915 measures the same as main within drift. Its gain is +3.0% and +6.6% against main's +3.8% and +7.5%.

A caution about absolute numbers on this hardware. Running the two heads back to back showed PR #915's baseline about 8% below main's, which looks like a regression. An A-B-A control says it is not: re-running main on the now-warm machine gave 43.81 and 41.65 t/s against its own earlier 45.71 and 43.39 — roughly 4% of absolute throughput lost to fifteen minutes of continuous load, with PR #915 sitting between the two main runs. The ratio holds steady across all three sweeps while the absolute sags, so single-head absolute figures on a laptop are worth treating carefully.

Correcting my own earlier data, since it is the opposite of the above and may be circulating: I measured --dspark on 2026-08-08 as lossless but 23–44% slower at every setting tried, with --dspark-strict matching baseline. That no longer reproduces. Whatever changed in the intervening three weeks moved it from a clear loss to a small gain on this hardware. The old measurement did not record a build SHA, which is why I'm retiring it rather than trying to reconcile it.

Caveat on all of the above: three prompts per configuration, one machine.

evandhoffman avatar Aug 31 '26 11:08 evandhoffman

One more data point at real (non-greedy) sampling, since everything measured so far in this thread — mine, and evandhoffman's corroboration above — is --temp 0.

Setup: M5 Max 128GB, Metal, DeepSeek-V4-Flash 0731, main @ 6844cf7 (current, includes #915), --warm-weights, single GPU. --dspark --mtp-exact-sampling, default confidence (0.8 for exact-sampling per the README), scheduler on. --temp 1.0 --top-p 1.0 --min-p 0 (DeepSeek's own recommended sampling, not a synthetic choice). 5 short realistic prompts (tests/dspark_acceptance_fixture.sh's fixture set: a greeting, a one-line factual question, arithmetic, a code-generation request, a C-completion request), 150 tokens each, one seed.

prompt baseline t/s dspark t/s delta accept_rate
hello 42.57 39.18 -8.0% 40.0%
redis (one-liner) 42.49 38.04 -10.5% 66.7%
math 40.57 35.27 -13.1% 0% (no draft)
python_reverse (code) 43.04 44.58 +3.6% 91.8%
c_add (code) 42.23 41.51 -1.7% 92.9%

Average: -5.9%. No errors, no crashes, output not required/expected to match baseline byte-for-byte at temp>0 (didn't check for divergence bugs here, just throughput).

The pattern lines up with the acceptance-rate story, but not cleanly: c_add has 92.9% acceptance and avg_accept=1.0 (perfect once a draft starts) and is still a net loss (-1.7%), because 18 of its 26 cycles proposed no draft at all and each such cycle still pays the propose-path overhead. python_reverse clears the bar only because its accept rate is high and it drafts on most cycles (no_draft=81 out of 95, but the drafted ones are long and mostly full-accept).

So on this hardware, at real (non-greedy) sampling: DSpark exact-sampling is a net loss on ordinary conversational/short-answer traffic, and only pays for itself on long, structurally repetitive generations that draft on most cycles — which matches the same lesson from a completely unrelated speculative-decoding effort (ngram-mod on a different model/engine): synthetic or cherry-picked long-generation benchmarks look great, ordinary dialogue does not reproduce it. Greedy mode (this thread's other numbers) doesn't have this problem since the verifier participates on every cycle by design.

Not proposing a fix here, just flagging the shape of the regression for anyone deciding whether to default this on for temp>0 traffic — right now it looks workload-dependent enough that a blanket default-on would regress plenty of real usage.

Flor1an-B avatar Sep 01 '26 14:09 Flor1an-B

Sorry for the noise — I opened #951 with this same finding before checking back on this thread carefully enough and realizing it's already here (the "-5.9% average, net loss on ordinary conversational/short-answer traffic" result above is the same thing I re-found independently). Closing #951 and posting the parts of it that add something beyond what's already here.

Setup: M5 Max 128GB, Metal, main@110afdd, DeepSeek-V4-Flash-Vision-Exp (different checkpoint than the 0731 numbers above, same qualitative result), custom Q4_K drafter conversion (see #695 for how/why — official Vision-Exp support GGUF is IQ2_XXS/Q2_K, same low-bit default as the main model's routed experts; a --experts q4_k conversion gets meaningfully higher accept rate). Fixed repetitive code-completion prompt, 300 tokens, DS4_DSPARK_STATS=1.

Full --dspark-confidence sweep with --mtp-exact-sampling, --temp 1.0, 5 seeds per value — this extends the single-confidence (0.8 default) data point above across the whole range:

confidence avg gen t/s (n=5) vs no-dspark baseline (45.33 t/s avg)
0.0 (gate disabled) 34.11 -24.7%
0.3 36.63 -19.2%
0.5 36.96 -18.4%
0.7 43.47 -4.1%
0.85 39.10 -13.7%
0.9 35.20 -22.3%
default (auto 0.8, n=3) net_saved avg -611.9ms, high spread (42.85-49.19 t/s) ~flat but unreliable

No confidence value flips this to a win on my content — confirms the loss isn't a confidence-tuning problem, matching this thread's existing conclusion that it's workload-dependent rather than a threshold to find.

One thing that might explain part of the "propose-path overhead even on high-acceptance cycles" cost you identified (the c_add case above, 92.9% accept but still -1.7% because of per-cycle propose overhead): reading ds4_session_eval_dspark_speculative_stochastic (ds4.c ~70283), the verify loop does, per draft position after the first:

metal_graph_read_spec_logits_row(&s->graph, (uint32_t)(i - 1), s->spec_row_logits);
sample_build_probabilities(s->spec_row_logits, DS4_N_VOCAB, temperature, top_k, top_p, min_p, s->sample_probs);
speculative_point_accept(s->sample_probs[drafts[i]], 1.0f, rng);

i.e. a full-vocabulary logits readback from GPU plus a full probability-distribution build, one position at a time, sequentially — versus the opportunistic/greedy path's much cheaper per-position argmax-token-ID comparison (and its dedicated fast-commit path from #746). This is paid regardless of whether the block ends up accepted, which lines up with your observation that overhead accumulates even on cycles that don't draft or that accept perfectly. I haven't profiled this at the instruction level to confirm it's the dominant cost, so treating it as a plausible lead rather than a proven root cause — flagging it in case it's useful for whoever looks at optimizing this path.

Also confirmed independently on real HTTP traffic (ds4-server, /v1/chat/completions, temperature: 1.0, matching my own client config) that this isn't a synthetic-benchmark artifact — same result through the actual server with --batched-session 1 and 4, with and without --vision.

Flor1an-B avatar Sep 02 '26 18:09 Flor1an-B