Skip to content

perf(mtp): Optimize Qwen3.8 Flash Next MTP - #51

Merged
sammysun0711 merged 9 commits into
qwen38-flash-next-amd-current-fix-installfrom
qwen38_mtp_qsa_mtp_only
Oct 20, 2026
Merged

sammysun0711 merged 9 commits into
qwen38-flash-next-amd-current-fix-installfrom
qwen38_mtp_qsa_mtp_only

Conversation

@apinge

@apinge apinge commented Oct 18, 2026 •

Copy link
Copy Markdown
Owner

Motivation

This PR optimizes Qwen3.8 Flash Next MTP perf. Modifications include:

  1. Expand pyhip qsa attention to draft extend (currently pyhip qsa attn runs on target extend and draft extend)
  2. In the stage DRAFT_EXTEND_V2 , utilize pyhip decode qsa indexer
  3. Add support for qwen qsa DRAFT_EXTEND_V2's cudagraph
  4. Reuse target embedding in draft mtp embedding.
  5. Skip softmax when topk=1 in draft
  6. Replace qkv split copy in gdn target verify by using split and view
  7. Simplify and fuse metadata kernels in DRAFT_EXTEND_V2 and proposal decode

Co-authored-by: Cheng Luo [email protected]

Modifications

Simplify and fuse metadata kernels in DRAFT_EXTEND_V2 and proposal decode

In proposal decode init_forward_metadata_out_graph, this pr replaces _qsa_graph_layout_kernel and _qsa_graph_row_metadata_kernel with _qsa_mtp_shared_decode_metadata_kernel.
before change, there are 4 kernels.
image
after change only 1 kernel
image

InDRAFT_EXTEND_V2 stage, this pr fuses _qsa_graph_layout_kernel and _qsa_graph_row_metadata_kernel into _qsa_graph_draft_extend_metadata_kernel

after
image

Accuracy Tests

 bash /opt/sglang/scripts/run_gsm8k_qwen38.sh
[aiter] WARNING: NUMA balancing is enabled, which may cause errors. It is recommended to disable NUMA balancing by running "sudo sh -c 'echo 0 > /proc/sys/kernel/numa_balancing'" for more details: https://rocm.docs.amd.com/en/latest/how-to/system-optimization/mi300x.html#disable-numa-auto-balancing
[aiter] import [module_aiter_core] under /opt/aiter/aiter/jit/module_aiter_core.so
Downloading from https://raw.githubusercontent.com/openai/grade-school-math/master/grade_school_math/data/test.jsonl to /tmp/test.jsonl
/tmp/test.jsonl: 732kB [00:00, 3.85MB/s]                                                                                                                                                             
ChatCompletionSampler initialized with self.system_message=None self.temperature=0.0 self.max_tokens=16384 self.reasoning_effort=None self.extra_body=None self.stop=None self.record_meta_info=True
100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1314/1314 [07:57<00:00,  2.75it/s]
Total latency: 477.581 s
Score: 0.977
Output throughput: 1269.442 token/s
[METRIC] gsm8k_score=0.9771689497716894 labels={"model": "Qwen/Qwen3.8-Flash-Next-PTPC-FP8-PLE-BF16", "eval": "gsm8k"}
[METRIC] gsm8k_latency=477.58067998313345 labels={"model": "Qwen/Qwen3.8-Flash-Next-PTPC-FP8-PLE-BF16", "eval": "gsm8k"}
====================
Speculative accept length (per-request, from meta_info): n=1314 mean=3.1378 min=2.5410 max=3.5625
====================
Writing report to /tmp/gsm8k_Qwen_Qwen3.8-Flash-Next-PTPC-FP8-PLE-BF16.html
{'score:std': np.float64(0.14936463227211075), 'score': np.float64(0.9771689497716894), 'latency': 477.58067998313345, 'output_throughput': 1269.4420553641557}
Writing results to /tmp/gsm8k_Qwen_Qwen3.8-Flash-Next-PTPC-FP8-PLE-BF16.json

Speed Tests and Profiling

