Skip to content

Support MHA with chunked prefix cache for flashinfer/flashmla backend, support page size > 1 for MHA chunked prefix - #8616

Merged
zhyncs merged 21 commits into
sgl-project:mainfrom
xu-yfei:xyf/flashinfer_chunk_kv
Aug 22, 2025
Merged

zhyncs merged 21 commits into
sgl-project:mainfrom
xu-yfei:xyf/flashinfer_chunk_kv

Conversation

@xu-yfei

@xu-yfei xu-yfei commented Jul 31, 2025 •

Copy link
Copy Markdown
Contributor

Motivation

Based on #5113, for issue #6959, support flashinfer and flashmla (actually flashinfer as well) backend. remove the page-size=1 restriction: support page size > 1.

Modifications

Accuracy Test

export SGL_ENABLE_JIT_DEEPGEMM=1
export TORCHINDUCTOR_CACHE_DIR=/home/admin/inductor_root_cache
export SGLANG_TORCH_PROFILER_DIR=/home/admin/torch_profiler
model_path=/home/models/deepseek-ai__DeepSeek-R1_64k

nohup python3 -m sglang.launch_server --model-path $model_path \
--host 0.0.0.0 --port 8000 --trust-remote-code  --enable-mixed-chunk \
--enable-cache-report --quantization fp8 --log-level info --max-running-requests 16 \
--mem-fraction-static 0.92 --chunked-prefill-size 8192 --context-length 65535 --chat-template /home/admin/r1.jinja \
--attention-backend flashinfer \
--tp-size 8 --enable-metrics --cuda-graph-max-bs 16 

gsm8k flashinfer page-size=1

Accuracy: 0.954
Invalid: 0.000
Latency: 327.817 s
Output throughput: 385.446 token/s

gsm8k flashmla page-size=64

Accuracy: 0.955
Invalid: 0.000
Latency: 332.966 s
Output throughput: 380.763 token/s

mmlu flashinfer page-size=1

subject: abstract_algebra, #q:100, acc: 0.750
subject: anatomy, #q:135, acc: 0.852
subject: astronomy, #q:152, acc: 0.934
subject: business_ethics, #q:100, acc: 0.870
subject: clinical_knowledge, #q:265, acc: 0.928
subject: college_biology, #q:144, acc: 0.965
subject: college_chemistry, #q:100, acc: 0.630
subject: college_computer_science, #q:100, acc: 0.840
subject: college_mathematics, #q:100, acc: 0.770
subject: college_medicine, #q:173, acc: 0.884
subject: college_physics, #q:102, acc: 0.833
subject: computer_security, #q:100, acc: 0.880
subject: conceptual_physics, #q:235, acc: 0.940
subject: econometrics, #q:114, acc: 0.737
subject: electrical_engineering, #q:145, acc: 0.869
subject: elementary_mathematics, #q:378, acc: 0.934
subject: formal_logic, #q:126, acc: 0.802
subject: global_facts, #q:100, acc: 0.680
subject: high_school_biology, #q:310, acc: 0.961
subject: high_school_chemistry, #q:203, acc: 0.847
subject: high_school_computer_science, #q:100, acc: 0.960
subject: high_school_european_history, #q:165, acc: 0.873
subject: high_school_geography, #q:198, acc: 0.960
subject: high_school_government_and_politics, #q:193, acc: 0.984
subject: high_school_macroeconomics, #q:390, acc: 0.931
subject: high_school_mathematics, #q:270, acc: 0.744
subject: high_school_microeconomics, #q:238, acc: 0.958
subject: high_school_physics, #q:151, acc: 0.841
subject: high_school_psychology, #q:545, acc: 0.974
subject: high_school_statistics, #q:216, acc: 0.866
subject: high_school_us_history, #q:204, acc: 0.956
subject: high_school_world_history, #q:237, acc: 0.937
subject: human_aging, #q:223, acc: 0.857
subject: human_sexuality, #q:131, acc: 0.931
subject: international_law, #q:121, acc: 0.950
subject: jurisprudence, #q:108, acc: 0.907
subject: logical_fallacies, #q:163, acc: 0.933
subject: machine_learning, #q:112, acc: 0.795
subject: management, #q:103, acc: 0.913
subject: marketing, #q:234, acc: 0.949
subject: medical_genetics, #q:100, acc: 0.950
subject: miscellaneous, #q:783, acc: 0.949
subject: moral_disputes, #q:346, acc: 0.867
subject: moral_scenarios, #q:895, acc: 0.769
subject: nutrition, #q:306, acc: 0.918
subject: philosophy, #q:311, acc: 0.897
subject: prehistory, #q:324, acc: 0.938
subject: professional_accounting, #q:282, acc: 0.879
subject: professional_law, #q:1534, acc: 0.694
subject: professional_medicine, #q:272, acc: 0.963
subject: professional_psychology, #q:612, acc: 0.915
subject: public_relations, #q:110, acc: 0.809
subject: security_studies, #q:245, acc: 0.886
subject: sociology, #q:201, acc: 0.970
subject: us_foreign_policy, #q:100, acc: 0.930
subject: virology, #q:166, acc: 0.590
subject: world_religions, #q:171, acc: 0.930
Total latency: 633.687
Average accuracy: 0.870

