Skip to content

Enable CUDA graph for MTP draft - #28549

Merged
gaugarg-nv merged 3 commits into
ggml-org:masterfrom
gaugarg-nv:mtp_graph
Sep 16, 2026
Merged

gaugarg-nv merged 3 commits into
ggml-org:masterfrom
gaugarg-nv:mtp_graph

Conversation

@gaugarg-nv

@gaugarg-nv gaugarg-nv commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Overview

This PR prevents repeated CUDA graph capture during MTP speculative decoding.

MTP alternates between- Output-producing draft batches, and No-output prefill and catch-up batches.

Previously both shapes reused one llm_graph_result, so they shared the same CUDA graph cache key and repeatedly replaced each other’s captured graph.

This PR:

  • Adds a second graph-result arena for MTP no-output batches.
  • Gives both graph shapes distinct, stable CUDA graph cache keys.

Additional information

Nsight profile Master: At every decode iteration, CUDA graph is not used for MTP catch-up and the first MTP draft token. Second MTP draft token always recaptures the graph. This happens after every iteration of verification.

Screenshot 2026-09-07 at 6 57 08 PM

Nsight profile PR: At steady state, CUDA graph is always used with no need for recapture in both catch-up and draft AR.

Screenshot 2026-09-07 at 6 54 15 PM

Performance: RTX 5090 on Windows with Qwen3.6-35B-A3B-UD-Q4_K_M.gguf MTP3 shows a gain of 4-5%

Command: llama-server -m Qwen3.6-35B-A3B-UD-Q4_K_M.gguf --spec-type draft-mtp
Benchmarking: python tools\server\bench\speed-bench\speed_bench.py --url localhost:8080 --bench qualitative --osl 256 --concurrency 1 --limit 8 --category stem

Master:

Summary (elapsed=24.61s)
category  samples  avg_prompt_t/s  avg_pred_t/s  avg_latency  accept_rate
--------  -------  --------------  ------------  -----------  -----------
stem      8        87.02           279.04        3.076s       0.7061
overall   8        87.02           279.04        3.076s       0.7061

PR:

Summary (elapsed=24.11s)
category  samples  avg_prompt_t/s  avg_pred_t/s  avg_latency  accept_rate
--------  -------  --------------  ------------  -----------  -----------
stem      8        91.10           291.33        3.013s       0.7061
overall   8        91.10           291.33        3.013s       0.7061

Requirements

Comment thread src/llama-context.h Resolved
@am17an

am17an commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

For dflash/dflash2 the situation is worse as it has even more graphs. I'm not sure what the correct direction is but I was thinking some of cache in llama.cpp would be good as it cycles through different graph shapes. Currently this behaves like a cache of size of 2 vs 1.

@ruixiang63

ruixiang63 commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

For dflash/dflash2 the situation is worse as it has even more graphs. I'm not sure what the correct direction is but I was thinking some of cache in llama.cpp would be good as it cycles through different graph shapes. Currently this behaves like a cache of size of 2 vs 1.

I think now it has three graphs: target_verify + fused dflash encoder + KV cachge injection + dflash decoder.
image
Compared to MTP, IMO MTP_prefill graph is similar to fused dflash encoder + KV cachge injection, and dflash decoder is similar to MTP_decode graph but it is even better as it is called only once for each spec dec step.

@am17an

am17an commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

@ruixiang63 are you agreeing me that they also thrash similarly to MTP or are you saying something else?

@aendk

aendk commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

For dflash/dflash2 the situation is worse as it has even more graphs.

@am17an have you checked this recently? I tested last week and it looks like DFLASH/MTP3 has the exact same number of graph launches.

@ruixiang63

ruixiang63 commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

@ruixiang63 are you agreeing me that they also thrash similarly to MTP or are you saying something else?

I mean both DFlash and MTP now have three seperate cuda graphs for each spec dec step, i.e. target_verify, fused dflash encode/ KV cachge injection or MTP_prefill, dflash decode or MTP decode. From my understanding, these already appear to be optimized. I’m not sure whether any fusion opportunities remain that would further improve them. @am17an

Note: With this PR, MTP will have three CUDA graphs, as described above.

@am17an

am17an commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Ah okay, you're right. So this PR already targets all supported spec-dec techniques to enable cuda graph for the drafters?

@ruixiang63

Copy link
Copy Markdown
Member

So this PR can target all supported spec-dec techniques to enable cuda graph for the drafters?

This PR applies only to MTP. An improved PR for DFlash was merged previously #27310, so DFlash already uses three cuda graphs in the current master branch. With this PR, MTP will also use three cuda graphs.

@am17an

am17an commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Yes but this is not about fusing the graphs. It's about gf_res_prev not allowing re-use which thrashes CUDA graphs, this PR only fixes it for the MTP