12K in 1conc
launch server with

  --disable-radix-cache  
  --speculative-algorithm NEXTN
  --speculative-num-steps 3
  --speculative-eagle-topk 1
  --speculative-num-draft-tokens 4

before

#Input tokens: 384000
#Output tokens: 11200
Starting warmup with 10 sequences...
Warmup completed with 10 sequences. Starting main benchmark run...
100%|██████████| 32/32 [01:35<00:00,  2.99s/it]

============ Serving Benchmark Result ============
Backend:                                 sglang    
Traffic request rate:                    inf       
Max request concurrency:                 1         
Successful requests:                     32        
Benchmark duration (s):                  95.58     
Total input tokens:                      384000    
Total input text tokens:                 384000    
Total generated tokens:                  11200     
Total generated tokens (retokenized):    11182     
Request throughput (req/s):              0.33      
Input token throughput (tok/s):          4017.48   
Output token throughput (tok/s):         117.18    
Peak output token throughput (tok/s):    190.00    
Peak concurrent requests:                2         
Total token throughput (tok/s):          4134.66   
Concurrency:                             1.00      
Accept length:                           3.30      
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   2985.89   
Median E2E Latency (ms):                 2737.83   
P90 E2E Latency (ms):                    3558.85   
P95 E2E Latency (ms):                    3697.10   
P99 E2E Latency (ms):                    3767.02   
---------------Time to First Token----------------
Mean TTFT (ms):                          837.06    
Median TTFT (ms):                        836.31    
P90 TTFT (ms):                           843.70    
P95 TTFT (ms):                           853.23    
P99 TTFT (ms):                           857.89    
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          6.16      
Median TPOT (ms):                        5.48      
P90 TPOT (ms):                           7.80      
P95 TPOT (ms):                           8.16      
P99 TPOT (ms):                           8.37      
---------------Inter-Token Latency----------------
Mean ITL (ms):                           6.16      
Median ITL (ms):                         5.27      
P90 ITL (ms):                            7.04      
P95 ITL (ms):                            10.56     
P99 ITL (ms):                            21.11     
Max ITL (ms):                            133.50    
==================================================

After

#Input tokens: 384000
#Output tokens: 11200
Starting warmup with 10 sequences...
Warmup completed with 10 sequences. Starting main benchmark run...
100%|██████████| 32/32 [01:09<00:00,  2.17s/it]

============ Serving Benchmark Result ============
Backend:                                 sglang    
Traffic request rate:                    inf       
Max request concurrency:                 1         
Successful requests:                     32        
Benchmark duration (s):                  69.31     
Total input tokens:                      384000    
Total input text tokens:                 384000    
Total generated tokens:                  11200     
Total generated tokens (retokenized):    11180     
Request throughput (req/s):              0.46      
Input token throughput (tok/s):          5540.17   
Output token throughput (tok/s):         161.59    
Peak output token throughput (tok/s):    308.00    
Peak concurrent requests:                2         
Total token throughput (tok/s):          5701.76   
Concurrency:                             1.00      
Accept length:                           3.30      
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   2164.69   
Median E2E Latency (ms):                 2008.73   
P90 E2E Latency (ms):                    2496.74   
P95 E2E Latency (ms):                    2569.17   
P99 E2E Latency (ms):                    2610.14   
---------------Time to First Token----------------
Mean TTFT (ms):                          813.42    
Median TTFT (ms):                        807.81    
P90 TTFT (ms):                           833.20    
P95 TTFT (ms):                           854.92    
P99 TTFT (ms):                           868.77    
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          3.87      
Median TPOT (ms):                        3.43      
P90 TPOT (ms):                           4.77      
P95 TPOT (ms):                           4.94      
P99 TPOT (ms):                           5.10      
---------------Inter-Token Latency----------------
Mean ITL (ms):                           3.87      
Median ITL (ms):                         3.19      
P90 ITL (ms):                            6.05      
P95 ITL (ms):                            6.45      
P99 ITL (ms):                            12.79     
Max ITL (ms):                            50.88     
==================================================

Checklist