mmlu flashmla page-size=64

subject: abstract_algebra, #q:100, acc: 0.760
subject: anatomy, #q:135, acc: 0.852
subject: astronomy, #q:152, acc: 0.941
subject: business_ethics, #q:100, acc: 0.880
subject: clinical_knowledge, #q:265, acc: 0.921
subject: college_biology, #q:144, acc: 0.972
subject: college_chemistry, #q:100, acc: 0.610
subject: college_computer_science, #q:100, acc: 0.830
subject: college_mathematics, #q:100, acc: 0.790
subject: college_medicine, #q:173, acc: 0.867
subject: college_physics, #q:102, acc: 0.843
subject: computer_security, #q:100, acc: 0.880
subject: conceptual_physics, #q:235, acc: 0.923
subject: econometrics, #q:114, acc: 0.754
subject: electrical_engineering, #q:145, acc: 0.883
subject: elementary_mathematics, #q:378, acc: 0.947
subject: formal_logic, #q:126, acc: 0.802
subject: global_facts, #q:100, acc: 0.680
subject: high_school_biology, #q:310, acc: 0.955
subject: high_school_chemistry, #q:203, acc: 0.862
subject: high_school_computer_science, #q:100, acc: 0.960
subject: high_school_european_history, #q:165, acc: 0.879
subject: high_school_geography, #q:198, acc: 0.965
subject: high_school_government_and_politics, #q:193, acc: 0.984
subject: high_school_macroeconomics, #q:390, acc: 0.921
subject: high_school_mathematics, #q:270, acc: 0.737
subject: high_school_microeconomics, #q:238, acc: 0.966
subject: high_school_physics, #q:151, acc: 0.834
subject: high_school_psychology, #q:545, acc: 0.969
subject: high_school_statistics, #q:216, acc: 0.861
subject: high_school_us_history, #q:204, acc: 0.951
subject: high_school_world_history, #q:237, acc: 0.941
subject: human_aging, #q:223, acc: 0.843
subject: human_sexuality, #q:131, acc: 0.931
subject: international_law, #q:121, acc: 0.959
subject: jurisprudence, #q:108, acc: 0.907
subject: logical_fallacies, #q:163, acc: 0.926
subject: machine_learning, #q:112, acc: 0.786
subject: management, #q:103, acc: 0.913
subject: marketing, #q:234, acc: 0.940
subject: medical_genetics, #q:100, acc: 0.960
subject: miscellaneous, #q:783, acc: 0.950
subject: moral_disputes, #q:346, acc: 0.870
subject: moral_scenarios, #q:895, acc: 0.766
subject: nutrition, #q:306, acc: 0.918
subject: philosophy, #q:311, acc: 0.894
subject: prehistory, #q:324, acc: 0.935
subject: professional_accounting, #q:282, acc: 0.872
subject: professional_law, #q:1534, acc: 0.696
subject: professional_medicine, #q:272, acc: 0.952
subject: professional_psychology, #q:612, acc: 0.913
subject: public_relations, #q:110, acc: 0.836
subject: security_studies, #q:245, acc: 0.890
subject: sociology, #q:201, acc: 0.965
subject: us_foreign_policy, #q:100, acc: 0.930
subject: virology, #q:166, acc: 0.590
subject: world_religions, #q:171, acc: 0.936
Total latency: 498.679
Average accuracy: 0.869

