Skip to content

[w2] Speculative decoding host gaps: timing, single output sync, opt-in backend greedy verify - #169

Merged
rafasmour merged 1 commit into
masterfrom
opt/w2-dflash-launch-cuts
Dec 4, 2026
Merged

rafasmour merged 1 commit into
masterfrom
opt/w2-dflash-launch-cuts

Conversation

@rafasmour

Copy link
Copy Markdown
Owner

What

Host round trips of the speculative loop (Nemotron DFlash, and the same server loop for MTP: Qwen4, Qwen3.8, Gemma; DSpark: MiniCPM5, LFM3).

  1. LLAMA_SPEC_TIMING=1 per-step timers, per-request summary in the slot log (draft total/decode/sample, feature reads, inject, verify launch, verify sync, candidate prepare, accept, plus llama_synchronize waits and skipped reads, target + draft context).
  2. Single output sync (essence of upstream 30196; kill switch LLAMA_SPEC_NO_SINGLE_SYNC=1, bit-identical, default ON). Today every llama_get_* and every common_sampler_sample() calls llama_synchronize(), which is a hipStreamSynchronize even when the stream is idle: about 6 per sampled row, about 40 for a 6-row verify, and the same again for the draft rows (the "0.35 ms verify->draft sync"). Now the output readers (llama_get_logits*/embeddings*/nextn*/layer_inp/sampled*, common_sampler_sample/prepare) wait only if a graph was computed since the last wait (llama_synchronize_outputs(), outputs_pending flag). The explicit llama_synchronize() is unchanged.
    Deviation from the task text: I did not port the 30196 diff itself. The fork already has its own common_sampler_prepare / preselect machinery in common/sampling.cpp that conflicts with it in 4 places; the flag gives the same effect (one wait per batch) with a much smaller surface. The "one batched D2H" half is not done: the per-row/per-layer D2H copies are separate tensors, batching them needs a gather in the graph (see below).
  3. LLAMA_SPEC_DEVICE_VERIFY=1 (opt-in, default OFF). In a server with a speculative drafter, a greedy request (common_sampler_is_greedy: temp<=0, last sampler temp 0 or top_k 1, only max-preserving samplers, no grammar / reasoning budget / logit bias / suppress tokens / n_probs) registers a per-slot backend greedy sampler on the target context. The verify decode then computes the argmax of each output row on the GPU, does not copy the logits of the rows (needs_raw_logits), and the host skips the candidate scan; common_sampler_sample returns the backend token. Non-greedy requests, and slots that already use --backend-sampling, are untouched (fall back). Not the full 33586 (which also verifies on the device and returns accept length); that needs the graph-side verify stages, about 800 lines, and is a follow-up if the numbers justify it. Caveat: ties between the two largest logits of a row may resolve differently from the host sampler (GPU argmax vs host scan).
    Cost: the graph gets n_outputs_max_per_seq argmax chains per registered sampler, and registering/unregistering a sampler triggers a scheduler reserve at request start.
  4. Launch cuts: analysis only, nothing implemented. Without a GPU I cannot tell which existing matchers (rms_norm+mul+rope, add+rms_norm, q8_1 sharing, gate/up) already fire on the DFlash graphs, and the rule was no blind fusions. Candidates for tonight's trace (tr.sh on nb-df, count kernels per verify and per draft decode), estimated at 2-3 us per removed launch:
    • Drafter layer (src/models/dflash.cpp build_layers / build_inject): attn_norm rms_norm + 3 Q/K/V mat-vecs (3 launches, separate matrices; the Q/K/V-in-one-launch attempt gave -0.2 % on Gemma), V weightless ggml_rms_norm (not fused with anything), K/V cpy_k/cpy_v set_rows (2), ffn_norm, residual adds. Inject graph runs the same K/V path per accepted row batch.
    • build_logits: ggml_cont(view) + (with a trimmed draft vocab) ggml_fill(-inf) + ggml_set_rows scatter over the full vocab every draft step: owned by spec-trimmed-draft-vocab.
    • DFlash2 conv (build_dflash2_conv): per layer, side and tap: cont, repeat, add, view+cont, mul, add; this is the largest pile of tiny kernels (Qwen3.8 DFlash2 only, not Nemotron) and has no matcher; selector build_dflash2_selector adds about 25 small ops per step.
    • Nemotron decode trace (kern/prof/nem-tg.txt): 167 Q8_0 mat-vecs at 5 us, about 210 rms_norm, 84 quantize_q8_1.
  5. MTP / DSpark use the same common_sampler_*, llama_get_embeddings_nextn* and server paths, so (2) and (3) apply to them unchanged. get_h_nextn_rows (blocking D2H of one hidden row per MTP step) is untouched.