@gaugarg-nv

Copy link
Copy Markdown
Contributor Author

For dflash/dflash2 the situation is worse as it has even more graphs.

Yes, @ruixiang63 is right. DFlash2 uses a separate graph for catch-up, whereas MTP share the same graph for catch-up and draft AR. That's why this issue is specific to MTP.

I'm not sure what the correct direction is but I was thinking some of cache in llama.cpp would be good as it cycles through different graph shapes. Currently this behaves like a cache of size of 2 vs 1.

Yes, this could be one approach. Another alternative that I thought was to keep the cache in backend itself, but allow llama.cpp to pass an id to the backend. This id can be based on the shape/batch size. The CUDA graph cache in the backend will use both first_node_ptr and the new id passed by upper layer as key. This way multiple CUDA graphs can be kept even if they share the first_node_ptr as long as the new id is unique for each. I didn't go for this approach as it would have required adding new APIs to pass these ids. llama.cpp layer has to make sure the id is stable per reusable variant.

@am17an

am17an commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

From my tests the dflash encoder and decoder both seem to collide i.e. they have the same key. This causes the CUDA graph warm-up instead of steadily replaying a captured graph. Does this not happen in your tests?

@ruixiang63

ruixiang63 commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

From my tests the dflash encoder and decoder both seem to collide i.e. they have the same key. This causes the CUDA graph warm-up instead of steadily replaying a captured graph. Does this not happen in your tests?

I didn't encounter this issue. Did you see something similar when you did profling? @aendk

@am17an

am17an commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Hmm okay, I was experimenting with -sm tensor and RPC + dspark, maybe just crossing wires. Ignore my comments.

@aendk

aendk commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

@ruixiang63 have not seen it (but I also have not looked for it).

@am17an have you switched your stance on this potential issue, do you think we should retest ?

If need be I can investigate this specific issue to move this PR forward.

@am17an

am17an commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

okay so my point was not that CUDA graphs are not re-used, it's the cgraph is rebuilt every step. It seems to me it survives the CUDA graph re-use only because of the full-graph memcmp check and not the uid check. But the draft rebuild is not very costly as it's mostly a single layer so it's not a real problem IMO. So we can fix the CUDA graph reuse for MTP, for DFlash it already works well.

@gaugarg-nv

Copy link
Copy Markdown
Contributor Author

okay so my point was not that CUDA graphs are not re-used, it's the cgraph is rebuilt every step. It seems to me it survives the CUDA graph re-use only because of the full-graph memcmp check and not the uid check. But the draft rebuild is not very costly as it's mostly a single layer so it's not a real problem IMO. So we can fix the CUDA graph reuse for MTP, for DFlash it already works well.

Yes, this is correct, Aman. Do you think the current approach in the PR makes sense?
This is not a generic solution, but is simple and works fine for MTP-specific issue.

@ggerganov

Copy link
Copy Markdown
Member

MTP alternates between- Output-producing draft batches, and No-output prefill and catch-up batches.

Which part in the graph causes the two cases to be different?

@ggerganov

Copy link
Copy Markdown
Member

From quick look, it seems the only difference could be in this code:

// TODO: make static using `ggml_build_forward_select()`
// see llm_graph_context::build_inp_embd() for reference
ggml_tensor * tok_embd;
if (ubatch.token) {
ggml_tensor * tok_embd_w = layer.nextn.embed_tokens ? layer.nextn.embed_tokens : model.tok_embd;
tok_embd = ggml_get_rows(ctx0, tok_embd_w, inp->tokens);
} else {
tok_embd = inp->embd;
}
cb(tok_embd, "mtp_tok_embd", il);

Simply resolving the TODO should make the graph static with respect to prefill/decode batches.

deadtrickster added a commit to deadtrickster/llama.cpp that referenced this pull request Sep 16, 2026
… step

llm_graph_input_kpool had no can_reuse override, so it inherited the base
class's false, and a GLM-5.3-Flash decode rebuilt the ggml graph, re-ran the
scheduler allocation and re-captured the CUDA graph on every verify step.
The server reported it all along: `graphs reused = 0` on every request.
Found with LLAMA_GRAPH_RESULT_DEBUG=2 once the debug line named the input
instead of printing "placeholder" (also fixed here).

The override derives every shape exactly as build_inp_kpool does (n_tokens,
n_kv, n_stream, n_tps, n_ps -> n_pools, n_new_max) and additionally requires
the stored `rebuild` flag to equal the cache's current kpool_dirty state:
set_input acts on the stored flag, so reusing a clean graph over a dirty
cache would leave every pooled key stale.