frame oracle, avg input len 15767, in 8*H20(96GB)
normal range: 80.46 to 82.04, with possible accuracy fluctuations.
flashinfer page size 1, mixed, disable chunk: 80.83

enable chunk kv:
flashmla page size 64, without mixed: 81.67
flashinfer page size 64, enable mixed: 80.10
flashinfer page size 1, mixed: 81.92

Benchmark & Profiling

export SGL_ENABLE_JIT_DEEPGEMM=1
export TORCHINDUCTOR_CACHE_DIR=/home/admin/inductor_root_cache
export SGLANG_TORCH_PROFILER_DIR=/home/admin/torch_profiler
model_path=/home/models/deepseek-ai__DeepSeek-R1_64k

nohup python3 -m sglang.launch_server --model-path $model_path \
--host 0.0.0.0 --port 8000 --trust-remote-code  \
--enable-cache-report --quantization fp8 --log-level info --max-running-requests 16 \
--mem-fraction-static 0.92 --chunked-prefill-size 8192 --context-length 65535 --chat-template /home/admin/r1.jinja \
--attention-backend flashinfer \
--tp-size 8 --enable-metrics --cuda-graph-max-bs 16 

add --disable-chunked-prefix-cache disable chunked prefix.

flashinfer MHA with chunked prefix:

# context len: 8192+3575
TTFT 1.415292501449585, TPOT 0.011880073547363281, 0.012364864349365234
TTFT 1.7534656524658203, TPOT 0.011905488967895507, 0.012394309043884277
TTFT 1.6541788578033447, TPOT 0.011828327178955078, 0.01231357455253601
TTFT 1.650024175643921, TPOT 0.011895389556884765, 0.012383649746576944
TTFT 1.6498384475708008, TPOT 0.01190070152282715, 0.01238952080408732
TTFT 1.6516165733337402, TPOT 0.011910390853881837, 0.012399405241012573
TTFT 1.6515693664550781, TPOT 0.011913814544677735, 0.012403180201848349
TTFT 1.664086103439331, TPOT 0.011901226043701172, 0.012390226125717163
TTFT 1.6539785861968994, TPOT 0.011902732849121094, 0.01239168643951416
TTFT 1.649728536605835, TPOT 0.011927766799926758, 0.012417882680892944

# context len: 6*8192+646
TTFT 10.09317421913147, TPOT 0.014095582962036134, 0.014671474695205688
TTFT 10.253344297409058, TPOT 0.014484329223632813, 0.01508068044980367
TTFT 10.215717792510986, TPOT 0.014594602584838866, 0.015193641185760498
TTFT 10.221231937408447, TPOT 0.014469633102416992, 0.015062501033147177
TTFT 10.215486764907837, TPOT 0.01447087287902832, 0.015063981215159098
TTFT 10.219701528549194, TPOT 0.014470472335815429, 0.015066395203272501
TTFT 10.217058897018433, TPOT 0.014257678985595703, 0.014844675858815512
TTFT 10.166539192199707, TPOT 0.014454021453857421, 0.01504938801129659
TTFT 10.1655855178833, TPOT 0.014482975006103516, 0.015079379081726074
TTFT 10.165235757827759, TPOT 0.014461278915405273, 0.015056838591893515

flashinfer MHA without chunked prefix:

# context len: 8192+3575
TTFT 1.826446294784546, TPOT 0.011873006820678711, 0.012357463439305624
TTFT 2.1014158725738525, TPOT 0.011897096633911133, 0.012385408083597818
TTFT 2.084930419921875, TPOT 0.011740846633911133, 0.0122224489847819
TTFT 2.0820162296295166, TPOT 0.011892366409301757, 0.012380828460057577
TTFT 2.0788328647613525, TPOT 0.011880369186401367, 0.012368331352869669
TTFT 2.0783514976501465, TPOT 0.011872711181640625, 0.012360225121180216
TTFT 2.0790295600891113, TPOT 0.011880865097045898, 0.012368818124135336
TTFT 2.091287136077881, TPOT 0.011883220672607421, 0.012371132771174112
TTFT 2.081286907196045, TPOT 0.011871509552001953, 0.012358337640762329
TTFT 2.076235055923462, TPOT 0.011887903213500977, 0.01237619916598002