Expected gain (estimates, not measured)

Scout: up to 0.35 ms of a ~5.5 ms DFlash step (about 6 %) from (2) if an idle hipStreamSynchronize costs about 10 us; (3) additionally saves the logits D2H (about 0.5 MB per row for a 131k vocab) and the host scan, at the price of one tiny D2H per row.

Env switches

LLAMA_SPEC_TIMING=1 (logging), LLAMA_SPEC_NO_SINGLE_SYNC=1 (kill switch, bit-identical), LLAMA_SPEC_DEVICE_VERIFY=1 (opt-in).

Files

src/llama-context.{h,cpp}, src/llama-ext.h (llama_synchronize_outputs, llama_get_sync_stats), common/sampling.{h,cpp}, common/speculative.{h,cpp}, tools/server/server-context.cpp, tests/test-spec-device-verify.cpp (+ CMake).

Risks

Server state machine: mixed spec/non-spec slots (the logits are copied if any output row's sequence has no backend sampler, so mixing is fine), checkpoint replays (flag is kept across common_sampler_copy), sampler registration reserve at request start. Merge order: this task merges before spec-trimmed-draft-vocab (both touch common/speculative.cpp and server-context.cpp).

Checks done (CPU only, no GPU used)

  • CPU build of llama-server, test-spec-device-verify, test-speculative-rejection-sampling, test-llama-archs: OK, no new warnings.
  • test-spec-device-verify (new, tiny generated llama model): backend greedy tokens == host tokens, accept lengths equal, logits and tokens independent of LLAMA_SPEC_NO_SINGLE_SYNC; 2 waits + 65 skipped reads per batch vs 67 waits with the kill switch; common_sampler_is_greedy accept/reject cases. test-speculative-rejection-sampling: pass.
  • CPU llama-server with draft-simple (tiny model as its own draft = 100 % acceptance, and a differently seeded one = 0 % acceptance), greedy 300 tokens: identical text hash with default, NO_SINGLE_SYNC=1, DEVICE_VERIFY=1, TIMING=1, and identical to the non-speculative hash in the 0 % case.

GPU validation tonight (NOT YET RUN)

Preamble (P) from the wave plan, then:

./gpublock.sh python3 -I $TB/specbench.py nb-df-b0 $B0 --n 256 --modes greedy,preset -- $(python3 -I $TB/preset2args.py nemotron-3.5-bolt-e4b-dflash)
./gpublock.sh python3 -I $TB/specbench.py nb-df-ba $BA --n 256 --modes greedy,preset -- $(python3 -I $TB/preset2args.py nemotron-3.5-bolt-e4b-dflash)
./gpublock.sh env SB_ENV=LLAMA_SPEC_DEVICE_VERIFY=1 python3 -I $TB/specbench.py nb-df-dv $BA --n 256 --modes greedy -- $(python3 -I $TB/preset2args.py nemotron-3.5-bolt-e4b-dflash)

Same three runs for minicpm5-15b-a2.5b-dspark, qwen-4-35b-a3b-128k-f16-mtp, gemma-4-31b-it. Timing: one run with SB_ENV=LLAMA_SPEC_TIMING=1, read the spec-timing block from the server log (ba with and without LLAMA_SPEC_NO_SINGLE_SYNC=1 shows the wait/skip counters). Pass: greedy hashes identical across b0, ba and dv. Also count kernels with tr.sh for the launch-cut candidates above.

Hard rules: no GPU, no production, nothing touched in ggml-org/llama.cpp (upstream PRs 30196 and 33586 were only fetched read-only).

- LLAMA_SPEC_TIMING=1: per-step timers (draft decode/sample, feature reads, inject,
  verify launch/sync/prepare/accept) and sync counters, per-request summary.
- Readers of decode outputs (llama_get_*, common_sampler_sample/prepare) wait for the
  backend once per computed batch instead of once per read.
  LLAMA_SPEC_NO_SINGLE_SYNC=1 restores a wait per read. Bit-identical.
- LLAMA_SPEC_DEVICE_VERIFY=1 (opt-in): greedy requests in a speculative server register a
  backend greedy sampler, so the verify decode does not copy the logits of the rows and
  the host skips the candidate scan.
- tests/test-spec-device-verify.cpp

Assisted-by: Claude Sonnet 5.5
@rafasmour
rafasmour merged commit 787c5f1 into master Dec 4, 2026
5 of 30 checks passed
@rafasmour

Copy link
Copy Markdown
Owner Author

Reverted from master on 2026-12-04 (w2 build crashed Qwen4-single at >20k ctx; no measured gain). Commit preserved on branch archive/w2-25f0def; will be re-landed individually after GPU validation.

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