Review and Merge Process

  1. Ping Merge Oncalls to start the process. See the PR Merge Process.
  2. Get approvals from CODEOWNERS and other reviewers.
  3. Trigger CI tests with comments or contact authorized users to do so.
    • Common commands include /tag-and-rerun-ci, /tag-run-ci-label, /rerun-failed-ci
  4. After green CI and required approvals, ask Merge Oncalls or people with Write permission to merge the PR.

Refresh shared-index proposal metadata for all draft steps in one GPU launch and skip unused compressed-key and ring metadata. Fuse draft-extend layout with full metadata preparation and avoid scalar readbacks in eager metadata builders.

Keep the PyHIP decode page-table width within its ABI limit. Add coverage for shared metadata, graph replay, padding, bucket changes, paged attention output, and eager readback removal.
Reuse target prompt embeddings for draft prefill and accelerate the MTP
input broadcast add. Use ROCm max selection for topk=1 draft proposals
without computing full-vocabulary softmax.

Use q/k/v views for ROCm GDN target verification when ReplaySSM buffers
are absent. This verification optimization also serves other speculative
models; it is grouped with the MTP execution-path changes.

Split the MTP and speculative execution changes from fe69548 (add c8 opt).
@apinge apinge changed the title Qwen38 mtp qsa mtp only perf(mtp): Optimize Qwen3.8 Flash Next MTP Oct 18, 2026
@apinge
apinge marked this pull request as ready for review October 19, 2026 04:05
@apinge
apinge requested review from yicyang and a balanced review from Copilot October 19, 2026 05:10

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Copilot review overview

3 open issues
What changed in this PR

This PR targets improved MTP performance for Qwen3.8 Flash Next / Qwen QSA paths, focusing on faster draft-extend / decode metadata handling, broader PyHIP utilization, and reduced redundant embedding work.

Changes:

  • Expand PyHIP QSA usage (including draft-extend indexer and additional mode gating) and add shared-metadata fast paths for MTP decode.
  • Introduce/adjust Triton and graph-metadata kernels to avoid syncs and improve CUDA graph replay behavior.
  • Add/extend kernel tests covering shared metadata refresh, graph replay, and eager paths without CPU scalar readbacks.
File Description
test/​registered/​kernels/​test_qsa_mtp_shared_indexer.py Updates test setup for MTP sparse-index capture expectations.
test/​registered/​kernels/​test_qsa.py Adds coverage for shared draft metadata refresh + CPU-mirror paths.
test/​registered/​kernels/​test_pyhip_qsa.py Extends PyHIP QSA tests to draft worker + draft-extend indexer eager/graph behavior.
python/​sglang/​srt/​speculative/​eagle_worker_v2.py Optimizes topk=1 sampling on ROCm; reuses/reshapes target embeddings for draft extend.
python/​sglang/​srt/​models/​qwen4_exp_mtp.py Adds Triton kernel to speed broadcast-add of embeddings into HC streams; adjusts embedding prep logic.
python/​sglang/​srt/​models/​qwen4_exp.py Plumbs text-only prefill embeddings into forward_batch for MTP reuse.
python/​sglang/​srt/​layers/​attention/​qwen_sparse_attn_backend.py Adds shared-decode metadata fast path; refactors graph-mode constants; avoids sync-heavy scalar reads.
python/​sglang/​srt/​layers/​attention/​qsa/​pyhip_backend.py Enables PyHIP indexer path for draft-extend; tightens decode support constraints.
python/​sglang/​srt/​layers/​attention/​qsa/​graph_metadata.py Adds new Triton kernels for combined draft-extend metadata + shared decode metadata refresh.
python/​sglang/​srt/​layers/​attention/​qsa/​config.py Introduces internal graph-mode constants.
python/​sglang/​srt/​layers/​attention/​linear/​gdn_backend.py Avoids fused split path when target_verify reads can consume views directly.

Review effort: Lite

"token-slot bound reads them back once per forward"
)
return max(1, int(sequence_lengths.max()))
return self.req_to_token.shape[1]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Why not use return max(1, int(sequence_lengths.max().item())) to avoid large table.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