# context len: 6*8192+646
TTFT 35.04837417602539, TPOT 0.01548692860554174, 0.01564573993285497
TTFT 23.982365608215332, TPOT 0.015507449808808946, 0.015667142967383068
TTFT 23.986497402191162, TPOT 0.015482983638330833, 0.01564240703980128
TTFT 23.990475177764893, TPOT 0.015511662689680905, 0.015671399732430775
TTFT 23.985933780670166, TPOT 0.015503268880942432, 0.01566299796104431
TTFT 23.982086896896362, TPOT 0.01549855458367731, 0.015658237040042877
TTFT 23.982810974121094, TPOT 0.015499606574933553, 0.015659173329671223
TTFT 23.983214378356934, TPOT 0.015512476262358046, 0.01567217707633972
TTFT 23.943363189697266, TPOT 0.015505414648154347, 0.015665205816427868
TTFT 23.819607734680176, TPOT 0.015483612866745782, 0.015642789502938587

compared to fa3 backend with chunked prefix

# context len: 8192+3575
TTFT 1.6638422012329102, TPOT 0.01160696029663086, 0.012079834938049316
TTFT 1.691746473312378, TPOT 0.011508455276489258, 0.011980712413787842
TTFT 1.6588833332061768, TPOT 0.011630563735961915, 0.012107312679290771
TTFT 1.659040927886963, TPOT 0.011636505126953125, 0.01211404800415039
TTFT 1.658553123474121, TPOT 0.011646757125854492, 0.012125213940938314
TTFT 1.6618986129760742, TPOT 0.01163797378540039, 0.012115806341171265
TTFT 1.6601159572601318, TPOT 0.011763010025024414, 0.012246022621790567
TTFT 1.693976879119873, TPOT 0.01165050506591797, 0.01212876041730245
TTFT 1.6600775718688965, TPOT 0.011636619567871093, 0.012114395697911581
TTFT 1.6595323085784912, TPOT 0.011659269332885741, 0.012138168017069498

# context len: 6*8192+646
TTFT 11.146169900894165, TPOT 0.014118127822875977, 0.014696756998697916
TTFT 10.232312202453613, TPOT 0.014182100296020508, 0.014766097068786621
TTFT 10.231981039047241, TPOT 0.01421259880065918, 0.014793545007705688
TTFT 10.23215126991272, TPOT 0.014191131591796875, 0.014772375424702963
TTFT 10.229960441589355, TPOT 0.01428633689880371, 0.014871209859848022
TTFT 10.228401184082031, TPOT 0.014174270629882812, 0.014757990837097168
TTFT 10.228224039077759, TPOT 0.01417679786682129, 0.014760355154673258
TTFT 10.17477822303772, TPOT 0.01417057991027832, 0.014754106601079306
TTFT 10.173377513885498, TPOT 0.014154329299926757, 0.01473309596379598
TTFT 10.17001748085022, TPOT 0.014161109924316406, 0.014739016691843668
  1. Flashinfer and fa3 have similar performance for context lengths of 8192+3575 and 6*8192+646.
  2. Flashinfer significantly improves performance in long sequence scenarios after enabling MHA with chunked prefix cache.

profiler detail context len: 6*8192+646
with mha chunked prefix

image

without mha chunked prefix

image

flashinfer mha chunked prefix increase attention time cost from (19807+160) to (4862+965), time cost was reduced by 14140 ms, which is consistent with the reduction of ttft from 23.99 to 10.22.

Checklist

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Summary of Changes

Hello @xu-yfei, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces comprehensive support for Multi-Head Attention (MHA) with a chunked prefix cache within the FlashInfer backend. The primary goal is to significantly enhance performance, particularly for processing very long sequences, by optimizing KV cache management. This involves adding new attention logic, a dedicated runner for chunked operations, and updating the attention dispatch mechanism to leverage these improvements.