Also carries upstream PR ggml-org#28549 (two graph-result arenas for the MTP draft
context, so output and no-output batches keep stable CUDA graph keys). Noise
level on this model - the draft graph is 149 nodes - but correct and
upstream-bound.

Measured on lab2x1 (2x RTX PRO 6000 + RTX 4080 SUPER over USB4, blk 3-5
experts on the 4080), temperature 0, output byte-identical to the pre-fix
reference on all runs:

  graphs reused / 300-tok request   0      -> ~124 (every target step)
  decode, 23-tok prompt             88.4   -> 93.4-93.9 t/s
  decode, 33,164-tok prompt, n=6    72.1   -> 76.7 +/- 0.6 t/s
  prefill, 33,164-tok               708.8  -> 703.0 t/s (unchanged)

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01G62YYJvLF2k2JBfizQL2op
@gaugarg-nv

Copy link
Copy Markdown
Contributor Author

@ggerganov This issue is not due to differences in graph. Both phases use the same graph.

The issue is due to differences in batch dimensions and output count. Tensor dimensions, strides, and pointers should match for CUDA graph reuse.

This PR allows storing and reusing two separate CUDA graphs for both phases, so that these can just be replayed in each iteration.

@ggerganov

Copy link
Copy Markdown
Member

I see. However the current logic is very MTP specific and I expect it will create various conflicts in the future. Can we make this more generic?

Maybe we can map batch dimensions to graph result. For example:

  • small batch -> use gf_res_0
  • large batch -> use gf_res_1
    ...

Not sure how many batch categories we want to have? And how many we can afford to have (memory usage?)?

This is loosely related to the graph reserve logic where we "probe" a few common batch size to determine the worst-case graph size. It is in the TODOs to improve this and make it more generic, which would likely involve some batch categorization too. Just FYI, not necessarily related to the current PR.

@gaugarg-nv

Copy link
Copy Markdown
Contributor Author

Categorization based on batch size makes sense, but we might run into cases where we end-up using the same llm_graph_result for AR and catch-up depending on concurrency and draft length values used.

How about we make it generic by removing LLAMA_CONTEXT_TYPE_MTP check and keep multiple graph results based on whether output is requested or not? This approach will address MTP CUDA graph issue as both catch-up and AR graphs have this difference.

Latest commit in this PR takes this approach. Please see if it makes sense.

@am17an

am17an commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

is a graph cache not workable here, similar to the one we have in CUDA?

@gaugarg-nv

Copy link
Copy Markdown
Contributor Author

is a graph cache not workable here, similar to the one we have in CUDA?

My opinion is that as this issue is very specific to MTP, the current two-category approach makes sense.
Generic cache approach would make sense if there are wide variety of cases hitting this CUDA graph replay issue.

@gaugarg-nv
gaugarg-nv merged commit 2f3fd02 into ggml-org:master Sep 16, 2026
24 of 26 checks passed
@gaugarg-nv
gaugarg-nv deleted the mtp_graph branch September 16, 2026 16:17
adromir pushed a commit to adromir/llama-cpp-turboquant that referenced this pull request Sep 17, 2026
despc added a commit to despc/llama.cpp that referenced this pull request Sep 26, 2026
Conflicts resolved by hand, keeping the fork's functionality:
- allreduce.cu: our mixed-runtime collective kept; upstream's HIP enablement
  and CUDA_CHECK cleanup applied, #else stub comment taken from upstream.
- llama-context.cpp/.h: upstream's per-graph-type gf_res_prev and
  gf_res_prev_active (ggml-org#28549, CUDA graph for MTP draft) around our ubatch
  phase profiler; expert heatmap/hotstore members kept.
- server-context.cpp/.h: upstream's handle_count_tokens signature (ggml-org#29309)
  with our reject_unknown_model guard.
- fattn-common.cuh: our GGML_CUDA_FATTN_LAUNCH_PROFILE log kept.
qwen4exp.cpp auto-merged: our MTP head kept, upstream hc ops and sparse FA in
(PR ggml-org#28243 still unmerged upstream, so MTP stays ours).

Validation (greedy, temp 0 / top_k 1 / seed 42, hash of reasoning+content):
- Qwen3.8-27B 4-GPU MTP: byte-identical to the old build on all prompts.
- Qwen3.8-Flash 4-GPU MTP: 1 of 3 identical, 2 diverge late. Cause is the
  fused hc_pre_gated/hc_post ops from ggml-org#28901 (different rounding order);
  still diverges with GGML_CUDA_DISABLE_FUSION=1. test-backend-ops passes
  DSV4_HC_PRE/POST on CUDA0, CUDA1, V100_CUDA0, V100_CUDA1. Perplexity
  (docs corpus, 24x1024): 5.4967 +/- 0.127 old, 5.4707 +/- 0.126 new.
Generation speed unchanged on both models.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

5 participants