item() will add a gpu->cpu sync point which will slow down the gpu execution.

max_length = int(forward_batch.seq_lens_cpu[:batch_size].max())
else:
max_length = int(sequence_lengths.max())
max_length = self.req_to_token.shape[1]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Why not use max_length = max(1, int(sequence_lengths.max().item())) to avoid large table.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Same with above.

@apinge

apinge commented Oct 20, 2026

Copy link
Copy Markdown
Owner Author

Reverting change 7 in 026932d —it got a bit too complex and the gains aren't really clear. I'll consider a separate PR for it down the road if we still need it.

@sammysun0711
sammysun0711 merged commit d0a5b96 into qwen38-flash-next-amd-current-fix-install Oct 20, 2026
1 check failed
apinge added a commit that referenced this pull request Nov 10, 2026
* use pyhip qsa prefill kerenl for draft extend

* support pyhip indexer for draft_extend_v2

* support cudagraph for draft extend

* perf(qsa): reduce MTP draft replay metadata preparation

Refresh shared-index proposal metadata for all draft steps in one GPU launch and skip unused compressed-key and ring metadata. Fuse draft-extend layout with full metadata preparation and avoid scalar readbacks in eager metadata builders.

Keep the PyHIP decode page-table width within its ABI limit. Add coverage for shared metadata, graph replay, padding, bucket changes, paged attention output, and eager readback removal.

* perf(mtp): optimize draft processing and target verification

Reuse target prompt embeddings for draft prefill and accelerate the MTP
input broadcast add. Use ROCm max selection for topk=1 draft proposals
without computing full-vocabulary softmax.

Use q/k/v views for ROCm GDN target verification when ReplaySSM buffers
are absent. This verification optimization also serves other speculative
models; it is grouped with the MTP execution-path changes.

Split the MTP and speculative execution changes from fe69548 (add c8 opt).

* replace number with qsa graph mode

* update zero mm_input_embeds; update tests

* update condition of extend_seq_lens_cpu

* revert(qsa): restore full MTP replay metadata preparation

(cherry picked from commit d0a5b96)
sammysun0711 added a commit that referenced this pull request Nov 11, 2026
* perf(mtp): Optimize Qwen3.8 Flash Next MTP (#51)

* use pyhip qsa prefill kerenl for draft extend

* support pyhip indexer for draft_extend_v2

* support cudagraph for draft extend

* perf(qsa): reduce MTP draft replay metadata preparation

Refresh shared-index proposal metadata for all draft steps in one GPU launch and skip unused compressed-key and ring metadata. Fuse draft-extend layout with full metadata preparation and avoid scalar readbacks in eager metadata builders.

Keep the PyHIP decode page-table width within its ABI limit. Add coverage for shared metadata, graph replay, padding, bucket changes, paged attention output, and eager readback removal.

* perf(mtp): optimize draft processing and target verification

Reuse target prompt embeddings for draft prefill and accelerate the MTP
input broadcast add. Use ROCm max selection for topk=1 draft proposals
without computing full-vocabulary softmax.

Use q/k/v views for ROCm GDN target verification when ReplaySSM buffers
are absent. This verification optimization also serves other speculative
models; it is grouped with the MTP execution-path changes.

Split the MTP and speculative execution changes from fe69548 (add c8 opt).

* replace number with qsa graph mode

* update zero mm_input_embeds; update tests

* update condition of extend_seq_lens_cpu

* revert(qsa): restore full MTP replay metadata preparation

(cherry picked from commit d0a5b96)

* fix(qsa): adapt MTP backport to qwen4_v0.5.21

Keep the current 1M bounds, capability-based GDN routing, and fused topk1 paths. Reuse the per-request Eagle embedding shift once and initialize each tail before the draft repairs it.

Update draft PyHIP dispatch tests for the new contract, migrate the prefill-anchor case to the current QSA test file, and cover embedding alignment and broadcast-add graph replay.

---------

Co-authored-by: Xiake Sun <[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