Highlights

  • FlashInfer Chunked MHA Support: Implemented the necessary logic to enable Multi-Head Attention (MHA) with a chunked prefix cache when using the FlashInfer attention backend. This allows for more efficient processing of long sequences.
  • Performance Optimization: Benchmarking results demonstrate significant performance improvements (reduced TTFT - Time To First Token) for long context lengths (e.g., 6*8192+646) when the chunked prefix cache is enabled with FlashInfer, making it more competitive with or superior to other backends like FA3 in these scenarios.
  • Dedicated Chunking Runner: Introduced a new FlashInferMhaChunkKVRunner class to encapsulate the specific operations and metadata management required for FlashInfer's chunked KV cache attention, promoting modularity and clarity.
  • Dynamic Attention Dispatch: Updated the model's attention dispatch mechanism to intelligently select the new MHA_CHUNKED_KV method for FlashInfer when processing extended sequences that meet the defined chunking criteria, ensuring the optimized path is used automatically.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request adds support for MHA with chunked prefix cache for the flashinfer backend, which shows significant performance improvements for long sequences. The implementation is well-structured, introducing a new FlashInferMhaChunkKVRunner class to handle the new attention logic. I've identified a critical issue in deepseek_v2.py that could lead to a runtime error due to a potential UnboundLocalError. I've also pointed out a minor maintainability issue regarding a magic number. Once these are addressed, the PR should be in great shape.

Comment thread python/sglang/srt/models/deepseek_v2.py Resolved
@Fridge003

Fridge003 commented Aug 1, 2025 •

Copy link
Copy Markdown
Collaborator

@xu-yfei Thank you for your contribution~

Let me review for this weekend

@Fridge003 Fridge003 self-assigned this Aug 1, 2025
@xu-yfei
xu-yfei force-pushed the xyf/flashinfer_chunk_kv branch from 3a6d514 to d87bc66 Compare August 1, 2025 06:27
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

1 similar comment
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@xu-yfei
xu-yfei requested a review from xiezhq-hermann as a code owner August 1, 2025 16:43
Comment thread python/sglang/srt/models/deepseek_v2.py Resolved
Comment thread python/sglang/srt/models/deepseek_v2.py Resolved
@Fridge003

Copy link
Copy Markdown
Collaborator

@xu-yfei Just added a few comments. Please have a look.

@xu-yfei
xu-yfei force-pushed the xyf/flashinfer_chunk_kv branch from 8931182 to eefa65d Compare August 4, 2025 07:04
@xu-yfei

xu-yfei commented Aug 4, 2025 •

Copy link
Copy Markdown
Contributor Author

@xu-yfei Just added a few comments. Please have a look.
// Can you combine the dispatch logic of flashinfer and fa3?

@Fridge003 The logic of flashinfer and fa3 has been combined:

  1. flashinfer's MHA and MHA_CHUNKED_KV are merged into MHA_CHUNKED_KV, which is consistent with fa3. Moreover, when the prefix length of MHA_CHUNKED_KV is 0, it does not return the value of lse, which is semantically consistent with flashinfer's MHA.
  2. When the prefix length of fa3 is 0, it is not controlled by disable_chunked_prefix_cache, which is semantically consistent with flashinfer.
  3. Support the flashmla backend (the flashinfer backend is actually called during extension), and the page-size restriction has been removed.

@xu-yfei

xu-yfei commented Aug 4, 2025

Copy link
Copy Markdown
Contributor Author

@Fridge003 I would like to ask an additional question: What is the reason that chunk kv is disabled when page size > 1? The page size should only affect the allocation of kvcache, i.e., whether it is continuous blocks of tokens with a size of page-size. It is a special case where kv tokens with page-size=1 are distributed relatively randomly. I deleted the following code, and flashmla chunk kv can run normally.

 # srt/model_executor/model_runner.py
        elif self.page_size > 1:
            logger.info("Disable chunked prefix cache when page size > 1.")
            server_args.disable_chunked_prefix_cache = True

@xu-yfei
xu-yfei force-pushed the xyf/flashinfer_chunk_kv branch from 467c3ba to bf967fb Compare August 4, 2025 13:02
@xu-yfei xu-yfei changed the title Support MHA with chunked prefix cache for flashinfer backend Support MHA with chunked prefix cache for flashinfer/flashmla backend, support page size > 1 Aug 5, 2025
Comment thread python/sglang/srt/models/deepseek_v2.py Resolved
@xu-yfei xu-yfei changed the title Support MHA with chunked prefix cache for flashinfer/flashmla backend, support page size > 1 Support MHA with chunked prefix cache for flashinfer/flashmla backend, support page size > 1 for MHA chunked prefix Aug 15, 2025
@xu-yfei

xu-yfei commented Aug 15, 2025

Copy link
Copy Markdown
Contributor Author

#8593 Is there Page size > 1 support in your PR? I don't see the utilities for kv_indices getting updated. I think with Ragged Kernel for Chunked prefill, calling support for page size > 1 is not relevant because it is a variable sequence length ragged kernel with no paged kv cache. May be helpful to change the name to avoid confusion

OK, currently PR page size>1 is only for mha with chunk prefix cache, the title has been changed.

@xu-yfei

xu-yfei commented Aug 15, 2025

Copy link
Copy Markdown
Contributor Author

@zhyncs This PR has not been reviewed by the code owner for a long time. In the PD scenario, this PR can significantly reduce the time consumption of TTFT.

@fzyzcjy

fzyzcjy commented Aug 16, 2025

Copy link
Copy Markdown
Collaborator

hi, may I know whether it is fp8 or bf16 (or both is supported)?

@xu-yfei

xu-yfei commented Aug 16, 2025 •

Copy link
Copy Markdown
Contributor Author

hi, may I know whether it is fp8 or bf16 (or both is supported)?

Flashinfer MHA supports bfloat16 with normal precision. However, errors occur when using flashinfer MHA with fp8:

/root/.cache/flashinfer/90/generated/batch_prefill_with_kv_cache_dtype_q_e4m3_dtype_kv_e4m3_dtype_o_e4m3_dtype_idx_i32_head_dim_qk_192_head_dim_vo_128_posenc_0_use_swa_False_use_logits_cap_False_f16qk_False_sm90/batch_prefill_fp8_sm90.cu(117): error: static assertion failed with "head_dim_qk and head_dim_vo should be the same"

Therefore, the K and V in MHA will first be converted to bfloat16. But we found that this process leads to a precision drop for long inputs(frames orcale):

  1. Obtain KV latents with dtype fp8 from the KV cache.
  2. Perform matrix multiplication between the fp8 KV latents and kv_b to compute MHA K and V with dtype fp8.
  3. Convert the fp8 MHA K and V to bfloat16 first, then provide them to flashinfer MHA for computation.

@xu-yfei

xu-yfei commented Aug 17, 2025

Copy link
Copy Markdown
Contributor Author

hi, may I know whether it is fp8 or bf16 (or both is supported)?

Flashinfer MHA supports bfloat16 with normal precision. However, errors occur when using flashinfer MHA with fp8:

/root/.cache/flashinfer/90/generated/batch_prefill_with_kv_cache_dtype_q_e4m3_dtype_kv_e4m3_dtype_o_e4m3_dtype_idx_i32_head_dim_qk_192_head_dim_vo_128_posenc_0_use_swa_False_use_logits_cap_False_f16qk_False_sm90/batch_prefill_fp8_sm90.cu(117): error: static assertion failed with "head_dim_qk and head_dim_vo should be the same"

Therefore, the K and V in MHA will first be converted to bfloat16. But we found that this process leads to a precision drop for long inputs(frames orcale):

  1. Obtain KV latents with dtype fp8 from the KV cache.
  2. Perform matrix multiplication between the fp8 KV latents and kv_b to compute MHA K and V with dtype fp8.
  3. Convert the fp8 MHA K and V to bfloat16 first, then provide them to flashinfer MHA for computation.

@fzyzcjy @Fridge003 Correcting the previous conclusion about precision degradation: After rerunning the FP8 KV cache test, both FA3 and FlashInfer show normal accuracy. The dataset used was Frame Oracle with long-text inputs, averaging 15K context length.

Implementation details:

For FA3: Input Q, K, V are in FP8 format, with Q forcibly cast to the FP8 data type of K and V.

For FlashInfer: Input K and V are converted from FP8 to bfloat16 to match Q’s data type.

Performance improvement:
With 44K inputs, FA3’s Time To First Token (TTFT) decreased from 10–11s to approximately 8.5s.

        if self.kv_cache_dtype_str != "auto" and layer.head_dim <= 256:
            if layer.k_scale is not None:
                descale_shape = (forward_batch.batch_size, layer.tp_k_head_num)
                k_descale = layer.k_scale.expand(descale_shape)
                v_descale = layer.v_scale.expand(descale_shape)
            q = q.to(self.kv_cache_dtype)
            o = self.prefill_wrapper_ragged.forward(
                qall,
                k.view(-1, layer.tp_k_head_num, layer.head_dim).to(q.dtype),
                v.view(-1, layer.tp_k_head_num, layer.v_head_dim).to(q.dtype),
                causal=True,
                sm_scale=layer.scaling,
                logits_soft_cap=logits_soft_cap,
            )

@Fridge003

Fridge003 commented Aug 19, 2025 •

Copy link
Copy Markdown
Collaborator

Hi @xu-yfei , is it possible to add some accuracy results for GPQA dataset, for checking long context correctness?
If the results of GPQA before and after this PR can be aligned, then this PR will be ready for merging.

A sample command for running gpqa:

OPENAI_API_KEY=dummy python -m gpt_oss.evals --base-url http://localhost:40010/v1 --model dummy --reasoning-effort medium --eval gpqa --n-threads 1000

@xu-yfei

xu-yfei commented Aug 20, 2025 •

Copy link
Copy Markdown
Contributor Author

Hi @xu-yfei , is it possible to add some accuracy results for GPQA dataset, for checking long context correctness? If the results of GPQA before and after this PR can be aligned, then this PR will be ready for merging.

A sample command for running gpqa:

OPENAI_API_KEY=dummy python -m gpt_oss.evals --base-url http://localhost:40010/v1 --model dummy --reasoning-effort medium --eval gpqa --n-threads 1000

@Fridge003 @zhyncs

export SGL_ENABLE_JIT_DEEPGEMM=1
export TORCHINDUCTOR_CACHE_DIR=/home/admin/inductor_root_cache
export SGLANG_TORCH_PROFILER_DIR=/home/admin/torch_profiler

model_path=/home/models/deepseek-ai__DeepSeek-R1

python3 -m sglang.launch_server --model-path $model_path \
--host 0.0.0.0 --port 8000 --trust-remote-code  \
--enable-cache-report --quantization fp8 --log-level info --max-running-requests 16 \
--mem-fraction-static 0.92 --chunked-prefill-size 8192 --context-length 65535 --chat-template /home/r1.jinja \
--attention-backend flashinfer --page-size 64 \
--tp-size 8 --enable-metrics --cuda-graph-max-bs 16
git clone https://github.com/openai/gpt-oss.git
cd gpt-oss/
export OPENAI_API_KEY=dummy
python -m gpt_oss.evals --base-url http://localhost:8000/v1 --model dummy --reasoning-effort medium --eval gpqa --n-threads 1000

Before PR, 'score': 0.7001262626262627
After PR, 'score': 0.7007575757575758

@xu-yfei

xu-yfei commented Aug 21, 2025 •

Copy link
Copy Markdown
Contributor Author

@Fridge003
We previously found that the ragged interface of flashinfer is prone to generating NANs, which contaminates the subsequent KVCache and further causes precision issues in subsequent requests.In this PR, we also tried conducting bench_serving first and then initiating requests, only to find that the precision was incorrect. There might be two solutions going forward, but both require support from flashinfer:

1. Resolve the issue of NAN outputs in the ragged interface.
2. Support the mha paged interface where HEAD_DIM_QK != HEAD_DIM_VO

@xu-yfei

xu-yfei commented Aug 21, 2025

Copy link
Copy Markdown
Contributor Author

@Fridge003 We previously found that the ragged interface of flashinfer is prone to generating NANs, which contaminates the subsequent KVCache and further causes precision issues in subsequent requests. In this PR, we also tried conducting bench_serving first and then initiating requests, only to find that the precision was incorrect. There might be two solutions going forward, but both require support from flashinfer:

1. Resolve the issue of NAN outputs in the ragged interface. 2. Support the mha paged interface where HEAD_DIM_QK != HEAD_DIM_VO

@Fridge003
Sorry, this is caused by a problem in my newly developed code. I did not find this problem in this PR.

@zhyncs
zhyncs merged commit 9708d35 into sgl-project:main Aug 22, 2025
MahmoudAshraf97 pushed a commit to MahmoudAshraf97/sglang that referenced this pull request Sep 8, 2025
…, support page size > 1 for MHA chunked prefix (sgl-project#8616)

Co-authored-by: xuyongfei.xyf <[email protected]>
0826joyce pushed a commit to 0826joyce/sglang-perf-opt that referenced this pull request May 19, 2026
…, support page size > 1 for MHA chunked prefix (sgl-project#8616)

Co-authored-by: xuyongfei.xyf <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

high priority ready-to-merge The PR is ready to merge after the CI is green.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants