From ab42f41915ec30e498c7c3863fa7b0d5c472f5a2 Mon Sep 17 00:00:00 2001 From: Yongye Zhu Date: Fri, 23 Oct 2026 00:34:41 +0000 Subject: [PATCH 1/7] [MiniMax-M3.1] MiniMax-M3.1 Flash: NVFP4 KV/indexer, MegaMoE, DSpark, ROCm Squash of the MiniMax-M3.1 serving branch, rebased on 5d35ce3934. NVIDIA: - Route NVFP4 routed experts in MXFP8 checkpoints to the CT NVFP4 MoE - NVFP4 KV cache on the MSA sparse attention path, served only by the CUTLASS Q8KV4 kernels (E4M3 query) on SM100/SM103/SM107 - NVFP4 index-K cache via the MSA Q8KV4/Q8KV8 indexers; opt-in decode context parallelism for the NVFP4 indexer at TP4 - Vendor fmha_sm100 from vllm-project/MSA dev 25c1447 - NVFP4 MSA decode past 512 sequences: Q8KV4 limits, bounded indexer and plan memory - Decode metadata before the forward: 13 ops -> 2; in-place indexer I/O, no counter reset, PDL chain for the NVFP4 sparse decode - DeepGEMM NVFP4 MegaMoE on the unified DeepGemmMegaMoEExperts layer; per-token FC1 input scales outside MegaMoE; split staging rows over programs - Fuse small-batch MoE finalize into the all-reduce + Gemma norm + MXFP8 quant - QKV+indexer MXFP8 GEMM with fused epilogue; SM100 fused dense GEMM1 - Fused QK-norm/RoPE/KV insert: persistent row-group kernel - Read aux hidden states after the deferred TP all-reduce - FA4: pass no FP8 descale for a unit per-tensor scale - Keep KV cache zeroing for mixed-precision UniformTypeKVCacheSpecs groups - Clear per-token A4 metadata for NVFP4 W4A16 MoE kernels (Marlin only) - Hand the Q8KV4 prefill a per-device split workspace - Align image preprocessing: long-side resize with detail tiers, fp32 patch embedding - NIXL KV-head re-sharding for per-head-contiguous NVFP4 pages; BLHNC layout for NIXL transfer - SimpleCPUOffload: 1 GiB HugeTLB host buffer + PreferCE batch copies Spec decode: - DSpark for MiniMax-M3.1: draft model, fixes and perf; default the draft to the checkpoint's dspark/ subfolder - Fuse the draft's q/k norm + RoPE and its context-K/V write - FLASHINFER_TS: prims_ts paged decode for non-causal draft blocks - Store the draft tokens' K/V under torch.compile - Markov sampling: one step helper, bias in the Gumbel kernel - DFlash: pad the prepared inputs in wide blocks on every platform ROCm: - Re-quantize the NVFP4 routed experts to MXFP8 (or MXFP4) at load; NVFP4 -> MXFP4 re-quantization and fused shared experts through the online quantization API - Mono decode (one FlyDSL launch per layer): native MXFP8 shared expert, top-16 sort/merge, aux hidden states, indexer CP - NVFP4 KV + NVFP4 indexer on gfx950, decode indexer CP - Tune small-M MXFP8 linears - Sequence-parallel prefill under pure TP (opt-in), with MXFP4 MoE support; TBO/DBO under pure TP; warm the microbatch threads' hipBLASLt handles at init - gfx942: avoid the load-time FP8 MoE quant crash; fall back from the fused QK-norm - Keep the NVFP4 KV-insert helpers CUDA-only so the fused kernel builds on HIP Co-authored-by: Taoyu Zhu Co-authored-by: Hongxia Yang Co-authored-by: qizixi <22851944+zixi-qi@users.noreply.github.com> Co-authored-by: indivats Co-authored-by: andyluo7 <43718156+andyluo7@users.noreply.github.com> Co-authored-by: Thien Tran Co-authored-by: Jee Jee Li Co-authored-by: fxmarty-amd Co-authored-by: Jiejing Zhang <280536569+jiejingzhangamd@users.noreply.github.com> Co-authored-by: Prasun Gera Co-authored-by: Dao Le Co-authored-by: Isotr0py Co-authored-by: Neha Prakriya Co-authored-by: Summer Yang Co-authored-by: Zhewen Li Co-authored-by: Zijing Liu Co-authored-by: xiaozhoupy Co-authored-by: v Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yongye Zhu --- .buildkite/test_areas/kernels.yaml | 24 + .buildkite/test_areas/spec_decode.yaml | 3 + benchmarks/kernels/benchmark_mxfp8_tp4.py | 208 ++ cmake/external_projects/fmha_sm100.cmake | 2 +- ...minimax_m3_qknorm_rope_kv_insert_kernel.cu | 1550 ++++++++- csrc/ops.h | 13 +- csrc/torch_bindings.cpp | 14 +- .../test_speculative_draft_hf_overrides.py | 80 +- tests/distributed/test_custom_all_reduce.py | 146 + .../kernels/attention/minimax_m3_nvfp4_ref.py | 148 + tests/kernels/attention/test_minimax_m3.py | 401 +++ .../test_minimax_m3_index_topk_decode.py | 228 ++ ...st_minimax_m3_msa_cutlass_sparse_decode.py | 445 ++- .../test_minimax_m3_norm_rope_nvfp4_insert.py | 209 ++ .../attention/test_minimax_m3_nvfp4_index.py | 422 +++ ...test_minimax_m3_nvfp4_indexer_decode_cp.py | 129 + .../test_minimax_m3_nvfp4_prefill_flydsl.py | 260 ++ .../test_minimax_m3_nvfp4_sparse_decode.py | 242 ++ tests/kernels/mfma_spinner.py | 64 + tests/kernels/moe/test_deep_gemm_mega_moe.py | 2 +- .../moe/test_minimax_m3_moe_mxfp4_prefill.py | 206 ++ .../moe/test_minimax_m3_moe_prefill.py | 155 + .../moe/test_moe_weight_loading_padded.py | 2 + .../quantization/test_nvfp4_emulation.py | 56 + .../quantization/test_rocm_mxfp8_linear.py | 49 +- ..._fused_minimax_m3_qknorm_rope_kv_insert.py | 433 +++ tests/kernels/test_minimax_m3_amd_ops.py | 155 +- tests/kernels/test_minimax_m3_dspark_draft.py | 442 +++ tests/kernels/test_minimax_m3_sp_coll.py | 193 ++ .../test_minimax_m3_sp_prefill_kernels.py | 97 + .../layers/test_fused_shared_expert.py | 109 +- .../model_loader/test_reload.py | 2 +- tests/models/minimax_m3/__init__.py | 0 .../minimax_m3/test_dense_gemm1_mxfp8.py | 90 + .../minimax_m3/test_dspark_draft_compile.py | 135 + tests/models/minimax_m3/test_mono_host.py | 349 ++ .../test_qkv_index_fused_epilogue.py | 248 ++ .../multimodal/processing/test_minimax_m3.py | 208 +- tests/models/registry.py | 5 + tests/models/test_minimax_m3_mega_moe.py | 295 ++ .../test_qwen3_dflash_mxfp8_context_kv.py | 123 + tests/quantization/test_auto_gptq.py | 2 +- tests/quantization/test_fp8_per_channel.py | 75 + tests/quantization/test_modelopt.py | 75 + tests/quantization/test_online.py | 10 +- .../test_online_shared_expert_fusion.py | 898 ++++- tests/v1/attention/test_attention_backends.py | 73 + tests/v1/attention/test_flashinfer_ts.py | 227 ++ tests/v1/core/test_kv_cache_utils.py | 15 + .../kv_connector/unit/test_nixl_connector.py | 32 +- .../unit/test_nixl_desc_geometry.py | 69 +- tests/v1/sample/test_topk_topp_sampler.py | 21 + .../v1/simple_kv_offload/test_host_buffer.py | 87 + tests/v1/spec_decode/test_dflash2.py | 8 +- .../test_draft_attention_backend_override.py | 33 +- .../test_dspark_sharded_sampling.py | 408 +++ .../test_rejection_sampler_utils.py | 72 + tests/v1/worker/test_dbo_pure_tp.py | 186 ++ .../test_eagle3_aux_hidden_states_pp.py | 61 +- tests/v1/worker/test_gpu_batch_shard.py | 71 + tests/v1/worker/test_gpu_gumbel_sample.py | 30 + tests/v1/worker/test_gpu_input_batch_v2.py | 57 + vllm/_custom_ops.py | 59 +- vllm/config/attention.py | 21 +- vllm/config/parallel.py | 10 + vllm/config/speculative.py | 75 +- vllm/config/vllm.py | 8 +- vllm/cute_utils/__init__.py | 17 +- vllm/cute_utils/cvt.py | 8 +- .../kv_connector/v1/nixl/base_worker.py | 27 +- .../v1/simple_cpu_offload_connector.py | 11 + vllm/distributed/parallel_state.py | 15 + vllm/envs.py | 6 + .../kernels/linear/mxfp8/flashinfer.py | 4 +- .../kernels/linear/mxfp8/rocm_native.py | 51 +- .../layers/attention/attention.py | 7 +- .../layers/fused_allreduce_gemma_rms_norm.py | 6 +- .../model_executor/layers/fused_moe/config.py | 11 +- vllm/model_executor/layers/fused_moe/layer.py | 5 + .../layers/fused_moe/oracle/nvfp4.py | 46 +- .../fused_moe/prepare_finalize/no_dp_ep.py | 4 + .../layers/fused_moe/prepare_megamoe.py | 156 +- .../layers/fused_moe/routed_experts.py | 99 +- vllm/model_executor/layers/fused_moe/utils.py | 30 +- .../layers/quantization/base_config.py | 47 +- .../compressed_tensors_moe_w4a4_nvfp4.py | 37 +- .../layers/quantization/modelopt.py | 56 +- .../layers/quantization/online/base.py | 12 + .../layers/quantization/online/fp8.py | 41 +- .../layers/quantization/online/moe_base.py | 89 +- .../layers/quantization/online/mxfp4.py | 15 +- .../layers/quantization/online/mxfp8.py | 10 +- .../quantization/online/requantization.py | 25 + .../quantization/online/shared_expert.py | 340 ++ .../layers/quantization/quark/quark.py | 17 + .../layers/quantization/quark/quark_moe.py | 5 +- .../layers/quantization/utils/config_utils.py | 199 +- .../layers/quantization/utils/mxfp8_utils.py | 4 +- .../utils/nvfp4_emulation_utils.py | 64 +- .../layers/quantization/utils/quant_utils.py | 11 + vllm/model_executor/model_loader/utils.py | 6 + vllm/model_executor/models/config.py | 27 +- vllm/model_executor/models/qwen3_dflash.py | 96 +- vllm/model_executor/models/qwen3_dspark.py | 8 +- vllm/model_executor/models/registry.py | 4 + vllm/model_executor/warmup/kernel_warmup.py | 11 +- .../warmup/minimax_m3_msa_warmup.py | 75 +- .../common/ops/moe_tail_fusion/__init__.py | 5 + .../common/ops/moe_tail_fusion/primitives.py | 671 ++++ .../nvidia/ops/cute_dsl/all_reduce_mhc.py | 57 +- .../nvidia/ops/cute_dsl/primitives.py | 396 --- .../boundary/publishing_gemm.py | 8 +- .../moe/routed_expert_front_cute.py | 3 +- .../moe/routed_expert_gemm.py | 2 +- ...educe_rmsnorm_reduce_scatter_early_exit.py | 126 +- .../fused_add_multicast_gemm.py | 3 +- .../fused_add_multicast_skinny_gemm.py | 6 +- .../cute_dsl/latent_moe_tail/lamport_copy.py | 2 +- .../cute_dsl/latent_moe_tail/primitives.py | 576 ---- .../specialized_decode/cutedsl/common/host.py | 2 +- .../cutedsl/moe/small_batch/front_tp16.py | 2 +- .../specialized_decode/runtime/prefetch.py | 2 +- vllm/models/minimax_m3/amd/indexer_nvfp4.py | 239 ++ vllm/models/minimax_m3/amd/model.py | 315 +- vllm/models/minimax_m3/amd/mono/__init__.py | 4 + vllm/models/minimax_m3/amd/mono/check.py | 68 + vllm/models/minimax_m3/amd/mono/config.py | 108 + vllm/models/minimax_m3/amd/mono/dispatch.py | 216 ++ vllm/models/minimax_m3/amd/mono/envs.py | 20 + .../minimax_m3/amd/mono/kernels/__init__.py | 3 + .../minimax_m3/amd/mono/kernels/common.py | 418 +++ .../amd/mono/kernels/index_score.py | 471 +++ .../minimax_m3/amd/mono/kernels/post_attn.py | 2963 +++++++++++++++++ .../minimax_m3/amd/mono/kernels/pre_attn.py | 902 +++++ vllm/models/minimax_m3/amd/mono/layout.py | 230 ++ .../models/minimax_m3/amd/mono/peer_buffer.py | 49 + vllm/models/minimax_m3/amd/mono/runner.py | 334 ++ vllm/models/minimax_m3/amd/mono/weights.py | 377 +++ .../models/minimax_m3/amd/ops/flydsl_utils.py | 196 ++ .../minimax_m3/amd/ops/index_cp/__init__.py | 2 + .../minimax_m3/amd/ops/index_cp/host.py | 126 + .../amd/ops/index_topk_decode/__init__.py | 2 + .../amd/ops/index_topk_decode/host.py | 113 + .../ops/index_topk_decode/prefill_kernel.py | 387 +++ .../amd/ops/moe_flydsl_common/__init__.py | 3 + .../amd/ops/moe_flydsl_common/epilogue.py | 72 + .../amd/ops/moe_flydsl_common/launch.py | 32 + .../amd/ops/moe_flydsl_common/loaders.py | 397 +++ .../amd/ops/moe_flydsl_common/reduce_bf16.py | 98 + .../amd/ops/moe_flydsl_common/sort.py | 223 ++ .../amd/ops/moe_flydsl_common/tile_map.py | 91 + .../amd/ops/moe_flydsl_common/utils.py | 34 + .../minimax_m3/amd/ops/moe_mxfp4/__init__.py | 3 + .../amd/ops/moe_mxfp4/gemm1_prefill.py | 1192 +++++++ .../amd/ops/moe_mxfp4/gemm2_prefill.py | 1088 ++++++ .../minimax_m3/amd/ops/moe_mxfp4/prefill.py | 217 ++ .../minimax_m3/amd/ops/moe_mxfp8/__init__.py | 3 + .../amd/ops/moe_mxfp8/gemm1_prefill.py | 822 +++++ .../amd/ops/moe_mxfp8/gemm2_prefill.py | 682 ++++ .../amd/ops/moe_mxfp8/gemm2_prefill_bm256.py | 697 ++++ .../minimax_m3/amd/ops/moe_mxfp8/prefill.py | 228 ++ .../ops/norm_rope_nvfp4_insert/__init__.py | 2 + .../amd/ops/norm_rope_nvfp4_insert/host.py | 91 + .../amd/ops/norm_rope_nvfp4_insert/kernel.py | 581 ++++ .../amd/ops/nvfp4_index_decode/__init__.py | 2 + .../amd/ops/nvfp4_index_decode/host.py | 222 ++ .../amd/ops/nvfp4_index_decode/kernel.py | 564 ++++ .../ops/nvfp4_index_decode/kernel_cp_push.py | 611 ++++ .../amd/ops/nvfp4_index_prefill/__init__.py | 2 + .../amd/ops/nvfp4_index_prefill/host.py | 152 + .../amd/ops/nvfp4_index_prefill/kernel.py | 614 ++++ .../ops/nvfp4_index_prefill/kernel_shared.py | 382 +++ .../amd/ops/nvfp4_prefill/__init__.py | 2 + .../minimax_m3/amd/ops/nvfp4_prefill/host.py | 102 + .../amd/ops/nvfp4_prefill/kernel.py | 507 +++ .../amd/ops/nvfp4_sparse_decode/__init__.py | 2 + .../amd/ops/nvfp4_sparse_decode/host.py | 182 + .../amd/ops/nvfp4_sparse_decode/kernel.py | 576 ++++ .../minimax_m3/amd/ops/sp_coll/__init__.py | 7 + .../models/minimax_m3/amd/ops/sp_coll/host.py | 321 ++ .../minimax_m3/amd/ops/sp_coll/kernel.py | 438 +++ .../minimax_m3/amd/ops/sp_norm_quant.py | 113 + vllm/models/minimax_m3/amd/ops/sp_pack.py | 114 + vllm/models/minimax_m3/amd/sp_prefill.py | 737 ++++ .../minimax_m3/amd/sparse_attention_msa.py | 1 - .../minimax_m3/amd/sparse_attention_nvfp4.py | 170 + vllm/models/minimax_m3/common/dspark.py | 413 +++ vllm/models/minimax_m3/common/indexer.py | 60 +- .../models/minimax_m3/common/mm_preprocess.py | 131 +- .../common/ops/dspark_context_kv.py | 170 + .../minimax_m3/common/sparse_attention.py | 34 +- vllm/models/minimax_m3/common/vision_tower.py | 12 +- .../models/minimax_m3/nvidia/indexer_nvfp4.py | 481 +++ .../nvidia/indexer_nvfp4_decode_cp.py | 513 +++ vllm/models/minimax_m3/nvidia/model.py | 699 +++- .../nvidia/msa_cutlass_sparse_decode.py | 81 +- .../nvidia/ops/dense_gemm1_mxfp8.py | 664 ++++ .../nvidia/ops/finalize_allreduce_norm.py | 781 +++++ .../nvidia/ops/gather_nvfp4_index_k.py | 174 + .../nvidia/ops/qkv_index_fused_epilogue.py | 1101 ++++++ .../minimax_m3/nvidia/sparse_attention_msa.py | 414 ++- .../processors/minimax_m3.py | 315 +- vllm/transformers_utils/repo_utils.py | 24 + vllm/utils/flashinfer.py | 8 + vllm/v1/attention/backends/flash_attn.py | 26 +- vllm/v1/attention/backends/flashinfer_ts.py | 512 +++ vllm/v1/attention/backends/registry.py | 1 + vllm/v1/core/kv_cache_utils.py | 3 + vllm/v1/core/sched/scheduler.py | 19 +- vllm/v1/kv_cache_interface.py | 15 + vllm/v1/sample/ops/topk_topp_sampler.py | 11 +- vllm/v1/sample/ops/topk_topp_triton.py | 39 +- vllm/v1/simple_kv_offload/cuda_mem_ops.py | 33 +- vllm/v1/simple_kv_offload/host_buffer.py | 109 + vllm/v1/simple_kv_offload/worker.py | 72 +- vllm/v1/worker/gpu/dp_utils.py | 17 + vllm/v1/worker/gpu/input_batch.py | 36 + vllm/v1/worker/gpu/model_runner.py | 17 +- vllm/v1/worker/gpu/sample/batch_shard.py | 188 +- vllm/v1/worker/gpu/sample/gumbel.py | 84 +- .../gpu/spec_decode/dflash/speculator.py | 31 +- .../gpu/spec_decode/dspark/speculator.py | 159 +- vllm/v1/worker/gpu/spec_decode/speculator.py | 19 +- vllm/v1/worker/gpu/ubatch_utils.py | 58 +- vllm/v1/worker/gpu_model_runner.py | 22 + vllm/v1/worker/gpu_ubatch_wrapper.py | 39 +- vllm/v1/worker/gpu_worker.py | 4 + vllm/v1/worker/ubatch_utils.py | 10 + vllm/v1/worker/ubatching.py | 75 + vllm/v1/worker/workspace.py | 5 +- 230 files changed, 39417 insertions(+), 2370 deletions(-) create mode 100644 benchmarks/kernels/benchmark_mxfp8_tp4.py create mode 100644 tests/kernels/attention/minimax_m3_nvfp4_ref.py create mode 100644 tests/kernels/attention/test_minimax_m3_index_topk_decode.py create mode 100644 tests/kernels/attention/test_minimax_m3_norm_rope_nvfp4_insert.py create mode 100644 tests/kernels/attention/test_minimax_m3_nvfp4_index.py create mode 100644 tests/kernels/attention/test_minimax_m3_nvfp4_indexer_decode_cp.py create mode 100644 tests/kernels/attention/test_minimax_m3_nvfp4_prefill_flydsl.py create mode 100644 tests/kernels/attention/test_minimax_m3_nvfp4_sparse_decode.py create mode 100644 tests/kernels/mfma_spinner.py create mode 100644 tests/kernels/moe/test_minimax_m3_moe_mxfp4_prefill.py create mode 100644 tests/kernels/moe/test_minimax_m3_moe_prefill.py create mode 100644 tests/kernels/test_minimax_m3_dspark_draft.py create mode 100644 tests/kernels/test_minimax_m3_sp_coll.py create mode 100644 tests/kernels/test_minimax_m3_sp_prefill_kernels.py create mode 100644 tests/models/minimax_m3/__init__.py create mode 100644 tests/models/minimax_m3/test_dense_gemm1_mxfp8.py create mode 100644 tests/models/minimax_m3/test_dspark_draft_compile.py create mode 100644 tests/models/minimax_m3/test_mono_host.py create mode 100644 tests/models/minimax_m3/test_qkv_index_fused_epilogue.py create mode 100644 tests/models/test_minimax_m3_mega_moe.py create mode 100644 tests/models/test_qwen3_dflash_mxfp8_context_kv.py create mode 100644 tests/v1/attention/test_flashinfer_ts.py create mode 100644 tests/v1/simple_kv_offload/test_host_buffer.py create mode 100644 tests/v1/spec_decode/test_dspark_sharded_sampling.py create mode 100644 tests/v1/worker/test_dbo_pure_tp.py create mode 100644 vllm/model_executor/layers/quantization/online/shared_expert.py create mode 100644 vllm/models/common/ops/moe_tail_fusion/__init__.py create mode 100644 vllm/models/common/ops/moe_tail_fusion/primitives.py delete mode 100644 vllm/models/deepseek_v41/nvidia/ops/cute_dsl/primitives.py delete mode 100644 vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/primitives.py create mode 100644 vllm/models/minimax_m3/amd/indexer_nvfp4.py create mode 100644 vllm/models/minimax_m3/amd/mono/__init__.py create mode 100644 vllm/models/minimax_m3/amd/mono/check.py create mode 100644 vllm/models/minimax_m3/amd/mono/config.py create mode 100644 vllm/models/minimax_m3/amd/mono/dispatch.py create mode 100644 vllm/models/minimax_m3/amd/mono/envs.py create mode 100644 vllm/models/minimax_m3/amd/mono/kernels/__init__.py create mode 100644 vllm/models/minimax_m3/amd/mono/kernels/common.py create mode 100644 vllm/models/minimax_m3/amd/mono/kernels/index_score.py create mode 100644 vllm/models/minimax_m3/amd/mono/kernels/post_attn.py create mode 100644 vllm/models/minimax_m3/amd/mono/kernels/pre_attn.py create mode 100644 vllm/models/minimax_m3/amd/mono/layout.py create mode 100644 vllm/models/minimax_m3/amd/mono/peer_buffer.py create mode 100644 vllm/models/minimax_m3/amd/mono/runner.py create mode 100644 vllm/models/minimax_m3/amd/mono/weights.py create mode 100644 vllm/models/minimax_m3/amd/ops/flydsl_utils.py create mode 100644 vllm/models/minimax_m3/amd/ops/index_cp/__init__.py create mode 100644 vllm/models/minimax_m3/amd/ops/index_cp/host.py create mode 100644 vllm/models/minimax_m3/amd/ops/index_topk_decode/__init__.py create mode 100644 vllm/models/minimax_m3/amd/ops/index_topk_decode/host.py create mode 100644 vllm/models/minimax_m3/amd/ops/index_topk_decode/prefill_kernel.py create mode 100644 vllm/models/minimax_m3/amd/ops/moe_flydsl_common/__init__.py create mode 100644 vllm/models/minimax_m3/amd/ops/moe_flydsl_common/epilogue.py create mode 100644 vllm/models/minimax_m3/amd/ops/moe_flydsl_common/launch.py create mode 100644 vllm/models/minimax_m3/amd/ops/moe_flydsl_common/loaders.py create mode 100644 vllm/models/minimax_m3/amd/ops/moe_flydsl_common/reduce_bf16.py create mode 100644 vllm/models/minimax_m3/amd/ops/moe_flydsl_common/sort.py create mode 100644 vllm/models/minimax_m3/amd/ops/moe_flydsl_common/tile_map.py create mode 100644 vllm/models/minimax_m3/amd/ops/moe_flydsl_common/utils.py create mode 100644 vllm/models/minimax_m3/amd/ops/moe_mxfp4/__init__.py create mode 100644 vllm/models/minimax_m3/amd/ops/moe_mxfp4/gemm1_prefill.py create mode 100644 vllm/models/minimax_m3/amd/ops/moe_mxfp4/gemm2_prefill.py create mode 100644 vllm/models/minimax_m3/amd/ops/moe_mxfp4/prefill.py create mode 100644 vllm/models/minimax_m3/amd/ops/moe_mxfp8/__init__.py create mode 100644 vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm1_prefill.py create mode 100644 vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm2_prefill.py create mode 100644 vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm2_prefill_bm256.py create mode 100644 vllm/models/minimax_m3/amd/ops/moe_mxfp8/prefill.py create mode 100644 vllm/models/minimax_m3/amd/ops/norm_rope_nvfp4_insert/__init__.py create mode 100644 vllm/models/minimax_m3/amd/ops/norm_rope_nvfp4_insert/host.py create mode 100644 vllm/models/minimax_m3/amd/ops/norm_rope_nvfp4_insert/kernel.py create mode 100644 vllm/models/minimax_m3/amd/ops/nvfp4_index_decode/__init__.py create mode 100644 vllm/models/minimax_m3/amd/ops/nvfp4_index_decode/host.py create mode 100644 vllm/models/minimax_m3/amd/ops/nvfp4_index_decode/kernel.py create mode 100644 vllm/models/minimax_m3/amd/ops/nvfp4_index_decode/kernel_cp_push.py create mode 100644 vllm/models/minimax_m3/amd/ops/nvfp4_index_prefill/__init__.py create mode 100644 vllm/models/minimax_m3/amd/ops/nvfp4_index_prefill/host.py create mode 100644 vllm/models/minimax_m3/amd/ops/nvfp4_index_prefill/kernel.py create mode 100644 vllm/models/minimax_m3/amd/ops/nvfp4_index_prefill/kernel_shared.py create mode 100644 vllm/models/minimax_m3/amd/ops/nvfp4_prefill/__init__.py create mode 100644 vllm/models/minimax_m3/amd/ops/nvfp4_prefill/host.py create mode 100644 vllm/models/minimax_m3/amd/ops/nvfp4_prefill/kernel.py create mode 100644 vllm/models/minimax_m3/amd/ops/nvfp4_sparse_decode/__init__.py create mode 100644 vllm/models/minimax_m3/amd/ops/nvfp4_sparse_decode/host.py create mode 100644 vllm/models/minimax_m3/amd/ops/nvfp4_sparse_decode/kernel.py create mode 100644 vllm/models/minimax_m3/amd/ops/sp_coll/__init__.py create mode 100644 vllm/models/minimax_m3/amd/ops/sp_coll/host.py create mode 100644 vllm/models/minimax_m3/amd/ops/sp_coll/kernel.py create mode 100644 vllm/models/minimax_m3/amd/ops/sp_norm_quant.py create mode 100644 vllm/models/minimax_m3/amd/ops/sp_pack.py create mode 100644 vllm/models/minimax_m3/amd/sp_prefill.py create mode 100644 vllm/models/minimax_m3/amd/sparse_attention_nvfp4.py create mode 100644 vllm/models/minimax_m3/common/dspark.py create mode 100644 vllm/models/minimax_m3/common/ops/dspark_context_kv.py create mode 100644 vllm/models/minimax_m3/nvidia/indexer_nvfp4.py create mode 100644 vllm/models/minimax_m3/nvidia/indexer_nvfp4_decode_cp.py create mode 100644 vllm/models/minimax_m3/nvidia/ops/dense_gemm1_mxfp8.py create mode 100644 vllm/models/minimax_m3/nvidia/ops/finalize_allreduce_norm.py create mode 100644 vllm/models/minimax_m3/nvidia/ops/gather_nvfp4_index_k.py create mode 100644 vllm/models/minimax_m3/nvidia/ops/qkv_index_fused_epilogue.py create mode 100644 vllm/v1/attention/backends/flashinfer_ts.py create mode 100644 vllm/v1/simple_kv_offload/host_buffer.py diff --git a/.buildkite/test_areas/kernels.yaml b/.buildkite/test_areas/kernels.yaml index 9222612eab12..58c99e076660 100644 --- a/.buildkite/test_areas/kernels.yaml +++ b/.buildkite/test_areas/kernels.yaml @@ -244,6 +244,30 @@ steps: - tests/kernels/ - vllm/platforms/rocm.py +- label: ":nvidia: (B200) MiniMax M3 MegaMoE" + key: minimax-m3-mega-moe-test-b200 + timeout_in_minutes: 20 + device: b200-k8s + source_file_dependencies: + - cmake/external_projects/deepgemm.cmake + - vllm/models/minimax_m3/nvidia/ + - vllm/utils/deep_gemm.py + - tests/models/test_minimax_m3_mega_moe.py + commands: + - pytest -v -s models/test_minimax_m3_mega_moe.py + +- label: ":nvidia: (B200) MiniMax-M3 Model Tests" + key: minimax-m3-model-tests-b200 + timeout_in_minutes: 20 + device: b200-k8s + source_file_dependencies: + - vllm/models/minimax_m3/ + - vllm/cute_utils/ + - vllm/utils/flashinfer.py + - tests/models/minimax_m3/ + commands: + - pytest -v -s models/minimax_m3 + # Catch-all for test files at the tests/kernels root. This job collects # the whole root so new files are wired by default. # Files with dedicated jobs elsewhere in this file are excluded via --ignore diff --git a/.buildkite/test_areas/spec_decode.yaml b/.buildkite/test_areas/spec_decode.yaml index 871ed1f279b8..27fcdab2b439 100644 --- a/.buildkite/test_areas/spec_decode.yaml +++ b/.buildkite/test_areas/spec_decode.yaml @@ -351,8 +351,11 @@ steps: - vllm/v1/spec_decode/ - vllm/v1/worker/gpu/spec_decode/ - tests/v1/e2e/spec_decode/ + - vllm/model_executor/models/qwen3_dflash.py + - tests/models/test_qwen3_dflash_mxfp8_context_kv.py commands: - pytest -v -s v1/e2e/spec_decode/draft_model/ + - pytest -v -s models/test_qwen3_dflash_mxfp8_context_kv.py mirror: amd: label: ":amd: (MI355) Spec Decode Draft Model Nightly" diff --git a/benchmarks/kernels/benchmark_mxfp8_tp4.py b/benchmarks/kernels/benchmark_mxfp8_tp4.py new file mode 100644 index 000000000000..b68b906dd35b --- /dev/null +++ b/benchmarks/kernels/benchmark_mxfp8_tp4.py @@ -0,0 +1,208 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Validate MXFP8 TP4 linears and time HIP graph replay over rotating weights. + +Example (record the baseline and candidate SHAs): + baseline=$(git rev-parse origin/nho_tracking) + git rev-parse "$baseline" HEAD + git show "$baseline":vllm/model_executor/kernels/linear/mxfp8/rocm_native.py \ + > /tmp/baseline_rocm_native.py + .venv/bin/python benchmarks/kernels/benchmark_mxfp8_tp4.py \ + --baseline /tmp/baseline_rocm_native.py + +Reports cold (>400 MiB rotating weights) and warm timings separately. Each timing +is the median of 30 device-event samples; Python wall time is never ranked. +""" + +import argparse +import importlib.util +import json +import math +import statistics +from functools import partial +from pathlib import Path + +import torch + +from vllm.model_executor.kernels.linear.mxfp8 import rocm_native +from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( + dequant_mxfp8_to_bf16, + mxfp8_e4m3_quantize, +) +from vllm.triton_utils import triton + +SHAPES = [ + (m, n, k) + for n, k in [(2560, 6144), (6144, 2048), (1536, 6144), (6144, 768)] + for m in [1, 8, 16] +] + + +def time_graph(calls): + for call in calls: + call() + torch.accelerator.synchronize() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + for _ in range(2): + for call in calls: + call() + for _ in range(5): + graph.replay() + events = [ + (torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)) + for _ in range(30) + ] + for start, end in events: + start.record() + for _ in range(5): + graph.replay() + end.record() + # Bound outstanding HIP graph nodes on short-K cases with many slots. + end.synchronize() + torch.accelerator.synchronize() + return statistics.median( + start.elapsed_time(end) / (10 * len(calls)) for start, end in events + ) + + +def launch(module, xq, xs, w, ws, out, config): + bm, bn, bk, nw, ns = config + m, k = xq.shape + n = w.shape[0] + return module._mxfp8_linear_kernel[(triton.cdiv(m, bm), triton.cdiv(n, bn))]( + xq, + xs, + w, + ws, + out, + m, + n, + k, + *xq.stride(), + *xs.stride(), + *w.stride(), + *ws.stride(), + *out.stride(), + BLOCK_M=bm, + BLOCK_N=bn, + BLOCK_K=bk, + num_warps=nw, + num_stages=ns, + ) + + +def emit(**data): + print(json.dumps(data), flush=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--baseline", type=Path) + parser.add_argument("--device", type=int, default=0) + parser.add_argument("--shape", type=int, choices=range(len(SHAPES))) + parser.add_argument("--tune", action="store_true") + parser.add_argument("--profile", action="store_true") + parser.add_argument("--asm-dir", type=Path) + args = parser.parse_args() + torch.accelerator.set_device_index(args.device) + torch.manual_seed(42) + variants = {"candidate": rocm_native} + if args.baseline: + spec = importlib.util.spec_from_file_location( + "vllm.model_executor.kernels.linear.mxfp8.baseline_rocm_native", + args.baseline, + ) + baseline = importlib.util.module_from_spec(spec) + spec.loader.exec_module(baseline) + variants = {"baseline": baseline, **variants} + emit( + torch=torch.__version__, + triton=triton.__version__, + device=str(torch.cuda.get_device_properties(args.device)), + ) + for index, (m, n, k) in enumerate(SHAPES): + if args.shape is not None and index != args.shape: + continue + x = torch.randn(m, k, device="cuda", dtype=torch.bfloat16) * 0.5 + w, ws = mxfp8_e4m3_quantize( + torch.randn(n, k, device="cuda", dtype=torch.bfloat16) * 0.05 + ) + xq, xs = mxfp8_e4m3_quantize(x) + reference = ( + dequant_mxfp8_to_bf16(xq, xs).float() + @ dequant_mxfp8_to_bf16(w, ws).float().T + ) + out = torch.empty(m, n, device="cuda", dtype=x.dtype) + slots = math.ceil(400 * 1024**2 / (n * k)) + weights = [(w.clone(), ws.clone()) for _ in range(slots)] + calls = {} + for name, module in variants.items(): + configs = [module._select_cfg(m, n, k)] + if args.tune: + configs += [ + (16, 16, 1024, 2, 2), + (16, 16, 1024, 2, 3), + (16, 16, 1024, 2, 4), + (16, 16, 512, 2, 2), + (16, 32, 256, 4, 3), + (16, 16, 256, 2, 3), + (128, 128, 128, 8, 2), + ] + for config in dict.fromkeys(configs): + if k % config[2]: + continue + fn = partial(launch, module, xq, xs, config=config, out=out) + obj = fn(w=w, ws=ws) + rel = ((out.float() - reference).norm() / reference.norm()).item() + snr = -20 * math.log10(rel) if rel else float("inf") + assert rel < 0.005 and snr >= 30, (name, config, rel, snr) + emit( + shape=[m, n, k], + variant=name, + config=config, + rel=rel, + snr_db=snr, + registers=obj.n_regs, + spills=obj.n_spills, + lds=obj.metadata.shared, + ) + if args.asm_dir: + args.asm_dir.mkdir(parents=True, exist_ok=True) + (args.asm_dir / f"{name}-{m}-{n}-{k}-{config}.amdgcn").write_text( + obj.asm["amdgcn"] + ) + if args.profile: + for _ in range(10): + fn(w=w, ws=ws) + torch.accelerator.synchronize() + continue + calls[f"{name}-kernel-{config}"] = [ + partial(fn, w=wi, ws=si) for wi, si in weights + ] + if not args.profile and not args.tune: + wrapper = partial(module._mxfp8_dot_scaled_linear, x) + actual = wrapper(w, ws) + assert ((actual.float() - reference).norm() / reference.norm()) < 0.005 + calls[f"{name}-wrapper"] = [ + partial(wrapper, wi, si) for wi, si in weights + ] + for repeat in range(2): + order = list(calls.items()) + if repeat: + order.reverse() + for name, functions in order: + cold = time_graph(functions) + warm = time_graph([functions[0]] * 32) + emit( + shape=[m, n, k], + variant=name, + repeat=repeat, + cold_ms=cold, + warm_ms=warm, + slots=slots, + ) + + +if __name__ == "__main__": + main() diff --git a/cmake/external_projects/fmha_sm100.cmake b/cmake/external_projects/fmha_sm100.cmake index 6b84b35c9049..2336d66d23dc 100644 --- a/cmake/external_projects/fmha_sm100.cmake +++ b/cmake/external_projects/fmha_sm100.cmake @@ -17,7 +17,7 @@ else() FetchContent_Declare( fmha_sm100 GIT_REPOSITORY https://github.com/vllm-project/MSA.git - GIT_TAG 968061ab16cb14991a5c7d4c0e8eabf531be0dcf + GIT_TAG 25c144700f727b638067e98066a60507081b63ad GIT_PROGRESS TRUE CONFIGURE_COMMAND "" BUILD_COMMAND "" diff --git a/csrc/fused_minimax_m3_qknorm_rope_kv_insert_kernel.cu b/csrc/fused_minimax_m3_qknorm_rope_kv_insert_kernel.cu index 09484daf3315..c09a88610dd5 100644 --- a/csrc/fused_minimax_m3_qknorm_rope_kv_insert_kernel.cu +++ b/csrc/fused_minimax_m3_qknorm_rope_kv_insert_kernel.cu @@ -48,9 +48,11 @@ * ``qkv`` tensor. Caches (bf16) are scatter-written by slot. */ +#include #include #include #include +#include #include "torch_utils.h" @@ -271,11 +273,43 @@ __device__ __forceinline__ void storeElemsFp8( // Match scaled_fp8_quant(q_out): materialize q in scalar_t before applying the // inverse dequantization scale and converting it to E4M3. +#ifndef USE_ROCM +// storeScaledQElemsFp8 with inv_scale = 1, from the packed model-dtype values: +// E4M3 of a scalar_t equals E4M3 of its float, the max takes NaN and values +// below -448 to -448 as storeElemsFp8's fmaxf does, and the cvt saturates the +// top at 448. +template +__device__ __forceinline__ void storeUnitScaleQElemsFp8( + uint8_t* __restrict__ dst, float const (&elems)[kElemsPerLane]) { + using Converter = vllm::_typeConvert; + __nv_fp8x2_storage_t out2[kElemsPerLane / 2]; + #pragma unroll + for (int i = 0; i < kElemsPerLane / 2; i++) { + auto const v = + Converter::convert(make_float2(elems[2 * i], elems[2 * i + 1])); + if constexpr (std::is_same_v) { + out2[i] = __nv_cvt_bfloat16raw2_to_fp8x2( + __hmax2(v, __float2bfloat162_rn(-448.0f)), __NV_SATFINITE, __NV_E4M3); + } else { + out2[i] = __nv_cvt_halfraw2_to_fp8x2( + __hmax2(v, __float2half2_rn(-448.0f)), __NV_SATFINITE, __NV_E4M3); + } + } + *reinterpret_cast(dst) = *reinterpret_cast(out2); +} +#endif + template __device__ __forceinline__ void storeScaledQElemsFp8( uint8_t* __restrict__ dst, float const (&elems)[kElemsPerLane], float const inv_scale) { using Converter = vllm::_typeConvert; +#ifndef USE_ROCM + if (inv_scale == 1.0f) { + storeUnitScaleQElemsFp8(dst, elems); + return; + } +#endif float scaled[kElemsPerLane]; #pragma unroll for (int i = 0; i < kElemsPerLane; i++) { @@ -424,27 +458,14 @@ __device__ __forceinline__ uint16_t clearNegZeroNibbles(uint16_t packed) { return packed & (((packed & 0x7777u) + 0x7777u) | 0x7777u); } -// Quantize one K or V head row of one token into its NVFP4 page, where -// ``scale`` is the dequantization (global) scale. Every lane of the warp must -// call this (the scale-group reductions shuffle). +// The E2M1 codes (low nibble first) of four values x, already rounded to the +// model dtype, of a 16-value group with absolute maximum group_max, and the +// group's E4M3 scale in ``sf_byte``, where ``scale`` is the dequantization +// (global) scale. template -__device__ __forceinline__ void storeNvfp4CacheElems( - uint8_t* __restrict__ page, int const kv, int const head, int const token, - int const block_size, int const laneId, float const (&elems)[kElemsPerLane], - float const scale) { - // Quantize the model-dtype value that the unfused path reads back from qkv. - using Converter = vllm::_typeConvert; - float x[kElemsPerLane]; - float group_max = 0.0f; - #pragma unroll - for (int i = 0; i < kElemsPerLane; i++) { - x[i] = static_cast(Converter::convert(elems[i])); - group_max = fmaxf(group_max, fabsf(x[i])); - } - group_max = fmaxf(group_max, __shfl_xor_sync(FINAL_MASK, group_max, 1, 32)); - group_max = fmaxf(group_max, __shfl_xor_sync(FINAL_MASK, group_max, 2, 32)); - - uint8_t sf_byte; +__device__ __forceinline__ uint16_t +nvfp4EncodeElems(float const (&x)[kElemsPerLane], float const group_max, + float const scale, uint8_t& sf_byte) { float sf_rcp; float q[kElemsPerLane]; // (x / scale) / sf_value, E2M1-encoded below if (scale == 1.0f) { @@ -516,8 +537,49 @@ __device__ __forceinline__ void storeNvfp4CacheElems( for (int i = 0; i < kElemsPerLane; i++) codes |= e2m1Code(q[i]) << (4 * i); packed = static_cast(codes); #endif - packed = clearNegZeroNibbles(packed); + return clearNegZeroNibbles(packed); +} + +// Offset, within a K (kv 0) or V (kv 1) head's scale block, of the E4M3 scale +// of a token's 16-value group: linear for K, the SM100 trtllm-gen 4x4 +// token-quad swizzle for V. +__device__ __forceinline__ int nvfp4ScaleOffset(int const kv, int const token, + int const group) { + if (kv == 0) return token * kNvfp4ScaleBytes + group; + constexpr int kGroupsPerQuad = kNvfp4ScaleBytes / 4; + int const swizzled_t = (token / 4) * 4 + group / kGroupsPerQuad; + int const swizzled_s = (group % kGroupsPerQuad) * 4 + token % 4; + return swizzled_t * kNvfp4ScaleBytes + swizzled_s; +} + +// The E2M1 codes of this lane's four values of a K or V head row, rounded to +// the model dtype, and in ``sf_byte`` its 16-value group's E4M3 scale, where +// ``scale`` is the dequantization (global) scale. Every lane of the warp must +// call this (the scale-group reductions shuffle). +template +__device__ __forceinline__ uint16_t nvfp4QuantizeElems( + float const (&elems)[kElemsPerLane], float const scale, uint8_t& sf_byte) { + // Quantize the model-dtype value that the unfused path reads back from qkv. + using Converter = vllm::_typeConvert; + float x[kElemsPerLane]; + float group_max = 0.0f; + #pragma unroll + for (int i = 0; i < kElemsPerLane; i++) { + x[i] = static_cast(Converter::convert(elems[i])); + group_max = fmaxf(group_max, fabsf(x[i])); + } + group_max = fmaxf(group_max, __shfl_xor_sync(FINAL_MASK, group_max, 1, 32)); + group_max = fmaxf(group_max, __shfl_xor_sync(FINAL_MASK, group_max, 2, 32)); + + return nvfp4EncodeElems(x, group_max, scale, sf_byte); +} +// Store the codes and scale from nvfp4QuantizeElems of lane laneId's four +// values of a token's K (kv 0) or V (kv 1) head row. +__device__ __forceinline__ void nvfp4StoreElems( + uint8_t* __restrict__ page, int const kv, int const head, int const token, + int const block_size, int const laneId, uint16_t const packed, + uint8_t const sf_byte) { uint8_t* const slot = page + static_cast(2 * head + kv) * block_size * (kNvfp4DataBytes + kNvfp4ScaleBytes); @@ -526,19 +588,57 @@ __device__ __forceinline__ void storeNvfp4CacheElems( *reinterpret_cast(data) = packed; if (laneId % kNvfp4LanesPerGroup == 0) { - int const group = laneId / kNvfp4LanesPerGroup; - int offset; - if (kv == 0) { - offset = token * kNvfp4ScaleBytes + group; - } else { - constexpr int kGroupsPerQuad = kNvfp4ScaleBytes / 4; - int const swizzled_t = (token / 4) * 4 + group / kGroupsPerQuad; - int const swizzled_s = (group % kGroupsPerQuad) * 4 + token % 4; - offset = swizzled_t * kNvfp4ScaleBytes + swizzled_s; - } - slot[block_size * kNvfp4DataBytes + offset] = sf_byte; + slot[block_size * kNvfp4DataBytes + + nvfp4ScaleOffset(kv, token, laneId / kNvfp4LanesPerGroup)] = sf_byte; } } + +// nvfp4QuantizeElems for one lane holding a whole 16-value group x (already +// rounded to the model dtype): the group max is order-independent, so this is +// the same codes and scale without the shuffles. Low nibble first. +template +__device__ __forceinline__ uint2 nvfp4QuantizeGroup(float const (&x)[16], + float const scale, + uint8_t& sf_byte) { + float group_max = 0.0f; + #pragma unroll + for (int i = 0; i < 16; i++) group_max = fmaxf(group_max, fabsf(x[i])); + uint32_t codes[4]; + #pragma unroll + for (int k = 0; k < 4; k++) { + float const xk[kElemsPerLane] = {x[4 * k], x[4 * k + 1], x[4 * k + 2], + x[4 * k + 3]}; + codes[k] = nvfp4EncodeElems(xk, group_max, scale, sf_byte); + } + return make_uint2(codes[0] | codes[1] << 16, codes[2] | codes[3] << 16); +} + +// Store group ``group`` (its 8 code bytes and its scale) of a token's K +// (kv 0) or V (kv 1) head row into its NVFP4 page. +__device__ __forceinline__ void nvfp4StoreGroup( + uint8_t* __restrict__ page, int const kv, int const head, int const token, + int const block_size, int const group, uint2 const codes, + uint8_t const sf_byte) { + uint8_t* const slot = page + static_cast(2 * head + kv) * + block_size * + (kNvfp4DataBytes + kNvfp4ScaleBytes); + *reinterpret_cast(slot + token * kNvfp4DataBytes + 8 * group) = codes; + slot[block_size * kNvfp4DataBytes + nvfp4ScaleOffset(kv, token, group)] = + sf_byte; +} + +// Quantize one K or V head row of one token into its NVFP4 page, where +// ``scale`` is the dequantization (global) scale. Every lane of the warp must +// call this (the scale-group reductions shuffle). +template +__device__ __forceinline__ void storeNvfp4CacheElems( + uint8_t* __restrict__ page, int const kv, int const head, int const token, + int const block_size, int const laneId, float const (&elems)[kElemsPerLane], + float const scale) { + uint8_t sf_byte; + uint16_t const packed = nvfp4QuantizeElems(elems, scale, sf_byte); + nvfp4StoreElems(page, kv, head, token, block_size, laneId, packed, sf_byte); +} #endif // USE_ROCM // ──────────────────────────────────────────────────────────────────────────── @@ -553,18 +653,21 @@ __device__ __forceinline__ void storeNvfp4CacheElems( // Slots per token: // Q : nq (always — norm+RoPE) // K : nkv (always — norm+RoPE; +K-cache insert) -// V : nkv only if kInsertKV (V-cache insert; no warps in dense) +// V : nkv only if kInsertKV (V-cache insert) // IQ: niq only if kProcessIndex (norm+RoPE) // IK: 1 only if kProcessIndex (norm+RoPE; +index-cache insert) // cache_t/kv_dt: main attention KV-cache dtype (auto/fp8). out_idx_t/kFp8Idx: // indexer index-K cache + index-Q output dtype (scalar_t or e4m3 byte). +// kNvfp4Idx (implies kFp8Idx): the index-K cache is instead packed NVFP4 pages +// [nb, bs, 72] (bs*64 B E2M1, then bs*8 B linear E4M3 scales, no global scale), +// the layout of the MSA Q8KV4 indexer; index-Q stays e4m3. // kHasIndex means the qkv row is laid out as sparse [q|k|v|index_q|index_k]. // kProcessIndex controls whether this launch actually norms/ropes the index // branch and writes index_q/index_k outputs. Skip-index-topk reuse layers keep // kHasIndex=true but set kProcessIndex=false. template + bool kProcessIndex, bool kFp8Idx, bool kNvfp4Idx> __global__ void fusedMiniMaxM3QNormRopeKVInsertKernel( scalar_t* __restrict__ qkv, // [N, qkv_row] in/out (packs index if sparse) scalar_t* __restrict__ q_out, // [N, nq*128] contiguous, or nullptr @@ -588,6 +691,8 @@ __global__ void fusedMiniMaxM3QNormRopeKVInsertKernel( // NHD/HND layout choice is captured by the head/token strides. int64_t const kv_s_block, int64_t const kv_s_head, int64_t const kv_s_token, int64_t const kv_s_dim, + // NVFP4 index cache only: page stride in bytes. + int64_t const idx_s_block, // NVFP4 main cache only: per-layer K/V dequantization (global) scales. float const* __restrict__ kv_k_scale, float const* __restrict__ kv_v_scale) { @@ -604,8 +709,11 @@ __global__ void fusedMiniMaxM3QNormRopeKVInsertKernel( static_assert(!kProcessIndex || kHasIndex, "index processing requires sparse row layout"); + static_assert(!kNvfp4Idx || (kFp8Idx && kInsertKV), + "NVFP4 index cache requires fp8 index-Q and cache insert"); - // Slot layout (compile-time gated: dense has neither V nor index slots). + // Slot layout (compile-time gated: V slots only when inserting, index + // slots only on the sparse layer). int const v_slots = kInsertKV ? nkv : 0; int const idx_slots = kProcessIndex ? niq + 1 : 0; int const slots_per_token = nq + nkv + v_slots + idx_slots; @@ -743,7 +851,7 @@ __global__ void fusedMiniMaxM3QNormRopeKVInsertKernel( } } - // ── Cache inserts (sparse serving only). ─────────────────────────────── + // ── Cache inserts. ───────────────────────────────────────────────────── if constexpr (kInsertKV) { // Guard (not early-return) so every thread reaches the PDL trigger below. int64_t sm = -1; @@ -754,7 +862,16 @@ __global__ void fusedMiniMaxM3QNormRopeKVInsertKernel( } if (sm >= 0) { // skip padded / unscheduled tokens if (isIK) { - if constexpr (kFp8Idx) { + if constexpr (kNvfp4Idx) { +#ifndef USE_ROCM + // A single-head K side: data [bs, 64] then linear scales [bs, 8]. + storeNvfp4CacheElems( + reinterpret_cast(index_cache) + + (sm / block_size) * idx_s_block, + /*kv=*/0, /*head=*/0, static_cast(sm % block_size), + block_size, laneId, elems, /*scale=*/1.0f); +#endif + } else if constexpr (kFp8Idx) { storeElemsFp8(index_cache + sm * kHeadDim + dim_base, elems); } else { storeElems(index_cache + sm * kHeadDim + dim_base, elems); @@ -779,6 +896,15 @@ __global__ void fusedMiniMaxM3QNormRopeKVInsertKernel( int64_t const off = b * kv_s_block + head * kv_s_head + t * kv_s_token + (kv * kHeadDim + dim_base) * kv_s_dim; + if constexpr (!kHasIndex) { + // Dense layers stand in for reshape_and_cache_flash, which + // quantizes the k already materialized in the model dtype. + using Converter = vllm::_typeConvert; +#pragma unroll + for (int i = 0; i < kElemsPerLane; i++) { + elems[i] = Converter::convert(Converter::convert(elems[i])); + } + } storeCacheElems(kv_cache + off, elems); } } @@ -794,6 +920,754 @@ __global__ void fusedMiniMaxM3QNormRopeKVInsertKernel( #endif } +#ifndef USE_ROCM +// ──────────────────────────────────────────────────────────────────────────── +// Persistent row-group kernel +// ──────────────────────────────────────────────────────────────────────────── +// Writes the same bytes as the kernel above, for every instantiation of it, +// when rotary_dim == 64. A token's work is a group of warps with fixed roles: +// the q heads kQHeads (4 or 8) per warp, then K, V and index_q four heads per +// warp, then index_k. A branch of fewer than four heads, and index_k, takes +// one warp per head in the layout of the kernel above (lane l holds dims +// 4l .. 4l + 3); the others run four-row steps, where lane (g, v) holds dims +// 32c + 4v .. 32c + 4v + 3 (c = 0..3) of row g, the dims lane 8c + v holds +// above, so the stores call the same helpers with that lane id. A CTA runs +// some or all warps of the warp groups of tokens x, x + gridDim.x, ..., and +// each warp copies the qkv rows and cos/sin row of its next tokens into a +// kStages-deep shared-memory ring with cp.async. +namespace rg { + +constexpr int kRows = 4; +constexpr int kChunks = 4; +constexpr int kRotaryDim = 64; +constexpr int kStages = 3; // ring depth: two tokens in flight per warp +// A ring row: 256 B padded to 320 B, so that rows 1 apart start 16 banks apart +// and a 4-row step's 8-byte loads are conflict-free. +constexpr int kRowPitch = kHeadDim * 2 + 64; +constexpr int kCosSinBytes = kRotaryDim * 2; +enum Role : int { kQ = 0, kK, kV, kIQ, kIK }; + +// SM100's packed FP32 instructions where they exist; the same RN results. +__device__ __forceinline__ float2 mul2(float2 const a, float2 const b) { + #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 1000 + return __fmul2_rn(a, b); + #else + return make_float2(__fmul_rn(a.x, b.x), __fmul_rn(a.y, b.y)); + #endif +} + +__device__ __forceinline__ float2 fma2(float2 const a, float2 const b, + float2 const c) { + #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 1000 + return __ffma2_rn(a, b, c); + #else + return make_float2(__fmaf_rn(a.x, b.x, c.x), __fmaf_rn(a.y, b.y, c.y)); + #endif +} + +__device__ __forceinline__ float2 add2(float2 const a, float2 const b) { + #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 1000 + return __fadd2_rn(a, b); + #else + return make_float2(__fadd_rn(a.x, b.x), __fadd_rn(a.y, b.y)); + #endif +} + +// A head row as one lane holds it, paired for packed FP32 math: +// x[k][i] = element i of chunks 2k and 2k + 1. +using Row = float2[2][4]; + +template +__device__ __forceinline__ void loadRow(uint8_t const* row, int const v, + Row& x) { + float e[kChunks][kElemsPerLane]; + #pragma unroll + for (int c = 0; c < kChunks; c++) { + loadElems(reinterpret_cast(row + 64 * c + 8 * v), + e[c]); + } + #pragma unroll + for (int k = 0; k < 2; k++) { + #pragma unroll + for (int i = 0; i < kElemsPerLane; i++) { + x[k][i] = make_float2(e[2 * k][i], e[2 * k + 1][i]); + } + } +} + +__device__ __forceinline__ void chunkElems(Row const& x, int const c, + float (&e)[kElemsPerLane]) { + #pragma unroll + for (int i = 0; i < kElemsPerLane; i++) { + e[i] = c % 2 ? x[c / 2][i].y : x[c / 2][i].x; + } +} + +// normAndRope (Gemma RMSNorm, then NeoX RoPE on dims [0, 64)) with its +// rounding as compiled: an FFMA sum of squares per lane of the one-warp-per-row +// layout (one chunk here), the xor-16/8/4/2/1 tree (16 pairs chunks c and +// c ^ 2, 8 pairs c and c ^ 1), FFMA(sum, 1/128, eps), rsqrtf, x * rms * w, and +// x * cos -/+ RN(partner * sin) as one FFMA. +__device__ __forceinline__ void normRope(Row& x, Row const& w1, float const eps, + float const (&cos4)[4], + float const (&sin4)[4]) { + float2 sq[2]; + #pragma unroll + for (int k = 0; k < 2; k++) { + sq[k] = mul2(x[k][0], x[k][0]); // = FFMA(x, x, 0) + #pragma unroll + for (int i = 1; i < 4; i++) sq[k] = fma2(x[k][i], x[k][i], sq[k]); + } + float2 const xor16 = add2(sq[0], sq[1]); + float sum = __fadd_rn(xor16.x, xor16.y); + sum = __fadd_rn(sum, __shfl_xor_sync(FINAL_MASK, sum, 4, 32)); + sum = __fadd_rn(sum, __shfl_xor_sync(FINAL_MASK, sum, 2, 32)); + sum = __fadd_rn(sum, __shfl_xor_sync(FINAL_MASK, sum, 1, 32)); + float const rms_rcp = + rsqrtf(__fmaf_rn(sum, 1.0f / static_cast(kHeadDim), eps)); + float2 const r2 = make_float2(rms_rcp, rms_rcp); + #pragma unroll + for (int k = 0; k < 2; k++) { + #pragma unroll + for (int i = 0; i < 4; i++) x[k][i] = mul2(mul2(x[k][i], r2), w1[k][i]); + } + // x[0][i] = (x1, x2): dims 4v + i and 32 + 4v + i. + #pragma unroll + for (int i = 0; i < 4; i++) { + float2 const x_sin = mul2(x[0][i], make_float2(sin4[i], sin4[i])); + x[0][i] = make_float2(__fmaf_rn(x[0][i].x, cos4[i], -x_sin.y), + __fmaf_rn(x[0][i].y, cos4[i], x_sin.x)); + } +} + +__device__ __forceinline__ void cpAsync16(uint32_t const dst, void const* src) { + asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(dst), + "l"(src) + : "memory"); +} + +__device__ __forceinline__ void cpAsyncCommit() { + asm volatile("cp.async.commit_group;\n" ::: "memory"); +} + +template +__device__ __forceinline__ void cpAsyncWait() { + asm volatile("cp.async.wait_group %0;\n" ::"n"(kPending) : "memory"); +} + +// Warp roles of a token's warp group: the q heads kQHeads at a time, then K, +// V and index_q four heads at a time, then index_k. +// A branch of fewer than kRows heads (and index_k) takes one warp per head in +// the layout of the kernel above instead of a part-empty four-row step. +struct Roles { + int nq, nkv, niq; + bool kv_one, iq_one; // one warp per head + int q_warps, kv_warps, v_warps, iq_warps, ik_warps; + int warps; // one token's warp group + + __host__ __device__ Roles(int const q_heads, int const nq_, int const nkv_, + int const niq_, bool const insert_kv, + bool const process_index) + : nq(nq_), nkv(nkv_), niq(niq_) { + kv_one = nkv < kRows; + iq_one = niq < kRows; + q_warps = (nq + q_heads - 1) / q_heads; + kv_warps = kv_one ? nkv : (nkv + kRows - 1) / kRows; + v_warps = insert_kv ? kv_warps : 0; + iq_warps = process_index ? (iq_one ? niq : (niq + kRows - 1) / kRows) : 0; + ik_warps = process_index ? 1 : 0; + warps = q_warps + kv_warps + v_warps + iq_warps + ik_warps; + } + + // Shared-memory offset of warp w's ring: the q warps' rings, then the + // others'. + __host__ __device__ int ringOffset(int const w, int const q_ring, + int const side_ring) const { + return min(w, q_warps) * q_ring + max(w - q_warps, 0) * side_ring; + } +}; + +// CTA size limit, for 80 registers per thread. +constexpr int kMaxWarps = 24; + +template +constexpr int stageBytes() { + return kQHeads * kRowPitch + kCosSinBytes; +} + +// What a warp writes besides the caches, fixed per launch so that the stores +// of the other modes are not compiled into the loop: q (kQFp8Unit: only +// q_fp8_out, unit scale; kQFp8: only q_fp8_out; kQAny: decided per store), +// index_q (kIQOut: index_q_out; kIQInPlace: back into qkv; kNone), and the +// in-place k / index_k rewrite (kInPlace or kNone). +enum Out : int { + kNone = 0, + kInPlace, + kQFp8Unit, + kQFp8, + kQAny, + kIQOut, + kIQInPlace +}; + +// One warp's loop over its CTA's tokens: rows [head0, head0 + nrows) of one +// branch, kSteps four-row steps per token. +template +__device__ __forceinline__ void runWarp( + int const head0, int const nrows, int const qkv_head0, uint8_t* const ring, + int const stage_bytes, scalar_t* __restrict__ qkv, + scalar_t* __restrict__ q_out, uint8_t* __restrict__ q_fp8_out, + out_idx_t* __restrict__ index_q_out, scalar_t const* __restrict__ norm_w, + scalar_t const* __restrict__ cos_sin_cache, + int64_t const* __restrict__ positions, + int64_t const* __restrict__ slot_mapping, cache_t* __restrict__ kv_cache, + out_idx_t* __restrict__ index_cache, float const eps, + float const q_fp8_inv_scale, int const num_tokens, int const nq, + int const niq, int const qkv_row, int const block_size, + int64_t const kv_s_block, int64_t const kv_s_head, int64_t const kv_s_token, + int64_t const kv_s_dim, int64_t const idx_s_block, float const kv_scale, + bool const write_qkv) { + constexpr bool kNorm = kRole != kV; + constexpr bool kSlots = + kInsertKV && (kRole == kK || kRole == kV || kRole == kIK); + // kOneRow: a single row in the layout of the kernel above (lane l holds + // dims 4l .. 4l + 3), for branches of one head. + constexpr int kStepRows = kOneRow ? 1 : kRows; + constexpr int kLaneChunks = kOneRow ? 1 : kChunks; + int const lane = threadIdx.x % 32; + int const g = kOneRow ? 0 : lane / 8; + int const v = kOneRow ? lane : lane % 8; + constexpr int kCopies = (kSteps * kStepRows * 16 + 31) / 32; + uint32_t const ring_smem = + static_cast(__cvta_generic_to_shared(ring)); + + // Not produced by the predecessor: loaded before the PDL wait, used after. + uint2 w_raw[kChunks]; + if constexpr (kNorm && !kOneRow) { + #pragma unroll + for (int c = 0; c < kChunks; c++) { + w_raw[c] = __ldg(reinterpret_cast(norm_w + 32 * c + 4 * v)); + } + } + + // PDL: qkv comes from the predecessor (the qkv GEMM). + #if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900) + cudaGridDependencySynchronize(); + #endif + + Row w1; + if constexpr (kNorm && !kOneRow) { + float e[kChunks][kElemsPerLane]; + #pragma unroll + for (int c = 0; c < kChunks; c++) { + loadElems(reinterpret_cast(&w_raw[c]), e[c]); + } + #pragma unroll + for (int k = 0; k < 2; k++) { + #pragma unroll + for (int i = 0; i < kElemsPerLane; i++) { + w1[k][i] = make_float2(1.0f + e[2 * k][i], 1.0f + e[2 * k + 1][i]); + } + } + } + + int const stride = gridDim.x; + int const t0 = blockIdx.x; + int const n = (num_tokens - t0 + stride - 1) / stride; + // Lane j holds the position (slot) of the token of iteration base + j. + auto fetch = [&](int64_t const* src, int const base, int64_t const fill) { + int64_t const t = t0 + static_cast(base + lane) * stride; + return t < num_tokens ? static_cast(__ldg( + reinterpret_cast(src) + t)) + : fill; + }; + int pos_base = 0, slot_base = 0; + int64_t pos_l = 0, slot_l = -1; + if constexpr (kNorm) pos_l = fetch(positions, 0, 0); + if constexpr (kSlots) slot_l = fetch(slot_mapping, 0, -1); + + scalar_t const* const src0 = + qkv + static_cast(t0) * qkv_row + qkv_head0 * kHeadDim; + int64_t const src_step = static_cast(stride) * qkv_row; + auto issue_rows = [&](int const it) { + if (it >= n) return; + scalar_t const* const src = src0 + it * src_step; + uint32_t const stage = ring_smem + (it % kStages) * stage_bytes; + #pragma unroll + for (int k = 0; k < kCopies; k++) { + int const r = lane / 16 + 2 * k; + if (r < nrows && (!kOneRow || lane < 16)) { + cpAsync16(stage + r * kRowPitch + lane % 16 * 16, + src + r * kHeadDim + lane % 16 * 8); + } + } + }; + // The cos/sin row of iteration it, then the commit that closes its group. + auto issue_cos_sin = [&](int const it) { + if constexpr (kNorm) { + if (it < n) { + if (it - pos_base == 32) { + pos_base = it; + pos_l = fetch(positions, pos_base, 0); + } + int64_t const pos = __shfl_sync( + FINAL_MASK, static_cast(pos_l), it - pos_base, 32); + if (lane < kCosSinBytes / 16) { + cpAsync16(ring_smem + (it % kStages) * stage_bytes + + kSteps * kStepRows * kRowPitch + lane * 16, + cos_sin_cache + pos * kRotaryDim + lane * 8); + } + } + } + cpAsyncCommit(); + }; + + // The prologue's rows do not wait for the positions. + #pragma unroll + for (int it = 0; it < kStages - 1; it++) issue_rows(it); + #pragma unroll + for (int it = 0; it < kStages - 1; it++) issue_cos_sin(it); + + // This lane's dims 4v .. 4v + 3 (+ 32c) of row g of the first step, at the + // first token; each iteration advances them by stride tokens. Dims + // 32c + 4v of a row are lane 8c + v's dims in the kernel above. + scalar_t* in_place = qkv + static_cast(t0) * qkv_row + + (qkv_head0 + g) * kHeadDim + 4 * v; + int const head_rows = kRole == kQ ? nq : kRole == kIQ ? niq : 0; + int64_t const out_lane = + (static_cast(t0) * head_rows + head0 + g) * kHeadDim + 4 * v; + int64_t const out_step = static_cast(stride) * head_rows * kHeadDim; + int64_t out = out_lane; + + for (int it = 0; it < n; it++) { + issue_rows(it + kStages - 1); + issue_cos_sin(it + kStages - 1); + cpAsyncWait(); + __syncwarp(); + uint8_t const* const stage = ring + (it % kStages) * stage_bytes; + float cos4[4], sin4[4]; + if constexpr (kNorm) { + scalar_t const* const cs = reinterpret_cast( + stage + kSteps * kStepRows * kRowPitch); + if constexpr (!kOneRow) { + loadElems(cs + 4 * v, cos4); + loadElems(cs + kRotaryDim / 2 + 4 * v, sin4); + } + } + // Slot of the token: block and offset with one 32-bit division (the host + // checks that every slot fits). + int sm = -1; + uint32_t blk = 0, tok = 0; + if constexpr (kSlots) { + if (it - slot_base == 32) { + slot_base = it; + slot_l = fetch(slot_mapping, slot_base, -1); + } + sm = static_cast(__shfl_sync( + FINAL_MASK, static_cast(slot_l), it - slot_base, 32)); + blk = static_cast(sm) / static_cast(block_size); + tok = static_cast(sm) - blk * block_size; + } + + #pragma unroll + for (int step = 0; step < kSteps; step++) { + int const r = step * kStepRows + g; // row of the warp + int const head = head0 + r; + bool const row_ok = r < nrows; + int const so = step * kStepRows * kHeadDim; // step offset, elements + float e[kChunks][kElemsPerLane]; + if constexpr (kOneRow) { + loadElems( + reinterpret_cast(stage + r * kRowPitch) + 4 * v, + e[0]); + if constexpr (kNorm) { + normAndRope( + e[0], lane, eps, norm_w, /*do_rope=*/true, kRotaryDim, + reinterpret_cast(stage + kSteps * kRowPitch), + /*apply_norm=*/true); + } + } else { + Row x; + loadRow(stage + r * kRowPitch, v, x); + if constexpr (kNorm) normRope(x, w1, eps, cos4, sin4); + #pragma unroll + for (int c = 0; c < kChunks; c++) chunkElems(x, c, e[c]); + } + if constexpr (kRole == kQ) { + if (row_ok) { + #pragma unroll + for (int c = 0; c < kLaneChunks; c++) { + if constexpr (kOut == kQFp8Unit) { + storeUnitScaleQElemsFp8(q_fp8_out + out + so + 32 * c, + e[c]); + } else if constexpr (kOut == kQFp8) { + storeScaledQElemsFp8(q_fp8_out + out + so + 32 * c, + e[c], q_fp8_inv_scale); + } else { + if (q_out != nullptr) { + storeElems(q_out + out + so + 32 * c, e[c]); + } else if (q_fp8_out == nullptr && write_qkv) { + storeElems(in_place + so + 32 * c, e[c]); + } + if (q_fp8_out != nullptr) { + storeScaledQElemsFp8(q_fp8_out + out + so + 32 * c, + e[c], q_fp8_inv_scale); + } + } + } + } + } else if constexpr (kRole == kIQ) { + if (row_ok) { + #pragma unroll + for (int c = 0; c < kLaneChunks; c++) { + if constexpr (kOut == kIQOut) { + if constexpr (kFp8Idx) { + storeIndexQElemsFp8( + reinterpret_cast(index_q_out + out + so + 32 * c), + e[c]); + } else { + storeElems(index_q_out + out + so + 32 * c, e[c]); + } + } else if constexpr (kOut == kIQInPlace) { + storeElems(in_place + so + 32 * c, e[c]); + } + } + } + } else if constexpr (kRole == kK || kRole == kIK) { + if constexpr (kOut == kInPlace) { + if (row_ok) { + #pragma unroll + for (int c = 0; c < kLaneChunks; c++) { + storeElems(in_place + so + 32 * c, e[c]); + } + } + } + } + + if constexpr (kInsertKV && kRole == kIK) { + if constexpr (kNvfp4Idx) { + uint8_t* const page = + reinterpret_cast(index_cache) + blk * idx_s_block; + #pragma unroll + for (int c = 0; c < kLaneChunks; c++) { + uint8_t sf; + uint16_t const packed = + nvfp4QuantizeElems(e[c], 1.0f, sf); + if (sm >= 0 && row_ok) { + nvfp4StoreElems(page, /*kv=*/0, /*head=*/0, tok, block_size, + kOneRow ? lane : 8 * c + v, packed, sf); + } + } + } else if (sm >= 0 && row_ok) { + int64_t const off = static_cast(sm) * kHeadDim + 4 * v; + #pragma unroll + for (int c = 0; c < kLaneChunks; c++) { + if constexpr (kFp8Idx) { + storeElemsFp8( + reinterpret_cast(index_cache) + off + 32 * c, e[c]); + } else { + storeElems(index_cache + off + 32 * c, e[c]); + } + } + } + } else if constexpr (kInsertKV && (kRole == kK || kRole == kV)) { + constexpr int kv = kRole == kK ? 0 : 1; + if constexpr (kNvfp4 && !kOneRow) { + // One 16-value scale group per lane, regrouped through the ring + // row: lane (g, v) takes dims 16v .. 16v + 15 of row g. + uint8_t* const row = + ring + (it % kStages) * stage_bytes + r * kRowPitch; + if constexpr (kRole == kK) { + // The k in the model dtype, as the helper would quantize it (V + // rows already hold their model-dtype values). + #pragma unroll + for (int c = 0; c < kChunks; c++) { + storeElems( + reinterpret_cast(row + 64 * c + 8 * v), e[c]); + } + } + __syncwarp(); + float x[16]; + #pragma unroll + for (int k = 0; k < 4; k++) { + float q[kElemsPerLane]; + loadElems( + reinterpret_cast(row + 32 * v + 8 * k), q); + #pragma unroll + for (int i = 0; i < kElemsPerLane; i++) x[4 * k + i] = q[i]; + } + uint8_t sf; + uint2 const codes = nvfp4QuantizeGroup(x, kv_scale, sf); + if (sm >= 0 && row_ok) { + nvfp4StoreGroup( + reinterpret_cast(kv_cache) + blk * kv_s_block, kv, + head, tok, block_size, v, codes, sf); + } + } else if constexpr (kNvfp4) { + uint8_t* const page = + reinterpret_cast(kv_cache) + blk * kv_s_block; + #pragma unroll + for (int c = 0; c < kLaneChunks; c++) { + uint8_t sf; + uint16_t const packed = + nvfp4QuantizeElems(e[c], kv_scale, sf); + if (sm >= 0 && row_ok) { + nvfp4StoreElems(page, kv, head, tok, block_size, + kOneRow ? lane : 8 * c + v, packed, sf); + } + } + } else if (sm >= 0 && row_ok) { + cache_t* const dst = kv_cache + blk * kv_s_block + head * kv_s_head + + tok * kv_s_token + + (kv * kHeadDim + 4 * v) * kv_s_dim; + #pragma unroll + for (int c = 0; c < kLaneChunks; c++) { + if constexpr (!kHasIndex) { + using Converter = vllm::_typeConvert; + #pragma unroll + for (int i = 0; i < kElemsPerLane; i++) { + e[c][i] = Converter::convert(Converter::convert(e[c][i])); + } + } + storeCacheElems(dst + 32 * c * kv_s_dim, + e[c]); + } + } + } + } + in_place += src_step; + out += out_step; + __syncwarp(); + } +} + +template +__global__ void __launch_bounds__(kMaxWarps * 32) fusedMiniMaxM3RowGroupKernel( + scalar_t* __restrict__ qkv, scalar_t* __restrict__ q_out, + uint8_t* __restrict__ q_fp8_out, out_idx_t* __restrict__ index_q_out, + scalar_t const* __restrict__ q_norm_w, + scalar_t const* __restrict__ k_norm_w, + scalar_t const* __restrict__ iq_norm_w, + scalar_t const* __restrict__ ik_norm_w, + scalar_t const* __restrict__ cos_sin_cache, + int64_t const* __restrict__ positions, + int64_t const* __restrict__ slot_mapping, + int64_t const* __restrict__ index_slot_mapping, + cache_t* __restrict__ kv_cache, out_idx_t* __restrict__ index_cache, + float const eps, float const q_fp8_inv_scale, int const rotary_dim, + int const num_tokens, int const nq, int const nkv, int const niq, + int const block_size, int64_t const kv_s_block, int64_t const kv_s_head, + int64_t const kv_s_token, int64_t const kv_s_dim, int64_t const idx_s_block, + float const* __restrict__ kv_k_scale, float const* __restrict__ kv_v_scale, + bool const write_qkv) { + #if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 800) + extern __shared__ __align__(16) uint8_t smem[]; + Roles const roles(kQHeads, nq, nkv, niq, kInsertKV, kProcessIndex); + int const qkv_row = (nq + 2 * nkv + (kHasIndex ? niq + 1 : 0)) * kHeadDim; + // CTA (x, y) runs warps [y * cta_warps, (y + 1) * cta_warps) of the warp + // groups of tokens x, x + gridDim.x, ... + int const cta_warps = blockDim.x / 32; + int w = blockIdx.y * cta_warps + threadIdx.x / 32; + if (w >= roles.warps) return; + constexpr int kQStage = stageBytes(); + constexpr int kSideStage = stageBytes(); + int const q_ring = kStages * kQStage; + int const side_ring = kStages * kSideStage; + uint8_t* const ring_w = + smem + roles.ringOffset(w, q_ring, side_ring) - + roles.ringOffset(blockIdx.y * cta_warps, q_ring, side_ring); + #define RG_ARGS(NORM_W, SLOTS, CACHE_SCALE) \ + qkv, q_out, q_fp8_out, index_q_out, NORM_W, cos_sin_cache, positions, \ + SLOTS, kv_cache, index_cache, eps, q_fp8_inv_scale, num_tokens, nq, \ + niq, qkv_row, block_size, kv_s_block, kv_s_head, kv_s_token, \ + kv_s_dim, idx_s_block, CACHE_SCALE, write_qkv + #define RG_RUN(ROLE, STEPS, OUT) \ + runWarp + #define RG_RUN1(ROLE, OUT) \ + runWarp + if (w < roles.q_warps) { + int const h0 = w * kQHeads; + constexpr int kSteps = kQHeads / kRows; + uint8_t* const ring = ring_w; + int const rows = min(kQHeads, nq - h0); + if (q_out == nullptr && q_fp8_out != nullptr) { + if (q_fp8_inv_scale == 1.0f) { + RG_RUN(kQ, kSteps, kQFp8Unit) + (h0, rows, h0, ring, kQStage, RG_ARGS(q_norm_w, nullptr, 1.0f)); + } else { + RG_RUN(kQ, kSteps, kQFp8) + (h0, rows, h0, ring, kQStage, RG_ARGS(q_norm_w, nullptr, 1.0f)); + } + } else { + RG_RUN(kQ, kSteps, kQAny) + (h0, rows, h0, ring, kQStage, RG_ARGS(q_norm_w, nullptr, 1.0f)); + } + } else { + uint8_t* const ring = ring_w; + w -= roles.q_warps; + if (w < roles.kv_warps) { + int const h0 = roles.kv_one ? w : w * kRows; + float const scale = kNvfp4 ? *kv_k_scale : 1.0f; + int const rows = roles.kv_one ? 1 : min(kRows, nkv - h0); + if (rows == 1) { + if (write_qkv) { + RG_RUN1(kK, kInPlace) + (h0, 1, nq + h0, ring, kSideStage, + RG_ARGS(k_norm_w, slot_mapping, scale)); + } else { + RG_RUN1(kK, kNone) + (h0, 1, nq + h0, ring, kSideStage, + RG_ARGS(k_norm_w, slot_mapping, scale)); + } + } else if (write_qkv) { + RG_RUN(kK, 1, kInPlace) + (h0, rows, nq + h0, ring, kSideStage, + RG_ARGS(k_norm_w, slot_mapping, scale)); + } else { + RG_RUN(kK, 1, kNone) + (h0, rows, nq + h0, ring, kSideStage, + RG_ARGS(k_norm_w, slot_mapping, scale)); + } + } else if ((w -= roles.kv_warps) < roles.v_warps) { + if constexpr (kInsertKV) { + int const h0 = roles.kv_one ? w : w * kRows; + int const rows = roles.kv_one ? 1 : min(kRows, nkv - h0); + float const scale = kNvfp4 ? *kv_v_scale : 1.0f; + if (rows == 1) { + RG_RUN1(kV, kNone) + (h0, 1, nq + nkv + h0, ring, kSideStage, + RG_ARGS(nullptr, slot_mapping, scale)); + } else { + RG_RUN(kV, 1, kNone) + (h0, rows, nq + nkv + h0, ring, kSideStage, + RG_ARGS(nullptr, slot_mapping, scale)); + } + } + } else if ((w -= roles.v_warps) < roles.iq_warps) { + if constexpr (kProcessIndex) { + int const h0 = roles.iq_one ? w : w * kRows; + int const rows = roles.iq_one ? 1 : min(kRows, niq - h0); + int const qh0 = nq + 2 * nkv + h0; + if (rows == 1) { + if (index_q_out != nullptr) { + RG_RUN1(kIQ, kIQOut) + (h0, 1, qh0, ring, kSideStage, RG_ARGS(iq_norm_w, nullptr, 1.0f)); + } else if (write_qkv) { + RG_RUN1(kIQ, kIQInPlace) + (h0, 1, qh0, ring, kSideStage, RG_ARGS(iq_norm_w, nullptr, 1.0f)); + } else { + RG_RUN1(kIQ, kNone) + (h0, 1, qh0, ring, kSideStage, RG_ARGS(iq_norm_w, nullptr, 1.0f)); + } + } else if (index_q_out != nullptr) { + RG_RUN(kIQ, 1, kIQOut) + (h0, rows, qh0, ring, kSideStage, RG_ARGS(iq_norm_w, nullptr, 1.0f)); + } else if (write_qkv) { + RG_RUN(kIQ, 1, kIQInPlace) + (h0, rows, qh0, ring, kSideStage, RG_ARGS(iq_norm_w, nullptr, 1.0f)); + } else { + RG_RUN(kIQ, 1, kNone) + (h0, rows, qh0, ring, kSideStage, RG_ARGS(iq_norm_w, nullptr, 1.0f)); + } + } + } else if constexpr (kProcessIndex) { + if (write_qkv) { + RG_RUN1(kIK, kInPlace) + (0, 1, nq + 2 * nkv + niq, ring, kSideStage, + RG_ARGS(ik_norm_w, index_slot_mapping, 1.0f)); + } else { + RG_RUN1(kIK, kNone) + (0, 1, nq + 2 * nkv + niq, ring, kSideStage, + RG_ARGS(ik_norm_w, index_slot_mapping, 1.0f)); + } + } + } + #undef RG_RUN + #undef RG_RUN1 + #undef RG_ARGS + #if __CUDA_ARCH__ >= 900 + cudaTriggerProgrammaticLaunchCompletion(); + #endif + #endif +} + +// Shared memory of the largest CTA of cta_warps warps. +template +__host__ inline int smemBytes(Roles const& r, int const cta_warps) { + int const q_ring = kStages * stageBytes(); + int const side_ring = kStages * stageBytes(); + int bytes = 0; + for (int w0 = 0; w0 < r.warps; w0 += cta_warps) { + int const w1 = std::min(w0 + cta_warps, r.warps); + bytes = std::max(bytes, r.ringOffset(w1, q_ring, side_ring) - + r.ringOffset(w0, q_ring, side_ring)); + } + return bytes; +} + +// Launch with the grid this instantiation's occupancy allows: the CTAs walk +// the tokens with stride gridDim.x. +template +void launch(cudaLaunchConfig_t config, int const num_tokens, Args... args) { + auto* const kernel = + fusedMiniMaxM3RowGroupKernel; + // Per CTA shape (warps, shared memory), computed once: the resident CTAs + // per SM. + static bool const opted_in = + cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, + get_device_prop()->sharedMemPerBlockOptin) == + cudaSuccess; + static int smem_of[kMaxWarps + 1] = {}; + static int resident_of[kMaxWarps + 1] = {}; + int const warps = config.blockDim.x / 32; + int const smem = static_cast(config.dynamicSmemBytes); + if (smem_of[warps] != smem) { + (void)opted_in; + int n = 0; + cudaOccupancyMaxActiveBlocksPerMultiprocessor(&n, kernel, warps * 32, smem); + resident_of[warps] = n > 0 ? n : 1; + smem_of[warps] = smem; + } + int const ctas_per_token = config.gridDim.y; + config.gridDim.x = std::max( + 1, std::min(num_tokens, get_device_prop()->multiProcessorCount * + resident_of[warps] / ctas_per_token)); + cudaLaunchKernelEx(&config, kernel, args...); +} + +} // namespace rg +#endif // USE_ROCM + +#ifndef USE_ROCM +// q heads per q warp: four (one step, shorter warps) for a launch of at most +// 128 q rows, or while a token has at most 32 q heads and there are few q rows +// per SM; eight otherwise (fewer, longer warps keep more CTAs resident). +inline int rgQHeads(int const num_tokens, int const nq) { + static int const num_sms = get_device_prop()->multiProcessorCount; + int64_t const q_rows = static_cast(num_tokens) * nq; + return q_rows <= 128 || (nq <= 32 && q_rows < 64 * num_sms) ? 4 : 8; +} +// Warps per CTA: a token's whole warp group once there are enough tokens to +// give every SM CTAs; before that, eight, which spreads a token over SMs. +inline int rgCtaWarps(int const num_tokens) { + static int const num_sms = get_device_prop()->multiProcessorCount; + return 2 * num_tokens >= 3 * num_sms ? rg::kMaxWarps : 8; +} +#endif + // ──────────────────────────────────────────────────────────────────────────── // Launch wrapper // ──────────────────────────────────────────────────────────────────────────── @@ -809,9 +1683,10 @@ void launchFusedMiniMaxM3( float const q_fp8_inv_scale, int const rotary_dim, int const num_tokens, int const nq, int const nkv, int const niq, int const block_size, int64_t const kv_s_block, int64_t const kv_s_head, int64_t const kv_s_token, - int64_t const kv_s_dim, bool const has_index, bool const insert_kv, - bool const process_index, bool const fp8_idx, float const* kv_k_scale, - float const* kv_v_scale, cudaStream_t stream) { + int64_t const kv_s_dim, int64_t const idx_s_block, bool const has_index, + bool const insert_kv, bool const process_index, bool const fp8_idx, + bool const nvfp4_idx, float const* kv_k_scale, float const* kv_v_scale, + bool const write_qkv, bool const slots_fit_int32, cudaStream_t stream) { // Index outputs are scalar_t (bf16) or e4m3 bytes (uint8_t); reinterpret the // void* pointers per instantiation in the LAUNCH macro. // Slot count must match the kernel's compile-time gating. @@ -843,73 +1718,436 @@ void launchFusedMiniMaxM3( config.attrs = attrs; config.numAttrs = (sm_version >= 90) ? 1 : 0; - #define LAUNCH(HAS_INDEX, INSERT, PROCESS_INDEX, FP8, OUT_T) \ - cudaLaunchKernelEx( \ - &config, \ - fusedMiniMaxM3QNormRopeKVInsertKernel, \ - qkv, q_out, q_fp8_out, reinterpret_cast(index_q_out), \ - q_norm_w, k_norm_w, iq_norm_w, ik_norm_w, cos_sin_cache, positions, \ + // The row-group kernel: same bytes, for rotary_dim == 64 on SM80+ (cp.async). + int const q_heads = rgQHeads(num_tokens, nq); + rg::Roles const roles(q_heads, nq, nkv, niq, insert_kv, process_index); + auto const rg_smem = [&](int const warps) { + return q_heads == 8 ? rg::smemBytes<8>(roles, warps) + : rg::smemBytes<4>(roles, warps); + }; + int cta_warps = + std::min({roles.warps, rgCtaWarps(num_tokens), rg::kMaxWarps}); + // Eight warps take at most 63 KB; a whole group can exceed the 99 KB per + // block of SM 8.6 / 8.9 / 12.x. + static int const max_block_smem = get_device_prop()->sharedMemPerBlockOptin; + if (rg_smem(cta_warps) > max_block_smem) cta_warps = std::min(roles.warps, 8); + auto const aligned = [](void const* p, uintptr_t const n) { + return reinterpret_cast(p) % n == 0; + }; + bool const row_groups = + sm_version >= 80 && rotary_dim == rg::kRotaryDim && slots_fit_int32 && + aligned(qkv, 16) && aligned(cos_sin_cache, 16) && aligned(q_norm_w, 8) && + aligned(k_norm_w, 8) && aligned(iq_norm_w, 8) && aligned(ik_norm_w, 8); + cudaLaunchConfig_t rg_config = config; + rg_config.blockDim = dim3(cta_warps * 32); + rg_config.gridDim = dim3(1, (roles.warps + cta_warps - 1) / cta_warps); + rg_config.dynamicSmemBytes = rg_smem(cta_warps); + + #define LAUNCH_ARGS(OUT_T) \ + qkv, q_out, q_fp8_out, reinterpret_cast(index_q_out), q_norm_w, \ + k_norm_w, iq_norm_w, ik_norm_w, cos_sin_cache, positions, \ slot_mapping, index_slot_mapping, kv_cache, \ reinterpret_cast(index_cache), eps, q_fp8_inv_scale, \ rotary_dim, num_tokens, nq, nkv, niq, block_size, kv_s_block, \ - kv_s_head, kv_s_token, kv_s_dim, kv_k_scale, kv_v_scale) + kv_s_head, kv_s_token, kv_s_dim, idx_s_block, kv_k_scale, kv_v_scale + #define LAUNCH_RG(QH, HAS_INDEX, INSERT, PROCESS_INDEX, FP8, NVFP4_IDX, \ + OUT_T) \ + rg::launch(rg_config, num_tokens, \ + LAUNCH_ARGS(OUT_T), write_qkv) + #define LAUNCH(HAS_INDEX, INSERT, PROCESS_INDEX, FP8, NVFP4_IDX, OUT_T) \ + do { \ + if (!row_groups) { \ + cudaLaunchKernelEx( \ + &config, \ + fusedMiniMaxM3QNormRopeKVInsertKernel< \ + scalar_t, cache_t, kv_dt, kNvfp4, OUT_T, HAS_INDEX, INSERT, \ + PROCESS_INDEX, FP8, NVFP4_IDX>, \ + LAUNCH_ARGS(OUT_T)); \ + } else if (q_heads == 8) { \ + LAUNCH_RG(8, HAS_INDEX, INSERT, PROCESS_INDEX, FP8, NVFP4_IDX, OUT_T); \ + } else { \ + LAUNCH_RG(4, HAS_INDEX, INSERT, PROCESS_INDEX, FP8, NVFP4_IDX, OUT_T); \ + } \ + } while (0) #else // ROCm: standard kernel launch syntax (no PDL/stream serialization). // clang-format off - #define LAUNCH(HAS_INDEX, INSERT, PROCESS_INDEX, FP8, OUT_T) \ + #define LAUNCH(HAS_INDEX, INSERT, PROCESS_INDEX, FP8, NVFP4_IDX, OUT_T) \ fusedMiniMaxM3QNormRopeKVInsertKernel< \ scalar_t, cache_t, kv_dt, kNvfp4, OUT_T, HAS_INDEX, INSERT, \ - PROCESS_INDEX, FP8><<>>( \ + PROCESS_INDEX, FP8, NVFP4_IDX><<>>( \ qkv, q_out, q_fp8_out, reinterpret_cast(index_q_out), \ q_norm_w, k_norm_w, iq_norm_w, ik_norm_w, cos_sin_cache, positions, \ slot_mapping, index_slot_mapping, kv_cache, \ reinterpret_cast(index_cache), eps, q_fp8_inv_scale, \ rotary_dim, num_tokens, nq, nkv, niq, block_size, kv_s_block, \ - kv_s_head, kv_s_token, kv_s_dim, kv_k_scale, kv_v_scale) + kv_s_head, kv_s_token, kv_s_dim, idx_s_block, kv_k_scale, \ + kv_v_scale) // clang-format on #endif if constexpr (kNvfp4) { // NVFP4 main cache: sparse serving only (the host checks insert_kv). if (!process_index) { - LAUNCH(true, true, false, false, scalar_t); + LAUNCH(true, true, false, false, false, scalar_t); + } else if (nvfp4_idx) { + LAUNCH(true, true, true, true, true, uint8_t); } else if (fp8_idx) { - LAUNCH(true, true, true, true, uint8_t); + LAUNCH(true, true, true, true, false, uint8_t); } else { - LAUNCH(true, true, true, false, scalar_t); + LAUNCH(true, true, true, false, false, scalar_t); } } else if (has_index) { if (!process_index) { if (insert_kv) { - LAUNCH(true, true, false, false, scalar_t); + LAUNCH(true, true, false, false, false, scalar_t); } else { - LAUNCH(true, false, false, false, scalar_t); + LAUNCH(true, false, false, false, false, scalar_t); } } else if (insert_kv) { - if (fp8_idx) { - LAUNCH(true, true, true, true, + if (nvfp4_idx) { + LAUNCH(true, true, true, true, true, + uint8_t); // sparse serving, NVFP4 index-K, fp8 index_q + } else if (fp8_idx) { + LAUNCH(true, true, true, true, false, uint8_t); // sparse serving, fp8 index outputs } else { - LAUNCH(true, true, true, false, scalar_t); // sparse serving, bf16 + LAUNCH(true, true, true, false, false, + scalar_t); // sparse serving, bf16 } } else { if (fp8_idx) { - LAUNCH(true, false, true, true, + LAUNCH(true, false, true, true, false, uint8_t); // sparse profiling, fp8 index_q } else { - LAUNCH(true, false, true, false, scalar_t); // sparse profiling, bf16 + LAUNCH(true, false, true, false, false, + scalar_t); // sparse profiling, bf16 } } + } else if (insert_kv) { + LAUNCH(false, true, false, false, false, scalar_t); // dense, KV insert } else { - // Dense layer: never has an index branch and never inserts here (the - // generic Attention layer owns the KV insert). - LAUNCH(false, false, false, false, scalar_t); + LAUNCH(false, false, false, false, false, scalar_t); // dense } #undef LAUNCH +#undef LAUNCH_RG +#undef LAUNCH_ARGS +} + +#ifndef USE_ROCM +// ──────────────────────────────────────────────────────────────────────────── +// DSpark draft context K/V: every draft layer in one launch (bf16 in). +// ──────────────────────────────────────────────────────────────────────────── +// The draft projects the target's context states to the K/V of all its layers +// with one GEMM, ``all_kv [N, L, 2, nkv, 128]``. blockIdx.z picks the layer, +// blockIdx.y the head, blockIdx.x a run of tokens. Eight lanes own one token; +// lane l holds two 8-dim chunks of K and of V, A = dims [8l, 8l + 8) and +// B = dims [64 + 8l, 64 + 8l + 8), so with rotary_dim == 64 every lane rotates +// its A chunk (partner lane l ^ 4) and no lane idles through the RoPE. K gets +// the layer's Gemma k-norm (rounded to bf16 like the unfused norm) and partial +// NeoX RoPE (fp32 math rounded once, like rotary_embedding); K and V go into +// the token's cache row like reshape_and_cache_flash (fp8: e4m3(bf16(x) * +// (1 / scale)); a unit scale converts the bf16 pairs directly). +// Layer caches are separate allocations of one layout, logical shape +// [nb, nkv, bs, 2*128] with K at [..., :128] and V at [..., 128:]; they are +// addressed as layer 0's cache plus a per-layer element offset (likewise the +// fp8 k/v scales from layer 0's k scale), so the launch is CUDA-graph safe. +constexpr int kCtxLanesPerRow = 8; +constexpr int kCtxElems = 8; // bf16 per 16-byte chunk +constexpr int kCtxHalfVecs = kHeadDim / 2 / kCtxElems; // 8: chunk B offset +constexpr int kCtxBlockSize = 256; +constexpr int kCtxRowsPerBlock = kCtxBlockSize / kCtxLanesPerRow; // 32 + +__device__ __forceinline__ float bf16lo(uint32_t v) { + return __uint_as_float(v << 16); +} +__device__ __forceinline__ float bf16hi(uint32_t v) { + return __uint_as_float(v & 0xffff0000u); +} +__device__ __forceinline__ uint32_t packBf16(float lo, float hi) { + __nv_bfloat162 const r = __floats2bfloat162_rn(lo, hi); + return *reinterpret_cast(&r); +} +// Loads of what the PDL predecessor may still be writing: coherent (an .nc +// load may be hoisted above griddepcontrol.wait). +__device__ __forceinline__ uint4 ldgV4(uint4 const* p) { + uint4 r; + asm volatile("ld.global.v4.u32 {%0, %1, %2, %3}, [%4];" + : "=r"(r.x), "=r"(r.y), "=r"(r.z), "=r"(r.w) + : "l"(p)); + return r; +} +// Low 32 bits of an int64 (positions and slots fit). +__device__ __forceinline__ int ldgLo32(int64_t const* p) { + int r; + asm volatile("ld.global.b32 %0, [%1];" : "=r"(r) : "l"(p)); + return r; +} +// Same approximation as flashinfer's gemma_rmsnorm. +__device__ __forceinline__ float rsqrtApproxFtz(float x) { + float r; + asm("rsqrt.approx.ftz.f32 %0, %1;" : "=f"(r) : "f"(x)); + return r; +} +// e4m3 of four floats, low byte first. +__device__ __forceinline__ uint32_t packE4m3(float a, float b, float c, + float d) { + #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 890 + uint32_t r; + asm("{\n" + " .reg .b16 lo, hi;\n" + " cvt.rn.satfinite.e4m3x2.f32 lo, %2, %1;\n" + " cvt.rn.satfinite.e4m3x2.f32 hi, %4, %3;\n" + " mov.b32 %0, {lo, hi};\n" + "}" + : "=r"(r) + : "f"(a), "f"(b), "f"(c), "f"(d)); + return r; + #else + uint32_t const lo = + __nv_cvt_float2_to_fp8x2(make_float2(a, b), __NV_SATFINITE, __NV_E4M3); + uint32_t const hi = + __nv_cvt_float2_to_fp8x2(make_float2(c, d), __NV_SATFINITE, __NV_E4M3); + return lo | (hi << 16); + #endif +} +// Eight bf16 (4 packed pairs) * inv_scale -> e4m3, low byte first. +__device__ __forceinline__ uint2 bf16x8ToE4m3(uint4 const p, + float const inv_scale) { + uint32_t const w[4] = {p.x, p.y, p.z, p.w}; + uint32_t r[2]; + #pragma unroll + for (int i = 0; i < 2; i++) { + r[i] = packE4m3(bf16lo(w[2 * i]) * inv_scale, bf16hi(w[2 * i]) * inv_scale, + bf16lo(w[2 * i + 1]) * inv_scale, + bf16hi(w[2 * i + 1]) * inv_scale); + } + return make_uint2(r[0], r[1]); +} + #if (defined(__CUDA_ARCH_FAMILY_SPECIFIC__) && \ + __CUDA_ARCH_FAMILY_SPECIFIC__ >= 1000) || \ + (defined(__CUDA_ARCH_SPECIFIC__) && __CUDA_ARCH_SPECIFIC__ >= 1000) + #define VLLM_CTX_KV_BF16X2_TO_E4M3X2 + #endif +// Eight bf16 -> e4m3 with a unit scale (exact); one convert per pair where +// the arch converts bf16x2 -> e4m3x2. +__device__ __forceinline__ uint2 bf16x8ToE4m3(uint4 const p) { + #ifdef VLLM_CTX_KV_BF16X2_TO_E4M3X2 + uint32_t r[2]; + uint32_t const w[4] = {p.x, p.y, p.z, p.w}; + #pragma unroll + for (int i = 0; i < 2; i++) { + asm("{\n" + " .reg .b16 lo, hi;\n" + " cvt.rn.satfinite.e4m3x2.bf16x2 lo, %1;\n" + " cvt.rn.satfinite.e4m3x2.bf16x2 hi, %2;\n" + " mov.b32 %0, {lo, hi};\n" + "}" + : "=r"(r[i]) + : "r"(w[2 * i]), "r"(w[2 * i + 1])); + } + return make_uint2(r[0], r[1]); + #else + return bf16x8ToE4m3(p, 1.0f); + #endif } +template +__global__ void __launch_bounds__(kCtxBlockSize) + fusedMiniMaxM3DSparkContextKVKernel( + uint4 const* __restrict__ all_kv, // bf16 [N, L, 2, nkv, 128] + uint4 const* __restrict__ k_norm_w, // bf16 [L, 128] + uint4 const* __restrict__ cos_sin_cache, // bf16 [max_pos, rot] + int64_t const* __restrict__ positions, // [N] + int64_t const* __restrict__ slot_mapping, // [N], < 0: no write + uint8_t* __restrict__ kv_cache, // layer 0's cache, bytes + int64_t const* __restrict__ cache_offsets, // [L] elements from it + float const* __restrict__ scales, // layer 0's k scale + int64_t const* __restrict__ scale_offsets, // [2, L] k, v; floats + float const eps, int const rotary_dim, int const num_tokens, + int const num_layers, int const block_shift, int const s_token, + int const s_layer, int const s_side, int const s_head, + int const kv_s_block, int const kv_s_head, int const kv_s_token) { + // Strides are in 16-byte (8 x bf16) units for all_kv / cos_sin, elements + // for the cache. + constexpr int kElemBytes = kFp8 ? 1 : 2; + int const row0 = blockIdx.x * kCtxRowsPerBlock; + // Warps with no token exit; the others run their tail rows too (the + // shuffles need every lane) and skip the store. + if (row0 + threadIdx.x / 32 * (32 / kCtxLanesPerRow) >= num_tokens) return; + int const head = blockIdx.y; + int const layer = blockIdx.z; + int const lane = threadIdx.x % kCtxLanesPerRow; + int const dim0 = lane * kCtxElems; // chunk A; chunk B is 64 dims later + int const t = row0 + threadIdx.x / kCtxLanesPerRow; + + int const half = rotary_dim / 2; + bool const in_rope = dim0 < rotary_dim; + bool const first_half = dim0 < half; + int const cs_vec = + in_rope ? (first_half ? dim0 : dim0 - half) / kCtxElems : 0; + int const lane_xor = half / kCtxElems; + int const rot_vecs = rotary_dim / kCtxElems; + // x * cos - partner * sin in the first half, + in the second. + uint32_t const sin_sign = first_half ? 0x80008000u : 0u; + + uint8_t* const cache = + kv_cache + (cache_offsets[layer] + head * kv_s_head + dim0) * kElemBytes; + float k_scale = 1.0f, v_scale = 1.0f; + if constexpr (kFp8) { + int64_t const k_off = scale_offsets[layer]; + int64_t const v_off = scale_offsets[num_layers + layer]; + k_scale = scales[k_off]; + v_scale = scales[v_off]; + } + float g[2][kCtxElems]; // 1 + w, chunks A and B + #pragma unroll + for (int c = 0; c < 2; c++) { + uint4 const w = + k_norm_w[layer * (kHeadDim / kCtxElems) + c * kCtxHalfVecs + lane]; + uint32_t const wp[4] = {w.x, w.y, w.z, w.w}; + #pragma unroll + for (int i = 0; i < 4; i++) { + g[c][2 * i] = 1.0f + bf16lo(wp[i]); + g[c][2 * i + 1] = 1.0f + bf16hi(wp[i]); + } + } + + #if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900) + cudaGridDependencySynchronize(); + #endif + + bool const valid = t < num_tokens; + int const ts = valid ? t : 0; + int const pos = ldgLo32(positions + ts); + int const slot = valid ? ldgLo32(slot_mapping + ts) : -1; + uint4 const* const src = + all_kv + ts * s_token + layer * s_layer + head * s_head + lane; + uint4 kr[2], vr[2]; + #pragma unroll + for (int c = 0; c < 2; c++) { + kr[c] = ldgV4(src + c * kCtxHalfVecs); + vr[c] = ldgV4(src + s_side + c * kCtxHalfVecs); + } + // Lanes past the rotary dims load (and later discard) a valid row too. + uint4 const* const cs = cos_sin_cache + pos * rot_vecs + cs_vec; + uint4 const cr = cs[0]; + uint4 const sr = cs[lane_xor]; + + bool const store = slot >= 0; + // Power-of-two block size: shift and mask, not division. + uint8_t* const dst = + cache + (static_cast(slot >> block_shift) * kv_s_block + + (slot & ((1 << block_shift) - 1)) * kv_s_token) * + kElemBytes; + constexpr int kChunkB = kHeadDim / 2 * kElemBytes; + constexpr int kV = kHeadDim * kElemBytes; + float const k_inv = __fdividef(1.0f, k_scale); + float const v_inv = __fdividef(1.0f, v_scale); + #ifdef VLLM_CTX_KV_BF16X2_TO_E4M3X2 + bool const unit_scale = k_scale == 1.0f && v_scale == 1.0f; + #else + constexpr bool unit_scale = false; + #endif + // Eight bf16 -> the cache row at byte offset `off`. + auto put = [&](int const off, uint4 const x, float const inv_scale) { + if constexpr (kFp8) { + uint2 const y = unit_scale ? bf16x8ToE4m3(x) : bf16x8ToE4m3(x, inv_scale); + if (store) *reinterpret_cast(dst + off) = y; + } else { + if (store) *reinterpret_cast(dst + off) = x; + } + }; + + // V first, so its registers free up before the K math. + #pragma unroll + for (int c = 0; c < 2; c++) put(kV + c * kChunkB, vr[c], v_inv); + + // K: Gemma RMSNorm over the 8 lanes of the row. + float x[2][kCtxElems]; + float sumsq = 0.0f; + #pragma unroll + for (int c = 0; c < 2; c++) { + uint32_t const kp[4] = {kr[c].x, kr[c].y, kr[c].z, kr[c].w}; + #pragma unroll + for (int j = 0; j < 4; j++) { + x[c][2 * j] = bf16lo(kp[j]); + x[c][2 * j + 1] = bf16hi(kp[j]); + sumsq = fmaf(x[c][2 * j], x[c][2 * j], sumsq); + sumsq = fmaf(x[c][2 * j + 1], x[c][2 * j + 1], sumsq); + } + } + #pragma unroll + for (int mask = kCtxLanesPerRow / 2; mask > 0; mask >>= 1) { + sumsq += __shfl_xor_sync(FINAL_MASK, sumsq, mask, 32); + } + float const rr = rsqrtApproxFtz(sumsq * (1.0f / kHeadDim) + eps); + // bf16-rounded norm output, packed. + uint32_t kn[2][4]; + #pragma unroll + for (int c = 0; c < 2; c++) { + #pragma unroll + for (int j = 0; j < 4; j++) { + kn[c][j] = packBf16(x[c][2 * j] * rr * g[c][2 * j], + x[c][2 * j + 1] * rr * g[c][2 * j + 1]); + } + } + // RoPE on chunk A; the partner chunk is half / 8 lanes away. + uint32_t const cp[4] = {cr.x, cr.y, cr.z, cr.w}; + uint32_t const sp[4] = {sr.x ^ sin_sign, sr.y ^ sin_sign, sr.z ^ sin_sign, + sr.w ^ sin_sign}; + #pragma unroll + for (int j = 0; j < 4; j++) { + uint32_t const pn = __shfl_xor_sync(FINAL_MASK, kn[0][j], lane_xor, 32); + uint32_t const rot = + packBf16(__fmaf_rn(bf16lo(kn[0][j]), bf16lo(cp[j]), + __fmul_rn(bf16lo(pn), bf16lo(sp[j]))), + __fmaf_rn(bf16hi(kn[0][j]), bf16hi(cp[j]), + __fmul_rn(bf16hi(pn), bf16hi(sp[j])))); + kn[0][j] = in_rope ? rot : kn[0][j]; + } + #pragma unroll + for (int c = 0; c < 2; c++) { + put(c * kChunkB, make_uint4(kn[c][0], kn[c][1], kn[c][2], kn[c][3]), k_inv); + } + + #if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900) + cudaTriggerProgrammaticLaunchCompletion(); + #endif +} + +template +void launchFusedMiniMaxM3DSparkContextKV( + uint4 const* all_kv, uint4 const* k_norm_w, uint4 const* cos_sin_cache, + int64_t const* positions, int64_t const* slot_mapping, uint8_t* kv_cache, + int64_t const* cache_offsets, float const* scales, + int64_t const* scale_offsets, float const eps, int const rotary_dim, + int const num_tokens, int const num_layers, int const nkv, + int const block_shift, int const s_token, int const s_layer, + int const s_side, int const s_head, int const kv_s_block, + int const kv_s_head, int const kv_s_token, cudaStream_t stream) { + if (num_tokens == 0) return; + static int const sm_version = getSMVersion(); + cudaLaunchConfig_t config; + config.gridDim = dim3((num_tokens + kCtxRowsPerBlock - 1) / kCtxRowsPerBlock, + nkv, num_layers); + config.blockDim = dim3(kCtxBlockSize); + config.dynamicSmemBytes = 0; + config.stream = stream; + cudaLaunchAttribute attrs[1]; + attrs[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attrs[0].val.programmaticStreamSerializationAllowed = 1; + config.attrs = attrs; + config.numAttrs = (sm_version >= 90) ? 1 : 0; + cudaLaunchKernelEx(&config, fusedMiniMaxM3DSparkContextKVKernel, all_kv, + k_norm_w, cos_sin_cache, positions, slot_mapping, kv_cache, + cache_offsets, scales, scale_offsets, eps, rotary_dim, + num_tokens, num_layers, block_shift, s_token, s_layer, + s_side, s_head, kv_s_block, kv_s_head, kv_s_token); +} +#endif // !USE_ROCM + } // namespace minimax_m3_fused_ops } // namespace vllm @@ -948,8 +2186,9 @@ void launchFusedMiniMaxM3( static_cast(eps), 1.0f / static_cast(q_fp8_scale), \ static_cast(rotary_dim), num_tokens, nq, nkv, niq, \ static_cast(block_size), kv_s_block, kv_s_head, kv_s_token, \ - kv_s_dim, has_index, insert_kv, process_index, fp8_idx, kv_k_scale_ptr, \ - kv_v_scale_ptr, stream) + kv_s_dim, idx_s_block, has_index, insert_kv, process_index, fp8_idx, \ + nvfp4_idx, kv_k_scale_ptr, kv_v_scale_ptr, write_qkv, slots_fit_int32, \ + stream) #define CALL_FUSED_MINIMAX_M3(_RAW_T, CACHE_T, KV_DTYPE) \ CALL_FUSED_MINIMAX_M3_IMPL(CACHE_T, KV_DTYPE, false) // clang-format on @@ -980,7 +2219,7 @@ void fused_minimax_m3_qknorm_rope_kv_insert( q_fp8_out, // [N, nq*128] contiguous E4M3 double q_fp8_scale, std::optional kv_k_scale, // [] f32, NVFP4 only - std::optional kv_v_scale) { + std::optional kv_v_scale, bool write_qkv) { STD_TORCH_CHECK(qkv.is_cuda() && qkv.is_contiguous(), "qkv must be contiguous CUDA"); STD_TORCH_CHECK( @@ -1032,11 +2271,8 @@ void fused_minimax_m3_qknorm_rope_kv_insert( " + num_index_heads + 1) * 128 for sparse, " "(num_heads + 2*num_kv_heads) * 128 for dense"); - // Only the sparse layer inserts here (dense lets the generic Attention layer - // own the KV write); there is no dense+insert kernel instantiation. - STD_TORCH_CHECK( - !insert_kv || has_index, - "insert mode (kv_cache) requires the index branch (sparse layer)"); + STD_TORCH_CHECK(!nvfp4_kv || has_index, + "nvfp4 kv_cache requires the index branch (sparse layer)"); STD_TORCH_CHECK(has_index || !skip_index_branch, "skip_index_branch requires sparse qkv rows"); if (process_index) { @@ -1084,14 +2320,18 @@ void fused_minimax_m3_qknorm_rope_kv_insert( kv_cache->scalar_type() == torch::headeronly::ScalarType::Byte, "fp8 kv_cache must use uint8 storage"); } - // Indexer index-K cache: independent dtype -- qkv dtype or fp8 e4m3. + // Indexer index-K cache: independent dtype -- qkv dtype, fp8 e4m3, or + // uint8 packed NVFP4 pages. if (process_index) { STD_TORCH_CHECK( index_cache.has_value() && (index_cache->scalar_type() == qkv.scalar_type() || index_cache->scalar_type() == - torch::headeronly::ScalarType::Float8_e4m3fn), - "insert mode requires index_cache matching qkv dtype or fp8 e4m3"); + torch::headeronly::ScalarType::Float8_e4m3fn || + index_cache->scalar_type() == + torch::headeronly::ScalarType::Byte), + "insert mode requires index_cache matching qkv dtype, fp8 e4m3, " + "or uint8 (nvfp4)"); } STD_TORCH_CHECK(kv_cache->dim() == 4 && kv_cache->stride(3) == 1, "kv_cache must be [nb,nkv,bs,2*head_dim] with contiguous " @@ -1150,6 +2390,9 @@ void fused_minimax_m3_qknorm_rope_kv_insert( STD_TORCH_CHECK(std::isfinite(q_fp8_scale) && q_fp8_scale > 0.0, "q_fp8_scale must be finite and positive"); } + STD_TORCH_CHECK(write_qkv || (!q_out.has_value() && q_fp8_out.has_value()), + "write_qkv=False writes q only to q_fp8_out: pass q_fp8_out " + "and no q_out"); if (index_q_out.has_value()) { STD_TORCH_CHECK(process_index, "index_q_out requires index branch processing"); @@ -1166,16 +2409,36 @@ void fused_minimax_m3_qknorm_rope_kv_insert( } // fp8 index path: the index-K cache and index-Q outputs are e4m3 bytes while - // q/k/v + q_out stay qkv dtype. Both index outputs must agree. + // q/k/v + q_out stay qkv dtype. Both index outputs must agree. The NVFP4 + // index path keeps e4m3 index-Q and stores index-K as packed NVFP4 pages. auto const kFp8 = torch::headeronly::ScalarType::Float8_e4m3fn; + bool const nvfp4_idx = + process_index && insert_kv && + index_cache->scalar_type() == torch::headeronly::ScalarType::Byte; bool const fp8_idx = process_index && - ((index_cache.has_value() && index_cache->scalar_type() == kFp8) || + (nvfp4_idx || + (index_cache.has_value() && index_cache->scalar_type() == kFp8) || (index_q_out.has_value() && index_q_out->scalar_type() == kFp8)); - if (fp8_idx) { + int64_t idx_s_block = 0; + if (nvfp4_idx) { +#ifdef USE_ROCM + STD_TORCH_CHECK(false, "nvfp4 index_cache is not supported on ROCm"); +#endif + int64_t const page_width = kHeadDim / 2 + kHeadDim / 16; STD_TORCH_CHECK( - !index_cache.has_value() || index_cache->scalar_type() == kFp8, - "fp8 index path: index_cache must be fp8 e4m3"); + index_cache->dim() == 3 && index_cache->size(1) == block_size && + index_cache->size(2) == page_width && index_cache->stride(2) == 1 && + index_cache->stride(1) == page_width && + index_cache->stride(0) >= block_size * page_width, + "nvfp4 index_cache must be [nb, block_size, 72] uint8 with " + "contiguous pages"); + idx_s_block = index_cache->stride(0); + } + if (fp8_idx) { + STD_TORCH_CHECK(!index_cache.has_value() || nvfp4_idx || + index_cache->scalar_type() == kFp8, + "fp8 index path: index_cache must be fp8 e4m3"); STD_TORCH_CHECK( !index_q_out.has_value() || index_q_out->scalar_type() == kFp8, "fp8 index path: index_q_out must be fp8 e4m3"); @@ -1188,6 +2451,12 @@ void fused_minimax_m3_qknorm_rope_kv_insert( float const* kv_v_scale_ptr = nvfp4_kv ? kv_v_scale->const_data_ptr() : nullptr; + // The row-group kernel indexes cache slots in 32 bits. + bool const slots_fit_int32 = + !insert_kv || + (kv_cache->size(0) * block_size <= INT32_MAX && + (!process_index || index_cache->size(0) * block_size <= INT32_MAX)); + const torch::stable::accelerator::DeviceGuard device_guard( qkv.get_device_index()); auto stream = get_current_cuda_stream(qkv.get_device_index()); @@ -1216,3 +2485,122 @@ void fused_minimax_m3_qknorm_rope_kv_insert( #undef CALL_FUSED_MINIMAX_M3 #undef CALL_FUSED_MINIMAX_M3_IMPL + +// ──────────────────────────────────────────────────────────────────────────── +// DSpark context K/V torch op +// ──────────────────────────────────────────────────────────────────────────── +void fused_minimax_m3_dspark_context_kv( + torch::stable::Tensor const& all_kv, // bf16 [N, L, 2, nkv, 128] + torch::stable::Tensor const& k_norm_weight, // bf16 [L, 128] + torch::stable::Tensor const& cos_sin_cache, // bf16 [max_pos, rotary_dim] + torch::stable::Tensor const& positions, // [N] i64 + torch::stable::Tensor const& slot_mapping, // [N] i64 + torch::stable::Tensor& kv_cache, // layer 0's [nb, nkv, bs, 2*128] + torch::stable::Tensor const& cache_offsets, // [L] i64, elements + torch::stable::Tensor const& k_scale, // layer 0's [] f32 k scale + torch::stable::Tensor const& scale_offsets, // [2, L] i64, floats + int64_t rotary_dim, double eps, const std::string& kv_cache_dtype) { +#ifdef USE_ROCM + STD_TORCH_CHECK(false, "fused_minimax_m3_dspark_context_kv is CUDA-only"); +#else + using torch::headeronly::ScalarType; + int const kHeadDim = vllm::minimax_m3_fused_ops::kHeadDim; + STD_TORCH_CHECK(all_kv.is_cuda() && all_kv.dim() == 5 && + all_kv.size(2) == 2 && all_kv.size(4) == kHeadDim && + all_kv.stride(4) == 1 && + all_kv.scalar_type() == ScalarType::BFloat16, + "all_kv must be bf16 CUDA [N, L, 2, nkv, 128], last dim " + "contiguous"); + for (int d = 0; d < 4; d++) { + STD_TORCH_CHECK(all_kv.stride(d) % 8 == 0, + "all_kv strides must be multiples of 8 elements"); + } + STD_TORCH_CHECK(reinterpret_cast(all_kv.data_ptr()) % 16 == 0, + "all_kv must be 16-byte aligned"); + int const num_tokens = static_cast(all_kv.size(0)); + int const num_layers = static_cast(all_kv.size(1)); + int const nkv = static_cast(all_kv.size(3)); + STD_TORCH_CHECK(k_norm_weight.is_contiguous() && + k_norm_weight.scalar_type() == ScalarType::BFloat16 && + k_norm_weight.numel() == num_layers * kHeadDim, + "k_norm_weight must be contiguous bf16 [L, 128]"); + STD_TORCH_CHECK(cos_sin_cache.is_contiguous() && + cos_sin_cache.scalar_type() == ScalarType::BFloat16 && + cos_sin_cache.dim() == 2 && + cos_sin_cache.size(1) == rotary_dim, + "cos_sin_cache must be contiguous bf16 [max_pos, " + "rotary_dim]"); + STD_TORCH_CHECK(rotary_dim == 16 || rotary_dim == 32 || rotary_dim == 64, + "rotary_dim must be 16, 32 or 64"); + for (auto const* t : {&positions, &slot_mapping}) { + STD_TORCH_CHECK(t->is_cuda() && t->is_contiguous() && + t->scalar_type() == ScalarType::Long && + t->numel() == num_tokens, + "positions and slot_mapping must be contiguous int64 [N]"); + } + STD_TORCH_CHECK(cache_offsets.is_cuda() && cache_offsets.is_contiguous() && + cache_offsets.scalar_type() == ScalarType::Long && + cache_offsets.numel() == num_layers, + "cache_offsets must be int64 [L]"); + STD_TORCH_CHECK(scale_offsets.is_cuda() && scale_offsets.is_contiguous() && + scale_offsets.scalar_type() == ScalarType::Long && + scale_offsets.numel() == 2 * num_layers, + "scale_offsets must be int64 [2, L]"); + STD_TORCH_CHECK( + k_scale.is_cuda() && k_scale.scalar_type() == ScalarType::Float, + "k_scale must be a float32 CUDA tensor"); + bool const fp8 = kv_cache_dtype == "fp8" || kv_cache_dtype == "fp8_e4m3"; + STD_TORCH_CHECK(fp8 || kv_cache_dtype == "auto", + "kv_cache_dtype must be auto, fp8 or fp8_e4m3"); + STD_TORCH_CHECK(fp8 ? kv_cache.scalar_type() == ScalarType::Byte + : kv_cache.scalar_type() == ScalarType::BFloat16, + "kv_cache must be uint8 (fp8) or bf16 (auto)"); + STD_TORCH_CHECK( + kv_cache.dim() == 4 && kv_cache.size(1) == nkv && + kv_cache.size(3) == 2 * kHeadDim && kv_cache.stride(3) == 1 && + kv_cache.stride(0) % 16 == 0 && kv_cache.stride(1) % 16 == 0 && + kv_cache.stride(2) % 16 == 0, + "kv_cache must be [nb, nkv, bs, 256] with a contiguous last dim"); + int64_t const block_size = kv_cache.size(2); + STD_TORCH_CHECK(block_size > 0 && (block_size & (block_size - 1)) == 0, + "kv_cache block size must be a power of two"); + int block_shift = 0; + while ((int64_t{1} << block_shift) < block_size) block_shift++; + int64_t constexpr kIntMax = std::numeric_limits::max(); + STD_TORCH_CHECK(all_kv.numel() / 8 <= kIntMax && + kv_cache.stride(0) <= kIntMax && + kv_cache.size(0) * block_size <= kIntMax, + "all_kv / kv_cache too large for 32-bit indexing"); + + const torch::stable::accelerator::DeviceGuard device_guard( + all_kv.get_device_index()); + auto stream = get_current_cuda_stream(all_kv.get_device_index()); + // all_kv strides in 16-byte vectors. + auto launch = [&](auto fp8_tag) { + constexpr bool kFp8 = decltype(fp8_tag)::value; + vllm::minimax_m3_fused_ops::launchFusedMiniMaxM3DSparkContextKV( + reinterpret_cast(all_kv.data_ptr()), + reinterpret_cast(k_norm_weight.data_ptr()), + reinterpret_cast(cos_sin_cache.data_ptr()), + reinterpret_cast(positions.data_ptr()), + reinterpret_cast(slot_mapping.data_ptr()), + reinterpret_cast(kv_cache.data_ptr()), + reinterpret_cast(cache_offsets.data_ptr()), + reinterpret_cast(k_scale.data_ptr()), + reinterpret_cast(scale_offsets.data_ptr()), + static_cast(eps), static_cast(rotary_dim), num_tokens, + num_layers, nkv, block_shift, static_cast(all_kv.stride(0) / 8), + static_cast(all_kv.stride(1) / 8), + static_cast(all_kv.stride(2) / 8), + static_cast(all_kv.stride(3) / 8), + static_cast(kv_cache.stride(0)), + static_cast(kv_cache.stride(1)), + static_cast(kv_cache.stride(2)), stream); + }; + if (fp8) { + launch(std::true_type{}); + } else { + launch(std::false_type{}); + } +#endif +} diff --git a/csrc/ops.h b/csrc/ops.h index 1c5ddc0beb4c..d5ed7b1338a3 100644 --- a/csrc/ops.h +++ b/csrc/ops.h @@ -413,7 +413,18 @@ void fused_minimax_m3_qknorm_rope_kv_insert( const std::string& kv_cache_dtype, bool skip_index_branch, std::optional q_fp8_out, double q_fp8_scale, std::optional kv_k_scale, - std::optional kv_v_scale); + std::optional kv_v_scale, bool write_qkv); + +void fused_minimax_m3_dspark_context_kv( + torch::stable::Tensor const& all_kv, + torch::stable::Tensor const& k_norm_weight, + torch::stable::Tensor const& cos_sin_cache, + torch::stable::Tensor const& positions, + torch::stable::Tensor const& slot_mapping, torch::stable::Tensor& kv_cache, + torch::stable::Tensor const& cache_offsets, + torch::stable::Tensor const& k_scale, + torch::stable::Tensor const& scale_offsets, int64_t rotary_dim, double eps, + const std::string& kv_cache_dtype); #ifdef VLLM_ENABLE_FUSED_KDA_DECODE void fused_kda_decode( diff --git a/csrc/torch_bindings.cpp b/csrc/torch_bindings.cpp index 1c84b53ece2c..9056ac176147 100644 --- a/csrc/torch_bindings.cpp +++ b/csrc/torch_bindings.cpp @@ -538,7 +538,17 @@ STABLE_TORCH_LIBRARY_FRAGMENT(_C, ops) { "int block_size, Tensor!? q_out, Tensor!? index_q_out, " "str kv_cache_dtype, bool skip_index_branch=False, " "Tensor!? q_fp8_out=None, float q_fp8_scale=1.0, " - "Tensor? kv_k_scale=None, Tensor? kv_v_scale=None) -> ()"); + "Tensor? kv_k_scale=None, Tensor? kv_v_scale=None, " + "bool write_qkv=True) -> ()"); + + // MiniMax-M3 DSpark draft: Gemma k-norm + partial NeoX RoPE + K/V cache + // insert for every draft layer's context K/V in one launch. + ops.def( + "fused_minimax_m3_dspark_context_kv(" + "Tensor all_kv, Tensor k_norm_weight, Tensor cos_sin_cache, " + "Tensor positions, Tensor slot_mapping, Tensor! kv_cache, " + "Tensor cache_offsets, Tensor k_scale, Tensor scale_offsets, " + "int rotary_dim, float eps, str kv_cache_dtype) -> ()"); #ifdef VLLM_ENABLE_FUSED_KDA_DECODE ops.def( @@ -879,6 +889,8 @@ STABLE_TORCH_LIBRARY_IMPL(_C, CUDA, ops) { TORCH_BOX(&fused_muse_spark_qknorm_rope_kv_insert)); ops.impl("fused_minimax_m3_qknorm_rope_kv_insert", TORCH_BOX(&fused_minimax_m3_qknorm_rope_kv_insert)); + ops.impl("fused_minimax_m3_dspark_context_kv", + TORCH_BOX(&fused_minimax_m3_dspark_context_kv)); #ifdef VLLM_ENABLE_FUSED_KDA_DECODE ops.impl("fused_kda_decode", TORCH_BOX(&fused_kda_decode)); #endif diff --git a/tests/config/test_speculative_draft_hf_overrides.py b/tests/config/test_speculative_draft_hf_overrides.py index 39ebd7924bf2..bff3846b9f97 100644 --- a/tests/config/test_speculative_draft_hf_overrides.py +++ b/tests/config/test_speculative_draft_hf_overrides.py @@ -48,19 +48,24 @@ def test_none_overrides_fall_back_to_arch_mapping(): def _make_speculative_config( - hf_kwargs: dict, architecture: str, **speculative_kwargs + hf_kwargs: dict, + architecture: str, + target_model: str = "target", + **speculative_kwargs, ) -> SpeculativeConfig: hf_config = SpeculativeConfig.hf_config_override(_make_hf_config(**hf_kwargs)) draft = MagicMock( hf_config=hf_config, architectures=hf_config.architectures, max_model_len=128 ) draft.registry.inspect_model_cls.return_value = (None, architecture) - target = MagicMock(max_model_len=128, quantization=None, hf_overrides={}) + target = MagicMock( + model=target_model, max_model_len=128, quantization=None, hf_overrides={} + ) target.hf_config.model_type = hf_kwargs["model_type"] + speculative_kwargs.setdefault("model", "draft") with patch("vllm.config.speculative.ModelConfig", return_value=draft): return SpeculativeConfig( - model="draft", **speculative_kwargs, target_model_config=target, target_parallel_config=ParallelConfig(), @@ -113,6 +118,75 @@ def test_dspark_width_is_independent_of_mtp_stages( assert config.draft_model_config.hf_config.architectures == [architecture] +def _make_minimax_dspark_hf_kwargs() -> dict: + return dict( + model_type="minimax_m3_vl", + architectures=["DSparkMiniMaxDraftModel"], + quantization_config={ + "quant_method": "mxfp8", + "ignored_layers": ["language_model.model.dspark.fc"], + }, + text_config=_make_hf_config( + architectures=["DSparkMiniMaxDraftModel"], + model_type="", + num_hidden_layers=5, + dspark_block_size=7, + dspark_markov_rank=256, + dflash_config={"block_size": 7}, + ), + ) + + +@pytest.mark.cpu_test +def test_minimax_dspark_draft_promotes_text_config(): + """The MiniMax DSpark draft ships a VL wrapper config. It must keep its own + draft class (not MiniMax MTP or DeepSeek DSpark), with the DSpark keys and + the wrapper's quantization config on the promoted text config.""" + hf_kwargs = _make_minimax_dspark_hf_kwargs() + config = _make_speculative_config( + hf_kwargs, "DSparkMiniMaxDraftModel", method="dspark" + ) + + hf_config = config.draft_model_config.hf_config + assert hf_config is hf_kwargs["text_config"] + assert hf_config.architectures == ["DSparkMiniMaxDraftModel"] + assert config.num_speculative_tokens == 7 + assert hf_config.quantization_config == hf_kwargs["quantization_config"] + assert hf_config.markov_rank == 256 + assert hf_config.dflash_config["causal"] is False + + +@pytest.mark.cpu_test +def test_minimax_dspark_defaults_to_dspark_subfolder(tmp_path): + """With only method="dspark", MiniMax-M3 loads the draft checkpoint shipped + in the target's dspark/ subfolder, with its own quantization config.""" + (tmp_path / "dspark").mkdir() + (tmp_path / "dspark" / "config.json").write_text("{}") + config = _make_speculative_config( + _make_minimax_dspark_hf_kwargs(), + "DSparkMiniMaxDraftModel", + target_model=str(tmp_path), + model=None, + method="dspark", + ) + + assert config.model == str(tmp_path / "dspark") + assert config.quantization is None + assert config.num_speculative_tokens == 7 + + +@pytest.mark.cpu_test +def test_minimax_dspark_without_subfolder_raises(tmp_path): + with pytest.raises(ValueError, match="no draft checkpoint in the 'dspark/'"): + _make_speculative_config( + _make_minimax_dspark_hf_kwargs(), + "DSparkMiniMaxDraftModel", + target_model=str(tmp_path), + model=None, + method="dspark", + ) + + @pytest.mark.cpu_test def test_mtp_stages_are_independent_of_dspark_width(): hf_kwargs = dict( diff --git a/tests/distributed/test_custom_all_reduce.py b/tests/distributed/test_custom_all_reduce.py index dd462c380d19..57d22a47ce2f 100644 --- a/tests/distributed/test_custom_all_reduce.py +++ b/tests/distributed/test_custom_all_reduce.py @@ -182,6 +182,152 @@ def test_all_reduce_mhc_matches_unfused_path(monkeypatch): multi_process_parallel(monkeypatch, 4, 1, _all_reduce_mhc) +def _swizzled_scale_rows(scales: torch.Tensor, rows: int, cols: int) -> torch.Tensor: + """[rows, cols] UE8M0 scales read out of the 128x4 swizzled layout.""" + row = torch.arange(rows, device=scales.device)[:, None] + col = torch.arange(cols, device=scales.device)[None, :] + offset = ( + col % 4 + + col // 4 * 512 + + row % 32 * 16 + + row % 128 // 32 * 4 + + row // 128 * 128 * cols + ) + return scales[offset] + + +@ray.remote(num_gpus=1, max_calls=1) +def _finalize_all_reduce_gemma_norm_mxfp8( + monkeypatch, tp_size, pp_size, rank, distributed_init_port +): + from vllm.model_executor.layers.fused_moe.moe_output import ( + MoEOutput, + UnfinalizedMoEOutput, + ) + from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( + mxfp8_e4m3_quantize, + ) + from vllm.models.minimax_m3.nvidia.ops.finalize_allreduce_norm import ( + FinalizeAllReduceGemmaRMSNormMxfp8, + ) + + hidden, top_k, eps = 6144, 4, 1e-6 + with monkeypatch.context() as m: + m.delenv("CUDA_VISIBLE_DEVICES", raising=False) + device = torch.device(f"cuda:{rank}") + torch.accelerator.set_device_index(device) + init_test_distributed_environment(tp_size, pp_size, rank, distributed_init_port) + ensure_model_parallel_initialized(tp_size, pp_size) + op = FinalizeAllReduceGemmaRMSNormMxfp8( + hidden_size=hidden, + max_num_tokens=32, + top_k=top_k, + fp32_weights=False, + device=device, + ) + + def run(n): + torch.manual_seed(7 + rank) + # A padded permuted GEMM2 buffer, like the MoE's. + rows = n * top_k + 5 + gemm2 = torch.randn(rows, hidden, device=device, dtype=torch.bfloat16) + permuted = torch.randperm(rows, device=device)[: n * top_k] + permuted = permuted.view(n, top_k).int() + # A route to an expert this rank does not hold. + permuted[0, -1] = -1 + weights = torch.rand(n, top_k, device=device).bfloat16() + shared = torch.randn(n, hidden, device=device, dtype=torch.bfloat16) + torch.manual_seed(123) + residual = torch.randn(n, hidden, device=device, dtype=torch.bfloat16) + weight = torch.randn(hidden, device=device, dtype=torch.bfloat16) * 0.1 + moe_output = MoEOutput( + routed=UnfinalizedMoEOutput(gemm2, weights, permuted), + shared_output=shared, + ) + + def fused(): + return op(moe_output, residual, weight, eps) + + def check(outputs): + quantized, residual_out = outputs + # One FP32 FMA per route in route order, the shared add, one + # rounding: the partial each rank publishes. + acc = torch.zeros(n, hidden, device=device) + for k in range(top_k): + valid = (permuted[:, k] >= 0).unsqueeze(-1) + rows_k = gemm2[permuted[:, k].clamp_min(0).long()].float() + torch.addcmul( + acc, + torch.where(valid, rows_k, 0.0), + torch.where(valid, weights[:, k : k + 1].float(), 0.0), + out=acc, + ) + partial = (acc + shared.float()).bfloat16() + peers = get_tp_group().all_gather(partial, dim=0).view(tp_size, n, -1) + reduced = peers[0].float() + for peer in peers[1:]: + reduced = reduced + peer.float() + prenorm = (reduced + residual.float()).bfloat16() + assert torch.equal(residual_out, prenorm) + + inv_rms = torch.rsqrt( + prenorm.float().square().mean(-1, keepdim=True) + eps + ) + normed = (prenorm.float() * inv_rms * (weight.float() + 1)).bfloat16() + ref_values, ref_scales = mxfp8_e4m3_quantize( + normed, is_sf_swizzled_layout=True + ) + # The norm sums the squares in another order with an approximate + # rsqrt, so a value can move by one BF16 ULP, and with it rarely + # a block's scale. Padding rows' scales are zero in both. + assert quantized.scale.shape == ref_scales.shape + assert (quantized.scale == ref_scales).float().mean() >= 0.99 + codes = quantized.data.view(torch.uint8) + assert (codes == ref_values.view(torch.uint8)).float().mean() >= 0.99 + cols = hidden // 32 + scales = _swizzled_scale_rows( + quantized.scale, quantized.scale.numel() // cols, cols + ) + assert not scales[n:].any() + scales = scales[:n] + step = torch.exp2(scales.float() - 127).repeat_interleave(32, dim=1) + dequantized = quantized.data.float() * step + expected = normed.float() + # E4M3 rounding (3 mantissa bits) plus one BF16 ULP, and the + # smallest E4M3 subnormal step of the block. + tolerance = 0.07 * expected.abs() + step * 2.0**-9 + assert torch.all((dequantized - expected).abs() <= tolerance) + + check(fused()) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + for _ in range(5): + fused() + captured = fused() + for _ in range(20): + graph.replay() + check(captured) + # Replays must pick up in-place input changes. + gemm2.mul_(0.5) + residual.mul_(2) + graph.replay() + check(captured) + + # Changing shapes cover shrinking and growing batches in one mailbox. + for n in (1, 6, 32, 3, 17, 2, 1): + run(n) + + +@pytest.mark.skipif( + not current_platform.is_device_capability_family(100), reason="Requires SM100" +) +def test_finalize_all_reduce_gemma_norm_mxfp8_matches_unfused_path(monkeypatch): + """MiniMax-M3's fused MoE finalize + all-reduce + Gemma RMSNorm + MXFP8.""" + if torch.accelerator.device_count() < 4: + pytest.skip("Requires four GPUs with NVLink multicast") + multi_process_parallel(monkeypatch, 4, 1, _finalize_all_reduce_gemma_norm_mxfp8) + + @pytest.mark.parametrize( ("dtype", "expected"), [ diff --git a/tests/kernels/attention/minimax_m3_nvfp4_ref.py b/tests/kernels/attention/minimax_m3_nvfp4_ref.py new file mode 100644 index 000000000000..05f264eeb882 --- /dev/null +++ b/tests/kernels/attention/minimax_m3_nvfp4_ref.py @@ -0,0 +1,148 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Torch reference of MiniMax-M3's NVFP4 K/V and index-K pages on ROCm. + +A 128-token page is ``[K side | V side]``; a side holds every KV head's e2m1 +data (8192 B per head), then every head's e4m3 block scales (1024 B per head). +Within a head: K data ``[token][64 B]``, K scales in the FlyDSL prefill's lane +order, V data ``[token octet][dim octet][8 dims][4 B]`` (a byte holds two +consecutive tokens of one dim), V scales ``[group][token]``. An index page is +``[128 x 64 B data][128 x 8 B scales]``. +""" + +import torch + +BLOCK = 128 +D = 128 +E2M1_GRID = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0) + + +def quantize_nvfp4(x: torch.Tensor, global_scale: float): + """E2M1 codes ``[T, 128]`` and e4m3 scale bytes ``[T, 8]`` of fp32 rows. + + The CUDA encoder's scale math and a nearest-grid E2M1 rounding with ties to + the even code, written independently of the kernels' bit arithmetic. + """ + groups = x.view(-1, 8, 16) + one_sixth = torch.tensor(1 / 6, dtype=torch.float32) + # fp32 throughout, like the kernels: 1 / 0.002 is not 500 in fp32. + gs = torch.tensor(global_scale, dtype=torch.float32, device=x.device) + scale = (groups.abs().amax(-1) * one_sixth * (1.0 / gs)).clamp(max=448) + scale_e4m3 = scale.to(torch.float8_e4m3fn) + scale_value = scale_e4m3.float() + quant = torch.where(scale_value != 0, 1.0 / (scale_value * gs), 0.0) + y = groups * quant[..., None] + grid = torch.tensor(E2M1_GRID, device=x.device) + dist = (y.abs()[..., None] - grid).abs() + is_min = dist == dist.amin(-1, keepdim=True) + ids = torch.arange(8, device=x.device) + # Neighbouring codes alternate parity, so every tie has an even candidate. + even_min = torch.where(is_min & (ids % 2 == 0), ids, 8).amin(-1) + mag = torch.where(even_min < 8, even_min, dist.argmin(-1)) + codes = mag | (torch.signbit(y).long() << 3) + return codes.view(-1, D), scale_e4m3.view(torch.uint8).view(-1, 8) + + +def dequant(data: torch.Tensor, scales: torch.Tensor) -> torch.Tensor: + """Token-major NVFP4 rows -> fp32 e2m1 x block scale, ``[..., 128]``.""" + codes = torch.stack((data & 15, data >> 4), -1).flatten(-2).long() + grid = torch.tensor(E2M1_GRID, device=data.device) + mag = grid[codes & 7] * torch.where(codes >= 8, -1.0, 1.0) + s = scales.view(torch.float8_e4m3fn).float() + return (mag.unflatten(-1, (8, 16)) * s[..., None]).flatten(-2) + + +def head_offsets(side: int, device): + """Byte offsets inside one head's regions of side 0 (K) or 1 (V). + + Returns the data byte and nibble shift of each (token, dim) ``[128, 128]`` + and the scale byte of each (token, group) ``[128, 8]``. + """ + t = torch.arange(BLOCK, device=device)[:, None] + d = torch.arange(D, device=device)[None, :] + g = torch.arange(8, device=device)[None, :] + if side == 0: + r = t % 32 + n = 4 * (r // 8) + r % 4 + data = t * 64 + d // 2 + shift = (d % 2) * 4 + 0 * t + scale = ((((t // 32) * 4 + g // 2) * 16 + n) * 2 + (r % 8) // 4) * 2 + g % 2 + else: + data = ((t // 8 * 16 + d // 8) * 8 + d % 8) * 4 + (t % 8) // 2 + shift = (t % 2) * 4 + 0 * d + scale = g * BLOCK + t + return data, shift, scale + + +def _region_bases(side: int, heads: int, device): + """``[H, 1, 1]`` page offsets of each head's data and scale regions.""" + h = torch.arange(heads, device=device)[:, None, None] + side0 = side * heads * BLOCK * 72 + return side0 + h * BLOCK * 64, side0 + heads * BLOCK * 64 + h * BLOCK * 8 + + +def _flat(cache: torch.Tensor) -> torch.Tensor: + """Writable 1-D view of a cache whose block stride may exceed one page.""" + n = (cache.shape[0] - 1) * cache.stride(0) + cache[0].numel() + return cache.as_strided((n,), (1,)) + + +def _insert_side(cache, rows, slots, side, global_scale): + tokens, heads, _ = rows.shape + codes, scales = quantize_nvfp4(rows.reshape(-1, D).float(), global_scale) + slots = slots.long() + keep = slots >= 0 + codes = codes.view(tokens, heads, D)[keep].to(torch.uint8) + scales = scales.view(tokens, heads, 8)[keep] + blk, pos = slots[keep] // BLOCK, slots[keep] % BLOCK + data_off, shift, scale_off = head_offsets(side, rows.device) + data_base, scale_base = _region_bases(side, heads, rows.device) + page = (blk * cache.stride(0))[:, None, None] + byte = page + data_base[:, 0] + data_off[pos][:, None] # [n, H, 128] + sh = shift[pos][:, None].expand_as(byte) + flat = _flat(cache) + for s in (0, 4): # each byte takes one nibble per pass + m = sh == s + flat[byte[m]] = (flat[byte[m]] & (0xF0 >> s)) | (codes[m] << s) + flat[page + scale_base[:, 0] + scale_off[pos][:, None]] = scales + + +def insert_nvfp4_kv(k, v, kv_cache, slots, k_scale, v_scale): + """Quantize K / V ``[T, Hkv, 128]`` into their pages; slots < 0 skip.""" + _insert_side(kv_cache, k, slots, 0, float(k_scale)) + _insert_side(kv_cache, v, slots, 1, float(v_scale)) + + +def insert_nvfp4_index(index_cache, keys, slots): + """Quantize index keys ``[T, 128]`` into their pages (no global scale).""" + codes, scales = quantize_nvfp4(keys.float(), 1.0) + slots = slots.long() + keep = slots >= 0 + codes, scales = codes[keep].to(torch.uint8), scales[keep] + blk, pos = slots[keep] // BLOCK, slots[keep] % BLOCK + base = (blk * index_cache.stride(0))[:, None] + flat = _flat(index_cache) + flat[base + pos[:, None] * 64 + torch.arange(64, device=keys.device)] = codes[ + :, 0::2 + ] | (codes[:, 1::2] << 4) + flat[base + BLOCK * 64 + pos[:, None] * 8 + torch.arange(8, device=keys.device)] = ( + scales + ) + + +def nvfp4_kv_cache_token_major(kv_cache: torch.Tensor): + """``(k_data, k_scale, v_data, v_scale)`` of a main cache, token-major. + + Data ``[blocks, Hkv, 128, 64]`` (the low nibble the even dim), scales + ``[blocks, Hkv, 128, 8]``, all uint8. + """ + blocks, heads = kv_cache.shape[0], kv_cache.shape[1] // 2 + pages = kv_cache.reshape(blocks, -1) + out = [] + for side in (0, 1): + data_off, shift, scale_off = head_offsets(side, kv_cache.device) + data_base, scale_base = _region_bases(side, heads, kv_cache.device) + codes = (pages[:, data_base + data_off] >> shift.to(torch.uint8)) & 0xF + out.append(codes[..., 0::2] | (codes[..., 1::2] << 4)) + out.append(pages[:, scale_base + scale_off]) + return tuple(out) diff --git a/tests/kernels/attention/test_minimax_m3.py b/tests/kernels/attention/test_minimax_m3.py index 43c795642026..a193bafbdac7 100644 --- a/tests/kernels/attention/test_minimax_m3.py +++ b/tests/kernels/attention/test_minimax_m3.py @@ -1165,6 +1165,407 @@ def test_aiter_indexer_impl_matches_reference( assert torch.equal(sparse_ctx.cpu(), expected_ctx) +# NVFP4 index cache (SM100/SM103): MSA Q8KV4 decode on the packed pages, FP8 +# gather + Q8KV8 prefill. Both rank pages from e4m3_rn_satfinite(e2m1 * scale). +_E2M1_VALUES = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0) +_NVFP4_PAGE_WIDTH = HEAD_DIM // 2 + HEAD_DIM // 16 +_requires_q8_indexer = pytest.mark.skipif( + not ( + current_platform.is_device_capability(100) + or current_platform.is_device_capability(103) + or current_platform.is_device_capability(107) + ), + reason="The MSA Q8KV4/Q8KV8 indexers require SM100, SM103 or SM107.", +) + + +def _random_nvfp4_index_pages( + num_pages: int, scale_max: float = 0.5, page_pad: int = 0 +) -> torch.Tensor: + """``[num_pages, 128, 72]`` uint8 pages: random E2M1 codes, then E4M3 scales.""" + data_bytes = BLOCK_SIZE * HEAD_DIM // 2 + page_bytes = BLOCK_SIZE * _NVFP4_PAGE_WIDTH + raw = torch.zeros( + num_pages, page_bytes + page_pad, dtype=torch.uint8, device="cuda" + ) + raw[:, :data_bytes] = torch.randint( + 0, 256, (num_pages, data_bytes), dtype=torch.uint8, device="cuda" + ) + scale = torch.rand(num_pages, page_bytes - data_bytes, device="cuda") * scale_max + raw[:, data_bytes:page_bytes] = scale.to(torch.float8_e4m3fn).view(torch.uint8) + return raw[:, :page_bytes].view(num_pages, BLOCK_SIZE, _NVFP4_PAGE_WIDTH) + + +def _dequant_nvfp4_index_pages(pages: torch.Tensor) -> torch.Tensor: + """Reference ``[P, 128, 128]`` e4m3: e2m1 * scale, clamped, rounded once.""" + num_pages = pages.shape[0] + flat = pages.reshape(num_pages, -1) + data = flat[:, : BLOCK_SIZE * HEAD_DIM // 2].view(num_pages, BLOCK_SIZE, -1) + scale = flat[:, BLOCK_SIZE * HEAD_DIM // 2 :].view(torch.float8_e4m3fn) + codes = torch.stack((data & 0xF, data >> 4), dim=-1).reshape( + num_pages, BLOCK_SIZE, HEAD_DIM + ) + magnitude = torch.tensor(_E2M1_VALUES, device="cuda")[(codes & 7).long()] + value = torch.where(codes >= 8, -magnitude, magnitude) + value = value * scale.float().view(num_pages, BLOCK_SIZE, -1).repeat_interleave( + 16, dim=-1 + ) + return value.clamp_(-448.0, 448.0).to(torch.float8_e4m3fn) + + +@_requires_q8_indexer +@pytest.mark.parametrize("use_qmul4", [False, True]) +@pytest.mark.parametrize("scale_max", [0.5, 448.0]) +def test_gather_nvfp4_index_k_fp8_bitwise( + scale_max: float, use_qmul4: bool, monkeypatch +): + """Each request's leading pages land at its compact offset, bit-identical + to the reference dequant (incl. saturation), and nothing else is written, + on both the QMUL4 and the fp32 dequant paths.""" + import vllm.models.minimax_m3.nvidia.ops.gather_nvfp4_index_k as gather_mod + from vllm.models.minimax_m3.nvidia.ops.gather_nvfp4_index_k import ( + minimax_m3_gather_nvfp4_index_k_fp8, + ) + + if use_qmul4 and not gather_mod._qmul4_supported(0): + pytest.skip("Triton's Blackwell ptxas emits PTX older than 9.4 (no QMUL4).") + monkeypatch.setattr(gather_mod, "_qmul4_supported", lambda _: use_qmul4) + + torch.manual_seed(0) + num_physical = 40 + kv = _random_nvfp4_index_pages(num_physical, scale_max, page_pad=32) + block_table = torch.randperm(num_physical, device="cuda", dtype=torch.int32)[ + :36 + ].view(3, 12) + num_pages = torch.tensor([5, 0, 12], dtype=torch.int32, device="cuda") + page_offsets = torch.cumsum(num_pages, 0, dtype=torch.int32) - num_pages + total = int(num_pages.sum()) + out = torch.full((total + 1, BLOCK_SIZE, HEAD_DIM), 1.0, device="cuda").to( + torch.float8_e4m3fn + ) + + minimax_m3_gather_nvfp4_index_k_fp8( + kv, block_table, num_pages, page_offsets, 12, out + ) + + expected = _dequant_nvfp4_index_pages(kv) + for req, (count, offset) in enumerate( + zip(num_pages.tolist(), page_offsets.tolist()) + ): + pages = block_table[req, :count].long() + assert torch.equal( + out[offset : offset + count].view(torch.uint8), + expected[pages].view(torch.uint8), + ) + assert torch.all(out[total].float() == 1.0) + + +def _assert_forced_tail_topk( + actual: torch.Tensor, scores: torch.Tensor, lengths: torch.Tensor +) -> None: + """Check the Q8 top-k contract on ``[rows, 16]`` output. + + ``scores[row, :lengths[row] - 1]`` are the reference history-page scores. + Rows with <= 16 candidates are ``0 .. length - 1`` then ``-1``. Longer rows + hold 15 distinct history pages, then the local page. The ranked pages must + be the top 15 up to the kernel's 16-bit score-key quantization. + """ + actual = actual.long() + rows, max_pages = scores.shape + cols = torch.arange(TOPK, device=actual.device) + short = lengths <= TOPK + expected_short = torch.where(cols < lengths[:, None], cols, -1) + assert torch.equal(actual[short], expected_short[short]) + + long_rows = (~short).nonzero().flatten() + if long_rows.numel() == 0: + return + actual, scores, lengths = actual[long_rows], scores[long_rows], lengths[long_rows] + assert torch.equal(actual[:, -1], lengths - 1) + ranked = actual[:, :-1] + assert torch.all((ranked >= 0) & (ranked < (lengths - 1)[:, None])) + assert torch.all(ranked.sort(dim=1).values.diff(dim=1) > 0) + valid = torch.arange(max_pages, device=scores.device) < (lengths - 1)[:, None] + history = scores.masked_fill(~valid, float("-inf")) + high = history.amax(dim=1) + low = scores.masked_fill(~valid, float("inf")).amin(dim=1) + tol = 1.5 * (high - low) / 65534.0 + 1e-5 * high.abs() + threshold = history.topk(TOPK - 1, dim=1).values[:, -1] + assert torch.all(history.gather(1, ranked) >= (threshold - tol)[:, None]) + must_pick = history > (threshold + tol)[:, None] + picked = torch.zeros_like(must_pick).scatter_(1, ranked, True) + assert not torch.any(must_pick & ~picked) + + +@_requires_q8_indexer +@pytest.mark.parametrize("num_idx_heads", [1, 2, 4]) +@pytest.mark.parametrize("decode_query_len", [1, 3, 8]) +def test_nvfp4_indexer_impl_matches_reference( + num_idx_heads, decode_query_len, monkeypatch, workspace_init +): + """Drive MiniMaxM3IndexerNvfp4Impl through its metadata builder on a mixed + batch (short and full 8-query decodes, fresh and chunked prefills, a request + without history pages, several gather chunks) and check every row against + a reference computed from the dequantized NVFP4 keys.""" + import vllm.models.minimax_m3.common.indexer as indexer_mod + from tests.v1.attention.utils import ( + BatchSpec, + create_common_attn_metadata, + create_vllm_config, + ) + from vllm.config import set_current_vllm_config + from vllm.forward_context import set_forward_context + from vllm.models.minimax_m3.nvidia.indexer_nvfp4 import ( + MiniMaxM3IndexerNvfp4Impl, + MiniMaxM3IndexerNvfp4MetadataBuilder, + ) + + torch.manual_seed(0) + device = torch.device("cuda") + monkeypatch.setattr(indexer_mod, "get_tensor_model_parallel_world_size", lambda: 1) + vllm_config = create_vllm_config( + block_size=BLOCK_SIZE, max_model_len=8192, max_num_batched_tokens=8192 + ) + vllm_config.model_config.hf_config.sparse_attention_config = { + "sparse_num_index_heads": num_idx_heads + } + + decode_seq_lens = [2305, 2561, 9] + prefill = [(2624, 64), (2720, 96), (100, 100), (1500, 1500)] + batch = BatchSpec( + seq_lens=decode_seq_lens + [s for s, _ in prefill], + query_lens=[decode_query_len] * len(decode_seq_lens) + [q for _, q in prefill], + ) + common = create_common_attn_metadata(batch, BLOCK_SIZE, device) + num_blocks = common.block_table_tensor.shape[1] + num_physical = batch.batch_size * num_blocks + block_table = torch.randperm(num_physical, device=device, dtype=torch.int32) + common.block_table_tensor = block_table.view(batch.batch_size, num_blocks) + num_tokens = batch.compute_num_tokens() + + index_cache = _random_nvfp4_index_pages(num_physical) + index_q = ( + torch.randn(num_tokens, num_idx_heads * HEAD_DIM, device=device) * 0.5 + ).to(torch.float8_e4m3fn) + + impl_kwargs = dict( + num_kv_heads=num_idx_heads, + scale=HEAD_DIM**-0.5, + topk_blocks=TOPK, + sparse_block_size=BLOCK_SIZE, + num_index_heads=num_idx_heads, + index_head_dim=HEAD_DIM, + init_blocks=0, + local_blocks=1, + indexer_kv_dtype="nvfp4", + ) + spec = MLAAttentionSpec( + block_size=BLOCK_SIZE, + num_kv_heads=1, + head_size=_NVFP4_PAGE_WIDTH, + dtype=torch.uint8, + ) + with set_current_vllm_config(vllm_config): + impl = MiniMaxM3IndexerNvfp4Impl(prefix="idx_nvfp4", **impl_kwargs) + builder = MiniMaxM3IndexerNvfp4MetadataBuilder( + spec, [impl.index_cache.prefix], vllm_config, device + ) + index_spec = impl.index_cache.get_kv_cache_spec(vllm_config) + assert isinstance(index_spec, MLAAttentionSpec) + assert index_spec.page_size_bytes == BLOCK_SIZE * _NVFP4_PAGE_WIDTH + assert index_spec.dtype == torch.uint8 + # Spec decode would raise the threshold to 1 + num_speculative_tokens. + builder.reorder_batch_threshold = decode_query_len + # Fit the longest request's 21 history pages but not two such requests. + builder.max_gather_pages = 30 + impl.index_cache.kv_cache = index_cache + impl.topk_indices_buffer = torch.full( + (num_tokens, num_idx_heads, TOPK), -2, dtype=torch.int32, device=device + ) + + # Planning reads only host-side metadata: any device sync is an error. + torch.cuda.set_sync_debug_mode("error") + try: + md = builder.build(0, common) + finally: + torch.cuda.set_sync_debug_mode("default") + assert md.num_decode_tokens == decode_query_len * len(decode_seq_lens) + assert len(md.prefill_chunks) == 3 + with set_forward_context({impl.index_cache.prefix: md}, vllm_config): + assert impl(index_q) == (None, None) + + # Reference: max over each history page's 128 tokens of q . k. + keys = _dequant_nvfp4_index_pages(index_cache).float() + q = index_q.float().view(num_tokens, num_idx_heads, HEAD_DIM) + max_pages = num_blocks + scores = torch.full( + (num_tokens, num_idx_heads, max_pages), float("-inf"), device=device + ) + lengths = torch.empty(num_tokens, dtype=torch.long, device=device) + token = 0 + for req, (seq_len, q_len) in enumerate(zip(batch.seq_lens, batch.query_lens)): + pages = (seq_len + BLOCK_SIZE - 1) // BLOCK_SIZE + k = keys[common.block_table_tensor[req, :pages].long()] + rows = slice(token, token + q_len) + scores[rows, :, :pages] = torch.einsum("nhd,pkd->nhpk", q[rows], k).amax(dim=-1) + positions = torch.arange(seq_len - q_len, seq_len, device=device) + lengths[rows] = positions // BLOCK_SIZE + 1 + token += q_len + _assert_forced_tail_topk( + impl.topk_indices_buffer.view(-1, TOPK), + scores.view(-1, max_pages), + lengths.repeat_interleave(num_idx_heads), + ) + + +@_requires_q8_indexer +@pytest.mark.parametrize("decode_query_len", [1, 3, 8]) +@pytest.mark.parametrize("num_idx_heads", [1, 2, 4]) +def test_nvfp4_indexer_decode_cuda_graph_replay( + decode_query_len, num_idx_heads, monkeypatch, workspace_init +): + """A full CUDA graph captures the decode indexer once per padded batch + size; re-planning a later step (new lengths, pages and keys, one + zero-length padding request) outside capture and replaying must give that + step's top-k, which fails if any captured tensor was re-allocated. The + decode reads index_q and writes the top-k in place, copying nothing.""" + import vllm.models.minimax_m3.common.indexer as indexer_mod + from tests.v1.attention.utils import ( + BatchSpec, + create_common_attn_metadata, + create_vllm_config, + ) + from vllm.config import set_current_vllm_config + from vllm.forward_context import set_forward_context + from vllm.models.minimax_m3.nvidia.indexer_nvfp4 import ( + MiniMaxM3IndexerNvfp4Impl, + MiniMaxM3IndexerNvfp4MetadataBuilder, + ) + + torch.manual_seed(0) + device = torch.device("cuda") + monkeypatch.setattr(indexer_mod, "get_tensor_model_parallel_world_size", lambda: 1) + vllm_config = create_vllm_config( + block_size=BLOCK_SIZE, max_model_len=8192, max_num_batched_tokens=8192 + ) + vllm_config.model_config.hf_config.sparse_attention_config = { + "sparse_num_index_heads": num_idx_heads + } + num_reqs, max_blocks = 4, 24 + num_tokens = num_reqs * decode_query_len + num_physical = num_reqs * max_blocks + index_cache = _random_nvfp4_index_pages(num_physical) + + with set_current_vllm_config(vllm_config): + impl = MiniMaxM3IndexerNvfp4Impl( + prefix="idx_nvfp4_graph", + num_kv_heads=num_idx_heads, + scale=HEAD_DIM**-0.5, + topk_blocks=TOPK, + sparse_block_size=BLOCK_SIZE, + num_index_heads=num_idx_heads, + index_head_dim=HEAD_DIM, + init_blocks=0, + local_blocks=1, + indexer_kv_dtype="nvfp4", + ) + builder = MiniMaxM3IndexerNvfp4MetadataBuilder( + MLAAttentionSpec( + block_size=BLOCK_SIZE, + num_kv_heads=1, + head_size=_NVFP4_PAGE_WIDTH, + dtype=torch.uint8, + ), + [impl.index_cache.prefix], + vllm_config, + device, + ) + builder.reorder_batch_threshold = decode_query_len + impl.index_cache.kv_cache = index_cache + impl.topk_indices_buffer = torch.full( + (num_tokens, num_idx_heads, TOPK), -2, dtype=torch.int32, device=device + ) + index_q = torch.empty(num_tokens, num_idx_heads * HEAD_DIM, device=device).to( + torch.float8_e4m3fn + ) + + def step(seq_lens, query_lens): + common = create_common_attn_metadata( + BatchSpec(seq_lens=seq_lens, query_lens=query_lens), BLOCK_SIZE, device + ) + common.block_table_tensor = torch.randperm( + num_physical, device=device, dtype=torch.int32 + )[: num_reqs * max_blocks].view(num_reqs, max_blocks) + index_q.copy_( + (torch.randn(num_tokens, num_idx_heads * HEAD_DIM, device=device) * 0.5).to( + torch.float8_e4m3fn + ) + ) + return common, builder.build(0, common) + + # Warm up (compiles), then capture the forward of a full batch. + common, md = step([2305, 2561, 2944, 700], [decode_query_len] * num_reqs) + with set_forward_context({impl.index_cache.prefix: md}, vllm_config): + impl(index_q) + with torch.profiler.profile( + activities=[ + torch.profiler.ProfilerActivity.CPU, + torch.profiler.ProfilerActivity.CUDA, + ] + ) as prof: + impl(index_q) + torch.accelerator.synchronize() + copies = [ + e.name for e in prof.events() if "Memcpy" in e.name or "copy_" in e.name + ] + assert not copies, copies + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + impl(index_q) + + # A later step: the last request pads the graph batch with no tokens. + seq_lens = [2800, 1500, 3000, 0] + query_lens = [decode_query_len] * 3 + [0] + common, md = step(seq_lens, query_lens) + assert md.decode_q8kv4.num_reqs == num_reqs + # An eager step of another batch size runs before the replay; every decode + # wrapper shares one page-score scratch, which this one overwrites. + other = create_common_attn_metadata( + BatchSpec(seq_lens=[1800, 900], query_lens=[decode_query_len] * 2), + BLOCK_SIZE, + device, + ) + other.block_table_tensor = common.block_table_tensor[:2].clone() + other_md = builder.build(0, other) + with set_forward_context({impl.index_cache.prefix: other_md}, vllm_config): + impl(index_q[: 2 * decode_query_len]) + assert len(builder.decode_wrappers) == 2 + impl.topk_indices_buffer.fill_(-2) + graph.replay() + + num_real = 3 * decode_query_len + keys = _dequant_nvfp4_index_pages(index_cache).float() + q = index_q[:num_real].float().view(num_real, num_idx_heads, HEAD_DIM) + scores = torch.full( + (num_real, num_idx_heads, max_blocks), float("-inf"), device=device + ) + lengths = torch.empty(num_real, dtype=torch.long, device=device) + for req in range(3): + pages = (seq_lens[req] + BLOCK_SIZE - 1) // BLOCK_SIZE + k = keys[common.block_table_tensor[req, :pages].long()] + rows = slice(req * decode_query_len, (req + 1) * decode_query_len) + scores[rows, :, :pages] = torch.einsum("nhd,pkd->nhpk", q[rows], k).amax(dim=-1) + positions = torch.arange( + seq_lens[req] - decode_query_len, seq_lens[req], device=device + ) + lengths[rows] = positions // BLOCK_SIZE + 1 + _assert_forced_tail_topk( + impl.topk_indices_buffer[:num_real].view(-1, TOPK), + scores.view(-1, max_blocks), + lengths.repeat_interleave(num_idx_heads), + ) + + @pytest.mark.parametrize( ("decode_query_len", "max_decode_query_len"), [ diff --git a/tests/kernels/attention/test_minimax_m3_index_topk_decode.py b/tests/kernels/attention/test_minimax_m3_index_topk_decode.py new file mode 100644 index 000000000000..afbd90c009f3 --- /dev/null +++ b/tests/kernels/attention/test_minimax_m3_index_topk_decode.py @@ -0,0 +1,228 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MiniMax-M3 index top-k (FlyDSL) against AITER's ``pa_sparse_block_topk`` +block ids, bit for bit, on realistic and adversarial decode and prefill rows.""" + +import math + +import pytest +import torch + +from vllm.platforms import current_platform + +if not current_platform.is_rocm(): + pytest.skip("ROCm (gfx950) FlyDSL kernels", allow_module_level=True) + +from vllm.platforms.rocm import on_gfx950 # noqa: E402 + +if not on_gfx950(): + pytest.skip("gfx950 instructions", allow_module_level=True) + +from vllm.models.minimax_m3.amd.ops.index_topk_decode.host import ( # noqa: E402 + minimax_m3_index_topk_decode_indices, + minimax_m3_index_topk_prefill_indices, + supports_index_topk, +) + +BLOCK = 128 + + +def _width(max_seq_len: int) -> int: + n = math.ceil(math.ceil(max_seq_len / BLOCK) / 64) + return (1 << (n - 1).bit_length()) * 64 + + +def _scores(kind, heads, rows, width, nblk, gen): + s = torch.randn(heads, rows, width, generator=gen) + if kind == "real": # a few outliers, the init block 1e30, the last two 1e29 + s = torch.where(torch.rand(s.shape, generator=gen) < 4.0 / width, s + 6, s) + for r in range(rows): + b = min(int(nblk[r]), width) + if b > 0: + s[:, r, max(b - 2, 0) : b] = 1e29 + s[:, r, 0] = 1e30 + elif kind == "ties": + s = torch.randint(-3, 4, s.shape, generator=gen).float() + elif kind == "equal": + s = torch.full_like(s, 0.5) + elif kind == "neginf": + s = torch.full_like(s, float("-inf")) + elif kind == "nan": + s[torch.rand(s.shape, generator=gen) < 0.3] = float("nan") + neg_nan = torch.tensor([-4194303], dtype=torch.int32).view(torch.float32) + s[torch.rand(s.shape, generator=gen) < 0.1] = neg_nan.item() + elif kind == "zeros": # +0 / -0 / denormals + vals = torch.tensor([0.0, -0.0, 1e-40, -1e-40, 1e-45, -1e-45]) + s = vals[torch.randint(0, 6, s.shape, generator=gen)] + elif kind == "sentinels": + s = torch.where(torch.rand(s.shape, generator=gen) < 0.2, 1e29, s) + s = torch.where(torch.rand(s.shape, generator=gen) < 0.05, 1e30, s) + elif kind == "inf": + r = torch.rand(s.shape, generator=gen) + s = torch.where(r < 0.1, float("inf"), s) + s = torch.where((r > 0.1) & (r < 0.2), float("-inf"), s) + elif kind == "rising": # increasing with position + s = torch.arange(width, dtype=torch.float32).expand(heads, rows, width).clone() + # blocks past a row's length hold garbage the kernel must not read as scores + tail = torch.randn(s.shape, generator=gen) * 1e6 + tail[torch.rand(s.shape, generator=gen) < 0.1] = float("nan") + live = torch.arange(width)[None, None, :] < nblk[None, :, None] + return torch.where(live, s, tail) + + +def _topk_out(heads, rows, pad): + """``topk_idx`` and the tensor compared: with ``pad`` a view (non-zero row + start, larger head stride) of a larger persistent buffer, compared whole + (nothing outside the view is written).""" + if not pad: + t = torch.full((heads, rows, 16), -7, dtype=torch.int32, device="cuda") + return t, t + full = torch.full((heads, rows + 37, 16), -7, dtype=torch.int32, device="cuda") + return full[:, 5 : 5 + rows], full + + +def _aiter_topk(score, bt, seq, msl, nkv, pad, **kw): + from aiter.ops.msa_attention import pa_sparse_block_topk + + heads, rows, _ = score.shape + topk, compared = _topk_out(heads, rows, pad) + sbt = torch.empty(rows * nkv, 128, dtype=torch.int32, device="cuda") + sctx = torch.empty(rows * nkv, dtype=torch.int32, device="cuda") + pa_sparse_block_topk( + score, topk, bt, seq, sbt, sctx, max_seq_len=msl, block_size=BLOCK, + num_kv_heads=nkv, pages_per_block=8, **kw, + ) # fmt: skip + return compared + + +SHAPES = [ + # reqs, query_len, max_seq_len, (lo, hi) seq_len, num_kv_heads, index heads + (40, 4, 1 << 20, (30000, 210000), 1, 1), # the QPS decode batch + (8, 4, 262144, (1, 262144), 1, 1), + (5, 4, 1 << 20, (1 << 19, 1 << 20), 1, 1), # 4 windows of 2048 blocks + (16, 1, 1 << 20, (2040 * BLOCK, 2100 * BLOCK), 1, 1), # the window edge + (12, 1, 4000, (1, 4000), 1, 1), + (4, 2, 300000, (1, 300000), 2, 2), + (7, 4, 20000, (20000, 40000), 1, 1), # rows past max_seq_len + (256, 4, 1 << 20, (1, 3000), 1, 1), # 1024 short rows + (32, 6, 204800, (190000, 204800), 4, 4), # 6 rows, 4 heads + # rows past max_seq_len inside the padded width (2048 blocks): the window + # sized by max_seq_len must go on to the next one, not cut them + (8, 1, 200000, (200000, 262000), 4, 1), + (4, 2, 0, (0, 0), 1, 1), # a zero max_seq_len (dummy batch) + (1, 1, 1, (0, 1), 1, 1), +] +KINDS = [ + "real", + "ties", + "equal", + "neginf", + "nan", + "zeros", + "sentinels", + "inf", + "rising", +] + + +def _check_decode(kind, shape, pad=False): + reqs, ql, msl, (lo, hi), nkv, heads = shape + gen = torch.Generator().manual_seed(100 * KINDS.index(kind) + SHAPES.index(shape)) + seq = torch.randint(lo, hi + 1, (reqs,), generator=gen) + if reqs > 1: + seq[-1] = 0 # a cudagraph padding request + tok = torch.arange(reqs * ql) % ql + kv = (seq.repeat_interleave(ql) - ql + tok + 1).clamp(min=0) + score = _scores(kind, heads, reqs * ql, _width(msl), (kv + BLOCK - 1) // BLOCK, gen) + # the table covers every row's blocks (rows may run past max_seq_len) + cols = max(1, math.ceil(max(msl, int(seq.max())) / BLOCK)) + bt = torch.randint(0, 1 << 22, (reqs, cols), generator=gen).int().cuda() + score, seq = score.cuda(), seq.int().cuda() + ref = _aiter_topk(score, bt, seq, msl, nkv, pad, query_len=ql) + topk, got = _topk_out(heads, reqs * ql, pad) + minimax_m3_index_topk_decode_indices( + score, topk, seq, max_seq_len=msl, query_len=ql + ) + torch.testing.assert_close(got, ref, rtol=0, atol=0) + + +@pytest.mark.parametrize("kind", KINDS) +@pytest.mark.parametrize("shape", SHAPES) +def test_index_topk_decode_matches_aiter(kind, shape): + _check_decode(kind, shape) + + +@pytest.mark.parametrize("kind", ["real", "nan", "ties"]) +@pytest.mark.parametrize("shape", [SHAPES[0], SHAPES[5]]) +def test_index_topk_decode_padded_output(kind, shape): + _check_decode(kind, shape, pad=True) + + +def test_index_topk_decode_all_padding(): + """A captured dummy batch: every request padding (seq_len 0).""" + reqs, ql, msl = 48, 4, 1 << 20 + score = torch.randn(1, reqs * ql, _width(msl), device="cuda") + bt = torch.zeros(reqs, msl // BLOCK, dtype=torch.int32, device="cuda") + seq = torch.zeros(reqs, dtype=torch.int32, device="cuda") + ref = _aiter_topk(score, bt, seq, msl, 1, False, query_len=ql) + topk, _ = _topk_out(1, reqs * ql, False) + minimax_m3_index_topk_decode_indices( + score, topk, seq, max_seq_len=msl, query_len=ql + ) + torch.testing.assert_close(topk, ref, rtol=0, atol=0) + + +PREFILL_SHAPES = [ + # (q_len, seq_len) per request, max_seq_len, num_kv_heads, index heads + ([(1000, 1000)], 1000, 1, 1), # a fresh prompt: every row diagonal + ([(700, 30000), (1500, 1500)], 30000, 4, 4), # cached prefix + fresh + ([(2000, 9000), (513, 513), (3000, 20000)], 20000, 4, 1), # ragged + ([(300, 262144), (64, 200000)], 262144, 4, 4), # one window, 2048 blocks + ([(129, 2049 * BLOCK), (40, 1 << 20)], 1 << 20, 2, 2), # multi-window rows + ([(1, 1), (5, 5), (128, 128), (129, 129)], 4096, 1, 1), # tiny rows + # 3K new on a 200K prefix beside a fresh 3K prompt + ([(3072, 203072), (3072, 3072), (3072, 207872)], 207872, 4, 1), + ([(64, 262000), (3072, 203072)], 200000, 4, 1), # rows past max_seq_len +] + + +def _check_prefill(kind, shape, pad=False): + reqs, msl, nkv, heads = shape + gen = torch.Generator().manual_seed( + 100 * KINDS.index(kind) + PREFILL_SHAPES.index(shape) + ) + # every request's chunk ends its sequence: row positions seq - q .. seq - 1 + pos = torch.cat([torch.arange(s - q, s) for q, s in reqs]) + rid = torch.cat([torch.full((q,), r) for r, (q, _) in enumerate(reqs)]) + nvp = pos // BLOCK + 1 + seq = torch.tensor([s for _, s in reqs]) + score = _scores(kind, heads, pos.numel(), _width(msl), nvp, gen).cuda() + cols = max(1, math.ceil(max(msl, int(seq.max())) / BLOCK)) + bt = torch.randint(0, 1 << 22, (len(reqs), cols), generator=gen).int().cuda() + nvp, rid, kvl = (x.int().cuda() for x in (nvp, rid, pos + 1)) + ref = _aiter_topk( + score, bt, seq.int().cuda(), msl, nkv, pad, + num_valid_pages=nvp, row_req_id=rid, kv_lens=kvl, + ) # fmt: skip + topk, got = _topk_out(heads, pos.numel(), pad) + minimax_m3_index_topk_prefill_indices( + score, topk, max_seq_len=msl, num_valid_pages=nvp + ) + torch.testing.assert_close(got, ref, rtol=0, atol=0) + + +@pytest.mark.parametrize("kind", KINDS) +@pytest.mark.parametrize("shape", PREFILL_SHAPES) +def test_index_topk_prefill_matches_aiter(kind, shape): + _check_prefill(kind, shape) + + +@pytest.mark.parametrize("kind", ["real", "nan", "ties"]) +@pytest.mark.parametrize("shape", [PREFILL_SHAPES[2], PREFILL_SHAPES[4]]) +def test_index_topk_prefill_padded_output(kind, shape): + _check_prefill(kind, shape, pad=True) + + +def test_supports_index_topk(): + assert supports_index_topk(16, BLOCK) + assert not supports_index_topk(8, BLOCK) and not supports_index_topk(16, 64) diff --git a/tests/kernels/attention/test_minimax_m3_msa_cutlass_sparse_decode.py b/tests/kernels/attention/test_minimax_m3_msa_cutlass_sparse_decode.py index c7a4916737c0..966f00f547f3 100644 --- a/tests/kernels/attention/test_minimax_m3_msa_cutlass_sparse_decode.py +++ b/tests/kernels/attention/test_minimax_m3_msa_cutlass_sparse_decode.py @@ -4,6 +4,7 @@ NVFP4 KV cache).""" import math +from dataclasses import fields, replace from types import SimpleNamespace import pytest @@ -29,11 +30,13 @@ ) from vllm.models.minimax_m3.nvidia.model import MiniMaxM3SparseAttention from vllm.models.minimax_m3.nvidia.msa_cutlass_sparse_decode import ( + NVFP4_BLOCK_SCALE_SHIFT, MSACutlassDecodePlanCache, msa_cutlass_sparse_decode, nvfp4_kv_cache_views, prepare_decode_metadata, should_prepare_decode_metadata, + uses_q8kv4_decode, ) from vllm.models.minimax_m3.nvidia.sparse_attention_msa import ( MiniMaxM3SparseMSABackend, @@ -41,6 +44,8 @@ MiniMaxM3SparseMSAImpl, MiniMaxM3SparseMSAMetadataBuilder, MiniMaxM3SparseMSANvfp4Backend, + MiniMaxM3SparseMSANvfp4Impl, + MiniMaxM3SparseMSAPrefillMetadata, ) from vllm.platforms import current_platform from vllm.v1.attention.backends.registry import AttentionBackendEnum @@ -179,6 +184,26 @@ def test_msa_cutlass_decode_static_dispatch_requires_sm100( ) +def test_msa_cutlass_decode_static_dispatch_query_head_limits() -> None: + """FP8 plans fit the kv_mode 3 work list (65536 query-head rows); NVFP4 + plans run on the Q8KV4 kernel, which takes 65535 query tokens.""" + + def planned(batch_size: int, kv_cache_dtype: str) -> bool: + return should_prepare_decode_metadata( + batch_size, + 8, + decode_backend="cutlass", + num_q_heads=16, + num_kv_heads=1, + kv_cache_dtype=kv_cache_dtype, + page_size=BLOCK_SIZE, + topk_blocks=TOPK, + ) + + assert planned(512, "fp8") and not planned(513, "fp8") + assert planned(8191, "nvfp4") and not planned(8192, "nvfp4") + + @pytest.mark.parametrize("decode_backend", ["cutlass", "triton"]) def test_msa_cutlass_decode_static_dispatch_nvfp4_has_no_fallback( decode_backend: str, @@ -205,7 +230,7 @@ def test_nvfp4_selects_msa_nvfp4_backend_and_requires_sm100( num_kv_heads=1, ) assert backend_cls is MiniMaxM3SparseMSANvfp4Backend - assert impl_cls is MiniMaxM3SparseMSAImpl + assert impl_cls is MiniMaxM3SparseMSANvfp4Impl with pytest.raises(ValueError, match="nvfp4_4over6"): select_main_backend_and_impl_cls( topk_blocks=TOPK, @@ -229,12 +254,13 @@ def test_nvfp4_selects_msa_nvfp4_backend_and_requires_sm100( @pytest.mark.parametrize( ("backend", "expected"), [ + (None, "cutlass"), (AttentionBackendEnum.CUTLASS_MSA, "cutlass"), (AttentionBackendEnum.TRITON_MSA, "triton"), ], ) def test_msa_attention_backend_alias( - backend: AttentionBackendEnum, + backend: AttentionBackendEnum | None, expected: str, ) -> None: config = AttentionConfig(backend=backend) @@ -275,6 +301,7 @@ def test_msa_metadata_builder_prepares_cutlass_for_regular_decode( seq_lens = torch.full((batch,), 257, dtype=torch.int32, device="cuda") base_metadata = SimpleNamespace( num_decodes=batch, + prefill=None, decode=SimpleNamespace( block_table=block_table, seq_lens=seq_lens, @@ -300,6 +327,7 @@ def test_msa_metadata_builder_prepares_cutlass_for_regular_decode( builder.kv_cache_spec = SimpleNamespace(num_kv_heads=4) builder.kv_cache_dtype = "fp8_e4m3" builder.decode_backend = "cutlass" + builder.q8kv4_decode = False builder.msa_cutlass_plan_cache = object() builder.msa_cutlass_min_batch_size = None @@ -315,6 +343,39 @@ def test_msa_metadata_builder_prepares_cutlass_for_regular_decode( assert metadata.decode.msa_cutlass is expected_metadata +@pytest.mark.parametrize("is_sm107", [True, False]) +def test_msa_metadata_builder_reserves_prefill_workspace_only_on_sm107( + monkeypatch: pytest.MonkeyPatch, + is_sm107: bool, +) -> None: + monkeypatch.setattr( + MiniMaxM3SparseMetadataBuilder, "__init__", lambda *args, **kwargs: None + ) + monkeypatch.setattr( + current_platform, + "is_device_capability", + lambda capability: is_sm107 and capability == 107, + ) + vllm_config = SimpleNamespace( + model_config=SimpleNamespace( + hf_text_config=SimpleNamespace( + num_attention_heads=16, + sparse_attention_config={"sparse_topk_blocks": TOPK}, + ) + ), + parallel_config=SimpleNamespace(tensor_parallel_size=1), + cache_config=SimpleNamespace(cache_dtype="nvfp4"), + attention_config=SimpleNamespace(minimax_m3_msa_decode_backend="cutlass"), + scheduler_config=SimpleNamespace(max_num_batched_tokens=256), + ) + + builder = MiniMaxM3SparseMSAMetadataBuilder( + SimpleNamespace(num_kv_heads=1), [], vllm_config, torch.device("cuda") + ) + + assert (builder.prefill_workspace is not None) == is_sm107 + + def test_msa_cutlass_plan_cache_keys_query_len( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -382,7 +443,7 @@ def fake_build_plan(**kwargs): assert built_query_lens == [1, 2] -def test_query_fp8_stays_valid_when_cutlass_plan_appears_on_replay( +def test_query_stays_valid_when_cutlass_plan_appears_on_replay( monkeypatch: pytest.MonkeyPatch, ) -> None: import vllm.envs as envs @@ -430,20 +491,21 @@ def test_query_fp8_stays_valid_when_cutlass_plan_appears_on_replay( observed_ptrs: list[int] = [] @eager_break_during_capture - def run_attention(query_fp8: torch.Tensor | None) -> None: + def run_attention(query: torch.Tensor) -> None: if impl.should_use_msa_decode(layer_name): - assert query_fp8 is not None - observed_ptrs.append(query_fp8.data_ptr()) + assert query.dtype == torch.float8_e4m3fn + observed_ptrs.append(query.data_ptr()) stream = torch.cuda.Stream() with torch.cuda.stream(stream), override_forward_context(forward_context): capture = BreakableCUDAGraphCapture() with capture: - query_fp8 = MiniMaxM3SparseAttention._allocate_query_fp8(attention, qkv) - if query_fp8 is not None: - query_fp8.zero_() - run_attention(query_fp8) + query = MiniMaxM3SparseAttention._allocate_query( + attention, num_tokens, qkv.dtype, qkv.device + ) + query.zero_() + run_attention(query) qkv.zero_() assert capture.num_graphs == 2 @@ -797,18 +859,18 @@ def _make_nvfp4_kv_cache( return kv_cache, torch.cat(dequantized, dim=-1).to(torch.bfloat16) -def _e4m3_staged_kv_reference( +def _q8kv4_kv_reference( kv_reference: torch.Tensor, k_scale: torch.Tensor, v_scale: torch.Tensor ) -> torch.Tensor: - """The dequantized NVFP4 cache as an E4M3-query kernel reads it: each - code * block_scale rounded to E4M3, then the global scale.""" + """The dequantized cache as the Q8KV4 kernels read it: block scales staged + by 2**NVFP4_BLOCK_SCALE_SHIFT, and each code * block_scale rounded to E4M3 + for the FP8 tensor core.""" sides = [] for side, global_scale in zip( kv_reference.float().split(HEAD_DIM, dim=-1), (k_scale, v_scale) ): - sides.append( - (side / global_scale).to(torch.float8_e4m3fn).float() * global_scale - ) + unit = global_scale * 2.0**NVFP4_BLOCK_SCALE_SHIFT + sides.append((side / unit).to(torch.float8_e4m3fn).float() * unit) return torch.cat(sides, dim=-1).to(torch.bfloat16) @@ -862,6 +924,8 @@ def test_nvfp4_kv_cache_views_address_head_slots() -> None: pytest.param(64, 4, 1, 1, True, id="tp1-small-batch-query-len-1"), pytest.param(64, 4, 8, 8, False, id="tp1-query-len-8"), pytest.param(16, 1, 16, 4, True, id="tp4-query-len-4"), + # 1024 x 8 x 16 = 131072 query-head rows, past the kv_mode 3 work list. + pytest.param(16, 1, 512, 8, True, id="tp4-query-len-8-1024-requests"), ], ) def test_msa_cutlass_decode_nvfp4_matches_triton_on_dequantized_cache( @@ -871,8 +935,9 @@ def test_msa_cutlass_decode_nvfp4_matches_triton_on_dequantized_cache( query_len: int, capture: bool, ) -> None: - """CUTLASS decode reads vLLM's packed NVFP4 pages, including swizzled V - scales and device global scales, as their exact dequantized values.""" + """Q8KV4 decode reads vLLM's packed NVFP4 pages, including swizzled V + scales and device global scales, as their exact dequantized values, and a + reused plan follows new lengths and zero-length padding requests.""" torch.manual_seed(0) seq_lens_list = [257, 513] * num_request_pairs seq_lens_cpu = torch.tensor(seq_lens_list, dtype=torch.int32) @@ -890,18 +955,27 @@ def test_msa_cutlass_decode_nvfp4_matches_triton_on_dequantized_cache( ) query_fp8 = query.to(torch.float8_e4m3fn) topk = _make_topk(seq_lens_list, num_kv_heads, query_len) - expected = torch.empty_like(query) - minimax_m3_sparse_attn_decode( - query_fp8.to(torch.bfloat16), - kv_reference, - topk.transpose(0, 1), - block_table, - seq_lens, - num_kv_heads, - SM_SCALE, - expected, - query_len, - ) + kv_reference = _q8kv4_kv_reference(kv_reference, k_scale, v_scale) + + def reference(lens: list[int]) -> torch.Tensor: + # Padding requests (length 0) trail the batch and are not compared. + num_reqs = sum(1 for n in lens if n > 0) + rows = num_reqs * query_len + expected = torch.empty_like(query[:rows]) + minimax_m3_sparse_attn_decode( + query_fp8[:rows].to(torch.bfloat16), + kv_reference, + topk[:rows].transpose(0, 1), + block_table[:num_reqs], + seq_lens[:num_reqs], + num_kv_heads, + SM_SCALE, + expected, + query_len, + ) + return expected + + expected = reference(seq_lens_list) assert should_prepare_decode_metadata( len(seq_lens_list), @@ -913,16 +987,24 @@ def test_msa_cutlass_decode_nvfp4_matches_triton_on_dequantized_cache( page_size=BLOCK_SIZE, topk_blocks=TOPK, ) - metadata = prepare_decode_metadata( - block_table, - seq_lens, - seq_lens_cpu, - query_len, - num_q_heads=num_q_heads, - num_kv_heads=num_kv_heads, - page_size=BLOCK_SIZE, - topk_blocks=TOPK, - ) + plan_cache = MSACutlassDecodePlanCache() + + def prepare(lens_cpu: torch.Tensor): + return prepare_decode_metadata( + block_table, + seq_lens, + lens_cpu, + query_len, + num_q_heads=num_q_heads, + num_kv_heads=num_kv_heads, + page_size=BLOCK_SIZE, + topk_blocks=TOPK, + q8kv4=True, + plan_cache=plan_cache, + ) + + metadata = prepare(seq_lens_cpu) + assert "q8kv4" in metadata.plan[3] actual = torch.zeros_like(query) def run() -> None: @@ -940,6 +1022,7 @@ def run() -> None: v_scale=v_scale, ) + graph = None if capture: run() graph = torch.cuda.CUDAGraph() @@ -952,6 +1035,25 @@ def run() -> None: current_platform.synchronize() torch.testing.assert_close(actual, expected, atol=0.05, rtol=0.05) + # Next step on the same plan: shorter requests and, as a padded full CUDA + # graph batch has, a trailing zero-length request. + updated_seq_lens_list = [129, 385] * num_request_pairs + updated_seq_lens_list[-1] = 0 + seq_lens.copy_(torch.tensor(updated_seq_lens_list, dtype=torch.int32)) + topk.copy_(_make_topk(updated_seq_lens_list, num_kv_heads, query_len)) + updated_metadata = prepare(torch.tensor(updated_seq_lens_list, dtype=torch.int32)) + assert updated_metadata.plan is metadata.plan + expected = reference(updated_seq_lens_list) + actual.zero_() + if graph is not None: + graph.replay() + else: + run() + current_platform.synchronize() + torch.testing.assert_close( + actual[: expected.shape[0]], expected, atol=0.05, rtol=0.05 + ) + def _make_prefill_metadata( q_lens: list[int], @@ -1008,13 +1110,13 @@ def _make_prefill_metadata( [pytest.param(64, 4, id="tp1"), pytest.param(16, 1, id="tp4")], ) def test_msa_prefill_nvfp4_matches_triton_on_dequantized_cache( - monkeypatch: pytest.MonkeyPatch, num_q_heads: int, num_kv_heads: int, ) -> None: - """MSA prefill reads NVFP4 pages as their dequantized values, staged to E4M3 - for the E4M3 q, including chunked prefill over cached context; it attends - with the fp8 q (the only one the fused insert writes on this path).""" + """MSA prefill reads NVFP4 pages as their exact dequantized values, + including chunked prefill over cached context, with the fp8 q the fused + insert writes (the only q it writes on this path), on the CUTLASS Q8KV4 + kernel.""" torch.manual_seed(0) q_lens = [300, 128, 77] seq_lens_list = [300, 640, 1100] @@ -1025,10 +1127,10 @@ def test_msa_prefill_nvfp4_matches_triton_on_dequantized_cache( num_pages, num_kv_heads, "nvfp4", k_scale, v_scale ) + total_q = sum(q_lens) metadata, topk = _make_prefill_metadata( q_lens, seq_lens_list, block_table, num_kv_heads ) - total_q = sum(q_lens) layer_name = "model.layers.0.self_attn.attn" q_scale = 0.5 @@ -1046,7 +1148,7 @@ def test_msa_prefill_nvfp4_matches_triton_on_dequantized_cache( / q_scale ).to(torch.float8_e4m3fn) query = query_fp8.to(torch.bfloat16) * q_scale - kv_reference = _e4m3_staged_kv_reference(kv_reference, k_scale, v_scale) + kv_reference = _q8kv4_kv_reference(kv_reference, k_scale, v_scale) common = dict( num_heads=num_q_heads, head_size=HEAD_DIM, @@ -1055,7 +1157,6 @@ def test_msa_prefill_nvfp4_matches_triton_on_dequantized_cache( topk_blocks=TOPK, sparse_block_size=BLOCK_SIZE, ) - query_dtypes = _record_query_dtypes(monkeypatch, "sparse_atten_nvfp4_kv_func") forward_context = ForwardContext( no_compile_layers={}, attn_metadata={layer_name: metadata}, @@ -1065,100 +1166,97 @@ def test_msa_prefill_nvfp4_matches_triton_on_dequantized_cache( expected = MiniMaxM3SparseTritonImpl(**common).forward( layer, query, kv_reference, torch.empty_like(query) ) - actual = MiniMaxM3SparseMSAImpl(**common, kv_cache_dtype="nvfp4").forward( - layer, - torch.full_like(query, float("nan")), - kv_cache, - torch.zeros_like(query), - query_fp8=query_fp8, + # As the model calls it for NVFP4: the fp8 q is the only query. + actual = MiniMaxM3SparseMSANvfp4Impl(**common).forward( + layer, query_fp8, kv_cache, torch.zeros_like(query) ) current_platform.synchronize() - assert query_dtypes == [torch.float8_e4m3fn] _assert_close_fp8_prefill(actual, expected) -def test_msa_triton_decode_fallback_reads_dequantized_query_fp8() -> None: - """With CUTLASS decode on but not planned for the batch, the Triton decode - fallback attends with the dequantized fp8 q, the only q written.""" +@pytest.mark.parametrize( + ("num_q_heads", "num_kv_heads"), + [pytest.param(64, 4, id="tp1"), pytest.param(16, 1, id="tp4")], +) +def test_msa_prefill_nvfp4_uses_the_builders_workspace( + num_q_heads: int, + num_kv_heads: int, +) -> None: + """The NVFP4 prefill hands the builder's split workspace to ``run_prefill``: + a workspace reserved for the step's token budget is neither replaced nor + grown by the call, and the output equals the per-call-allocation path's.""" + from vllm.third_party.fmha_sm100.prefill_q8kv4 import PrefillWorkspace + torch.manual_seed(0) - num_q_heads, num_kv_heads, q_scale = 16, 1, 0.5 - seq_lens_list = [257, 513, 129] - seq_lens = torch.tensor(seq_lens_list, dtype=torch.int32, device="cuda") + q_lens = [300, 128, 77] + seq_lens_list = [300, 640, 1100] block_table, num_pages = _make_paged_layout(seq_lens_list) - kv_cache = ( - torch.randn( - num_pages, - num_kv_heads, - BLOCK_SIZE, - 2 * HEAD_DIM, - dtype=torch.bfloat16, - device="cuda", - ) - * 0.25 - ).to(torch.float8_e4m3fn) - num_tokens = len(seq_lens_list) - metadata = MiniMaxM3SparseMetadata( - seq_lens=seq_lens, - max_seq_len=max(seq_lens_list), - slot_mapping=torch.empty(num_tokens, dtype=torch.int64, device="cuda"), - num_actual_tokens=num_tokens, - num_decodes=num_tokens, - num_decode_tokens=num_tokens, - num_prefills=0, - num_prefill_tokens=0, - decode=MiniMaxM3SparseMSADecodeMetadata( - seq_lens=seq_lens, - block_table=block_table, - decode_query_len=1, - msa_cutlass=None, + k_scale = torch.tensor(1.0, dtype=torch.float32, device="cuda") + v_scale = torch.tensor(1.0, dtype=torch.float32, device="cuda") + kv_cache, _ = _make_nvfp4_kv_cache( + num_pages, num_kv_heads, "nvfp4", k_scale, v_scale + ) + metadata, topk = _make_prefill_metadata( + q_lens, seq_lens_list, block_table, num_kv_heads + ) + total_q = sum(q_lens) + max_num_batched_tokens = 2048 + workspace = PrefillWorkspace(torch.device("cuda"), block_scale_shift=0) + workspace.split_buffers(TOPK, max_num_batched_tokens, num_q_heads) + reserved = workspace.split_buffers(TOPK, total_q, num_q_heads)[0].data_ptr() + assert isinstance(metadata.prefill, MiniMaxM3SparsePrefillMetadata) + with_workspace = replace( + metadata, + prefill=MiniMaxM3SparseMSAPrefillMetadata( + **{ + f.name: getattr(metadata.prefill, f.name) + for f in fields(metadata.prefill) + }, + workspace=workspace, ), ) + layer_name = "model.layers.0.self_attn.attn" layer = SimpleNamespace( layer_name=layer_name, - topk_indices_buffer=_make_topk(seq_lens_list, num_kv_heads, 1), - _q_scale_float=q_scale, + topk_indices_buffer=topk, + _q_scale_float=1.0, + _k_scale=k_scale, + _v_scale=v_scale, ) query_fp8 = torch.randn( - num_tokens, num_q_heads * HEAD_DIM, dtype=torch.bfloat16, device="cuda" + total_q, num_q_heads * HEAD_DIM, dtype=torch.bfloat16, device="cuda" ).to(torch.float8_e4m3fn) - query = query_fp8.to(torch.bfloat16) * q_scale - common = dict( + impl = MiniMaxM3SparseMSANvfp4Impl( num_heads=num_q_heads, head_size=HEAD_DIM, scale=SM_SCALE, num_kv_heads=num_kv_heads, - kv_cache_dtype="fp8", topk_blocks=TOPK, sparse_block_size=BLOCK_SIZE, ) - impl = MiniMaxM3SparseMSAImpl(**common, msa_decode_backend="cutlass") - assert impl.use_cutlass_decode - forward_context = ForwardContext( - no_compile_layers={}, - attn_metadata={layer_name: metadata}, - slot_mapping={}, - ) - with override_forward_context(forward_context): - expected = MiniMaxM3SparseTritonImpl(**common).forward( - layer, query, kv_cache, torch.empty_like(query) + outputs = [] + for md in (metadata, with_workspace): + forward_context = ForwardContext( + no_compile_layers={}, + attn_metadata={layer_name: md}, + slot_mapping={}, ) - actual = impl.forward( - layer, - torch.full_like(query, float("nan")), - kv_cache, - torch.zeros_like(query), - query_fp8=query_fp8, + output = torch.zeros( + total_q, num_q_heads * HEAD_DIM, dtype=torch.bfloat16, device="cuda" ) + with override_forward_context(forward_context): + outputs.append(impl.forward(layer, query_fp8, kv_cache, output)) current_platform.synchronize() - torch.testing.assert_close(actual, expected, atol=0.02, rtol=0.02) + assert torch.equal(outputs[0], outputs[1]) + assert workspace.split_buffers(TOPK, total_q, num_q_heads)[0].data_ptr() == reserved @pytest.mark.parametrize( ("num_q_heads", "num_kv_heads"), [pytest.param(64, 4, id="tp1"), pytest.param(16, 1, id="tp4")], ) -def test_msa_prefill_reads_query_fp8_over_fp8_cache( +def test_msa_prefill_reads_the_e4m3_query_over_an_fp8_cache( monkeypatch: pytest.MonkeyPatch, num_q_heads: int, num_kv_heads: int, @@ -1219,13 +1317,126 @@ def test_msa_prefill_reads_query_fp8_over_fp8_cache( expected = MiniMaxM3SparseTritonImpl(**common).forward( layer, query, kv_cache, torch.empty_like(query) ) - actual = impl.forward( - layer, - torch.full_like(query, float("nan")), - kv_cache, - torch.zeros_like(query), - query_fp8=query_fp8, - ) + # As the model calls it: the fp8 q is the only query the insert wrote. + actual = impl.forward(layer, query_fp8, kv_cache, torch.zeros_like(query)) current_platform.synchronize() assert query_dtypes == [torch.float8_e4m3fn] _assert_close_fp8_prefill(actual, expected) + + +def test_nvfp4_kv_cache_never_takes_a_bf16_query() -> None: + """NVFP4 attention always reads an E4M3 q on the CUTLASS Q8KV4 kernels, and + a head layout either kernel cannot serve fails at init.""" + assert uses_q8kv4_decode(kv_cache_dtype="nvfp4", num_q_heads=16, num_kv_heads=1) + assert not uses_q8kv4_decode( + kv_cache_dtype="fp8_e4m3", num_q_heads=16, num_kv_heads=1 + ) + with pytest.raises(ValueError, match="Q8KV4"): + uses_q8kv4_decode(kv_cache_dtype="nvfp4", num_q_heads=4, num_kv_heads=1) + # 8 Q heads per KV head (TP8) decodes on Q8KV4, but Q8KV4 cannot prefill it. + with pytest.raises(ValueError, match="CUTLASS Q8KV4 prefill"): + MiniMaxM3SparseMSANvfp4Impl( + num_heads=8, + head_size=HEAD_DIM, + scale=SM_SCALE, + num_kv_heads=1, + topk_blocks=TOPK, + sparse_block_size=BLOCK_SIZE, + ) + + +@pytest.mark.parametrize( + "architecture", + ["MiniMaxM3SparseForCausalLM", "MiniMaxM3SparseForConditionalGeneration"], +) +def test_nvfp4_kv_cache_with_tp8_fails_at_config_time(architecture: str) -> None: + """An NVFP4 KV cache needs 16 query heads per KV head on each rank: the config + check rejects TP8 (8 per KV head) before the workers start; TP1/2/4 and other + KV cache dtypes pass.""" + from vllm.model_executor.models.config import MODELS_CONFIG_MAP + + def vllm_config(tensor_parallel_size: int, cache_dtype: str) -> SimpleNamespace: + text_config = SimpleNamespace(num_attention_heads=64, num_key_value_heads=4) + return SimpleNamespace( + model_config=SimpleNamespace(hf_text_config=text_config), + cache_config=SimpleNamespace(cache_dtype=cache_dtype), + parallel_config=SimpleNamespace(tensor_parallel_size=tensor_parallel_size), + ) + + verify = MODELS_CONFIG_MAP[architecture].verify_and_update_config + for tensor_parallel_size in (1, 2, 4): + verify(vllm_config(tensor_parallel_size, "nvfp4")) + verify(vllm_config(8, "fp8")) + with pytest.raises(ValueError, match="NVFP4 KV cache with tensor_parallel_size=8"): + verify(vllm_config(8, "nvfp4")) + + +def test_msa_triton_decode_fallback_reads_dequantized_query_fp8() -> None: + """With CUTLASS decode on but not planned for the batch, the Triton decode + fallback attends with the dequantized E4M3 query.""" + torch.manual_seed(0) + num_q_heads, num_kv_heads, q_scale = 16, 1, 0.5 + seq_lens_list = [257, 513, 129] + seq_lens = torch.tensor(seq_lens_list, dtype=torch.int32, device="cuda") + block_table, num_pages = _make_paged_layout(seq_lens_list) + kv_cache = ( + torch.randn( + num_pages, + num_kv_heads, + BLOCK_SIZE, + 2 * HEAD_DIM, + dtype=torch.bfloat16, + device="cuda", + ) + * 0.25 + ).to(torch.float8_e4m3fn) + num_tokens = len(seq_lens_list) + metadata = MiniMaxM3SparseMetadata( + seq_lens=seq_lens, + max_seq_len=max(seq_lens_list), + slot_mapping=torch.empty(num_tokens, dtype=torch.int64, device="cuda"), + num_actual_tokens=num_tokens, + num_decodes=num_tokens, + num_decode_tokens=num_tokens, + num_prefills=0, + num_prefill_tokens=0, + decode=MiniMaxM3SparseMSADecodeMetadata( + seq_lens=seq_lens, + block_table=block_table, + decode_query_len=1, + msa_cutlass=None, + ), + ) + layer_name = "model.layers.0.self_attn.attn" + layer = SimpleNamespace( + layer_name=layer_name, + topk_indices_buffer=_make_topk(seq_lens_list, num_kv_heads, 1), + _q_scale_float=q_scale, + ) + query_fp8 = torch.randn( + num_tokens, num_q_heads * HEAD_DIM, dtype=torch.bfloat16, device="cuda" + ).to(torch.float8_e4m3fn) + query = query_fp8.to(torch.bfloat16) * q_scale + common = dict( + num_heads=num_q_heads, + head_size=HEAD_DIM, + scale=SM_SCALE, + num_kv_heads=num_kv_heads, + kv_cache_dtype="fp8", + topk_blocks=TOPK, + sparse_block_size=BLOCK_SIZE, + ) + impl = MiniMaxM3SparseMSAImpl(**common, msa_decode_backend="cutlass") + assert impl.use_cutlass_decode + forward_context = ForwardContext( + no_compile_layers={}, + attn_metadata={layer_name: metadata}, + slot_mapping={}, + ) + with override_forward_context(forward_context): + expected = MiniMaxM3SparseTritonImpl(**common).forward( + layer, query, kv_cache, torch.empty_like(query) + ) + actual = impl.forward(layer, query_fp8, kv_cache, torch.zeros_like(query)) + current_platform.synchronize() + torch.testing.assert_close(actual, expected, atol=0.02, rtol=0.02) diff --git a/tests/kernels/attention/test_minimax_m3_norm_rope_nvfp4_insert.py b/tests/kernels/attention/test_minimax_m3_norm_rope_nvfp4_insert.py new file mode 100644 index 000000000000..2d7572de52e3 --- /dev/null +++ b/tests/kernels/attention/test_minimax_m3_norm_rope_nvfp4_insert.py @@ -0,0 +1,209 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""The fused FlyDSL norm + RoPE + NVFP4 insert against the HIP norm + RoPE +kernel followed by the reference NVFP4 inserts: every output byte, stale page +bytes included, and qkv left untouched.""" + +import pytest +import torch + +from vllm.platforms import current_platform + +if not current_platform.is_rocm(): + pytest.skip("ROCm (gfx950) FlyDSL kernel", allow_module_level=True) + +from vllm.platforms.rocm import on_gfx950 # noqa: E402 + +if not on_gfx950(): + pytest.skip("gfx950 instructions", allow_module_level=True) + +from tests.kernels.attention.minimax_m3_nvfp4_ref import ( # noqa: E402 + insert_nvfp4_index, + insert_nvfp4_kv, +) +from vllm import _custom_ops as ops # noqa: E402 +from vllm.models.minimax_m3.amd.ops.norm_rope_nvfp4_insert.host import ( # noqa: E402 + minimax_m3_norm_rope_nvfp4_insert, +) + +D = 128 +BLK = 128 +EPS = 1e-6 +ROT = 64 + + +def _request_slots(starts, lens, num_pages, gen): + """VLLM's slot mapping: request r's tokens at positions starts[r].. of its + own random pages.""" + perm = torch.randperm(num_pages, generator=gen) + out, p = [], 0 + for st, n in zip(starts, lens): + npg = (st + n + BLK - 1) // BLK + pos = torch.arange(st, st + n) + out.append(perm[p : p + npg][pos // BLK] * BLK + pos % BLK) + p += npg + return torch.cat(out) if out else torch.empty(0, dtype=torch.int64) + + +class _Batch: + def __init__(self, starts, lens, pad, heads, scales, seed=0): + g = torch.Generator().manual_seed(seed) + self.nq, self.nkv, self.niq = heads + n = self.n = sum(lens) + pad + row = (self.nq + 2 * self.nkv + self.niq + 1) * D + # magnitudes 1e-3 .. 3e3 per 16-value group, some all-zero groups + x = torch.randn(n, row // 16, 16, generator=g) + mags = torch.tensor([1e-3, 0.05, 1.0, 1.0, 30.0, 3e3]) + x *= mags[torch.randint(0, len(mags), (n, row // 16), generator=g)][..., None] + x[torch.rand(n, row // 16, generator=g) < 0.02] = 0.0 + self.qkv = x.view(n, row).to(torch.bfloat16).cuda() + self.w = [ + (torch.randn(D, generator=g) * 0.5).to(torch.bfloat16).cuda() + for _ in range(4) + ] + self.cs = (torch.rand(4096, ROT, generator=g) * 2 - 1).to(torch.bfloat16).cuda() + self.pos = torch.randint(0, 4096, (n,), generator=g).cuda() + pages = sum((s + m + BLK - 1) // BLK for s, m in zip(starts, lens)) + 2 + pad_slots = torch.full((pad,), -1, dtype=torch.int64) + self.slots = torch.cat( + [_request_slots(starts, lens, pages, g), pad_slots] + ).cuda() + self.islots = torch.cat( + [_request_slots(starts, lens, pages, g), pad_slots] + ).cuda() + # stale bytes; the layer views have a block stride past one page + main = 2 * self.nkv * BLK * 72 + self.kv_full = torch.randint(0, 256, (pages, main + 256), generator=g) + self.kv_full = self.kv_full.to(torch.uint8).cuda() + self.idx_full = torch.randint(0, 256, (pages, BLK * 72 + 64), generator=g) + self.idx_full = self.idx_full.to(torch.uint8).cuda() + self.ks = torch.tensor(scales[0], dtype=torch.float32, device="cuda") + self.vs = torch.tensor(scales[1], dtype=torch.float32, device="cuda") + + def kv(self, full): + return full[:, : 2 * self.nkv * BLK * 72].view(-1, 2 * self.nkv, BLK, 72) + + def idx(self, full): + return full[:, : BLK * 72].view(-1, BLK, 72) + + def reference(self): + qkv = self.qkv.clone() + q = torch.empty(self.n, self.nq * D, dtype=torch.bfloat16, device="cuda") + iq = torch.empty(self.n, self.niq * D, dtype=torch.float8_e4m3fn, device="cuda") + kv_full, idx_full = self.kv_full.clone(), self.idx_full.clone() + ops.fused_minimax_m3_qknorm_rope_kv_insert( + qkv, self.w[0], self.w[1], self.cs, self.pos, self.nq, self.nkv, ROT, + EPS, self.w[2], self.w[3], self.niq, q_out=q, index_q_out=iq, + ) # fmt: skip + k0, v0 = self.nq * D, (self.nq + self.nkv) * D + ik0 = (self.nq + 2 * self.nkv + self.niq) * D + insert_nvfp4_kv( + qkv[:, k0:v0].view(self.n, self.nkv, D), + qkv[:, v0 : v0 + self.nkv * D].view(self.n, self.nkv, D), + self.kv(kv_full), + self.slots, + self.ks, + self.vs, + ) + insert_nvfp4_index(self.idx(idx_full), qkv[:, ik0 : ik0 + D], self.islots) + return q, iq, kv_full, idx_full + + def run(self, qkv, pos, slots, islots, kv_full, idx_full, q, iq): + minimax_m3_norm_rope_nvfp4_insert( + qkv, *self.w, self.cs, pos, slots, islots, self.kv(kv_full), + self.idx(idx_full), self.ks, self.vs, q, iq, num_heads=self.nq, + num_kv_heads=self.nkv, num_index_heads=self.niq, eps=EPS, + ) # fmt: skip + + def fused(self, iq): + qkv = self.qkv.clone() + q = torch.empty(self.n, self.nq * D, dtype=torch.bfloat16, device="cuda") + kv_full, idx_full = self.kv_full.clone(), self.idx_full.clone() + self.run(qkv, self.pos, self.slots, self.islots, kv_full, idx_full, q, iq) + assert torch.equal(qkv.view(torch.int16), self.qkv.view(torch.int16)) + return q, kv_full, idx_full + + +def _check(batch, iq_mode="contiguous"): + q_ref, iq_ref, kv_ref, idx_ref = batch.reference() + n, w = batch.n, batch.niq * D + if iq_mode == "rank": # the context-parallel indexer's [4, n, 128] buffer + buf = torch.full((4, n, w), 0x7F, dtype=torch.uint8, device="cuda") + iq = buf[2] + elif iq_mode == "cols": + buf = torch.full((n, 3 * w), 0x7F, dtype=torch.uint8, device="cuda") + iq = buf[:, w : 2 * w] + else: + buf = iq = torch.full((n, w), 0x7F, dtype=torch.uint8, device="cuda") + q, kv, idx = batch.fused(iq.view(torch.float8_e4m3fn)) + assert torch.equal(q.view(torch.int16), q_ref.view(torch.int16)) + assert torch.equal(iq, iq_ref.view(torch.uint8)) + assert torch.equal(kv, kv_ref) + assert torch.equal(idx, idx_ref) + iq.fill_(0x7F) + assert bool((buf == 0x7F).all()), "bytes outside index_q_out written" + + +TP4, TP1 = (16, 1, 1), (64, 4, 4) +DSPARK = ([3 + 9 * i for i in range(43)], [4] * 43) # 172 decode rows + + +@pytest.mark.parametrize("heads", [TP4, TP1]) +@pytest.mark.parametrize( + ("starts", "lens", "pad"), + [ + ([5], [1], 0), # one decode token + ([0, 13], [7, 4], 1), # a run of 7, runs across an octet edge + ([125, 254, 4091], [6, 6, 6], 12), # Q6 crossing page boundaries + (*DSPARK, 20), # DSpark decode rows, graph padding + ([0, 3, 250, 128], [131, 61, 9, 99], 0), # unaligned prefill chunks + ([0, 100], [4096, 4000], 3), # the prefill tier + ], +) +@pytest.mark.parametrize("scales", [(1.0, 1.0), (0.002, 3.0)]) +def test_matches_two_kernel_path(heads, starts, lens, pad, scales): + _check(_Batch(starts, lens, pad, heads, scales)) + + +@pytest.mark.parametrize("iq_mode", ["rank", "cols"]) +@pytest.mark.parametrize(("starts", "lens"), [DSPARK, ([7], [600])]) +def test_index_q_out_view(iq_mode, starts, lens): + _check(_Batch(starts, lens, 5, TP4, (1.0, 1.0)), iq_mode) + + +def test_64k_tokens(): + _check(_Batch([0, 777], [32768, 32768], 0, TP4, (1.0, 1.0))) + + +def test_all_padding(): + """A graph-capture dummy batch: every slot -1, the pages stay as they were.""" + batch = _Batch([], [], 64, TP4, (1.0, 1.0)) + _check(batch) + iq = torch.empty(batch.n, D, dtype=torch.float8_e4m3fn, device="cuda") + _, kv, idx = batch.fused(iq) + assert torch.equal(kv, batch.kv_full) and torch.equal(idx, batch.idx_full) + + +def test_cuda_graph_replay(): + """Captured once, replayed on new qkv / positions / slots in place.""" + a = _Batch(*DSPARK, 4, TP4, (1.0, 1.0), seed=1) + b = _Batch(*DSPARK, 4, TP4, (1.0, 1.0), seed=2) + b.w, b.cs = a.w, a.cs # captured with the layer's weights and RoPE cache + qkv, pos = a.qkv.clone(), a.pos.clone() + slots, islots = a.slots.clone(), a.islots.clone() + kv_full, idx_full = b.kv_full.clone(), b.idx_full.clone() + q = torch.empty(a.n, a.nq * D, dtype=torch.bfloat16, device="cuda") + iq = torch.empty(a.n, D, dtype=torch.float8_e4m3fn, device="cuda") + args = (qkv, pos, slots, islots, kv_full, idx_full, q, iq) + a.run(*args) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + a.run(*args) + new = (b.qkv, b.pos, b.slots, b.islots, b.kv_full, b.idx_full) + for dst, src in zip(args[:6], new): + dst.copy_(src) + graph.replay() + q_ref, iq_ref, kv_ref, idx_ref = b.reference() + assert torch.equal(q.view(torch.int16), q_ref.view(torch.int16)) + assert torch.equal(iq.view(torch.uint8), iq_ref.view(torch.uint8)) + assert torch.equal(kv_full, kv_ref) and torch.equal(idx_full, idx_ref) diff --git a/tests/kernels/attention/test_minimax_m3_nvfp4_index.py b/tests/kernels/attention/test_minimax_m3_nvfp4_index.py new file mode 100644 index 000000000000..3116e6a26b25 --- /dev/null +++ b/tests/kernels/attention/test_minimax_m3_nvfp4_index.py @@ -0,0 +1,422 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MiniMax-M3 NVFP4 index scorers (FlyDSL) against AITER's FP8 scorers and an +fp32 reference over the same e4m3 keys; the context-parallel push scorer +against the single-head scorer, bit for bit, on one GPU.""" + +import pytest +import torch + +from vllm.platforms import current_platform + +if not current_platform.is_rocm(): + pytest.skip("ROCm (gfx950) FlyDSL kernels", allow_module_level=True) + +from vllm.platforms.rocm import on_gfx950 # noqa: E402 + +if not on_gfx950(): + pytest.skip("gfx950 instructions", allow_module_level=True) + +from tests.kernels.attention.minimax_m3_nvfp4_ref import dequant # noqa: E402 +from vllm.models.minimax_m3.amd.ops.nvfp4_index_decode import ( # noqa: E402 + host as decode_host, +) +from vllm.models.minimax_m3.amd.ops.nvfp4_index_decode import ( # noqa: E402 + kernel_cp_push as cp, +) +from vllm.models.minimax_m3.amd.ops.nvfp4_index_prefill import ( # noqa: E402 + host as prefill_host, +) + +minimax_m3_nvfp4_index_score_decode = decode_host.minimax_m3_nvfp4_index_score_decode +minimax_m3_nvfp4_index_score_prefill = prefill_host.minimax_m3_nvfp4_index_score_prefill + +BLOCK = 128 +D = 128 +SPECIAL_LENS = [0, 1, 2, 3, 127, 128, 129, 1024] # padding, short and edge rows + + +def _index_cache(num_blocks: int, page_step: int = 1) -> torch.Tensor: + """Random NVFP4 index pages ``page_step`` pages apart (a view of a larger + cache).""" + n = num_blocks * page_step + cache = torch.randint(0, 256, (n, BLOCK * 72), device="cuda").to(torch.uint8) + s = torch.rand(n, BLOCK * 8, device="cuda") * 1.75 + 0.25 + cache[:, BLOCK * 64 :] = s.to(torch.float8_e4m3fn).view(torch.uint8) + return cache.view(n, BLOCK, 72)[::page_step] + + +def _fp8_keys(cache: torch.Tensor) -> torch.Tensor: + """Every page's keys as e4m3_rn_satfinite(e2m1 x scale), [nb, 128, 128].""" + flat = cache.reshape(cache.shape[0], -1) + keys = dequant( + flat[:, : BLOCK * 64].view(-1, BLOCK, 64), + flat[:, BLOCK * 64 :].view(-1, BLOCK, 8), + ) + return keys.clamp(-448, 448).to(torch.float8_e4m3fn) + + +def _block_table(seq_lens, share=False): + """Shuffled pages per request; ``share``: some requests start with another + request's pages (a shared prefix).""" + widths = [(s + BLOCK - 1) // BLOCK for s in seq_lens] + num_blocks = sum(widths) + 2 + perm = torch.randperm(num_blocks, device="cuda", dtype=torch.int32) + table = torch.zeros(len(seq_lens), max(widths), dtype=torch.int32, device="cuda") + start = 0 + for r, w in enumerate(widths): + table[r, :w] = perm[start : start + w] + start += w + for r in range(len(seq_lens) if share else 0): + src = 0 if r % 2 == 0 else 3 * (r // 6) + n = min(widths[r], widths[src], 10 if r % 2 == 0 else 6) + if r != src: + table[r, :n] = table[src, :n] + return table, num_blocks + + +def _lens(num_reqs: int, hi: int) -> list[int]: + lens = torch.randint(1, hi, (num_reqs,)).tolist() + for i, v in enumerate(SPECIAL_LENS[: num_reqs // 2]): + lens[2 * i + 1] = v + return lens + + +def _ref_block_scores(q_rows, keys, kv_lens, init_blocks, local_blocks): + """[H, R, nb] per-block max of q . k over each row's visible tokens, -inf + where none is visible, AITER's init (1e30) / local (1e29) sentinels.""" + nb = keys.shape[0] // BLOCK + dots = torch.einsum("rhd,td->hrt", q_rows.float(), keys) + tok = torch.arange(nb * BLOCK, device=keys.device) + dots = dots.masked_fill(tok[None, None, :] >= kv_lens[None, :, None], -torch.inf) + mx = dots.view(dots.shape[0], dots.shape[1], nb, BLOCK).amax(-1) + rb = (kv_lens.clamp(min=0) + BLOCK - 1) // BLOCK # visible blocks per row + blk = torch.arange(nb, device=keys.device)[None, :] + vis = blk < rb[:, None] + init = vis & (blk < init_blocks) + local = vis & (blk >= (rb - local_blocks).clamp(min=0)[:, None]) + mx = torch.where(init[None], torch.full_like(mx, 1e30), mx) + return torch.where(local[None], torch.full_like(mx, 1e29), mx) + + +def _assert_scores(got, want, msg=None): + """Sentinels and -inf identical; finite scores close.""" + exact = ~torch.isfinite(want) | (want >= 1e28) + assert torch.equal(got[exact], want[exact]), msg + torch.testing.assert_close(got[~exact], want[~exact], rtol=2e-4, atol=1e-3, msg=msg) + + +def _check_decode(actual, q, keys, table, lens, query_len, init_blocks, local_blocks): + """Each request's rows against the reference; nothing past its blocks + written.""" + for r, s in enumerate(lens): + nb = (s + BLOCK - 1) // BLOCK + sl = slice(r * query_len, (r + 1) * query_len) + assert actual[:, sl, nb:].isnan().all(), (r, s) + if nb == 0: + continue + kv_lens = (s - query_len + 1 + torch.arange(query_len, device="cuda")).clamp( + min=0 + ) + page_keys = keys[table[r, :nb].long()].reshape(-1, D) + want = _ref_block_scores(q[sl], page_keys, kv_lens, init_blocks, local_blocks) + _assert_scores(actual[:, sl, :nb], want, (r, s)) + + +@pytest.mark.parametrize( + ("num_heads", "query_len"), + [(1, 1), (1, 4), (1, 16), (2, 4), (4, 1), (4, 4), (4, 5), (4, 8)], +) +@pytest.mark.parametrize("page_step", [1, 2]) +def test_index_decode_matches_aiter_fp8(num_heads, query_len, page_step): + """Every block a row can see against AITER's FP8 decode scorer.""" + from aiter.ops.msa_attention import pa_sparse_block_score_decode + + torch.manual_seed(0) + lens = [5, 300, 2100, 9000] + table, num_blocks = _block_table(lens) + seq_lens = torch.tensor(lens, dtype=torch.int32, device="cuda") + cache = _index_cache(num_blocks, page_step) + rows = len(lens) * query_len + q = (torch.randn(rows, num_heads, D, device="cuda") * 0.5).to(torch.float8_e4m3fn) + width = (max(lens) + BLOCK - 1) // BLOCK + args = (table, seq_lens, 1, 2, query_len, max(lens)) + actual = torch.full((num_heads, rows, width), float("nan"), device="cuda") + minimax_m3_nvfp4_index_score_decode(q, cache, actual, *args) + expected = torch.full_like(actual, float("nan")) + pages = _fp8_keys(cache) + for h0 in range(0, num_heads, 2): # AITER builds one- and two-head scorers + pa_sparse_block_score_decode( + q[:, h0 : h0 + 2].contiguous(), pages, expected[h0 : h0 + 2], *args + ) + torch.accelerator.synchronize() + for r, s in enumerate(lens): + for t in range(query_len): + row = r * query_len + t + seen = (max(s - query_len + t + 1, 0) + BLOCK - 1) // BLOCK + got, want = actual[:, row, :seen], expected[:, row, :seen] + finite = want < 1e28 + assert torch.equal(got[~finite], want[~finite]) + torch.testing.assert_close(got[finite], want[finite], rtol=1e-5, atol=1e-4) + + +@pytest.mark.parametrize( + ("num_heads", "query_len"), [(1, 1), (1, 4), (2, 3), (4, 1), (4, 4), (4, 6), (4, 8)] +) +@pytest.mark.parametrize("num_reqs", [1, 40, 130]) +@pytest.mark.parametrize(("init_blocks", "local_blocks"), [(1, 2), (0, 1)]) +@pytest.mark.parametrize("buffered", [False, True]) +def test_index_decode_matches_reference( + num_heads, query_len, num_reqs, init_blocks, local_blocks, buffered, monkeypatch +): + """Request chunks, shared prefixes, padding requests, sequences shorter + than the query; ``buffered`` forces the LDS-buffered variant.""" + if buffered: + monkeypatch.setattr(decode_host, "BUFFER_MIN_BYTES", 0) + monkeypatch.setattr(decode_host, "UNITS_PER_SLOT", 1) + torch.manual_seed(num_reqs) + lens = _lens(num_reqs, 6000) + table, num_blocks = _block_table(lens, share=True) + seq_lens = torch.tensor(lens, dtype=torch.int32, device="cuda") + cache = _index_cache(num_blocks, 2 if num_reqs == 40 else 1) + rows = num_reqs * query_len + q = (torch.randn(rows, num_heads, D, device="cuda") * 0.5).to(torch.float8_e4m3fn) + width = (max(lens) + BLOCK - 1) // BLOCK + 2 + actual = torch.full((num_heads, rows, width), float("nan"), device="cuda") + minimax_m3_nvfp4_index_score_decode( + q, + cache, + actual, + table, + seq_lens, + init_blocks, + local_blocks, + query_len, + max(lens), + ) + keys = _fp8_keys(cache).float() + torch.accelerator.synchronize() + _check_decode(actual, q, keys, table, lens, query_len, init_blocks, local_blocks) + + +@pytest.mark.parametrize(("num_heads", "query_len"), [(1, 4), (4, 4)]) +def test_index_decode_graph_replays_new_lengths(num_heads, query_len): + """Captured once at a large max_seq_len, replayed with new lengths and + queries.""" + torch.manual_seed(5) + sets = [ + [140000, 6, 70001, 129, 7, 5000, 0, 128], + [6, 127, 2048, 140000, 40000, 300, 129, 0], + ] + table, num_blocks = _block_table([max(x) for x in zip(*sets)]) + cache = _index_cache(num_blocks) + seq_lens = torch.tensor(sets[0], dtype=torch.int32, device="cuda") + rows = len(sets[0]) * query_len + q = torch.zeros(rows, num_heads, D, device="cuda", dtype=torch.float8_e4m3fn) + max_seq_len = 1 << 18 + out = torch.empty(num_heads, rows, max_seq_len // BLOCK, device="cuda") + args = (q, cache, out, table, seq_lens, 1, 2, query_len, max_seq_len) + minimax_m3_nvfp4_index_score_decode(*args) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + minimax_m3_nvfp4_index_score_decode(*args) + keys = _fp8_keys(cache).float() + for lens in sets + sets[:1]: + seq_lens.copy_(torch.tensor(lens, dtype=torch.int32)) + q.copy_((torch.randn(q.shape, device="cuda") * 0.5).to(q.dtype)) + out.fill_(float("nan")) + graph.replay() + torch.accelerator.synchronize() + _check_decode(out, q, keys, table, lens, query_len, 1, 2) + + +def _check_cp_push(lens, page_step, init_blocks, local_blocks, grid): + """The context-parallel scorer on one GPU, the other ranks' index-q rows + and flags pre-set locally: per rank, the single-head scorer's bits on its + blocks, -inf past the length inside its last run, nothing elsewhere; the + four ranks cover every block once.""" + num_reqs = len(lens) + table, num_blocks = _block_table(lens, share=True) + seq_lens = torch.tensor(lens, dtype=torch.int32, device="cuda") + cache = _index_cache(num_blocks, page_step) + query_len, heads = cp.QL, cp.HEADS + rows = num_reqs * query_len + q = (torch.randn(rows, heads, D, device="cuda") * 0.5).to(torch.float8_e4m3fn) + max_seq_len = max(lens) + width = max(64, ((max_seq_len + BLOCK - 1) // BLOCK + 63) // 64 * 64) + expected = torch.full((heads, rows, width), float("nan"), device="cuda") + for h in range(heads): + decode_host.minimax_m3_nvfp4_index_score_decode( + q[:, h : h + 1], cache, expected[h : h + 1], table, seq_lens, + init_blocks, local_blocks, query_len, max_seq_len, + ) # fmt: skip + blocks = torch.arange(width, device="cuda") + nblk = ((seq_lens + BLOCK - 1) // BLOCK).repeat_interleave(query_len)[:, None] + seen = torch.zeros(heads, rows, width, dtype=torch.int32, device="cuda") + for rank in range(cp.WORLD): + counts = torch.zeros(cp.CNT_WORDS, dtype=torch.int32, device="cuda") + flags = torch.zeros(cp.FLAG_BYTES // 4, dtype=torch.int32, device="cuda") + flags[cp.SC_FLAGS : cp.SC_FLAGS + cp.WORLD] = 1 << 30 + flags[cp.SC_FLAGS + rank] = 0 + iq_buf = torch.full((heads, rows, D), 0x7F, dtype=torch.uint8, device="cuda") + iq_buf = iq_buf.view(torch.float8_e4m3fn) + for p in range(heads): + if p != rank: + iq_buf[p] = q[:, p] + w = cp.SC_IQ + p * cp.SC_MAX_REQS + flags[w : w + cp.SC_MAX_REQS] = 1 << 30 + outs = [] + for _ in range(2): + actual = torch.full_like(expected, float("nan")) + dests = [actual[h].data_ptr() for h in range(heads)] + decode_host.minimax_m3_nvfp4_index_score_push_cp( + q[:, rank].contiguous(), cache, dests, width, rows * width * 4, + table, seq_lens, init_blocks, local_blocks, rank, counts, + [flags.data_ptr()] * 4, [iq_buf.data_ptr()] * 4, rows, grid=grid, + ) # fmt: skip + outs.append(actual) + torch.accelerator.synchronize() + actual = outs[0] + assert torch.equal(actual.view(torch.int32), outs[1].view(torch.int32)) + mine = (blocks // cp.CP_CH) % cp.WORLD == rank + in_runs = mine & (blocks // cp.CP_CH * cp.CP_CH < nblk) + inside = in_runs & (blocks < nblk) + assert actual[:, ~in_runs].isnan().all(), rank + assert (actual[:, in_runs & ~inside] == float("-inf")).all(), rank + assert torch.equal( + actual[:, inside].view(torch.int32), expected[:, inside].view(torch.int32) + ), rank + seen += inside.int() + assert torch.equal(seen, (~expected.isnan()).int()) + + +@pytest.mark.parametrize("num_reqs", [1, 5, 17, 45]) +@pytest.mark.parametrize("page_step", [1, 2]) +@pytest.mark.parametrize(("init_blocks", "local_blocks"), [(1, 2), (0, 1)]) +@pytest.mark.parametrize("grid", [3, 768]) +def test_index_decode_cp_push_matches_single_head( + num_reqs, page_step, init_blocks, local_blocks, grid +): + """Grid 3: many runs and requests per workgroup.""" + torch.manual_seed(num_reqs) + _check_cp_push(_lens(num_reqs, 9000), page_step, init_blocks, local_blocks, grid) + + +@pytest.mark.parametrize("grid", [3, 768]) +def test_index_decode_cp_push_all_padding(grid): + """Padding requests only (graph capture): nothing written.""" + _check_cp_push([0] * 5, 1, 1, 2, grid) + + +def _prefill_case(q_lens, seq_lens_list, num_heads, page_step=1): + torch.manual_seed(0) + table, num_blocks = _block_table(seq_lens_list) + seq_lens = torch.tensor(seq_lens_list, dtype=torch.int32, device="cuda") + cu = torch.zeros(len(q_lens) + 1, dtype=torch.int32, device="cuda") + cu[1:] = torch.tensor(q_lens, dtype=torch.int32, device="cuda").cumsum(0) + cache = _index_cache(num_blocks, page_step) + q = torch.randn(sum(q_lens), num_heads, D, device="cuda") * 0.5 + return table, seq_lens, cu, cache, q.to(torch.float8_e4m3fn) + + +def _causal_blocks(q_len, s, num_heads): + """[H, q_len, nb] blocks each row of a chunk ending its sequence sees.""" + nb = (s + BLOCK - 1) // BLOCK + row_pos = s - q_len + torch.arange(q_len, device="cuda") + seen = torch.arange(nb, device="cuda")[None, :] <= (row_pos // BLOCK)[:, None] + return row_pos, seen[None].expand(num_heads, -1, -1) + + +@pytest.mark.parametrize("num_heads", [1, 2, 4]) +@pytest.mark.parametrize( + ("q_lens", "seq_lens_list"), + [ + ([129, 300, 5], [129, 2500, 2049]), # 128-row tiles, ragged + ([1000, 700], [4300, 700]), # 256-row tiles, unaligned prefix + ], +) +@pytest.mark.parametrize("page_step", [1, 2]) +def test_index_prefill_matches_aiter_fp8(num_heads, q_lens, seq_lens_list, page_step): + """Every block a row can see against AITER's FP8 prefill scorer.""" + from aiter.ops.msa_attention import pa_sparse_block_score_prefill + + table, seq_lens, cu, cache, q = _prefill_case( + q_lens, seq_lens_list, num_heads, page_step + ) + msl = max(seq_lens_list) + args = (table, cu, seq_lens, 1, 2, max(q_lens), msl) + width = (msl + BLOCK - 1) // BLOCK + actual = torch.full((num_heads, sum(q_lens), width), float("nan"), device="cuda") + minimax_m3_nvfp4_index_score_prefill(q, cache, actual, *args) + expected = torch.full_like(actual, float("nan")) + pages = _fp8_keys(cache) + for h in range(num_heads): + pa_sparse_block_score_prefill( + q[:, h : h + 1].contiguous(), pages, expected[h : h + 1], *args + ) + torch.accelerator.synchronize() + q_start = 0 + for q_len, s in zip(q_lens, seq_lens_list): + _, seen = _causal_blocks(q_len, s, num_heads) + rows = slice(q_start, q_start + q_len) + got = actual[:, rows, : seen.shape[2]][seen] + want = expected[:, rows, : seen.shape[2]][seen] + finite = want < 1e28 + assert torch.equal(got[~finite], want[~finite]) + torch.testing.assert_close(got[finite], want[finite], rtol=1e-5, atol=1e-4) + q_start += q_len + + +@pytest.mark.parametrize( + ("q_lens", "seq_lens_list"), + [ + ([4096], [4096]), # fresh prompt: every tile diagonal + ([2000, 513, 3000], [9000, 513, 20000]), # ragged, unaligned prefixes + ([700, 1500], [30000, 1500]), # long cached prefix + fresh + ], +) +@pytest.mark.parametrize(("init_blocks", "local_blocks"), [(0, 1), (2, 2)]) +@pytest.mark.parametrize("num_heads", [1, 2, 4]) +def test_index_prefill_matches_reference( + q_lens, seq_lens_list, init_blocks, local_blocks, num_heads, monkeypatch +): + """Every kernel the host can pick (``kernel_shared.py`` with 128- and + 256-row tiles, ``kernel.py``) bit for bit alike, and against an fp32 + reference.""" + table, seq_lens, cu, cache, q = _prefill_case( + q_lens, seq_lens_list, num_heads, page_step=2 if num_heads == 2 else 1 + ) + width = (max(seq_lens_list) + BLOCK - 1) // BLOCK + 3 + args = (table, cu, seq_lens, init_blocks, local_blocks) + args += (max(q_lens), max(seq_lens_list)) + + def run(shared, mq): + monkeypatch.setattr(prefill_host, "PIN_SHARED", shared) + monkeypatch.setattr(prefill_host, "PIN_MQ", mq) + out = torch.full((num_heads, sum(q_lens), width), float("nan"), device="cuda") + minimax_m3_nvfp4_index_score_prefill(q, cache, out, *args) + return out + + variants = [(True, 1), (True, 2), (False, None)] + outs = [run(*v) for v in variants] + keys = _fp8_keys(cache).float() + torch.accelerator.synchronize() + q_start = 0 + for req, (q_len, s) in enumerate(zip(q_lens, seq_lens_list)): + row_pos, seen = _causal_blocks(q_len, s, num_heads) + nb = seen.shape[2] + rows = slice(q_start, q_start + q_len) + for v, out in zip(variants[1:], outs[1:]): + got, ref = out[:, rows, :nb][seen], outs[0][:, rows, :nb][seen] + assert torch.equal(got, ref), (v, q_len, s) + page_keys = keys[table[req, :nb].long()].reshape(-1, D) + for r0 in range(0, q_len, 512): # [H, rows, tokens] dots in slices + r1 = min(q_len, r0 + 512) + want = _ref_block_scores( + q[q_start + r0 : q_start + r1], page_keys, row_pos[r0:r1] + 1, + init_blocks, local_blocks, + ) # fmt: skip + got = outs[0][:, q_start + r0 : q_start + r1, :nb] + sl = seen[:, r0:r1] + _assert_scores(got[sl], want[sl], (q_len, s)) + q_start += q_len diff --git a/tests/kernels/attention/test_minimax_m3_nvfp4_indexer_decode_cp.py b/tests/kernels/attention/test_minimax_m3_nvfp4_indexer_decode_cp.py new file mode 100644 index 000000000000..74eea8da6326 --- /dev/null +++ b/tests/kernels/attention/test_minimax_m3_nvfp4_indexer_decode_cp.py @@ -0,0 +1,129 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""NVFP4 indexer decode CP at TP4: each rank's top-k must equal an exact fp32 +top-15 over the full-context scores, across repeated runs (sentinel reset).""" + +import os + +import pytest +import torch +import torch.multiprocessing as mp + +from vllm.platforms import current_platform + +if not current_platform.is_cuda(): + pytest.skip("MiniMax M3 NVFP4 indexer requires CUDA.", allow_module_level=True) + +PAGE = 128 +SLOTS = 8 +H = 4 + + +def _cache(num_pages: int, gen: torch.Generator) -> torch.Tensor: + kv = torch.randint( + 0, 256, (num_pages, PAGE, 72), dtype=torch.uint8, device="cuda", generator=gen + ) + # Positive normal E4M3 block scales keep every score finite. + s = torch.rand(num_pages, PAGE * 8, device="cuda", generator=gen) * 1.75 + 0.25 + kv.view(num_pages, -1)[:, 8192:] = s.to(torch.float8_e4m3fn).view(torch.uint8) + return kv + + +def _reference(scores, seq_lens, query_len, head) -> torch.Tensor: + num_reqs = seq_lens.shape[0] + out = torch.full((num_reqs * query_len, 16), -1, dtype=torch.int32) + for b in range(num_reqs): + for i in range(query_len): + t = b * query_len + i + own = (int(seq_lens[b]) - query_len + i) // PAGE + if own + 1 <= 16: + out[t, : own + 1] = torch.arange(own + 1) + continue + row = scores[b, (SLOTS - query_len + i) * H + head, :own] + out[t, :15] = torch.sort(-row, stable=True).indices[:15].to(torch.int32) + out[t, 15] = own + return out + + +def _run(rank: int, port: int, query_len: int, seq_lens_list: list[int]) -> None: + from vllm.distributed import ( + init_distributed_environment, + initialize_model_parallel, + ) + from vllm.models.minimax_m3.nvidia.indexer_nvfp4_decode_cp import ( + Nvfp4IndexerDecodeCP, + ) + from vllm.third_party.fmha_sm100.sparse import BatchDecodeIndexerQ8KV4Wrapper + + torch.accelerator.set_device_index(rank) + init_distributed_environment( + world_size=4, + rank=rank, + local_rank=rank, + distributed_init_method=f"tcp://127.0.0.1:{port}", + ) + initialize_model_parallel(tensor_model_parallel_size=4) + + gen = torch.Generator(device="cuda").manual_seed(0) # same on every rank + seq_lens = torch.tensor(seq_lens_list, dtype=torch.int32, device="cuda") + num_reqs = seq_lens.shape[0] + pages = (int(seq_lens.max()) + PAGE - 1) // PAGE + kv = _cache(num_reqs * pages + 8, gen) + # Sized to the longest context, as vLLM's block table is: the longest + # request then owns the last page of its rank's compact table. + block_table = ( + torch.randperm(num_reqs * pages, device="cuda", generator=gen) + .to(torch.int32) + .view(num_reqs, pages) + ) + rows = num_reqs * query_len + + cp = Nvfp4IndexerDecodeCP(max_reqs=num_reqs, device=torch.device("cuda", rank)) + layers = [cp.new_layer() for _ in range(2)] + plan = cp.plan(block_table, seq_lens) + + full = BatchDecodeIndexerQ8KV4Wrapper(num_heads=H) + full.plan(block_table, seq_lens) + for step in range(3): + for layer in layers: + q = (torch.randn(rows, H, 128, device="cuda", generator=gen) * 0.5).to( + torch.float8_e4m3fn + ) + out = torch.full((rows, 1, 16), -7, dtype=torch.int32, device="cuda") + cp.forward( + layer, plan, q[:, rank : rank + 1].contiguous(), kv, out, query_len + ) + q_tile = torch.zeros( + num_reqs, SLOTS, H, 128, dtype=torch.float8_e4m3fn, device="cuda" + ) + q_tile[:, SLOTS - query_len :] = q.view(num_reqs, query_len, H, 128) + # NaN in the columns the kernel leaves alone, so a selection + # that reads one cannot match the reference. + full._scores.fill_(float("nan")) + scores = full._run_scores(q_tile.view(-1, H, 128), kv) + expected = _reference(scores.cpu(), seq_lens.cpu(), query_len, rank) + torch.testing.assert_close(out[:, 0].cpu(), expected, rtol=0, atol=0) + + +def _worker(rank: int, port: int, query_len: int, seq_lens_list: list[int]) -> None: + from vllm.config import ParallelConfig, VllmConfig, set_current_vllm_config + + config = VllmConfig(parallel_config=ParallelConfig(tensor_parallel_size=4)) + with set_current_vllm_config(config): + _run(rank, port, query_len, seq_lens_list) + + +@pytest.mark.skipif( + torch.accelerator.device_count() < 4 + or not ( + current_platform.is_device_capability(100) + or current_platform.is_device_capability(103) + ), + reason="Needs 4 SM100/SM103 GPUs.", +) +@pytest.mark.parametrize("query_len", [1, 4, 8]) +def test_nvfp4_indexer_decode_cp_matches_exact_topk(query_len: int): + # Trivial rows (<= 16 pages), page boundaries, and long contexts. + seq_lens = [9, 2049, 2048 + query_len, 20000, 131072, 300001] + port = 29500 + (os.getpid() % 1000) + mp.spawn(_worker, args=(port, query_len, seq_lens), nprocs=4, join=True) diff --git a/tests/kernels/attention/test_minimax_m3_nvfp4_prefill_flydsl.py b/tests/kernels/attention/test_minimax_m3_nvfp4_prefill_flydsl.py new file mode 100644 index 000000000000..8e3b368dba38 --- /dev/null +++ b/tests/kernels/attention/test_minimax_m3_nvfp4_prefill_flydsl.py @@ -0,0 +1,260 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MiniMax-M3 NVFP4 sparse prefill (FlyDSL) against fp64 attention over the +exactly dequantized K / V, and bitwise stable across runs and call splits.""" + +import pytest +import torch + +from vllm.platforms import current_platform + +if not current_platform.is_rocm(): + pytest.skip("ROCm (gfx950) FlyDSL kernel", allow_module_level=True) + +from vllm.platforms.rocm import on_gfx950 # noqa: E402 + +if not on_gfx950(): + pytest.skip("gfx950 instructions", allow_module_level=True) + +from tests.kernels.attention.minimax_m3_nvfp4_ref import ( # noqa: E402 + dequant, + insert_nvfp4_kv, + nvfp4_kv_cache_token_major, +) +from tests.kernels.mfma_spinner import mfma_spinner # noqa: E402 +from vllm.models.minimax_m3.amd.ops.nvfp4_prefill.host import ( # noqa: E402 + minimax_m3_nvfp4_sparse_prefill, + supports_nvfp4_sparse_prefill, +) + +BLOCK = 128 +D = 128 +GROUP = 16 # query heads per KV head +TOPK = 16 +SM_SCALE = D**-0.5 + + +def _case(q_lens, ctx_lens, hkv, k_scale, v_scale, seed=0): + """The last q_lens[i] of ctx_lens[i] tokens are queries; shuffled pages; + each token picks its own block and 15 random earlier ones.""" + gen = torch.Generator().manual_seed(seed) + nbs = [(c + BLOCK - 1) // BLOCK for c in ctx_lens] + n_pages = sum(nbs) + 2 + cache = torch.zeros(n_pages, 2 * hkv, BLOCK, 72, dtype=torch.uint8, device="cuda") + slots = torch.arange(n_pages * BLOCK, device="cuda") + k = (torch.randn(slots.numel(), hkv, D, generator=gen) * 2).bfloat16().cuda() + v = (torch.randn(slots.numel(), hkv, D, generator=gen) * 2).bfloat16().cuda() + insert_nvfp4_kv(k, v, cache, slots, k_scale, v_scale) + perm = torch.randperm(n_pages, generator=gen).int() + table = torch.zeros(len(q_lens), max(nbs), dtype=torch.int32) + off = 0 + for r, nb in enumerate(nbs): + table[r, :nb] = perm[off : off + nb] + off += nb + pos = torch.cat([torch.arange(c - q, c) for q, c in zip(q_lens, ctx_lens)]).int() + req = torch.cat([torch.full((q,), r) for r, q in enumerate(q_lens)]).int() + rows = [] + for _ in range(hkv): + for p in pos.tolist(): + cur = p // BLOCK + sel = torch.cat( + [torch.tensor([cur]), torch.randperm(cur, generator=gen)[: TOPK - 1]] + ) + rows.append(torch.cat([sel, torch.full((TOPK - sel.numel(),), -1)])) + topk = torch.stack(rows).int().view(hkv, pos.numel(), TOPK) + q = (torch.randn(pos.numel(), hkv * GROUP, D, generator=gen) * 2).bfloat16() + return cache, table.cuda(), topk.cuda(), q.cuda(), pos.cuda(), req.cuda() + + +def _prefill(q, cache, topk, table, req, pos, hkv, k_scale=None, v_scale=None): + out = torch.empty_like(q) + minimax_m3_nvfp4_sparse_prefill( + q, cache, topk, table, req, pos, hkv, SM_SCALE, out, k_scale=k_scale, + v_scale=v_scale, + ) # fmt: skip + return out + + +def _fp64(q, cache, topk, table, req, pos, hkv, k_scale, v_scale, rows): + """fp64 attention of the token rows ``rows`` over the dequantized K / V.""" + k_data, k_sf, v_data, v_sf = nvfp4_kv_cache_token_major(cache) + kv = [ + (dequant(data, sf) * s).to(torch.bfloat16).double() # [pages, hkv, 128, 128] + for data, sf, s in ((k_data, k_sf, k_scale), (v_data, v_sf, v_scale)) + ] + ref = torch.empty(len(rows), hkv * GROUP, D, dtype=torch.float64, device="cuda") + for i, r in enumerate(rows): + for h in range(hkv): + blocks = [b for b in topk[h, r].tolist() if b >= 0] + pages = [int(table[int(req[r]), b]) for b in blocks] + kk = torch.cat([kv[0][p, h] for p in pages]) + vv = torch.cat([kv[1][p, h] for p in pages]) + key_pos = torch.cat( + [torch.arange(b * BLOCK, (b + 1) * BLOCK) for b in blocks] + ).cuda() + s = (q[r, h * GROUP : (h + 1) * GROUP].double() @ kk.T) * SM_SCALE + s[:, key_pos > int(pos[r])] = float("-inf") + ref[i, h * GROUP : (h + 1) * GROUP] = torch.softmax(s, -1) @ vv + return ref + + +def _rel(out, ref, rows): + o = out[rows].double() + return float((o - ref).norm() / ref.norm()) + + +MAX_REL = 3e-3 # fp16 P and the bf16 output: ~2e-3 + + +@pytest.mark.parametrize("scales", [(1.0, 1.0), (0.5, 2.0)]) +def test_matches_fp64(scales): + k_scale, v_scale = (torch.tensor(s, device="cuda") for s in scales) + cache, table, topk, q, pos, req = _case([2048], [2048], 1, k_scale, v_scale) + out = _prefill(q, cache, topk, table, req, pos, 1, k_scale, v_scale) + assert torch.isfinite(out).all() + rows = list(range(0, 2048, 37)) + list(range(2040, 2048)) + ref = _fp64(q, cache, topk, table, req, pos, 1, k_scale, v_scale, rows) + assert _rel(out, ref, rows) < MAX_REL + + +@pytest.mark.parametrize("hkv", [1, 2, 4]) +def test_batch_with_prefix_and_tiles_across_requests(hkv): + one = torch.tensor(1.0, device="cuda") + q_lens, ctx_lens = [1027, 514, 3, 262], [3000, 514, 1100, 900] + cache, table, topk, q, pos, req = _case(q_lens, ctx_lens, hkv, one, one, seed=1) + out = _prefill(q, cache, topk, table, req, pos, hkv, one, one) + assert torch.isfinite(out).all() + rows = [0, 1, 2, 3, 1026, 1027, 1028, 1540, 1541, 1542, 1543, 1544, 1805] + ref = _fp64(q, cache, topk, table, req, pos, hkv, one, one, rows) + assert _rel(out, ref, rows) < MAX_REL + + +@pytest.mark.parametrize("n_tok", [1, 3, 5]) +def test_few_tokens(n_tok): + one = torch.tensor(1.0, device="cuda") + cache, table, topk, q, pos, req = _case([n_tok], [700], 1, one, one, seed=2) + out = _prefill(q, cache, topk, table, req, pos, 1) # unit scales by default + rows = list(range(n_tok)) + ref = _fp64(q, cache, topk, table, req, pos, 1, one, one, rows) + assert _rel(out, ref, rows) < MAX_REL + + +@pytest.mark.parametrize("hkv", [1, 4]) +def test_block_outer_pages_bitwise(hkv): + """A page inside a wider block (stride(0) past one page): the dense + cache's output.""" + one = torch.tensor(1.0, device="cuda") + q_lens, ctx_lens = [1027, 3, 262], [3000, 1100, 900] + cache, table, topk, q, pos, req = _case(q_lens, ctx_lens, hkv, one, one, seed=3) + page = cache[0].numel() + wide = torch.full( + (cache.shape[0], 3 * page), 0x7F, dtype=torch.uint8, device="cuda" + ) + wide = wide[:, page : 2 * page].view(cache.shape) + wide.copy_(cache) + out = _prefill(q, cache, topk, table, req, pos, hkv) + assert torch.isfinite(out).all() + assert torch.equal(out, _prefill(q, wide, topk, table, req, pos, hkv)) + + +def _shared_picks(pos, req, hkv, seed): + """Indexer-like top-k: the own block, then a per-request base of 15 + earlier blocks, each swapped for a random one with probability 0.1.""" + gen = torch.Generator().manual_seed(seed) + first_blk: dict[int, int] = {} + for p, r in zip(pos.tolist(), req.tolist()): + first_blk.setdefault(r, p // BLOCK) + base = { + r: torch.randperm(max(b, TOPK), generator=gen)[: TOPK - 1].tolist() + for r, b in first_blk.items() + } + rows = [] + for _ in range(hkv): + for p, r in zip(pos.tolist(), req.tolist()): + cur = p // BLOCK + sel = [cur] + for b in base[r]: + if torch.rand(1, generator=gen).item() < 0.1: + b = int(torch.randint(0, max(cur, 1), (1,), generator=gen)) + if b < cur and b not in sel: + sel.append(b) + rows.append(sel + [-1] * (TOPK - len(sel))) + return torch.tensor(rows, dtype=torch.int32).view(hkv, pos.numel(), TOPK).cuda() + + +# Grids above / below the CU count: the two- and one-round combine. +SHARED_CASES = [ + ( + [1501, 6, 2050], + [9000, 2100, 6200], + [0, 1, 2, 3, 1499, 1500, 1501, 1502, 1506, 3556], + ), # fmt: skip + ( + [201, 6, 150], + [5000, 2100, 3000], + [0, 1, 2, 3, 199, 200, 201, 202, 206, 207, 356], + ), # fmt: skip +] + + +@pytest.mark.parametrize("hkv", [1, 2]) +@pytest.mark.parametrize("case", SHARED_CASES) +def test_shared_picks_deterministic(hkv, case): + """Pages shared within a tile, tiles across requests: matches fp64, + bitwise repeatable.""" + one = torch.tensor(1.0, device="cuda") + q_lens, ctx_lens, rows = case + cache, table, _, q, pos, req = _case(q_lens, ctx_lens, hkv, one, one, seed=3) + topk = _shared_picks(pos, req, hkv, seed=4) + out = _prefill(q, cache, topk, table, req, pos, hkv) + ref = _fp64(q, cache, topk, table, req, pos, hkv, one, one, rows) + assert _rel(out, ref, rows) < MAX_REL + assert torch.equal(out, _prefill(q, cache, topk, table, req, pos, hkv)) + + +def test_fresh_prompt_calls_bitwise(): + """A fresh 4096-token prompt in one call equals the same rows in calls of + 1024 / 2048 / 1024 tokens, bitwise (DBO microbatches).""" + one = torch.tensor(1.0, device="cuda") + n = 4096 + cache, table, _, q, pos, req = _case([n], [n], 1, one, one, seed=5) + topk = _shared_picks(pos, req, 1, seed=6) + assert (topk[0, : 15 * BLOCK] == -1).any(1).all() + + def run(a, b): + return _prefill(q[a:b], cache, topk[:, a:b], table, req[a:b], pos[a:b], 1) + + full = run(0, n) + assert torch.equal(full, torch.cat([run(0, 1024), run(1024, 3072), run(3072, n)])) + + +@pytest.mark.parametrize("n_tok, ctx", [(1024, 31024), (4096, 64096)]) +def test_bitwise_next_to_mfma_waves(n_tok, ctx): + """Another kernel's MFMA waves on every CU leave the output unchanged + (v_pk_mul_f32 gives wrong products there on MI355X).""" + one = torch.tensor(1.0, device="cuda") + cache, table, topk, q, pos, req = _case([n_tok], [ctx], 1, one, one, seed=7) + + def run(stream): + with torch.cuda.stream(stream): + return _prefill(q, cache, topk, table, req, pos, 1) + + # A high-priority queue, so the spinner never waits behind the attention. + main, side = torch.cuda.Stream(), torch.cuda.Stream(priority=-1) + ref = run(main) + torch.accelerator.synchronize() + spin = mfma_spinner(torch.cuda.get_device_properties(0).multi_processor_count) + for _ in range(8): + spin(200_000, side) # 2 ms + out = run(main) + torch.accelerator.synchronize() + assert torch.equal(out, ref) + + +def test_supported_shapes(): + """16 query heads per KV head, 16 selected 128-token blocks only.""" + assert supports_nvfp4_sparse_prefill(16, 1, D, TOPK, BLOCK) + assert supports_nvfp4_sparse_prefill(32, 2, D, TOPK, BLOCK) + assert not supports_nvfp4_sparse_prefill(8, 1, D, TOPK, BLOCK) + assert not supports_nvfp4_sparse_prefill(16, 1, D, 8, BLOCK) + assert not supports_nvfp4_sparse_prefill(16, 1, 64, TOPK, BLOCK) diff --git a/tests/kernels/attention/test_minimax_m3_nvfp4_sparse_decode.py b/tests/kernels/attention/test_minimax_m3_nvfp4_sparse_decode.py new file mode 100644 index 000000000000..3ed91611949a --- /dev/null +++ b/tests/kernels/attention/test_minimax_m3_nvfp4_sparse_decode.py @@ -0,0 +1,242 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MiniMax-M3 NVFP4 sparse decode (FlyDSL) against fp64 attention over +K / V = e4m3_rn_satfinite(e2m1 x block scale) x global scale.""" + +import pytest +import torch + +from vllm.platforms import current_platform + +if not current_platform.is_rocm(): + pytest.skip("ROCm (gfx950) FlyDSL kernel", allow_module_level=True) + +from vllm.platforms.rocm import on_gfx950 # noqa: E402 + +if not on_gfx950(): + pytest.skip("gfx950 instructions", allow_module_level=True) + +from tests.kernels.attention.minimax_m3_nvfp4_ref import ( # noqa: E402 + dequant, + head_offsets, + insert_nvfp4_kv, + nvfp4_kv_cache_token_major, +) +from vllm.models.minimax_m3.amd.ops.nvfp4_sparse_decode.host import ( # noqa: E402 + minimax_m3_nvfp4_sparse_decode_fly, +) + +BLOCK = 128 +D = 128 +GROUP = 16 # query heads per KV head +TOPK = 16 +SM_SCALE = D**-0.5 + + +def _nvfp4_cache(num_blocks, k_scale, v_scale, num_kv_heads=1): + """Every slot of the cache filled with random K / V.""" + cache = torch.zeros( + num_blocks, 2 * num_kv_heads, BLOCK, 72, dtype=torch.uint8, device="cuda" + ) + slots = torch.arange(num_blocks * BLOCK, device="cuda") + shape = (slots.numel(), num_kv_heads, D) + k = (torch.randn(shape, device="cuda") * 2).bfloat16() + v = (torch.randn(shape, device="cuda") * 2).bfloat16() + insert_nvfp4_kv(k, v, cache, slots, k_scale, v_scale) + return cache + + +def _block_table(seq_lens): + widths = [(s + BLOCK - 1) // BLOCK for s in seq_lens] + num_blocks = sum(widths) + 3 + perm = torch.randperm(num_blocks, device="cuda", dtype=torch.int32) + table = torch.zeros(len(seq_lens), max(widths), dtype=torch.int32, device="cuda") + start = 0 + for r, w in enumerate(widths): + table[r, :w] = perm[start : start + w] + start += w + return table, num_blocks + + +def _scales(): + return ( + torch.tensor(0.5, dtype=torch.float32, device="cuda"), + torch.tensor(2.0, dtype=torch.float32, device="cuda"), + ) + + +def _selections(seq_lens, qlen, num_kv_heads=1, seed=0): + """[Hkv, rows, 16] picks, mostly shared within a request, with -1 padding + and an out-of-range entry; head h's picks rotated by h.""" + g = torch.Generator(device="cuda").manual_seed(seed) + topk = torch.full( + (1, len(seq_lens) * qlen, TOPK), -1, dtype=torch.int32, device="cuda" + ) + for r, s in enumerate(seq_lens): + nb = (s + BLOCK - 1) // BLOCK + base = torch.randperm(nb, device="cuda", generator=g).to(torch.int32) + for q in range(qlen): + cur = max(s - qlen + q, 0) // BLOCK + older = base[(base != cur) & (base <= cur)] + pick = torch.cat([older[:10], older[10 + 3 * q : 13 + 3 * q]]) + sel = torch.cat([torch.tensor([cur], device="cuda"), pick]) + sel = torch.cat([sel, torch.tensor([nb + 5], device="cuda")])[:TOPK] + topk[0, r * qlen + q, : sel.numel()] = sel.to(torch.int32) + return torch.cat([topk.roll(h, -1) for h in range(num_kv_heads)]) + + +def _reference(q, cache, topk, table, seq_lens, scales, qlen): + """fp64 attention over the dequantized K / V; rows that see nothing give 0.""" + k_data, k_sf, v_data, v_sf = nvfp4_kv_cache_token_major(cache) + k_all, v_all = ( + dequant(data, sf).clamp(-448, 448).to(torch.float8_e4m3fn).double() * s.item() + for data, sf, s in ((k_data, k_sf, scales[0]), (v_data, v_sf, scales[1])) + ) + hkv, rows, _ = topk.shape + req = torch.arange(rows, device="cuda") // qlen + pos = seq_lens.long()[req] - qlen + torch.arange(rows, device="cuda") % qlen + offs = torch.arange(BLOCK, device="cuda") + out = torch.zeros(q.shape, dtype=torch.float64, device="cuda") + for h in range(hkv): + blk = topk[h, :rows].long() + ok = (pos[:, None] >= 0) & (blk >= 0) & (blk <= (pos // BLOCK)[:, None]) + blk = torch.where(ok, blk, 0) + tok = blk[..., None] * BLOCK + offs # [rows, TOPK, BLOCK] + ok = (ok[..., None] & (tok <= pos[:, None, None])).flatten(1) + page = table[req[:, None], blk].long()[..., None].expand_as(tok) + k = k_all[page, h, tok % BLOCK].flatten(1, 2) + v = v_all[page, h, tok % BLOCK].flatten(1, 2).masked_fill(~ok[..., None], 0) + heads = slice(h * GROUP, (h + 1) * GROUP) + s = torch.einsum("nhd,ntd->nht", q[:, heads].double(), k) * SM_SCALE + s = s.masked_fill(~ok[:, None, :], float("-inf")) + p = torch.softmax(s, -1).nan_to_num(0.0) + out[:, heads] = torch.einsum("nht,ntd->nhd", p, v) + return out + + +def _rel(a, b): + a, b = a.double(), b.double() + return float((a - b).norm() / b.norm()) + + +def _decode(q, cache, topk, table, seq_lens, qlen, out=None, **kw): + k_scale, v_scale = _scales() + out = torch.full_like(q, float("nan")) if out is None else out + minimax_m3_nvfp4_sparse_decode_fly( + q, cache, topk, table, seq_lens, SM_SCALE, out, k_scale=k_scale, + v_scale=v_scale, decode_query_len=qlen, **kw, + ) # fmt: skip + return out + + +@pytest.mark.parametrize("decode_query_len", [1, 4, 8]) +@pytest.mark.parametrize("splits", [None, 1, 2, 4, 8]) +@pytest.mark.parametrize("random_bytes", [False, True]) +@pytest.mark.parametrize("xcd_count", [0, 8]) +def test_decode_matches_reference(decode_query_len, splits, random_bytes, xcd_count): + """Realistic and random-byte caches: close to fp64, bitwise repeatable.""" + torch.manual_seed(0) + lens = [9, 300, 2100, 20000, 131, 4096] + table, num_blocks = _block_table(lens) + seq_lens = torch.tensor(lens, dtype=torch.int32, device="cuda") + topk = _selections(lens, decode_query_len) + rows = topk.shape[1] + if random_bytes: + cache = torch.randint( + 0, 256, (num_blocks, 2, BLOCK, 72), dtype=torch.uint8, device="cuda" + ) + for side in range(2): + sf = cache.view(num_blocks, -1)[:, side * 9216 + 8192 : (side + 1) * 9216] + sf.masked_fill_((sf & 0x7F) == 0x7F, 0x38) # no NaN scales + q = (torch.randn(rows, GROUP, D, device="cuda") * 0.01).bfloat16() + else: + cache = _nvfp4_cache(num_blocks, *_scales()) + q = torch.randn(rows, GROUP, D, device="cuda").bfloat16() + kw = dict(splits=splits, xcd_count=xcd_count) + out = _decode(q, cache, topk, table, seq_lens, decode_query_len, **kw) + again = _decode(q, cache, topk, table, seq_lens, decode_query_len, **kw) + ref = _reference(q, cache, topk, table, seq_lens, _scales(), decode_query_len) + assert torch.isfinite(out).all() + assert torch.equal(out, again) + assert _rel(out, ref) < 5e-3 + + +@pytest.mark.parametrize("num_kv_heads", [1, 4]) +@pytest.mark.parametrize("decode_query_len", [1, 4, 6]) +@pytest.mark.parametrize("splits", [1, 4]) +def test_decode_padding_rows_and_kv_heads(num_kv_heads, decode_query_len, splits): + """Padding requests (seq_len 0) give zero rows; nothing past the rows is + written.""" + torch.manual_seed(1) + lens = [700, 0, 3000, 0, 0, 129] + table, num_blocks = _block_table([max(s, 1) for s in lens]) + seq_lens = torch.tensor(lens, dtype=torch.int32, device="cuda") + topk = _selections([max(s, 1) for s in lens], decode_query_len, num_kv_heads) + cache = _nvfp4_cache(num_blocks, *_scales(), num_kv_heads) + rows = topk.shape[1] + q = torch.randn(rows, GROUP * num_kv_heads, D, device="cuda").bfloat16() + out = torch.full((rows + 3, *q.shape[1:]), float("nan"), device="cuda").bfloat16() + _decode( + q, cache, topk, table, seq_lens, decode_query_len, out[:rows], splits=splits + ) + ref = _reference(q, cache, topk, table, seq_lens, _scales(), decode_query_len) + real = (seq_lens.repeat_interleave(decode_query_len) > 0).cpu() + assert _rel(out[:rows][real], ref[real]) < 5e-3 + assert (out[:rows][~real] == 0).all() + assert out[rows:].isnan().all() + zeros = torch.zeros_like(seq_lens) + pad = _decode(q, cache, topk, table, zeros, decode_query_len, splits=splits) + assert (pad == 0).all() + + +@pytest.mark.parametrize( + "num_kv_heads,qlen,splits,xcd_count", + [(1, 1, 1, 0), (1, 4, 4, 8), (4, 6, 1, 8), (4, 8, 4, 0)], +) +def test_garbage_past_the_length_is_ignored(num_kv_heads, qlen, splits, xcd_count): + """NaN scale bytes past each request's length leave the output unchanged.""" + torch.manual_seed(42) + lens = [131, 4097, 2100, 777, 65] + table, blocks = _block_table(lens) + seq_lens = torch.tensor(lens, dtype=torch.int32, device="cuda") + topk = _selections(lens, qlen, num_kv_heads) + cache = _nvfp4_cache(blocks, *_scales(), num_kv_heads) + q = torch.randn(len(lens) * qlen, num_kv_heads * GROUP, D, device="cuda").bfloat16() + kw = dict(splits=splits, xcd_count=xcd_count) + out = _decode(q, cache, topk, table, seq_lens, qlen, **kw) + dirty = cache.clone().view(blocks, -1) + for side in range(2): + start = side * num_kv_heads * 9216 + num_kv_heads * 8192 + region = dirty[:, start : start + num_kv_heads * 1024] + region = region.view(blocks, num_kv_heads, 1024) + _, _, offsets = head_offsets(side, cache.device) + for req, length in enumerate(lens): + page = table[req, length // BLOCK] + region[page, :, offsets[length % BLOCK :].reshape(-1)] = 0x7F + dirty_out = _decode(q, dirty.view_as(cache), topk, table, seq_lens, qlen, **kw) + assert torch.isfinite(out).all() + assert torch.equal(out, dirty_out) + + +@pytest.mark.parametrize("num_kv_heads", [1, 4]) +@pytest.mark.parametrize("decode_query_len", [1, 4]) +def test_decode_block_outer_pages_bitwise(num_kv_heads, decode_query_len): + """A page inside a wider block (stride(0) past one page): the dense + cache's output.""" + torch.manual_seed(2) + lens = [300, 2100, 20000, 131] + table, num_blocks = _block_table(lens) + seq_lens = torch.tensor(lens, dtype=torch.int32, device="cuda") + topk = _selections(lens, decode_query_len, num_kv_heads) + cache = _nvfp4_cache(num_blocks, *_scales(), num_kv_heads) + page = cache[0].numel() + wide = torch.full((num_blocks, 3 * page), 0x7F, dtype=torch.uint8, device="cuda") + wide_cache = wide[:, page : 2 * page].view(cache.shape) + wide_cache.copy_(cache) + q = torch.randn(topk.shape[1], GROUP * num_kv_heads, D, device="cuda").bfloat16() + outs = [ + _decode(q, c, topk, table, seq_lens, decode_query_len) + for c in (cache, wide_cache) + ] + assert torch.isfinite(outs[0]).all() + assert torch.equal(outs[0], outs[1]) diff --git a/tests/kernels/mfma_spinner.py b/tests/kernels/mfma_spinner.py new file mode 100644 index 000000000000..09b7e07b20ac --- /dev/null +++ b/tests/kernels/mfma_spinner.py @@ -0,0 +1,64 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""An MFMA co-runner for gfx950 kernel tests: on MI355X, v_pk_mul_f32 can +return wrong products while another kernel's MFMA waves share the CU.""" + +import torch + + +def mfma_spinner(n_wg): + """``n_wg`` workgroups looping v_mfma_f32_16x16x32_bf16 for ``ticks`` + (s_memrealtime, 100 per us). + + Launch it on a high-priority stream: on a normal one it can share a hardware + queue with the kernel under test and never overlap it. + """ + import flydsl.compiler as flyc + import flydsl.expr as fx + from flydsl._mlir.dialects import llvm + from flydsl.expr import range_constexpr + from flydsl.expr.typing import T + from flydsl.expr.typing import Vector as Vec + + @fx.struct + class Shared: + a: fx.Array[fx.Int32, 4096, 16] + + def now(): + return fx.Int64( + llvm.call_intrinsic(T.i64, "llvm.amdgcn.s.memrealtime", [], [], []) + ) + + @flyc.kernel(name="test_mfma_spinner", known_block_size=[256, 1, 1]) + def spinner(arg_out: fx.Int64, i64_ticks: fx.Int64): + sm = fx.SharedAllocator().allocate(Shared).peek() + tx = fx.thread_idx.x + sm.a.ptr[tx] = tx + a4 = Vec.from_elements([tx, tx + 1, tx + 2, tx + 3], fx.Int32) + acc = Vec.filled(4, 0.0, fx.Float32) + t0 = now() + t = now() + while t - t0 < i64_ticks: + for _ in range_constexpr(16): + ab = Vec(a4).bitcast(fx.BFloat16) + acc = Vec( + fx.rocdl.mfma_f32_16x16x32_bf16( + Vec.make_type(4, fx.Float32), [ab, ab, acc, 0, 0, 0] + ) + ) + t = now() + f32p = fx.PointerType.get( + T.f32, address_space=fx.AddressSpace.Global, alignment=4 + ) + out = fx.inttoptr(f32p, arg_out) + out[fx.block_idx.x * 256 + tx] = acc[0] + fx.Float32(sm.a.ptr[255 - tx]) + + @flyc.jit + def launch(arg_out: fx.Int64, i64_ticks: fx.Int64, stream: fx.Stream): + spinner(arg_out, i64_ticks).launch( + grid=(n_wg, 1, 1), block=(256, 1, 1), stream=stream + ) + + buf = torch.zeros(n_wg * 256, device="cuda") + compiled = flyc.compile(launch, buf.data_ptr(), 1, torch.cuda.current_stream()) + return lambda ticks, stream: compiled(buf.data_ptr(), ticks, stream) diff --git a/tests/kernels/moe/test_deep_gemm_mega_moe.py b/tests/kernels/moe/test_deep_gemm_mega_moe.py index 0f707e16ea9f..dee9478615e2 100644 --- a/tests/kernels/moe/test_deep_gemm_mega_moe.py +++ b/tests/kernels/moe/test_deep_gemm_mega_moe.py @@ -940,7 +940,7 @@ def test_prepare_megamoe_inputs_masks_padding(nonfinite_padding, num_tokens, qua @requires_sm100 @pytest.mark.parametrize("shared", [None, "mxfp8", "bf16"]) -@pytest.mark.parametrize("num_tokens", [0, 7, 65, 135]) +@pytest.mark.parametrize("num_tokens", [0, 7, 65, 135, 600]) def test_prepare_megamoe_nvfp4_inputs_is_bitwise_exact(num_tokens, shared): """Per-token NVFP4 dispatch, shared-expert inputs, unrouted padding and the L2 alphas match DeepGEMM's reference quantizers bit for bit.""" diff --git a/tests/kernels/moe/test_minimax_m3_moe_mxfp4_prefill.py b/tests/kernels/moe/test_minimax_m3_moe_mxfp4_prefill.py new file mode 100644 index 000000000000..84f66bea5716 --- /dev/null +++ b/tests/kernels/moe/test_minimax_m3_moe_mxfp4_prefill.py @@ -0,0 +1,206 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MiniMax-M3 FlyDSL W4A4 MoE prefill chain at TP4 vs aiter's ``fused_moe`` (the +``AITER_MXFP4_MXFP4`` backend's call) and a float reference, routed only and with +aiter's fused shared expert (expert 129, every token, weight 1).""" + +import pytest +import torch + +from vllm.platforms import current_platform +from vllm.platforms.rocm import on_gfx950 + +pytestmark = [ + pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm only"), + pytest.mark.skipif(not on_gfx950(), reason="gfx950 only"), +] + +HIDDEN, INTER, NUM_ROUTED, TOPK = 6144, 768, 128, 4 +SWIGLU_ALPHA, SWIGLU_LIMIT = 1.702, 7.0 +CHECK_TOKENS = 64 + + +def _quantize_like_backend(w13: torch.Tensor, w2: torch.Tensor): + """Per-1x32 MXFP4 + the shuffles oracle/mxfp4.py applies for + AITER_MXFP4_MXFP4.""" + from aiter import dtypes + from aiter.ops.quant import per_1x32_f4_quant + from aiter.utility.fp4_utils import e8m0_shuffle + + from vllm._aiter_ops import rocm_aiter_ops + + e = w13.shape[0] + fp4 = torch.float4_e2m1fn_x2 + w13_q, w13_s = per_1x32_f4_quant(w13, quant_dtype=dtypes.fp4x2) + w2_q, w2_s = per_1x32_f4_quant(w2, quant_dtype=dtypes.fp4x2) + w13_q = w13_q.view(e, w13.shape[1], w13.shape[2] // 2) + w2_q = w2_q.view(e, w2.shape[1], w2.shape[2] // 2) + w13_s = w13_s.view(torch.uint8).view(e, w13.shape[1], w13.shape[2] // 32) + w2_s = w2_s.view(torch.uint8).view(e, w2.shape[1], w2.shape[2] // 32) + raw = (w13_q, w13_s, w2_q, w2_s) + w13_k, w2_k = rocm_aiter_ops.shuffle_weights(w13_q.view(fp4), w2_q.view(fp4)) + w13_sk = e8m0_shuffle(w13_s.view(e * w13.shape[1], -1)).view(e, w13.shape[1], -1) + w2_sk = e8m0_shuffle(w2_s.view(e * w2.shape[1], -1)).view(e, w2.shape[1], -1) + shuffled = (w13_k.contiguous(), w13_sk.contiguous()) + return raw, shuffled + (w2_k.contiguous(), w2_sk.contiguous()) + + +def _routing(m: int, shared: bool, device): + routed = torch.stack( + [torch.randperm(NUM_ROUTED, device=device)[:TOPK] for _ in range(m)] + ) + w = torch.rand((m, TOPK), device=device) + w = w / w.sum(dim=1, keepdim=True) + if shared: + routed = torch.cat([routed, torch.full((m, 1), NUM_ROUTED, device=device)], 1) + w = torch.cat([w, torch.ones((m, 1), device=device)], dim=1) + return routed.to(torch.int32), w.to(torch.float32) + + +def _dequant(q: torch.Tensor, s: torch.Tensor, n_cols: int) -> torch.Tensor: + from aiter.utility import fp4_utils + + v = fp4_utils.mxfp4_to_f32(q.view(torch.uint8)).view(q.shape[0], -1) + sc = fp4_utils.e8m0_to_f32(s.view(torch.uint8)).view(q.shape[0], -1) + return (v.view(q.shape[0], -1, 32) * sc.unsqueeze(-1)).view(q.shape[0], n_cols) + + +_FP4_GRID = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0) + + +def _fp4_quant_dequant(h: torch.Tensor) -> torch.Tensor: + """Per-32 MXFP4 of fp32 rows: e8m0 scale ceil_pow2(amax / 6) (aiter's RoundUp, + computed on the f32 bits like the kernels), round-to-nearest-even onto e2m1.""" + g = h.view(*h.shape[:-1], -1, 32) + amax = g.abs().amax(-1, keepdim=True) + bits = (amax * torch.tensor(1.0 / 6.0, dtype=torch.float32)).view(torch.int32) + e = (bits >> 23) & 0xFF + e = e + (((bits & 0x7FFFFF) != 0) & (e < 255)).to(torch.int32) + scale = (e << 23).view(torch.float32) + v = (g / torch.where(scale > 0, scale, 1.0)).abs() + mids = torch.tensor([0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0], device=h.device) + idx = torch.bucketize(v, mids) # a tie goes to the lower code ... + idx = idx + ((v == 0.75) | (v == 1.75) | (v == 3.5)).to(idx.dtype) # ... or even + q = torch.tensor(_FP4_GRID, device=h.device)[idx] * g.sign() + return (q * scale).view_as(h) + + +def _float_reference(x, raw, topk_ids, topk_weights, tokens, same_operands): + """fp32 MoE on the dequantized experts. ``same_operands``: the kernel's x (the + per-token MXFP4 codes) and its intermediate rounding (bf16, then MXFP4); + otherwise bf16 x and no intermediate quant (the W4A4 error, cos ~0.98).""" + from vllm.models.minimax_m3.amd.ops.moe_mxfp4.prefill import mxfp4_quant + + w13_q, w13_s, w2_q, w2_s = raw + xs = x[tokens] + if same_operands: + xs = _dequant(*mxfp4_quant(xs, None, None), HIDDEN) + xs = xs.float() + deq = {} + out = torch.zeros((len(tokens), HIDDEN), dtype=torch.float32, device=x.device) + for i, t in enumerate(tokens): + for j in range(topk_ids.shape[1]): + e = int(topk_ids[t, j]) + if e not in deq: + deq[e] = ( + _dequant(w13_q[e], w13_s[e], HIDDEN), + _dequant(w2_q[e], w2_s[e], INTER), + ) + w13e, w2e = deq[e] + h = xs[i] @ w13e.T + g = h[:INTER].clamp(max=SWIGLU_LIMIT) + u = h[INTER:].clamp(-SWIGLU_LIMIT, SWIGLU_LIMIT) + a = g * torch.sigmoid(SWIGLU_ALPHA * g) * (u + 1.0) + if same_operands: + a = _fp4_quant_dequant(a.bfloat16().float()) + out[i] += float(topk_weights[t, j]) * (a @ w2e.T) + return out + + +def _cos(a: torch.Tensor, b: torch.Tensor) -> float: + a, b = a.float().flatten(), b.float().flatten() + return float((a @ b) / (a.norm() * b.norm() + 1e-12)) + + +@pytest.fixture(scope="module", params=[False, True], ids=["routed", "fused_shared"]) +def weights(request): + torch.manual_seed(0) + num_experts = NUM_ROUTED + int(request.param) + w13 = torch.randn( + (num_experts, 2 * INTER, HIDDEN), dtype=torch.bfloat16, device="cuda" + ) + w2 = torch.randn((num_experts, HIDDEN, INTER), dtype=torch.bfloat16, device="cuda") + raw, shuffled = _quantize_like_backend(w13 * 0.02, w2 * 0.02) + return request.param, raw, shuffled + + +def _run(shuffled, x, topk_ids, topk_weights): + from vllm.models.minimax_m3.amd.ops.moe_mxfp4.prefill import ( + a4w4_prefill_moe, + mxfp4_quant, + ) + + w13, w13_s, w2, w2_s = shuffled + return a4w4_prefill_moe( + mxfp4_quant(x, None, None), + w13, + w13_s, + w2, + w2_s, + topk_weights, + topk_ids, + hidden_size=HIDDEN, + intermediate_size=INTER, + num_experts=w13.shape[0], + ) + + +def _run_aiter(shuffled, x, topk_ids, topk_weights): + from aiter import ActivationType, QuantType + from aiter.fused_moe import fused_moe + from aiter.ops.flydsl.moe_common import GateMode + + w13, w13_s, w2, w2_s = shuffled + return fused_moe( + x, + w13, + w2, + topk_weights, + topk_ids, + quant_type=QuantType.per_1x32, + activation=ActivationType.Swiglu, + w1_scale=w13_s, + w2_scale=w2_s, + swiglu_limit=SWIGLU_LIMIT, + gate_mode=GateMode.SEPARATED.value, + ) + + +@pytest.mark.parametrize("m", [4096, 16384, 32768]) +def test_moe_mxfp4_prefill(weights, m): + """4096: 128-row sort blocks; 16384 and 32768: 256-row blocks.""" + from vllm.models.minimax_m3.amd.ops.moe_mxfp4.prefill import supports_shapes + + assert supports_shapes(HIDDEN, INTER) + shared, raw, shuffled = weights + torch.manual_seed(m) + x = torch.randn((m, HIDDEN), dtype=torch.bfloat16, device="cuda") + topk_ids, topk_weights = _routing(m, shared, x.device) + out = _run(shuffled, x, topk_ids, topk_weights) + out2 = _run(shuffled, x, topk_ids, topk_weights) + ref_aiter = _run_aiter(shuffled, x, topk_ids, topk_weights) + torch.cuda.synchronize() + assert out.shape == (m, HIDDEN) and out.dtype == torch.bfloat16 + assert torch.equal(out, out2) # no atomics: the same bits every call + tokens = torch.randperm(m, device=x.device)[:CHECK_TOKENS].tolist() + ref = _float_reference(x, raw, topk_ids, topk_weights, tokens, True) + ref_hp = _float_reference(x, raw, topk_ids, topk_weights, tokens, False) + cos, cos_hp = _cos(out[tokens], ref), _cos(out[tokens], ref_hp) + aiter_hp = _cos(ref_aiter[tokens], ref_hp) + print( + f"\nRESULT m={m} shared={shared}: cos vs same-operand ref {cos:.6f}, vs " + f"high-precision ref {cos_hp:.6f} (aiter {aiter_hp:.6f})" + ) + # the kernel computes what it should; W4A4 loses no more than aiter's path + assert cos > 0.9999 + assert cos_hp >= aiter_hp - 1e-3 diff --git a/tests/kernels/moe/test_minimax_m3_moe_prefill.py b/tests/kernels/moe/test_minimax_m3_moe_prefill.py new file mode 100644 index 000000000000..7ed7207fa113 --- /dev/null +++ b/tests/kernels/moe/test_minimax_m3_moe_prefill.py @@ -0,0 +1,155 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MiniMax-M3 FlyDSL MXFP8 MoE prefill chain vs aiter and a float reference, routed +only and with aiter's fused shared expert (expert 129, every token, weight 1).""" + +from types import SimpleNamespace + +import pytest +import torch + +from vllm.platforms import current_platform +from vllm.platforms.rocm import on_gfx950 + +pytestmark = [ + pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm only"), + pytest.mark.skipif(not on_gfx950(), reason="gfx950 only"), +] + +HIDDEN, INTER, NUM_ROUTED, TOPK = 6144, 768, 128, 4 +SWIGLU_ALPHA, SWIGLU_LIMIT = 1.702, 7.0 +CHECK_TOKENS = 64 + + +def _quantize(x: torch.Tensor): + """Aiter's per-1x32 MX quant.""" + from aiter import dtypes + from aiter.ops.quant import per_1x32_mx_quant_hip + + *lead, k = x.shape + q, s = per_1x32_mx_quant_hip( + x.reshape(-1, k), quant_dtype=dtypes.fp8, scale_type=dtypes.fp8_e8m0 + ) + return q.view(*lead, k), s.view(torch.uint8).view(*lead, k // 32) + + +def _dequant(q: torch.Tensor, s: torch.Tensor) -> torch.Tensor: + n, k = q.shape + sc = torch.ldexp(torch.ones_like(s, dtype=torch.float32), s.to(torch.int32) - 127) + return (q.float().view(n, k // 32, 32) * sc.unsqueeze(-1)).view(n, k) + + +@pytest.fixture( + scope="module", params=[NUM_ROUTED, NUM_ROUTED + 1], ids=["routed", "fse"] +) +def m3_weights(request): + from vllm.model_executor.layers.fused_moe.oracle.fp8 import ( + Fp8MoeBackend, + convert_to_fp8_moe_kernel_format, + ) + + torch.manual_seed(0) + device = torch.device("cuda") + e = request.param + w13 = torch.randn((e, 2 * INTER, HIDDEN), device=device) * 0.02 + w2 = torch.randn((e, HIDDEN, INTER), device=device) * 0.02 + raw = (*_quantize(w13.bfloat16()), *_quantize(w2.bfloat16())) + shuffled = convert_to_fp8_moe_kernel_format( + fp8_backend=Fp8MoeBackend.AITER_MXFP8, + layer=SimpleNamespace(weight_block_size=[1, 32]), + w13=raw[0], + w2=raw[2], + w13_scale=raw[1], + w2_scale=raw[3], + w13_input_scale=None, + w2_input_scale=None, + ) + return raw, shuffled + + +def _routing(m: int, device, shared: bool): + ids = torch.stack( + [torch.randperm(NUM_ROUTED, device=device)[:TOPK] for _ in range(m)] + ) + w = torch.rand((m, TOPK), device=device) + w = w / w.sum(dim=1, keepdim=True) * 2.0 + if shared: + ids = torch.cat([ids, torch.full((m, 1), NUM_ROUTED, device=device)], 1) + w = torch.cat([w, torch.ones((m, 1), device=device)], dim=1) + return ids.to(torch.int32).contiguous(), w.to(torch.float32).contiguous() + + +def _float_reference(x, raw, topk_ids, topk_weights, tokens): + w13_q, w13_s, w2_q, w2_s = raw + out = torch.zeros((len(tokens), HIDDEN), dtype=torch.float32, device=x.device) + for i, t in enumerate(tokens): + for j in range(topk_ids.shape[1]): + e = int(topk_ids[t, j]) + h = x[t].float() @ _dequant(w13_q[e], w13_s[e]).T + g = h[:INTER].clamp(max=SWIGLU_LIMIT) + u = h[INTER:].clamp(-SWIGLU_LIMIT, SWIGLU_LIMIT) + a = g * torch.sigmoid(SWIGLU_ALPHA * g) * (u + 1.0) + out[i] += float(topk_weights[t, j]) * (a @ _dequant(w2_q[e], w2_s[e]).T) + return out + + +def _cos(a: torch.Tensor, b: torch.Tensor) -> float: + a, b = a.float().flatten(), b.float().flatten() + return float((a @ b) / (a.norm() * b.norm() + 1e-12)) + + +@pytest.mark.parametrize("m", [4096, 16384, 32768]) +def test_prefill_matches_aiter(m3_weights, m): + """4096: 128-row gemm2 tiles; 16384: 256-row tiles; 32768: the large n-split.""" + from aiter import ActivationType, QuantType + from aiter.fused_moe import fused_moe + from aiter.ops.flydsl.moe_common import GateMode + + from vllm.models.minimax_m3.amd.ops.moe_mxfp8 import prefill + + raw, (w13, w2, w13_s, w2_s) = m3_weights + torch.manual_seed(m) + device = w13.device + num_experts = w13.shape[0] + x = torch.randn((m, HIDDEN), dtype=torch.bfloat16, device=device) + topk_ids, topk_weights = _routing(m, device, num_experts > NUM_ROUTED) + + def ours(): + return prefill.a8w8_prefill_moe( + _quantize(x), + w13, + w13_s, + w2, + w2_s, + topk_weights, + topk_ids, + hidden_size=HIDDEN, + intermediate_size=INTER, + num_experts=num_experts, + ) + + out, out2 = ours(), ours() + ref_aiter = fused_moe( + x, + w13, + w2, + topk_weights, + topk_ids, + activation=ActivationType.Swiglu, + quant_type=QuantType.per_1x32, + w1_scale=w13_s, + w2_scale=w2_s, + gate_mode=GateMode.INTERLEAVE.value, + swiglu_limit=SWIGLU_LIMIT, + ) + torch.accelerator.synchronize() + assert out.shape == (m, HIDDEN) and out.dtype == torch.bfloat16 + assert torch.equal(out, out2) # no atomics: the same bits every call + tokens = torch.randperm(m, device=device)[:CHECK_TOKENS].tolist() + ref = _float_reference(x, raw, topk_ids, topk_weights, tokens) + ours_t, theirs = out[tokens].float(), ref_aiter[tokens].float() + assert _cos(ours_t, ref) > 0.997 + assert _cos(ours_t, ref) >= _cos(theirs, ref) - 1e-3 + err_ours = (ours_t - ref).abs().max().item() + err_theirs = (theirs - ref).abs().max().item() + assert err_ours <= err_theirs * 1.1 + 1e-3, (err_ours, err_theirs) diff --git a/tests/kernels/moe/test_moe_weight_loading_padded.py b/tests/kernels/moe/test_moe_weight_loading_padded.py index 407c71e1e0dc..189b431333d8 100644 --- a/tests/kernels/moe/test_moe_weight_loading_padded.py +++ b/tests/kernels/moe/test_moe_weight_loading_padded.py @@ -480,6 +480,7 @@ class TestLoadWeightsExpertBias: def _make_experts(self, has_bias: bool) -> torch.nn.Module: experts = torch.nn.Module() experts.layer_name = "model.layers.0.mlp.experts" + experts.shared_expert_online_loader = None experts.moe_config = make_dummy_moe_config(num_experts=self.NUM_EXPERTS) mapping = RoutedExperts.build_expert_params_mapping( "gate_proj", @@ -573,6 +574,7 @@ def _load( ): experts = torch.nn.Module() experts.layer_name = layer_name + experts.shared_expert_online_loader = None experts.moe_config = SimpleNamespace(is_act_and_mul=is_gated) experts.get_expert_mapping = lambda **_: mapping experts.is_fused_checkpoint_transposed = transposed diff --git a/tests/kernels/quantization/test_nvfp4_emulation.py b/tests/kernels/quantization/test_nvfp4_emulation.py index 9fc97d0e09a8..f58222693c86 100644 --- a/tests/kernels/quantization/test_nvfp4_emulation.py +++ b/tests/kernels/quantization/test_nvfp4_emulation.py @@ -864,3 +864,59 @@ def test_nvfp4_dense_emulation( torch.testing.assert_close(actual, saved, atol=0, rtol=0) assert torch.equal(layer.weight, original_weight) assert torch.equal(layer.weight_scale.view(torch.uint8), original_scale) + + +@pytest.mark.parametrize("invert_global_scales", [True, False]) +@pytest.mark.parametrize("experts_per_chunk", [1, 2, 3, 8]) +def test_dequantize_nvfp4_moe_weights_chunked_matches_full( + experts_per_chunk: int, invert_global_scales: bool, monkeypatch +) -> None: + """Chunked dequantization must equal the single-chunk dequantization exactly. + + 5 experts cover one expert per chunk, a smaller last chunk (2, 3) and a + chunk larger than the number of experts (8). + """ + set_random_seed(0) + device = torch.device(current_platform.device_type) + num_experts, hidden, inter, group = 5, 64, 32, 16 + + def packed(rows: int, cols: int) -> torch.Tensor: + return torch.randint( + 0, 256, (num_experts, rows, cols // 2), dtype=torch.uint8, device=device + ) + + def block_scale(rows: int, cols: int) -> torch.Tensor: + scale = torch.rand(num_experts, rows, cols // group, device=device) * 4 + 0.5 + return scale.to(torch.float8_e4m3fn) + + w13_packed, w13_scale = packed(2 * inter, hidden), block_scale(2 * inter, hidden) + w2_packed, w2_scale = packed(hidden, inter), block_scale(hidden, inter) + w13_global = torch.rand(num_experts, 2, device=device) + 0.5 + w2_global = torch.rand(num_experts, device=device) + 0.5 + + args = (w13_packed, w13_scale, w13_global, w2_packed, w2_scale, w2_global) + dtype = torch.float32 + # The default chunk budget holds all experts at once. + ((_, expected_w13, expected_w2),) = ( + nvfp4_emulation_utils.dequantize_nvfp4_moe_weights( + *args, dtype, invert_global_scales=invert_global_scales + ) + ) + + expert_bytes = dtype.itemsize * 2 * (w13_packed[0].numel() + w2_packed[0].numel()) + monkeypatch.setattr( + nvfp4_emulation_utils, + "_DEQUANT_CHUNK_BYTES", + experts_per_chunk * expert_bytes, + ) + chunks = list( + nvfp4_emulation_utils.dequantize_nvfp4_moe_weights( + *args, dtype, invert_global_scales=invert_global_scales + ) + ) + + expected_starts = list(range(0, num_experts, experts_per_chunk)) + assert [c[0].start for c in chunks] == expected_starts + assert chunks[-1][0].stop == num_experts + assert torch.equal(torch.cat([c[1] for c in chunks]), expected_w13) + assert torch.equal(torch.cat([c[2] for c in chunks]), expected_w2) diff --git a/tests/kernels/quantization/test_rocm_mxfp8_linear.py b/tests/kernels/quantization/test_rocm_mxfp8_linear.py index d5e48f2aafa2..7e138bbc8623 100644 --- a/tests/kernels/quantization/test_rocm_mxfp8_linear.py +++ b/tests/kernels/quantization/test_rocm_mxfp8_linear.py @@ -36,6 +36,13 @@ ("wo_b", 5120, 8192 // 4), ] +M31_TP4_SHAPES = [ + ("fused_qkv", 2560, 6144), + ("o_proj", 6144, 2048), + ("shared_gate_up", 1536, 6144), + ("shared_down", 6144, 768), +] + def _make_layer(n: int, k: int, device: str) -> torch.nn.Module: weight_bf16 = torch.randn(n, k, device=device, dtype=torch.bfloat16) * 0.05 @@ -46,8 +53,46 @@ def _make_layer(n: int, k: int, device: str) -> torch.nn.Module: return layer -@pytest.mark.parametrize("name,n,k", V41_ATTN_SHAPES, ids=lambda v: str(v)) -@pytest.mark.parametrize("num_tokens", [1, 2, 7, 16, 31, 32, 128, 1024]) +@pytest.mark.parametrize( + "n,k,selected,fallback", + [ + (2560, 6144, (16, 16, 1024, 2, 3), (16, 16, 1024, 2, 2)), + (1536, 6144, (16, 16, 1024, 2, 3), (16, 16, 1024, 2, 2)), + (6144, 768, (16, 16, 256, 2, 3), (16, 32, 256, 4, 3)), + ], +) +def test_rocm_mxfp8_linear_selects_m31_tp4_tiles(n, k, selected, fallback): + """The gfx950 small-M tuning is shape-scoped and ends after M=16.""" + from vllm.model_executor.kernels.linear.mxfp8 import rocm_native + from vllm.platforms.rocm import on_gfx950 + + if not on_gfx950(): + pytest.skip("MiniMax-M3.1 small-M tuning requires gfx950") + for num_tokens in (1, 8, 16): + assert rocm_native._select_cfg(num_tokens, n, k) == selected + assert rocm_native._select_cfg(17, n, k) == fallback + + +@pytest.mark.parametrize( + "n,k,fallback", + [ + (2560, 6144, (16, 16, 1024, 2, 2)), + (1536, 6144, (16, 16, 1024, 2, 2)), + (6144, 768, (16, 32, 256, 4, 3)), + ], +) +def test_rocm_mxfp8_linear_preserves_non_gfx950_tiles(monkeypatch, n, k, fallback): + from vllm.model_executor.kernels.linear.mxfp8 import rocm_native + + monkeypatch.setattr(rocm_native, "_ON_GFX950", False) + for num_tokens in (1, 8, 16, 17): + assert rocm_native._select_cfg(num_tokens, n, k) == fallback + + +@pytest.mark.parametrize( + "name,n,k", V41_ATTN_SHAPES + M31_TP4_SHAPES, ids=lambda v: str(v) +) +@pytest.mark.parametrize("num_tokens", [1, 2, 7, 8, 16, 31, 32, 128, 1024]) @torch.inference_mode() def test_rocm_mxfp8_linear_matches_dequant_reference(name, n, k, num_tokens): """Output is finite and matches an exact MXFP8 GEMM of the same inputs. diff --git a/tests/kernels/test_fused_minimax_m3_qknorm_rope_kv_insert.py b/tests/kernels/test_fused_minimax_m3_qknorm_rope_kv_insert.py index d6a96c6c9960..9ae8c6fd2dbf 100644 --- a/tests/kernels/test_fused_minimax_m3_qknorm_rope_kv_insert.py +++ b/tests/kernels/test_fused_minimax_m3_qknorm_rope_kv_insert.py @@ -156,6 +156,74 @@ def test_dense_norm_rope(num_tokens, num_heads, num_kv_heads): torch.testing.assert_close(v_out, v_in, rtol=0, atol=0) +@pytest.mark.parametrize("num_tokens", [1, 7, 513]) +@pytest.mark.parametrize("block_size", [16, 128]) +@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8"]) +def test_dense_insert_matches_reshape_and_cache_flash( + num_tokens, block_size, kv_cache_dtype +): + """A dense layer's insert stores exactly what reshape_and_cache_flash + writes from the normed/roped k (unit scales), and leaves q/k/v as the + insert-free call does.""" + torch.manual_seed(0) + device, dtype, eps = "cuda", torch.bfloat16, 1e-6 + num_heads, num_kv_heads, max_pos = 8, 2, 4096 + q_w = torch.randn(HEAD_DIM, dtype=dtype, device=device) * 0.1 + k_w = torch.randn(HEAD_DIM, dtype=dtype, device=device) * 0.1 + cos_sin = make_cos_sin_cache(max_pos, ROTARY_DIM, 5_000_000.0, dtype, device) + positions = torch.randint( + 0, max_pos, (num_tokens,), dtype=torch.int64, device=device + ) + qsz, kvsz = num_heads * HEAD_DIM, num_kv_heads * HEAD_DIM + qkv = torch.randn(num_tokens, qsz + 2 * kvsz, dtype=dtype, device=device) + qkv_ref = qkv.clone() + num_blocks = (num_tokens + block_size - 1) // block_size + 2 + slot_mapping = torch.randperm(num_blocks * block_size, device=device)[ + :num_tokens + ].to(torch.int64) + slot_mapping[::4] = -1 # padding: no write + cache_dtype = torch.uint8 if kv_cache_dtype == "fp8" else dtype + kv_cache = torch.zeros( + num_blocks, + num_kv_heads, + block_size, + 2 * HEAD_DIM, + dtype=cache_dtype, + device=device, + ) + ref_cache = torch.zeros_like(kv_cache) + + args = (qkv, q_w, k_w, cos_sin, positions, num_heads, num_kv_heads) + ops.fused_minimax_m3_qknorm_rope_kv_insert( + *args, + ROTARY_DIM, + eps, + slot_mapping=slot_mapping, + kv_cache=kv_cache, + block_size=block_size, + kv_cache_dtype=kv_cache_dtype, + ) + ops.fused_minimax_m3_qknorm_rope_kv_insert( + qkv_ref, *args[1:], ROTARY_DIM, eps, kv_cache_dtype="auto" + ) + assert torch.equal(qkv, qkv_ref) + + _, k, v = qkv_ref.split([qsz, kvsz, kvsz], dim=-1) + key_cache, value_cache = ref_cache.transpose(1, 2).split(HEAD_DIM, dim=-1) + one = torch.ones((), dtype=torch.float32, device=device) + ops.reshape_and_cache_flash( + k.reshape(num_tokens, num_kv_heads, HEAD_DIM), + v.reshape(num_tokens, num_kv_heads, HEAD_DIM), + key_cache, + value_cache, + slot_mapping, + kv_cache_dtype, + one, + one, + ) + assert torch.equal(kv_cache, ref_cache) + + # ── Test 2: sparse mode (full: index branch + cache inserts) ───────────────── @@ -756,3 +824,368 @@ def test_sparse_full_nvfp4(num_tokens, num_kv_heads, block_size, kv_scales): torch.testing.assert_close( index_cache.view(-1, HEAD_DIM), expected_index_cache, rtol=0, atol=0 ) + + +@pytest.mark.skipif( + not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] != 10, + reason="NVFP4 KV caches need SM100", +) +@pytest.mark.parametrize("num_tokens", [7, 513]) +@pytest.mark.parametrize("block_size", [16, 128]) +@pytest.mark.parametrize("heads_per_rank", [1, 2]) +@pytest.mark.parametrize("kv_scales", [(0.5, 2.0), (1.0, 1.0)]) +def test_nvfp4_kv_head_major_slots_match_insert( + num_tokens, block_size, heads_per_rank, kv_scales +): + """The MSA NVFP4 spec's ``kv_head_major_slots`` claim holds for the bytes + the fused insert writes: slicing a TP1 page by KV head at the spec's byte + offsets, as NIXL does for a hetero-TP transfer, gives exactly the page a + decode rank holding those heads writes itself.""" + from vllm.models.minimax_m3.nvidia.sparse_attention_msa import ( + MiniMaxM3SparseMSANvfp4Backend, + ) + from vllm.v1.kv_cache_interface import FullAttentionSpec, KVQuantMode + + torch.manual_seed(7) + device, dtype, eps = "cuda", torch.bfloat16, 1e-6 + base, max_pos = 5_000_000.0, 4096 + num_kv_heads, q_per_kv, num_idx_heads = 4, 4, 1 + row_bytes = HEAD_DIM // 2 + HEAD_DIM // 16 + + spec = MiniMaxM3SparseMSANvfp4Backend.customize_spec( + FullAttentionSpec( + block_size=block_size, + num_kv_heads=num_kv_heads, + head_size=HEAD_DIM, + dtype=torch.uint8, + kv_quant_mode=KVQuantMode.NVFP4, + ) + ) + assert spec.kv_head_major_slots + assert spec.page_size_bytes == 2 * num_kv_heads * block_size * row_bytes + head_bytes = spec.page_size_bytes // num_kv_heads + + weights = [ + torch.randn(HEAD_DIM, dtype=dtype, device=device) * 0.1 for _ in range(4) + ] + cos_sin = make_cos_sin_cache(max_pos, ROTARY_DIM, base, dtype, device) + positions = torch.randint( + 0, max_pos, (num_tokens,), dtype=torch.int64, device=device + ) + k_scale, v_scale = ( + torch.tensor(s, dtype=torch.float32, device=device) for s in kv_scales + ) + num_blocks = (num_tokens + block_size - 1) // block_size + 1 + slot_mapping = torch.randperm( + num_blocks * block_size, dtype=torch.int64, device=device + )[:num_tokens] + index_slot_mapping = torch.randperm( + num_blocks * block_size, dtype=torch.int64, device=device + )[:num_tokens] + + # Per-head q / k / v columns, then the replicated index q / k columns. + q, k, v = ( + torch.randn(num_tokens, n, HEAD_DIM, dtype=dtype, device=device) + for n in (num_kv_heads * q_per_kv, num_kv_heads, num_kv_heads) + ) + v.copy_(nvfp4_edge_values(num_tokens * num_kv_heads, v_scale.item()).view_as(v)) + index_qk = torch.randn( + num_tokens, (num_idx_heads + 1) * HEAD_DIM, dtype=dtype, device=device + ) + + def insert(first_head, nkv): + heads = slice(first_head, first_head + nkv) + q_heads = slice(first_head * q_per_kv, (first_head + nkv) * q_per_kv) + qkv = torch.cat( + [q[:, q_heads].flatten(1), k[:, heads].flatten(1)] + + [v[:, heads].flatten(1), index_qk], + dim=-1, + ) + kv_cache = torch.zeros( + num_blocks * spec.page_size_bytes // num_kv_heads * nkv, + dtype=torch.uint8, + device=device, + ).view(num_blocks, 2 * nkv, block_size, row_bytes) + ops.fused_minimax_m3_qknorm_rope_kv_insert( + qkv, + *weights[:2], + cos_sin, + positions, + nkv * q_per_kv, + nkv, + ROTARY_DIM, + eps, + *weights[2:], + num_idx_heads, + slot_mapping, + index_slot_mapping, + kv_cache, + torch.zeros(num_blocks, block_size, HEAD_DIM, dtype=dtype, device=device), + block_size, + torch.empty( + num_tokens, nkv * q_per_kv * HEAD_DIM, dtype=dtype, device=device + ), + torch.empty( + num_tokens, num_idx_heads * HEAD_DIM, dtype=dtype, device=device + ), + "nvfp4", + kv_k_scale=k_scale, + kv_v_scale=v_scale, + ) + return kv_cache.view(num_blocks, -1) + + full_pages = insert(0, num_kv_heads) + rank_bytes = heads_per_rank * head_bytes + for first_head in range(0, num_kv_heads, heads_per_rank): + offset = first_head * head_bytes + sliced = full_pages[:, offset : offset + rank_bytes] + rank_pages = insert(first_head, heads_per_rank) + assert torch.equal(sliced, rank_pages), ( + f"heads {first_head}..{first_head + heads_per_rank - 1}: " + f"{int((sliced != rank_pages).sum())} bytes differ" + ) + + +# ── Test 6: sparse mode with an NVFP4 index-K cache ────────────────────────── + + +@pytest.mark.skipif( + not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] != 10, + reason="The NVFP4 reshape_and_cache_flash reference needs SM100", +) +@pytest.mark.parametrize("num_tokens", [1, 7, 513]) +@pytest.mark.parametrize("kv_cache_dtype", ["auto", "nvfp4"]) +@pytest.mark.parametrize("page_pad", [0, 48]) +def test_sparse_full_nvfp4_index(num_tokens, kv_cache_dtype, page_pad): + """The NVFP4 index-K insert writes MiniMax-M3.1 KV4 bytes as a single-head + NVFP4 K side with no global scale (E2M1 page, then linear E4M3 scales: the + MSA Q8KV4 page), honours a padded page stride and skips padded slots, while + index-Q and everything else match the fp8 index path exactly.""" + torch.manual_seed(6) + device, dtype, eps = "cuda", torch.bfloat16, 1e-6 + base, max_pos = 5_000_000.0, 4096 + num_heads, num_kv_heads, num_idx_heads, block_size = 16, 4, 4, 128 + page_width = HEAD_DIM // 2 + HEAD_DIM // 16 + + weights = [ + torch.randn(HEAD_DIM, dtype=dtype, device=device) * 0.1 for _ in range(4) + ] + cos_sin = make_cos_sin_cache(max_pos, ROTARY_DIM, base, dtype, device) + positions = torch.randint( + 0, max_pos, (num_tokens,), dtype=torch.int64, device=device + ) + qsz, kvsz = num_heads * HEAD_DIM, num_kv_heads * HEAD_DIM + iqsz = num_idx_heads * HEAD_DIM + qkv0 = torch.randn( + num_tokens, qsz + 2 * kvsz + iqsz + HEAD_DIM, dtype=dtype, device=device + ) + num_blocks = (num_tokens + block_size - 1) // block_size + 1 + slot_mapping = torch.randperm( + num_blocks * block_size, dtype=torch.int64, device=device + )[:num_tokens] + index_slot_mapping = torch.randperm( + num_blocks * block_size, dtype=torch.int64, device=device + )[:num_tokens] + index_slot_mapping[::5] = -1 # padded / unscheduled tokens are not written + nvfp4_kwargs = {} + if kv_cache_dtype == "nvfp4": + nvfp4_kwargs = dict( + kv_k_scale=torch.tensor(0.5, dtype=torch.float32, device=device), + kv_v_scale=torch.tensor(2.0, dtype=torch.float32, device=device), + ) + + def run(index_cache): + qkv = qkv0.clone() + if kv_cache_dtype == "nvfp4": + kv_cache = torch.zeros( + num_blocks, + 2 * num_kv_heads, + block_size, + page_width, + dtype=torch.uint8, + device=device, + ) + else: + kv_cache = torch.zeros( + num_blocks, + num_kv_heads, + block_size, + 2 * HEAD_DIM, + dtype=dtype, + device=device, + ) + index_q = torch.empty( + num_tokens, iqsz, dtype=torch.float8_e4m3fn, device=device + ) + ops.fused_minimax_m3_qknorm_rope_kv_insert( + qkv, + *weights[:2], + cos_sin, + positions, + num_heads, + num_kv_heads, + ROTARY_DIM, + eps, + *weights[2:], + num_idx_heads, + slot_mapping, + index_slot_mapping, + kv_cache, + index_cache, + block_size, + torch.empty(num_tokens, qsz, dtype=dtype, device=device), + index_q, + kv_cache_dtype, + **nvfp4_kwargs, + ) + return qkv, kv_cache, index_q + + fp8_index_cache = torch.zeros( + num_blocks, block_size, HEAD_DIM, dtype=torch.float8_e4m3fn, device=device + ) + qkv_fp8, kv_cache_fp8, index_q_fp8 = run(fp8_index_cache) + raw = torch.zeros( + num_blocks, + block_size * page_width + page_pad, + dtype=torch.uint8, + device=device, + ) + index_cache = raw[:, : block_size * page_width].view( + num_blocks, block_size, page_width + ) + qkv, kv_cache, index_q = run(index_cache) + + assert torch.equal(qkv, qkv_fp8) + assert torch.equal(kv_cache, kv_cache_fp8) + assert torch.equal(index_q.view(torch.uint8), index_q_fp8.view(torch.uint8)) + + # A one-head NVFP4 page's K side is [bs, 64] E2M1 then [bs, 8] linear + # scales, which is exactly the index page. + index_k = qkv.split([qsz, kvsz, kvsz, iqsz, HEAD_DIM], dim=-1)[-1] + expected = nvfp4_pages( + [(index_k.reshape(num_tokens, 1, HEAD_DIM), 1.0)], + index_slot_mapping, + num_blocks, + block_size, + ) + assert torch.equal(index_cache, expected[:, 0]), ( + f"{int((index_cache != expected[:, 0]).sum())} NVFP4 index bytes differ" + ) + assert not raw[:, block_size * page_width :].any() + + +# ── Test 7: write_qkv=False, for callers that read only the FP8 q ──────────── + + +@pytest.mark.skipif( + not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] != 10, + reason="NVFP4 KV caches need SM100", +) +@pytest.mark.parametrize("num_tokens", [1, 7, 513]) +@pytest.mark.parametrize("num_heads,num_kv_heads", [(64, 4), (32, 2), (16, 1)]) +@pytest.mark.parametrize("index_cache_dtype", ["nvfp4", "fp8"]) +@pytest.mark.parametrize("scales", [(1.0, 1.0, 1.0), (0.5, 2.0, 0.5)]) +def test_write_qkv_false( + num_tokens, num_heads, num_kv_heads, index_cache_dtype, scales +): + """write_qkv=False without q_out writes the same q_fp8_out, index_q_out and + cache bytes as a default call, and leaves qkv either untouched or as the + default call rewrites it (k and index_k need not be rewritten).""" + torch.manual_seed(7) + device, dtype, eps = "cuda", torch.bfloat16, 1e-6 + base, max_pos = 5_000_000.0, 4096 + num_idx_heads, block_size = num_kv_heads, 128 + page_width = HEAD_DIM // 2 + HEAD_DIM // 16 + k_scale, v_scale, q_scale = scales + + weights = [ + torch.randn(HEAD_DIM, dtype=dtype, device=device) * 0.1 for _ in range(4) + ] + cos_sin = make_cos_sin_cache(max_pos, ROTARY_DIM, base, dtype, device) + positions = torch.randint( + 0, max_pos, (num_tokens,), dtype=torch.int64, device=device + ) + qsz, kvsz = num_heads * HEAD_DIM, num_kv_heads * HEAD_DIM + iqsz = num_idx_heads * HEAD_DIM + qkv0 = torch.randn( + num_tokens, qsz + 2 * kvsz + iqsz + HEAD_DIM, dtype=dtype, device=device + ) + qkv0[:, qsz + kvsz : qsz + 2 * kvsz] = nvfp4_edge_values( + num_tokens * num_kv_heads, v_scale + ).view(num_tokens, kvsz) + num_blocks = (num_tokens + block_size - 1) // block_size + 1 + slot_mapping = torch.randperm( + num_blocks * block_size, dtype=torch.int64, device=device + )[:num_tokens] + slot_mapping[::5] = -1 + index_slot_mapping = torch.randperm( + num_blocks * block_size, dtype=torch.int64, device=device + )[:num_tokens] + kv_cache0 = torch.randint( + 0, + 256, + (num_blocks, 2 * num_kv_heads, block_size, page_width), + dtype=torch.uint8, + device=device, + ) + if index_cache_dtype == "nvfp4": + index_cache0 = torch.randint( + 0, + 256, + (num_blocks, block_size, page_width), + dtype=torch.uint8, + device=device, + ) + else: + index_cache0 = torch.randn(num_blocks, block_size, HEAD_DIM, device=device).to( + torch.float8_e4m3fn + ) + + def run(write_qkv): + qkv = qkv0.clone() + kv_cache, index_cache = kv_cache0.clone(), index_cache0.clone() + q_fp8 = torch.empty(num_tokens, qsz, dtype=torch.float8_e4m3fn, device=device) + index_q = torch.empty( + num_tokens, iqsz, dtype=torch.float8_e4m3fn, device=device + ) + ops.fused_minimax_m3_qknorm_rope_kv_insert( + qkv, + *weights[:2], + cos_sin, + positions, + num_heads, + num_kv_heads, + ROTARY_DIM, + eps, + *weights[2:], + num_idx_heads, + slot_mapping, + index_slot_mapping, + kv_cache, + index_cache, + block_size, + torch.empty(num_tokens, qsz, dtype=dtype, device=device) + if write_qkv + else None, + index_q, + "nvfp4", + q_fp8_out=q_fp8, + q_fp8_scale=q_scale, + kv_k_scale=torch.tensor(k_scale, dtype=torch.float32, device=device), + kv_v_scale=torch.tensor(v_scale, dtype=torch.float32, device=device), + write_qkv=write_qkv, + ) + return qkv, q_fp8, index_q, kv_cache, index_cache + + expected = run(True) + qkv, *got = run(False) + assert torch.equal(qkv.view(torch.int16), qkv0.view(torch.int16)) or ( + torch.equal(qkv.view(torch.int16), expected[0].view(torch.int16)) + ) + for name, g, e in zip( + ("q_fp8", "index_q", "kv_cache", "index_cache"), got, expected[1:] + ): + assert torch.equal(g.view(torch.uint8), e.view(torch.uint8)), ( + f"{name}: {int((g.view(torch.uint8) != e.view(torch.uint8)).sum())} " + "bytes differ" + ) diff --git a/tests/kernels/test_minimax_m3_amd_ops.py b/tests/kernels/test_minimax_m3_amd_ops.py index 868c2fcac7be..a984ce9b7557 100644 --- a/tests/kernels/test_minimax_m3_amd_ops.py +++ b/tests/kernels/test_minimax_m3_amd_ops.py @@ -27,6 +27,7 @@ import pytest import torch +from transformers import PreTrainedConfig from vllm.platforms import current_platform @@ -40,7 +41,12 @@ _mxfp8_e4m3_quantize_triton, dequant_mxfp8_to_bf16, ) -from vllm.models.minimax_m3.amd.model import _kv_insert_operand # noqa: E402 +from vllm.models.minimax_m3.amd.model import ( # noqa: E402 + MiniMAXGemmaRMSNorm, + MiniMaxM3SparseAttention, + _build_rotary_emb, + _kv_insert_operand, +) from vllm.models.minimax_m3.amd.ops import ( # noqa: E402 gemma_fused_add_rmsnorm, gemma_rmsnorm, @@ -48,6 +54,7 @@ swiglu_oai_split, ) from vllm.models.minimax_m3.amd.ops.gemma_rmsnorm import _num_warps # noqa: E402 +from vllm.platforms.rocm import on_gfx942 # noqa: E402 DEVICE = "cuda" EPS = 1e-6 @@ -688,3 +695,149 @@ def test_kv_insert_operand_copies_unsupported_layouts(): flat = k.reshape(32, -1) assert _kv_insert_operand(flat).is_contiguous() + + +@pytest.mark.skipif(not on_gfx942(), reason="Requires gfx942.") +@torch.inference_mode() +def test_gfx942_native_qknorm_rope_writes_main_and_index_caches(): + """The gfx942 fallback writes both caches and ignores padded slots.""" + from types import SimpleNamespace + + torch.manual_seed(0) + num_tokens = 3 + num_heads = 2 + num_kv_heads = num_idx_heads = 1 + head_dim = idx_head_dim = 16 + block_size = 4 + + attention = object.__new__(MiniMaxM3SparseAttention) + torch.nn.Module.__init__(attention) + attention.num_heads = num_heads + attention.num_kv_heads = num_kv_heads + attention.num_idx_heads = num_idx_heads + attention.head_dim = head_dim + attention.idx_head_dim = idx_head_dim + attention.q_size = num_heads * head_dim + attention.kv_size = num_kv_heads * head_dim + attention.index_q_size = num_idx_heads * idx_head_dim + attention.layer_name = "model.layers.0.self_attn" + attention.skip_index_topk = False + attention.kv_cache_dtype = "fp8" + + attention.q_norm = MiniMAXGemmaRMSNorm(head_dim).to( + device=DEVICE, dtype=torch.bfloat16 + ) + attention.k_norm = MiniMAXGemmaRMSNorm(head_dim).to( + device=DEVICE, dtype=torch.bfloat16 + ) + attention.index_q_norm = MiniMAXGemmaRMSNorm(idx_head_dim).to( + device=DEVICE, dtype=torch.bfloat16 + ) + attention.index_k_norm = MiniMAXGemmaRMSNorm(idx_head_dim).to( + device=DEVICE, dtype=torch.bfloat16 + ) + config = PreTrainedConfig( + rope_theta=10000.0, + partial_rotary_factor=0.5, + max_position_embeddings=32, + ) + from vllm.config import VllmConfig, set_current_vllm_config + + with set_current_vllm_config(VllmConfig()): + attention.rotary_emb = _build_rotary_emb(config, head_dim).to(DEVICE) + attention.index_rotary_emb = attention.rotary_emb + + fp8_dtype = current_platform.fp8_dtype() + attention.kv_cache = torch.zeros( + 2, + num_kv_heads, + block_size, + 2 * head_dim, + device=DEVICE, + dtype=fp8_dtype, + ) + attention._k_scale = torch.ones((), device=DEVICE, dtype=torch.float32) + attention._v_scale = torch.ones((), device=DEVICE, dtype=torch.float32) + index_cache = torch.zeros( + 2, block_size, idx_head_dim, device=DEVICE, dtype=torch.bfloat16 + ) + index_prefix = "model.layers.0.self_attn.indexer" + attention.indexer = SimpleNamespace( + index_cache=SimpleNamespace( + dtype=torch.bfloat16, + kv_cache=index_cache, + prefix=index_prefix, + ) + ) + + width = ( + attention.q_size + + 2 * attention.kv_size + + attention.index_q_size + + attention.idx_head_dim + ) + qkv = torch.randn(num_tokens, width, device=DEVICE, dtype=torch.bfloat16).mul_(0.25) + positions = torch.tensor([0, 1, 2], device=DEVICE, dtype=torch.long) + main_slots = torch.tensor([0, -1, 5], device=DEVICE, dtype=torch.long) + index_slots = torch.tensor([2, -1, 6], device=DEVICE, dtype=torch.long) + + q_raw, k_raw, v_raw, index_q_raw, index_k_raw = qkv.clone().split( + [ + attention.q_size, + attention.kv_size, + attention.kv_size, + attention.index_q_size, + attention.idx_head_dim, + ], + dim=-1, + ) + expected_q = attention.q_norm(q_raw.view(num_tokens, num_heads, head_dim)) + expected_k = attention.k_norm(k_raw.view(num_tokens, num_kv_heads, head_dim)) + expected_q, expected_k = attention.rotary_emb.forward_native( + positions, expected_q, expected_k + ) + expected_index_q = attention.index_q_norm( + index_q_raw.view(num_tokens, num_idx_heads, idx_head_dim) + ) + expected_index_k = attention.index_k_norm( + index_k_raw.view(num_tokens, idx_head_dim) + ) + expected_index_q, expected_index_k = attention.index_rotary_emb.forward_native( + positions, expected_index_q, expected_index_k + ) + assert expected_k is not None + assert expected_index_k is not None + + q, index_q = attention._native_gfx942_qknorm_rope_cache( + qkv, + positions, + { + attention.layer_name: main_slots, + index_prefix: index_slots, + }, + ) + + torch.testing.assert_close(q, expected_q.reshape(num_tokens, -1)) + assert index_q is not None + torch.testing.assert_close(index_q, expected_index_q.reshape(num_tokens, -1)) + + expected_v = v_raw.view(num_tokens, num_kv_heads, head_dim) + for token, slot in ((0, 0), (2, 5)): + block, offset = divmod(slot, block_size) + assert torch.equal( + attention.kv_cache[block, 0, offset, :head_dim], + expected_k[token, 0].to(fp8_dtype), + ) + assert torch.equal( + attention.kv_cache[block, 0, offset, head_dim:], + expected_v[token, 0].to(fp8_dtype), + ) + assert torch.count_nonzero(attention.kv_cache[0, 0, 1]) == 0 + + for token, slot in ((0, 2), (2, 6)): + block, offset = divmod(slot, block_size) + assert torch.equal( + index_cache[block, offset], + expected_index_k[token].to(index_cache.dtype), + ) + assert torch.count_nonzero(index_cache[0, 1]) == 0 diff --git a/tests/kernels/test_minimax_m3_dspark_draft.py b/tests/kernels/test_minimax_m3_dspark_draft.py new file mode 100644 index 000000000000..1a5c3be14466 --- /dev/null +++ b/tests/kernels/test_minimax_m3_dspark_draft.py @@ -0,0 +1,442 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MiniMax-M3.1 DSpark draft fusions against the unfused ops they replace. + +- The context-KV CUDA kernel + (vllm/models/minimax_m3/common/ops/dspark_context_kv.py) against flashinfer + gemma_rmsnorm per layer, vllm._custom_ops.rotary_embedding (partial NeoX) and + vllm._custom_ops.reshape_and_cache_flash into FlashAttention-layout caches + [num_blocks, nkv, block_size, 2 * hd] viewed as + kv_cache.transpose(1, 2).split(hd, dim=-1). +- The draft attention's fused q/k Gemma norm + RoPE against DFlash's q-norm, + k-norm and RoPE. +""" + +from types import SimpleNamespace + +import pytest +import torch + +import vllm._custom_ops as ops +from vllm.models.minimax_m3.common.ops.dspark_context_kv import ( + DSparkContextKVWriter, +) +from vllm.platforms import current_platform +from vllm.utils.torch_utils import set_default_torch_dtype + +flashinfer_norm = pytest.importorskip("flashinfer.norm") + +HEAD_DIM = 128 +ROTARY_DIM = 64 +BLOCK_SIZE = 16 +EPS = 1e-6 + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available(), reason="CUDA not available" +) + + +def make_cos_sin_cache(max_pos, rotary_dim, dtype, device): + inv_freq = 1.0 / ( + 5_000_000.0 + ** ( + torch.arange(0, rotary_dim, 2, dtype=torch.float32, device=device) + / rotary_dim + ) + ) + t = torch.arange(max_pos, dtype=torch.float32, device=device) + freqs = torch.einsum("i,j->ij", t, inv_freq) + return torch.cat((freqs.cos(), freqs.sin()), dim=-1).to(dtype) + + +def make_slots(num_ctx, num_blocks, device): + """Unique valid slots with ~1/4 padding (-1), at least one valid.""" + num_slots = num_blocks * BLOCK_SIZE + slots = torch.randperm(num_slots, device=device)[:num_ctx].to(torch.int64) + num_pad = max(1, num_ctx // 4) + slots[:num_pad] = -1 + return slots + + +def build_layers(kv_cache_dtype, L, nkv, num_blocks, device, seed, unit_scale=False): + g = torch.Generator(device="cpu").manual_seed(seed) + if kv_cache_dtype == "fp8" and not unit_scale: + dtype = torch.uint8 + scale = lambda: ( # noqa: E731 + torch.rand((), generator=g).to(device) * 1.5 + 0.25 + ) + else: + dtype = torch.uint8 if kv_cache_dtype == "fp8" else torch.bfloat16 + scale = lambda: torch.ones((), device=device) # noqa: E731 + layers = [] + for _ in range(L): + layers.append( + SimpleNamespace( + kv_cache=torch.zeros( + num_blocks, + nkv, + BLOCK_SIZE, + 2 * HEAD_DIM, + dtype=dtype, + device=device, + ), + _k_scale=scale(), + _v_scale=scale(), + kv_cache_dtype=kv_cache_dtype, + ) + ) + return layers + + +def reference_update( + all_kv, k_norm_w, positions, cos_sin, slot_mapping, layers, kv_cache_dtype +): + """The unfused path, run on `layers`' caches.""" + num_ctx, L, _, nkv, hd = all_kv.shape + all_k = torch.stack( + [ + flashinfer_norm.gemma_rmsnorm(all_kv[:, layer, 0], k_norm_w[layer], EPS) + for layer in range(L) + ] + ) # [L, num_ctx, nkv, hd] + all_v = all_kv[:, :, 1] # [num_ctx, L, nkv, hd] + k_flat = all_k.view(L * num_ctx, nkv * hd) + ops.rotary_embedding( + positions.repeat(L), + k_flat, + None, + hd, + cos_sin.to(k_flat.dtype), + True, + ) + all_k = k_flat.view(L, num_ctx, nkv, hd) + for layer, a in enumerate(layers): + kc, vc = a.kv_cache.transpose(1, 2).split(hd, dim=-1) + ops.reshape_and_cache_flash( + all_k[layer], + all_v[:, layer].contiguous(), + kc, + vc, + slot_mapping, + kv_cache_dtype, + a._k_scale, + a._v_scale, + ) + + +def assert_bf16_close(got, exp): + diff = (got.view(torch.int16).int() - exp.view(torch.int16).int()).abs() + assert int(diff.max()) <= 1, ( + f"bf16 cache differs by {int(diff.max())} ulp " + f"in {int((diff > 0).sum())} elements" + ) + + +def assert_fp8_close(got, exp): + equal = got == exp + frac = equal.float().mean().item() + assert frac >= 0.999, f"fp8 cache matches only {frac:.4%} of bytes" + bad = ~equal + if bad.any(): + byte_diff = (got[bad].int() - exp[bad].int()).abs() + g = got[bad].view(torch.float8_e4m3fn).float() + e = exp[bad].view(torch.float8_e4m3fn).float() + ok = (byte_diff <= 1) | ((g == 0) & (e == 0)) + assert bool(ok.all()), ( + f"fp8 cache differs by more than 1 step in {int((~ok).sum())} bytes" + ) + + +def run_case( + kv_cache_dtype, num_ctx, nkv, L, seed=0, rotary_dim=ROTARY_DIM, unit_scale=False +): + torch.manual_seed(seed) + device = "cuda" + num_blocks = (num_ctx * 2 + BLOCK_SIZE - 1) // BLOCK_SIZE + 1 + + layers, ref_layers = ( + build_layers(kv_cache_dtype, L, nkv, num_blocks, device, seed, unit_scale) + for _ in range(2) + ) + + all_kv = torch.randn( + num_ctx, L, 2, nkv, HEAD_DIM, dtype=torch.bfloat16, device=device + ) + k_norm_w = torch.randn(L, HEAD_DIM, dtype=torch.bfloat16, device=device) * 0.2 + positions = torch.randint(0, 2048, (num_ctx,), dtype=torch.int64, device=device) + cos_sin = make_cos_sin_cache(2048, rotary_dim, torch.bfloat16, device) + slot_mapping = make_slots(num_ctx, num_blocks, device) + + writer = DSparkContextKVWriter(layers) + writer(all_kv, k_norm_w, EPS, positions, cos_sin, rotary_dim, slot_mapping) + reference_update( + all_kv, k_norm_w, positions, cos_sin, slot_mapping, ref_layers, kv_cache_dtype + ) + + for a, b in zip(layers, ref_layers): + if kv_cache_dtype == "fp8": + assert_fp8_close(a.kv_cache, b.kv_cache) + else: + assert_bf16_close(a.kv_cache, b.kv_cache) + + +@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8"]) +@pytest.mark.parametrize("num_ctx", [1, 7, 64, 300]) +@pytest.mark.parametrize("nkv", [1, 2]) +@pytest.mark.parametrize("L", [1, 5]) +def test_dspark_context_kv(kv_cache_dtype, num_ctx, nkv, L): + run_case(kv_cache_dtype, num_ctx, nkv, L) + + +@pytest.mark.parametrize("num_ctx", [7, 300]) +def test_dspark_context_kv_fp8_unit_scale(num_ctx): + """Unit k/v scales take the kernel's direct bf16 -> e4m3 conversion.""" + run_case("fp8", num_ctx, nkv=2, L=5, unit_scale=True) + + +@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8"]) +@pytest.mark.parametrize("rotary_dim", [16, 32]) +def test_dspark_context_kv_short_rope(kv_cache_dtype, rotary_dim): + """Only some lanes rotate when rotary_dim < 64.""" + run_case(kv_cache_dtype, 64, nkv=2, L=2, rotary_dim=rotary_dim) + + +@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8"]) +def test_dspark_context_kv_cuda_graph(kv_cache_dtype): + torch.manual_seed(0) + device = "cuda" + num_ctx, nkv, L = 16, 1, 5 + num_blocks = 8 + + layers = build_layers(kv_cache_dtype, L, nkv, num_blocks, device, seed=0) + all_kv = torch.randn( + num_ctx, L, 2, nkv, HEAD_DIM, dtype=torch.bfloat16, device=device + ) + k_norm_w = torch.randn(L, HEAD_DIM, dtype=torch.bfloat16, device=device) * 0.2 + positions = torch.randint(0, 2048, (num_ctx,), dtype=torch.int64, device=device) + cos_sin = make_cos_sin_cache(2048, ROTARY_DIM, torch.bfloat16, device) + slot_mapping = make_slots(num_ctx, num_blocks, device) + + writer = DSparkContextKVWriter(layers) + writer._ensure_tables() # build pointer tables outside the graph + + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + writer(all_kv, k_norm_w, EPS, positions, cos_sin, ROTARY_DIM, slot_mapping) + torch.cuda.current_stream().wait_stream(stream) + + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + writer(all_kv, k_norm_w, EPS, positions, cos_sin, ROTARY_DIM, slot_mapping) + + # Change every input in place, replay, and compare against the unfused + # reference run on the new inputs. + all_kv.copy_(torch.randn_like(all_kv)) + positions.copy_( + torch.randint(0, 2048, (num_ctx,), dtype=torch.int64, device=device) + ) + slot_mapping.copy_(make_slots(num_ctx, num_blocks, device)) + + sentinel = 0x5A if kv_cache_dtype == "fp8" else 0x3F80 + for a in layers: + a.kv_cache.fill_(sentinel) + graph.replay() + + ref_layers = build_layers(kv_cache_dtype, L, nkv, num_blocks, device, seed=0) + for a in ref_layers: + a.kv_cache.fill_(sentinel) + reference_update( + all_kv, k_norm_w, positions, cos_sin, slot_mapping, ref_layers, kv_cache_dtype + ) + + torch.accelerator.synchronize() + for a, b in zip(layers, ref_layers): + if kv_cache_dtype == "fp8": + assert_fp8_close(a.kv_cache, b.kv_cache) + else: + assert_bf16_close(a.kv_cache, b.kv_cache) + + +def test_dspark_context_kv_supported_by_cache_layout(): + """The writer engages on the [nb, nkv, bs, 2 * 128] page that FLASH_ATTN + and FLASHINFER_TS share, whatever the backend, and not on a 5-D cache.""" + layers = build_layers("fp8", 5, 1, 4, "cuda", seed=0, unit_scale=True) + assert DSparkContextKVWriter.supported(layers) + layers[0].kv_cache = torch.zeros( + 4, 2, BLOCK_SIZE, 1, HEAD_DIM, dtype=torch.uint8, device="cuda" + ) + assert not DSparkContextKVWriter.supported(layers) + + +class _CaptureAttention(torch.nn.Module): + """Stands in for the draft's Attention: records the q/k/v it is given.""" + + _q_scale_float = 1.0 + + def __init__(self, layer_name): + super().__init__() + self.layer_name = layer_name + + def forward(self, q, k, v, output_dtype=None): + self.qkv = tuple(None if t is None else t.clone() for t in (q, k, v)) + return torch.zeros_like(q, dtype=output_dtype) + + +@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8"]) +def test_draft_attention_fused_qk_norm_rope( + dist_init, default_vllm_config, kv_cache_dtype +): + """One fused launch gives the q of DFlash's q-norm and RoPE and stores its + k/v in a bf16 or fp8 cache as the layer's reshape_and_cache_flash would; + the attention layer gets q alone.""" + from vllm.forward_context import set_forward_context + from vllm.model_executor.models.qwen3_dflash import DFlashQwen3Attention + from vllm.models.minimax_m3.common.dspark import MiniMaxM3DSparkAttention + from vllm.transformers_utils.configs.minimax_m3 import MiniMaxM3TextConfig + + torch.manual_seed(0) + config = MiniMaxM3TextConfig( + hidden_size=512, + num_attention_heads=8, + num_key_value_heads=2, + head_dim=HEAD_DIM, + max_position_embeddings=8192, + ) + with torch.device("cuda"), set_default_torch_dtype(torch.bfloat16): + attn = MiniMaxM3DSparkAttention( + config, + sliding_window=None, + causal=False, + cache_config=None, + quant_config=None, + prefix="model.layers.0.self_attn", + ) + for param in (attn.qkv_proj.weight, attn.q_norm.weight, attn.k_norm.weight): + param.data.normal_(std=0.05) + layer = attn.attn + cache_dtype = torch.uint8 if kv_cache_dtype == "fp8" else torch.bfloat16 + layer.kv_cache = torch.zeros( + 4, 2, BLOCK_SIZE, 2 * HEAD_DIM, dtype=cache_dtype, device="cuda" + ) + attn.attn = _CaptureAttention(layer.layer_name) + + hidden = torch.randn(7, config.hidden_size, device="cuda", dtype=torch.bfloat16) + positions = torch.tensor([0, 1, 127, 128, 4000, 8190, 9], device="cuda") + slots = torch.tensor([5, -1, 17, 18, 40, 63, 0], device="cuda") + DFlashQwen3Attention.forward(attn, positions, hidden) + q_ref, k_ref, v_ref = attn.attn.qkv + with set_forward_context( + None, default_vllm_config, slot_mapping={layer.layer_name: slots} + ): + attn(positions, hidden) + q, k, v = attn.attn.qkv + torch.testing.assert_close(q, q_ref, atol=2e-2, rtol=2e-2) + assert k is None and v is None + expected = torch.zeros_like(layer.kv_cache) + key_cache, value_cache = expected.transpose(1, 2).split(HEAD_DIM, dim=-1) + one = torch.ones((), dtype=torch.float32, device="cuda") + ops.reshape_and_cache_flash( + k_ref.reshape(7, 2, HEAD_DIM), + v_ref.reshape(7, 2, HEAD_DIM), + key_cache, + value_cache, + slots, + kv_cache_dtype, + one, + one, + ) + got, rtol = layer.kv_cache, 2e-2 + if kv_cache_dtype == "fp8": + # k/v_ref come from DFlash's unfused kernels: allow one e4m3 step. + got = got.view(torch.float8_e4m3fn).float() + expected = expected.view(torch.float8_e4m3fn).float() + rtol = 0.13 + torch.testing.assert_close(got, expected, atol=2e-2, rtol=rtol) + + +class _FixedOutputAttention(torch.nn.Module): + """Stands in for the draft's Attention: returns a fixed output in the + requested dtype and records the dtypes asked for.""" + + def __init__(self, layer_name, out): + super().__init__() + self.layer_name, self.out, self.output_dtypes = layer_name, out, [] + + def forward(self, q, k, v, output_dtype): + self.output_dtypes.append(output_dtype) + return self.out.to(output_dtype) + + +@pytest.mark.skipif( + not current_platform.is_device_capability_family(100), + reason="Native MXFP8 kernels require SM100-family CUDA", +) +@torch.inference_mode() +def test_draft_fp16_attention_output_feeds_mxfp8_o_proj(dist_init, default_vllm_config): + """A backend that writes an FP8 query's output as FP16 hands it to the + MXFP8 o_proj without a conversion pass; o_proj quantizes it and still + returns bf16, bit-identical to the bf16 path for values both dtypes hold.""" + from vllm.forward_context import set_forward_context + from vllm.model_executor.layers.quantization.modelopt import ModelOptMxFp8Config + from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( + _mxfp8_e4m3_quantize_torch, + ) + from vllm.models.minimax_m3.common.dspark import MiniMaxM3DSparkAttention + from vllm.transformers_utils.configs.minimax_m3 import MiniMaxM3TextConfig + + torch.manual_seed(0) + config = MiniMaxM3TextConfig( + hidden_size=512, + num_attention_heads=8, + num_key_value_heads=2, + head_dim=HEAD_DIM, + max_position_embeddings=8192, + ) + quant_config = ModelOptMxFp8Config.from_config( + { + "quant_method": "mxfp8", + "activation_scheme": "dynamic", + "weight_block_size": [1, 32], + "ignored_layers": [], + } + ) + with torch.device("cuda"), set_default_torch_dtype(torch.bfloat16): + attn = MiniMaxM3DSparkAttention( + config, + sliding_window=None, + causal=False, + cache_config=None, + quant_config=quant_config, + prefix="model.layers.0.self_attn", + query_pre_quantized=True, + ) + for proj in (attn.qkv_proj, attn.o_proj): + weight, scale = _mxfp8_e4m3_quantize_torch( + torch.randn(proj.weight.shape, device="cuda") / 16 + ) + proj.weight.data.copy_(weight) + proj.weight_scale.data.copy_(scale) + proj.quant_method.process_weights_after_loading(proj) + layer = attn.attn + layer.kv_cache = torch.zeros( + 4, 2, BLOCK_SIZE, 2 * HEAD_DIM, dtype=torch.uint8, device="cuda" + ) + num_tokens = 7 + out = torch.randint(-256, 256, (num_tokens, attn.q_size), device="cuda") / 128 + attn.attn = _FixedOutputAttention(layer.layer_name, out.to(torch.bfloat16)) + + hidden = torch.randn( + num_tokens, config.hidden_size, device="cuda", dtype=torch.bfloat16 + ) + positions = torch.arange(num_tokens, device="cuda") + outputs = [] + for attn_output_dtype in (torch.float16, None): + attn._attn_output_dtype = attn_output_dtype + with set_forward_context( + None, default_vllm_config, slot_mapping={layer.layer_name: positions} + ): + outputs.append(attn(positions, hidden)) + assert attn.attn.output_dtypes == [torch.float16, torch.bfloat16] + assert outputs[0].dtype == torch.bfloat16 + torch.testing.assert_close(outputs[0], outputs[1], atol=0, rtol=0) diff --git a/tests/kernels/test_minimax_m3_sp_coll.py b/tests/kernels/test_minimax_m3_sp_coll.py new file mode 100644 index 000000000000..bfa5919fd7d0 --- /dev/null +++ b/tests/kernels/test_minimax_m3_sp_coll.py @@ -0,0 +1,193 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""ops.sp_coll on four GPUs vs CPU references: gathers bitwise, reduce-scatter = +the fp32 rank-order sum; slot reuse, in-place inputs and the RCCL fallback.""" + +import pytest +import torch +import torch.distributed as dist +import torch.multiprocessing as mp + +from vllm.platforms import current_platform + +WORLD = 4 +HIDDEN = 1024 +ROWS = 256 # rows per rank + +pytestmark = pytest.mark.skipif( + not current_platform.is_rocm(), reason="FlyDSL kernel is ROCm-only" +) + + +class _NoRccl: + """Records the calls that fell back to RCCL.""" + + def __init__(self): + self.calls = [] + + def all_gather(self, outs, ins): + self.calls.append("all_gather") + for o, i in zip(outs, ins): + gathered = [torch.empty_like(i.cpu()) for _ in range(WORLD)] + dist.all_gather(gathered, i.cpu()) + exp = torch.cat(gathered) + o.view(exp.shape).copy_(exp.to(o.device)) + + def reduce_scatter(self, out, x): + raise AssertionError("unexpected fallback") + + def all_to_all(self, out, x): + raise AssertionError("unexpected fallback") + + +def _gather_cpu(x: torch.Tensor) -> list[torch.Tensor]: + xs = [torch.empty_like(x.cpu()) for _ in range(WORLD)] + dist.all_gather(xs, x.cpu().contiguous()) + return xs + + +def _worker(rank: int, init_file: str, errors): + try: + _run(rank, init_file) + except Exception as e: # noqa: BLE001 + errors.put(f"rank {rank}: {type(e).__name__}: {e}") + raise + + +def _run(rank: int, init_file: str): + torch.cuda.set_device(rank) + dev = torch.device("cuda", rank) + dist.init_process_group( + "gloo", init_method=f"file://{init_file}", rank=rank, world_size=WORLD + ) + from vllm.models.minimax_m3.amd.ops import sp_coll + + padded = ROWS * WORLD + q = 512 + # the largest phase: bf16 partials + two bf16 gathers (as sp_prefill sizes it) + slot = padded * HIDDEN * 2 + 2 * ROWS * HIDDEN * 2 + 4096 + pools = sp_coll.Pools(rank, WORLD, dist.group.WORLD, dev, slot, sets=3) + stream = torch.cuda.current_stream() + gen = torch.Generator().manual_seed(100 + rank) + + def rnd_u8(*shape): + return torch.randint(0, 256, shape, generator=gen, dtype=torch.uint8).to(dev) + + for phase in range(6): + set_id = phase % 3 # three slot sets + rccl = _NoRccl() + coll = sp_coll.Collectives(pools, set_id).bind(stream, rccl) + # attention phase: all-to-all, then gathers + send = rnd_u8(WORLD * ROWS, q + q // 32) + recv = torch.empty_like(send) + coll.all_to_all(recv, send) + codes = rnd_u8(ROWS, HIDDEN).view(torch.float8_e4m3fn) + scales = rnd_u8(ROWS, HIDDEN // 32) + routing = torch.randint( + -(2**31), 2**31 - 1, (ROWS, 18), generator=gen, dtype=torch.int32 + ).to(dev) + g_codes = torch.empty((padded, HIDDEN), dtype=codes.dtype, device=dev) + g_scales = torch.empty((padded, HIDDEN // 32), dtype=torch.uint8, device=dev) + g_routing = torch.empty((padded, 18), dtype=torch.int32, device=dev) + coll.all_gather([g_codes, g_scales, g_routing], [codes, scales, routing]) + torch.cuda.synchronize() + sends = _gather_cpu(send) + for p in range(WORLD): + exp = sends[p][rank * ROWS : (rank + 1) * ROWS] + assert torch.equal(recv[p * ROWS : (p + 1) * ROWS].cpu(), exp), (phase, p) + for g, x in ((g_codes, codes), (g_scales, scales), (g_routing, routing)): + if x.dtype != torch.int32: + g, x = g.view(torch.uint8), x.view(torch.uint8) + assert torch.equal(g.cpu(), torch.cat(_gather_cpu(x))), (phase, x.dtype) + assert rccl.calls == [] + # MoE phase: reduce-scatter, then gathers + coll = sp_coll.Collectives(pools, set_id).bind(stream, rccl) + part = torch.randn((padded, HIDDEN), generator=gen) * (1 + rank) + part = part.bfloat16().to(dev) + h = torch.empty((ROWS, HIDDEN), dtype=torch.bfloat16, device=dev) + coll.reduce_scatter(h, part) + aux = (torch.randn((ROWS, HIDDEN), generator=gen)).bfloat16().to(dev) + ctx = (torch.randn((ROWS, HIDDEN), generator=gen)).bfloat16().to(dev) + g_aux = torch.empty((padded, HIDDEN), dtype=torch.bfloat16, device=dev) + g_ctx = torch.empty((padded, HIDDEN), dtype=torch.bfloat16, device=dev) + coll.all_gather([g_aux, g_ctx], [aux, ctx]) + torch.cuda.synchronize() + parts = _gather_cpu(part) + acc = torch.zeros((ROWS, HIDDEN), dtype=torch.float32) + for p in range(WORLD): + acc += parts[p][rank * ROWS : (rank + 1) * ROWS].float() + assert torch.equal(h.cpu(), acc.bfloat16()), phase + assert torch.equal(g_aux.cpu(), torch.cat(_gather_cpu(aux))), phase + assert torch.equal(g_ctx.cpu(), torch.cat(_gather_cpu(ctx))), phase + assert rccl.calls == [] + # slot views from alloc are read in place + rccl = _NoRccl() + coll = sp_coll.Collectives(pools, 1) + send = coll.alloc((WORLD * ROWS, q + q // 32), torch.uint8) + send.copy_(rnd_u8(WORLD * ROWS, q + q // 32)) + recv = torch.empty((WORLD * ROWS, q + q // 32), dtype=torch.uint8, device=dev) + coll.bind(stream, rccl).all_to_all(recv, send) + coll = sp_coll.Collectives(pools, 1) + part = coll.alloc((padded, HIDDEN), torch.bfloat16) + part.copy_((torch.randn((padded, HIDDEN), generator=gen) * 3).bfloat16()) + h = torch.empty((ROWS, HIDDEN), dtype=torch.bfloat16, device=dev) + coll.bind(stream, rccl).reduce_scatter(h, part) + torch.cuda.synchronize() + sends, parts = _gather_cpu(send), _gather_cpu(part) + for p in range(WORLD): + exp = sends[p][rank * ROWS : (rank + 1) * ROWS] + assert torch.equal(recv[p * ROWS : (p + 1) * ROWS].cpu(), exp), p + acc = torch.zeros((ROWS, HIDDEN), dtype=torch.float32) + for p in range(WORLD): + acc += parts[p][rank * ROWS : (rank + 1) * ROWS].float() + assert torch.equal(h.cpu(), acc.bfloat16()) + assert rccl.calls == [] + # all_to_all_unpack = all_to_all + mxfp8_unpack + from vllm.models.minimax_m3.amd.ops.sp_pack import mxfp8_unpack + + rccl = _NoRccl() + coll = sp_coll.Collectives(pools, 0).bind(stream, rccl) + send = rnd_u8(WORLD * ROWS, q + q // 32) + recv = torch.empty_like(send) + coll.all_to_all(recv, send) + coll = sp_coll.Collectives(pools, 0).bind(stream, rccl) + codes, scales = coll.all_to_all_unpack(send, q) + torch.cuda.synchronize() + ref_codes, ref_scales = mxfp8_unpack(recv, WORLD, ROWS, q) + assert torch.equal(codes.view(torch.uint8), ref_codes.view(torch.uint8)) + assert torch.equal(scales, ref_scales) + assert rccl.calls == [] + # a phase that does not fit the slot falls back to RCCL + rccl = _NoRccl() + coll = sp_coll.Collectives(pools, 0).bind(stream, rccl) + big = rnd_u8(4 * padded, HIDDEN) + g_big = torch.empty((WORLD, 4 * padded, HIDDEN), dtype=torch.uint8, device=dev) + coll.all_gather([g_big], [big]) + torch.cuda.synchronize() + assert rccl.calls == ["all_gather"] + assert torch.equal(g_big.view(-1, HIDDEN).cpu(), torch.cat(_gather_cpu(big))) + dist.barrier() + dist.destroy_process_group() + + +def test_sp_coll_four_gpus(tmp_path): + if torch.cuda.device_count() < WORLD: + pytest.skip("needs four GPUs") + from vllm.platforms.rocm import on_gfx950 + + if not on_gfx950(): + pytest.skip("the kernels use gfx950 instructions") + ctx = mp.get_context("spawn") + errors = ctx.Queue() + init_file = str(tmp_path / "init") + procs = [ + ctx.Process(target=_worker, args=(r, init_file, errors)) for r in range(WORLD) + ] + for p in procs: + p.start() + for p in procs: + p.join(timeout=600) + msgs = [] + while not errors.empty(): + msgs.append(errors.get()) + assert all(p.exitcode == 0 for p in procs), msgs or [p.exitcode for p in procs] diff --git a/tests/kernels/test_minimax_m3_sp_prefill_kernels.py b/tests/kernels/test_minimax_m3_sp_prefill_kernels.py new file mode 100644 index 000000000000..bd1b5121dd06 --- /dev/null +++ b/tests/kernels/test_minimax_m3_sp_prefill_kernels.py @@ -0,0 +1,97 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MiniMax-M3 sequence-parallel prefill kernels, bit for bit against the kernels +they replace.""" + +import pytest +import torch + +from vllm.platforms import current_platform + +if not current_platform.is_rocm(): + pytest.skip("ROCm sequence-parallel prefill kernels", allow_module_level=True) + +from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( # noqa: E402 + _mxfp8_e4m3_quantize_triton, +) +from vllm.models.minimax_m3.amd.ops.gemma_rmsnorm import ( # noqa: E402 + gemma_fused_add_rmsnorm, + gemma_rmsnorm, +) +from vllm.models.minimax_m3.amd.ops.sp_norm_quant import ( # noqa: E402 + MOE_MIN_SCALE_BYTE, + gemma_rmsnorm_mx, +) +from vllm.models.minimax_m3.amd.ops.sp_pack import ( # noqa: E402 + mxfp8_quant_pack, + mxfp8_unpack, +) + + +def _rows(m: int, n: int, seed: int) -> torch.Tensor: + g = torch.Generator(device="cuda").manual_seed(seed) + x = torch.randn(m, n, device="cuda", generator=g) + x = x * torch.rand(m, 1, device="cuda", generator=g) * 40 + x[1] = 0 # an all-zero row: the scale floor + x[2, :32] = 2.0**-36 # a tiny block + x[3, :64] = 3e4 # a large block + return x.to(torch.bfloat16) + + +@pytest.mark.parametrize("rows", [64, 1032]) +@pytest.mark.parametrize("world", [4]) +def test_quant_pack_unpack(rows: int, world: int): + d = 2048 + x = _rows(world * rows, d, 0) + codes, scales = _mxfp8_e4m3_quantize_triton(x) + packed = mxfp8_quant_pack(x) + assert torch.equal(packed[:, :d], codes.view(torch.uint8)) + assert torch.equal(packed[:, d:], scales) + got_codes, got_scales = mxfp8_unpack(packed, world, rows, d) + blocks = packed.view(world, rows, -1).transpose(0, 1) + assert torch.equal(got_codes.view(torch.uint8), blocks[:, :, :d].reshape(rows, -1)) + assert torch.equal(got_scales, blocks[:, :, d:].reshape(rows, -1)) + + +@pytest.mark.parametrize("rows", [7, 2048]) +@pytest.mark.parametrize("with_residual", [False, True]) +@pytest.mark.parametrize("moe", [False, True]) +def test_rmsnorm_mx(rows: int, with_residual: bool, moe: bool): + """The linear input = gemma norm + ``mxfp8_e4m3_quantize``; the MoE input = + gemma norm + aiter's ``per_1x32_mx_quant`` (the AITER MXFP8 MoE's quant).""" + hidden = 6144 + x = _rows(rows, hidden, 1) + residual = _rows(rows, hidden, 2) * 4 if with_residual else None + weight = torch.randn(hidden, device="cuda") * 0.3 + if residual is None: + norm_ref, res_ref = gemma_rmsnorm(x, weight, 1e-6), x + else: + norm_ref, res_ref = gemma_fused_add_rmsnorm(x, residual, weight, 1e-6) + if moe: + from aiter import dtypes + from aiter.ops.quant import per_1x32_mx_quant_hip + + q_ref, s_ref = per_1x32_mx_quant_hip( + norm_ref, + scale=None, + quant_dtype=dtypes.fp8, + scale_type=dtypes.fp8_e8m0, + shuffle=False, + ) + else: + q_ref, s_ref = _mxfp8_e4m3_quantize_triton(norm_ref) + norm, res, q, s = gemma_rmsnorm_mx( + x, + residual, + weight, + 1e-6, + min_scale_byte=MOE_MIN_SCALE_BYTE if moe else 0, + store_out=moe, + ) + if moe: + assert torch.equal(norm, norm_ref) + else: + assert norm is None + assert torch.equal(res, res_ref) + assert torch.equal(q.view(torch.uint8), q_ref.view(torch.uint8)) + assert torch.equal(s, s_ref.view(torch.uint8)) diff --git a/tests/model_executor/layers/test_fused_shared_expert.py b/tests/model_executor/layers/test_fused_shared_expert.py index 30b7e2fbd34a..7c207f185760 100644 --- a/tests/model_executor/layers/test_fused_shared_expert.py +++ b/tests/model_executor/layers/test_fused_shared_expert.py @@ -15,8 +15,10 @@ from transformers import Qwen3_5MoeTextConfig import vllm.config as vllm_config_module +import vllm.envs as envs from vllm.config import ParallelConfig, VllmConfig, set_current_vllm_config from vllm.config.quantization import QuantizationConfigArgs +from vllm.logger import _print_warning_once from vllm.model_executor.layers.fused_moe import utils as fused_moe_utils from vllm.model_executor.layers.fused_moe.layer import determine_expert_counts from vllm.model_executor.layers.quantization.experts_int8 import ExpertsInt8Config @@ -42,6 +44,13 @@ reason="ROCm-specific aiter ops are not supported on XPU", ) + +@pytest.fixture(autouse=True) +def reset_warning_once(): + """`logger.warning_once` dedupes across tests: make each test see its warnings.""" + _print_warning_once.cache_clear() + + _QUARK_FSE_CONFIG: dict[str, Any] = { "global_quant_config": { "input_tensors": { @@ -423,6 +432,31 @@ def test_resolve_layer_fused_shared_expert_rejects_incompatible_quantization( assert "shared experts are excluded" in caplog.text +def test_resolve_layer_fused_shared_expert_warns_when_aiter_disabled( + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + monkeypatch.setattr( + fused_moe_utils, + "envs", + SimpleNamespace( + VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS=True, + VLLM_ROCM_USE_AITER=False, + VLLM_ROCM_USE_AITER_MOE=True, + ), + ) + monkeypatch.setattr( + fused_moe_utils.rocm_aiter_ops, + "is_fusion_moe_shared_experts_enabled", + lambda: False, + ) + + assert not fused_moe_utils.resolve_layer_fused_shared_expert( + ExpertsInt8Config(), "model.layers.0.mlp" + ) + assert "VLLM_ROCM_USE_AITER=1 (currently False)" in caplog.text + + def test_deepseek_v4_shared_expert_fse_uses_mtp_quantization_config_prefix( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -986,15 +1020,12 @@ def test_models_fse_init( glm5_next_model, "_fused_shared_experts_tuned", lambda _: True ) - import vllm.envs as envs from vllm._aiter_ops import rocm_aiter_ops if model_type == "deepseek_v4": from vllm.models.deepseek_v4.amd import model as deepseek_v4_model warning_logger = deepseek_v4_model.logger - elif model_type == "minimax_m3": - warning_logger = minimax_m3_model.logger else: warning_logger = fused_moe_utils.logger @@ -1011,11 +1042,9 @@ def test_models_fse_init( mp.setattr(envs, "VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS", use_fse) rocm_aiter_ops.refresh_env_variables() aiter_fse_enabled = bool(rocm_aiter_ops.is_fusion_moe_shared_experts_enabled()) - # These AMD-specific models currently use the raw environment flag. - # and do not rely on `rocm_aiter_ops.is_fusion_moe_shared_experts_enabled()`. - fse_enabled = use_fse and ( - aiter_fse_enabled or model_type in {"deepseek_v4", "minimax_m3"} - ) + # This AMD-specific model currently uses the raw environment flag + # and does not rely on `rocm_aiter_ops.is_fusion_moe_shared_experts_enabled()`. + fse_enabled = use_fse and (aiter_fse_enabled or model_type == "deepseek_v4") with ( patch.object(warning_logger, "warning") as warning, @@ -1065,6 +1094,42 @@ def test_models_fse_init( rocm_aiter_ops.refresh_env_variables() +def _modelopt_mxfp8_config(exclude_modules=(), moe_quant_algo="NVFP4"): + from vllm.model_executor.layers.quantization.modelopt import ModelOptMxFp8Config + + return ModelOptMxFp8Config( + is_checkpoint_mxfp8_serialized=True, + kv_cache_quant_algo=None, + exclude_modules=list(exclude_modules), + moe_quant_algo=moe_quant_algo, + ) + + +@pytest.mark.parametrize( + ("moe_quant_algo", "expected"), + [ + # NVFP4 routed experts cannot share a slot layout with the MXFP8 shared + # expert without online requantization of both. + ("NVFP4", False), + # A plain MXFP8 checkpoint (both sides MXFP8). + (None, True), + ], +) +def test_modelopt_mxfp8_shared_expert_fse_keeps_the_stored_format( + moe_quant_algo: str | None, expected: bool +) -> None: + """Without online requantization, the shared expert is fused only in the + format it is stored in.""" + compatible, reason = is_shared_expert_quant_fse_compatible( + _modelopt_mxfp8_config(moe_quant_algo=moe_quant_algo), + "model.layers.0.mlp.experts", + "model.layers.0.mlp.shared_experts", + ) + + assert compatible is expected + assert (reason is None) is expected + + @pytest.mark.parametrize( ("setting", "value", "reason"), [ @@ -1194,7 +1259,9 @@ def test_online_targets_off_shared_expert_defer_to_checkpoint( ) -def test_online_targeting_only_one_shared_projection_rejects_fse() -> None: +def test_online_only_one_shared_projection_matching_keys() -> None: + """An online target on part of the shared expert is fine as long as every + projection runs with the routed experts' keys (MXFP4 here).""" shared_prefix = "model.layers.0.mlp.shared_expert" quant_config = QuarkConfig({**_QUARK_FSE_CONFIG, "exclude": []}) quant_config.online_quantization_config = OnlineQuantizationConfig( @@ -1205,11 +1272,7 @@ def test_online_targeting_only_one_shared_projection_rejects_fse() -> None: quant_config, "model.layers.0.mlp.experts", shared_prefix, - ) == ( - False, - "online quantization targets only part of the shared expert at " - f"{shared_prefix}", - ) + ) == (True, None) def test_online_fp8_shared_expert_rejects_quark_mxfp4_fse() -> None: @@ -1219,14 +1282,15 @@ def test_online_fp8_shared_expert_rejects_quark_mxfp4_fse() -> None: QuantizationConfigArgs(targets={f"{shared_prefix}*": "fp8_per_tensor"}) ) - assert is_shared_expert_quant_fse_compatible( + compatible, reason = is_shared_expert_quant_fse_compatible( quant_config, "model.layers.0.mlp.experts", shared_prefix, - ) == ( - False, - "online shared-expert quantization keys do not match the routed expert keys", ) + assert not compatible + assert reason is not None + assert reason.startswith("shared expert (weight, activation) keys ") + assert f"at {shared_prefix} do not match the routed expert keys" in reason def test_online_mxfp4_shared_expert_rejects_quark_weight_only_mxfp4_fse() -> None: @@ -1246,14 +1310,15 @@ def test_online_mxfp4_shared_expert_rejects_quark_weight_only_mxfp4_fse() -> Non QuantizationConfigArgs(targets={f"{shared_prefix}*": "mxfp4"}) ) - assert is_shared_expert_quant_fse_compatible( + compatible, reason = is_shared_expert_quant_fse_compatible( quant_config, "model.layers.0.mlp.experts", shared_prefix, - ) == ( - False, - "online shared-expert quantization keys do not match the routed expert keys", ) + assert not compatible + assert reason is not None + assert reason.startswith("shared expert (weight, activation) keys ") + assert f"at {shared_prefix} do not match the routed expert keys" in reason @pytest.mark.parametrize( diff --git a/tests/model_executor/model_loader/test_reload.py b/tests/model_executor/model_loader/test_reload.py index eac5245bd988..b8489db133f3 100644 --- a/tests/model_executor/model_loader/test_reload.py +++ b/tests/model_executor/model_loader/test_reload.py @@ -737,7 +737,7 @@ def test_padded_moe_reload_releases_each_layer( layer.quant_method = method layer.expert_map_manager = SimpleNamespace(map_global_to_local=lambda i: i) layer._loaded_expert_biases = set() - layer._fused_shared_expert_quantizer = None + layer.shared_expert_online_loader = None method.create_weights( layer, experts, diff --git a/tests/models/minimax_m3/__init__.py b/tests/models/minimax_m3/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/models/minimax_m3/test_dense_gemm1_mxfp8.py b/tests/models/minimax_m3/test_dense_gemm1_mxfp8.py new file mode 100644 index 000000000000..cd7516a82559 --- /dev/null +++ b/tests/models/minimax_m3/test_dense_gemm1_mxfp8.py @@ -0,0 +1,90 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Correctness test for the MiniMax-M3.1 fused dense GEMM1 kernel +(vllm/models/minimax_m3/nvidia/ops/dense_gemm1_mxfp8.py). +""" + +import pytest +import torch + +from vllm.platforms import current_platform + +pytestmark = pytest.mark.skipif( + not (current_platform.is_cuda() and current_platform.has_device_capability(100)), + reason="dense GEMM1 MXFP8 kernel is SM100+ CUDA only", +) + + +def _mxfp8_quantize_f32(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """MXFP8-quantize fp32 [M, N] with the kernel's integer-exact scale math: + scale byte = E - 8 + (amax > 1.75 * 2^E) with E the biased exponent of the + 32-elem group amax (0 for amax=0), clamped to [0, 254]. Returns q and the + unswizzled [M, N//32] scale bytes. + """ + M, N = x.shape + g = x.float().view(M, N // 32, 32) + amax = g.abs().amax(-1) + e_bias = amax.view(torch.int32) >> 23 + thr = torch.ldexp(torch.full_like(amax, 1.75), e_bias - 127) + sb = (e_bias - 8 + (amax > thr).to(torch.int32)).clamp(0, 254) + q = g * torch.ldexp(torch.ones_like(amax), 127 - sb)[..., None] + q = q.clamp(-448.0, 448.0).to(torch.float8_e4m3fn) + return q.view(M, N), sb.to(torch.uint8) + + +# Per-rank I: TP4 shared expert, TP4 dense / TP1 shared, TP1 dense. 12288 is +# the only one whose weight exceeds half of L2 (grouped rasterization). +@pytest.mark.parametrize("num_tokens", [1, 37, 128, 1000, 4096]) +@pytest.mark.parametrize("intermediate", [768, 3072, 12288]) +def test_dense_gemm1_mxfp8_correctness(num_tokens: int, intermediate: int): + from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( + mxfp8_e4m3_quantize, + swizzle_mxfp8_scale, + ) + from vllm.models.minimax_m3.nvidia.ops.dense_gemm1_mxfp8 import run + + limit, alpha, beta = 7.0, 1.702, 1.0 + hidden = 6144 + torch.manual_seed(num_tokens) + x = torch.randn(num_tokens, hidden, device="cuda", dtype=torch.bfloat16) * 0.5 + w1 = ( + torch.randn(intermediate * 2, hidden, device="cuda", dtype=torch.bfloat16) + * 0.05 + ) + + # What Mxfp8OnlineLinearMethod.process_weights_after_loading produces. + w1q, wsf_2d = mxfp8_e4m3_quantize(w1, is_sf_swizzled_layout=False) + w1sf = swizzle_mxfp8_scale(wsf_2d, M=intermediate * 2, K=hidden) + + M, N = num_tokens, intermediate + e8 = torch.float8_e8m0fnu + q = torch.empty((M, N), dtype=torch.float8_e4m3fn, device="cuda") + sf = torch.zeros( + ((M + 127) // 128) * 128 * (N // 32), dtype=torch.uint8, device="cuda" + ) + xq, xsf = mxfp8_e4m3_quantize(x, is_sf_swizzled_layout=True) + run(xq, w1q, xsf.view(-1).view(e8), w1sf.view(e8), q, sf, limit, alpha, beta) + + # fp32 mirror chain: same MXFP8 GEMM (fp32 out) -> fp32 clamped SwiGLU + # -> MXFP8 quantize with the kernel's scale math. + gemm = torch._scaled_mm( + xq, + w1q.t(), + scale_a=xsf.view(e8), + scale_b=w1sf.view(e8), + out_dtype=torch.float32, + ) + gate = gemm[:, :N].clamp(max=limit) + up = gemm[:, N:].clamp(-limit, limit) + act = gate * torch.sigmoid(gate * alpha) * (up + beta) + q_ref, sf_ref_2d = _mxfp8_quantize_f32(act) + sf_ref = swizzle_mxfp8_scale(sf_ref_2d, M=M, K=N) + + # Measured envelope: sf bytes identical; q bytes differ on <=0.007% of + # elements, always by 1 fp8 ulp. Bounds below carry >10x margin. + sf_mism = (sf != sf_ref).sum().item() + assert sf_mism <= sf.numel() * 1e-4, f"sf byte mismatches: {sf_mism}" + q_mism = q.view(torch.uint8) != q_ref.view(torch.uint8) + assert q_mism.sum().item() <= q.numel() * 1e-3, ( + f"q byte mismatches: {q_mism.sum().item()}" + ) diff --git a/tests/models/minimax_m3/test_dspark_draft_compile.py b/tests/models/minimax_m3/test_dspark_draft_compile.py new file mode 100644 index 000000000000..dc24bfb18da0 --- /dev/null +++ b/tests/models/minimax_m3/test_dspark_draft_compile.py @@ -0,0 +1,135 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""The MiniMax-M3.1 DSpark draft attention under vLLM's torch.compile. + +vLLM traces the draft model once, in the memory-profiling run, whose forward +context has no slot mapping, and reuses that graph afterwards. The draft +tokens' k/v insert must still happen on the later calls. +""" + +import pytest +import torch +from torch import nn + +from vllm.utils.torch_utils import set_default_torch_dtype + +HEAD_DIM = 128 +BLOCK_SIZE = 16 + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available(), reason="CUDA not available" +) + + +class _QueryAttention(nn.Module): + """Stands in for the draft's Attention: returns its query, so the layer + output shows the q the attention got.""" + + def __init__(self, layer_name): + super().__init__() + self.layer_name = layer_name + + def forward(self, q, k, v, output_dtype=None): + return q.to(output_dtype) + + +@pytest.mark.parametrize( + "kv_cache_dtype,query_pre_quantized", + [("auto", False), ("fp8", False), ("fp8", True)], +) +def test_draft_attention_stores_kv_after_compile( + dist_init, monkeypatch, kv_cache_dtype, query_pre_quantized +): + from vllm.compilation.decorators import support_torch_compile + from vllm.config import ( + CompilationConfig, + CompilationMode, + CUDAGraphMode, + VllmConfig, + set_current_vllm_config, + ) + from vllm.forward_context import set_forward_context + from vllm.models.minimax_m3.common.dspark import MiniMaxM3DSparkAttention + from vllm.transformers_utils.configs.minimax_m3 import MiniMaxM3TextConfig + + monkeypatch.setenv("VLLM_DISABLE_COMPILE_CACHE", "1") + config = MiniMaxM3TextConfig( + hidden_size=512, + num_attention_heads=8, + num_key_value_heads=2, + head_dim=HEAD_DIM, + max_position_embeddings=8192, + ) + + @support_torch_compile + class DraftAttention(nn.Module): + def __init__(self, *, vllm_config: VllmConfig, prefix: str = "", **kwargs): + super().__init__() + self.self_attn = MiniMaxM3DSparkAttention( + config, + sliding_window=None, + causal=False, + cache_config=None, + quant_config=None, + prefix=f"{prefix}.self_attn", + query_pre_quantized=query_pre_quantized, + ) + + def forward( + self, positions: torch.Tensor, hidden_states: torch.Tensor + ) -> torch.Tensor: + return self.self_attn(positions, hidden_states) + + vllm_config = VllmConfig( + compilation_config=CompilationConfig( + mode=CompilationMode.VLLM_COMPILE, cudagraph_mode=CUDAGraphMode.NONE + ) + ) + torch.manual_seed(0) + with ( + set_current_vllm_config(vllm_config), + torch.device("cuda"), + set_default_torch_dtype(torch.bfloat16), + ): + model = DraftAttention(vllm_config=vllm_config, prefix="model.layers.0") + attn = model.self_attn + for param in ( + attn.qkv_proj.weight, + attn.q_norm.weight, + attn.k_norm.weight, + attn.o_proj.weight, + ): + param.data.normal_(std=0.05) + layer = attn.attn + cache_dtype = torch.uint8 if kv_cache_dtype == "fp8" else torch.bfloat16 + layer.kv_cache = torch.zeros( + 4, 2, BLOCK_SIZE, 2 * HEAD_DIM, dtype=cache_dtype, device="cuda" + ) + attn.attn = _QueryAttention(layer.layer_name) + + hidden = torch.randn(7, config.hidden_size, device="cuda", dtype=torch.bfloat16) + positions = torch.tensor([0, 1, 127, 128, 4000, 8190, 9], device="cuda") + slots = {layer.layer_name: torch.tensor([5, -1, 17, 18, 40, 63, 0], device="cuda")} + + with torch.inference_mode(): + with set_forward_context(None, vllm_config, slot_mapping=slots): + expected_out = attn(positions, hidden) + expected_cache = layer.kv_cache.clone() + assert expected_cache.any() + layer.kv_cache.zero_() + + # The memory-profiling run: no slot mapping, nothing is stored. + with set_forward_context(None, vllm_config): + model(positions, hidden) + assert not layer.kv_cache.any() + + with set_forward_context(None, vllm_config, slot_mapping=slots): + out = model(positions, hidden) + assert layer.kv_cache.any(), "the compiled draft attention stored no k/v" + got, expected, rtol = layer.kv_cache, expected_cache, 2e-2 + if kv_cache_dtype == "fp8": + got = got.view(torch.float8_e4m3fn).float() + expected = expected.view(torch.float8_e4m3fn).float() + rtol = 0.13 + torch.testing.assert_close(got, expected, atol=2e-2, rtol=rtol) + torch.testing.assert_close(out, expected_out, atol=2e-2, rtol=2e-2) diff --git a/tests/models/minimax_m3/test_mono_host.py b/tests/models/minimax_m3/test_mono_host.py new file mode 100644 index 000000000000..64b557ea9a04 --- /dev/null +++ b/tests/models/minimax_m3/test_mono_host.py @@ -0,0 +1,349 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Host-side logic of the MiniMax-M3 mono decode path that needs no GPU. + +The kernel package imports flydsl at module import, so these tests run where it +is installed (the ROCm images); elsewhere they are skipped. +""" + +from types import SimpleNamespace + +import pytest +import torch + +pytest.importorskip("flydsl") + +from vllm.models.minimax_m3.amd.mono import config as mono_config # noqa: E402 +from vllm.models.minimax_m3.amd.mono import dispatch as mono_dispatch # noqa: E402 +from vllm.models.minimax_m3.amd.mono import envs as mono_envs # noqa: E402 +from vllm.models.minimax_m3.amd.mono.config import ( # noqa: E402 + MAX_CONTEXT, + MAX_TOKENS, + SPARSE_BLOCK, + TP, + MonoUnsupported, +) +from vllm.models.minimax_m3.amd.mono.dispatch import ( # noqa: E402 + _config_refusal, + _step_refusal, +) +from vllm.models.minimax_m3.amd.mono.runner import ( # noqa: E402 + dense_prefix, + token_rows, +) + + +def _layer(moe: bool, sparse: bool): + attn = ( + SimpleNamespace( + layer_name="attn", + indexer=SimpleNamespace(index_cache=SimpleNamespace(prefix="idx")), + ) + if sparse + else SimpleNamespace() + ) + return SimpleNamespace(is_moe_layer=moe, self_attn=attn) + + +def test_token_rows_single_query_token_passes_tables_through(): + bt = torch.arange(12, dtype=torch.int32).view(3, 4) + seq = torch.tensor([10, 20, 30], dtype=torch.int32) + rows_bt, rows_seq = token_rows(bt, seq, q=1, n=3) + assert rows_bt is bt and rows_seq is seq + + +def test_token_rows_expands_speculative_verify_rows(): + bt = torch.arange(8, dtype=torch.int32).view(2, 4) + seq = torch.tensor([10, 20], dtype=torch.int32) + rows_bt, rows_seq = token_rows(bt, seq, q=3, n=6) + # token j of a request sees seq_len - (q - 1 - j) keys + assert rows_seq.tolist() == [8, 9, 10, 18, 19, 20] + assert rows_bt.shape == (6, 4) and torch.equal(rows_bt[:3], bt[0].expand(3, 4)) + assert rows_bt.stride(0) == rows_bt.shape[1] + + +def test_dense_prefix_counts_leading_dense_ffn_layers(): + layers = [_layer(False, True)] * 3 + [_layer(True, True)] * 5 + assert dense_prefix(layers) == 3 + assert dense_prefix([_layer(True, True)] * 2) == 0 + + +@pytest.mark.parametrize( + "layers", + [ + [_layer(False, True)] * 3, # no MoE layer at all + [ + _layer(True, True), + _layer(False, True), + _layer(True, True), + ], # dense after MoE + [ + _layer(False, True), + _layer(True, False), + ], # MoE layer without sparse attention + ], +) +def test_dense_prefix_refuses_other_layer_mixes(layers): + with pytest.raises(MonoUnsupported): + dense_prefix(layers) + + +def test_configure_accepts_only_the_two_kv_page_strides(): + saved = (mono_config.KV_PAGE_STRIDE, mono_config.STATIC_KV_SCALE) + try: + mono_config.configure(kv_page_stride=16, static_kv_scale=True) + assert (mono_config.KV_PAGE_STRIDE, mono_config.STATIC_KV_SCALE) == (16, True) + with pytest.raises(AssertionError): + mono_config.configure(kv_page_stride=4, static_kv_scale=True) + finally: + mono_config.configure(kv_page_stride=saved[0], static_kv_scale=saved[1]) + + +def _vllm_config(**overrides): + cg = SimpleNamespace(requires_piecewise_compilation=lambda: False) + cfg = SimpleNamespace( + parallel_config=SimpleNamespace( + tensor_parallel_size=TP, + data_parallel_size=1, + pipeline_parallel_size=1, + enable_expert_parallel=False, + ), + cache_config=SimpleNamespace(cache_dtype="fp8", block_size=SPARSE_BLOCK), + compilation_config=SimpleNamespace(cudagraph_mode=cg), + model_config=SimpleNamespace( + max_model_len=32768, hf_text_config=SimpleNamespace() + ), + attention_config=SimpleNamespace( + resolve_indexer_kv_dtype=lambda default: "fp8" + ), + ) + for path, value in overrides.items(): + obj, _, attr = path.rpartition(".") + setattr(eval(f"cfg.{obj}") if obj else cfg, attr, value) + return cfg + + +def _model(fse: bool = True, shared_mlp: bool = True, aux=()): + moe = _layer(True, True) + moe.block_sparse_moe = SimpleNamespace( + is_fused_shared_expert_enabled=fse, + shared_experts=object() if shared_mlp else None, + ) + return SimpleNamespace( + is_fused_shared_expert_enabled=fse, + aux_hidden_state_layers=aux, + layers=[_layer(False, True)] * 3 + [moe] * 2, + ) + + +@pytest.mark.parametrize("fse", [True, False]) +@pytest.mark.parametrize("aux", [(), (2, 30, 57)]) +def test_config_refusal_accepts_the_supported_deployment(fse, aux): + assert _config_refusal(_vllm_config(), _model(fse=fse, aux=aux)) is None + + +@pytest.mark.parametrize( + "cfg, model, why", + [ + (_vllm_config(**{"parallel_config.tensor_parallel_size": 8}), _model(), "TP"), + (_vllm_config(**{"cache_config.cache_dtype": "auto"}), _model(), "kv cache"), + (_vllm_config(**{"cache_config.block_size": 64}), _model(), "block size"), + ( + _vllm_config(**{"model_config.max_model_len": MAX_CONTEXT + 1}), + _model(), + "max_model_len", + ), + (_vllm_config(), _model(fse=False, shared_mlp=False), "neither fused nor"), + ], +) +def test_config_refusal_names_the_unmet_condition(cfg, model, why): + assert why in _config_refusal(cfg, model) + + +def _fwd(n: int, q: int = 1, reqs: int | None = None, prefills: int = 0): + reqs = n // q if reqs is None else reqs + decode = SimpleNamespace( + decode_query_len=q, + block_table=torch.zeros(reqs, 8, dtype=torch.int32), + seq_lens=torch.ones(reqs, dtype=torch.int32), + ) + md = SimpleNamespace(decode=decode, num_prefills=prefills) + return SimpleNamespace( + ubatch_slices=None, + attn_metadata={"attn": md}, + slot_mapping={"attn": torch.zeros(n, dtype=torch.int64)}, + ) + + +def test_step_refusal_accepts_a_pure_decode(): + pos = torch.zeros(4, dtype=torch.int64) + assert _step_refusal(_fwd(4), "attn", 4, pos) is None + assert _step_refusal(_fwd(6, q=3), "attn", 6, pos) is None + + +def test_step_refusal_rejects_what_the_kernels_cannot_serve(): + pos = torch.zeros(4, dtype=torch.int64) + assert "tokens" in _step_refusal(_fwd(MAX_TOKENS + 1), "attn", MAX_TOKENS + 1, pos) + assert "prefill" in _step_refusal(_fwd(4, prefills=1), "attn", 4, pos) + assert "per request" in _step_refusal(_fwd(4, q=3, reqs=2), "attn", 4, pos) + assert "shorter" in _step_refusal(_fwd(4, reqs=2), "attn", 4, pos) + assert "positions" in _step_refusal(_fwd(4), "attn", 4, pos.to(torch.int32)) + fwd = _fwd(4) + fwd.attn_metadata["attn"].decode.block_table = fwd.attn_metadata[ + "attn" + ].decode.block_table.t() + assert "contiguous" in _step_refusal(fwd, "attn", 4, pos) + + +# ---- MonoDecode host contract: enable, runner life cycle, slot check, routing ---- +# Everything the kernels are not: these pin the dispatcher's behaviour so a refactor +# of the host side (or of the switch) must keep passing them. + + +class _FakeRunner: + built = 0 + + def __init__(self, model, config, *, stale=False, fp8=False): + _FakeRunner.built += 1 + self._stale = stale + self.shared_fp8 = fp8 + self.sparse = [] + self.rank = 0 + self.closed = False + self.calls = [] + + def stale(self): + return self._stale + + def close(self): + self.closed = True + + def forward(self, input_ids, positions, inputs_embeds): + self.calls.append(positions.numel()) + return "mono-out" + + +@pytest.fixture +def mono(monkeypatch): + """An enabled dispatcher on a supported deployment, outside graph capture, + with the runner build stubbed.""" + monkeypatch.setattr(mono_dispatch.envs, "MONO_ENABLE", True) + monkeypatch.setattr(mono_dispatch.envs, "MONO_CHECK", False) + monkeypatch.setattr(mono_dispatch, "MonoDecodeRunner", _FakeRunner) + monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False) + _FakeRunner.built = 0 + return mono_dispatch.MonoDecode(_model(), _vllm_config()) + + +def _fwd_shared(n: int, shared: bool = True): + fwd = _fwd(n) + slots = fwd.slot_mapping["attn"] + fwd.slot_mapping["idx"] = slots.clone() if shared else slots + 1 + return fwd + + +def test_env_flag_parsing(monkeypatch): + for raw, want in (("1", True), ("true", True), ("True", True), ("0", False)): + monkeypatch.setenv("VLLM_ROCM_MINIMAX_M3_MONO_TESTFLAG", raw) + assert mono_envs._flag("VLLM_ROCM_MINIMAX_M3_MONO_TESTFLAG") is want + monkeypatch.delenv("VLLM_ROCM_MINIMAX_M3_MONO_TESTFLAG") + assert mono_envs._flag("VLLM_ROCM_MINIMAX_M3_MONO_TESTFLAG") is False + + +def test_disabled_without_the_switch(monkeypatch): + monkeypatch.setattr(mono_dispatch.envs, "MONO_ENABLE", False) + mono = mono_dispatch.MonoDecode(_model(), _vllm_config()) + assert not mono._enabled + assert not mono.supports(None, torch.zeros(1, dtype=torch.int64), None, None) + + +def test_unsupported_deployment_falls_back(monkeypatch): + monkeypatch.setattr(mono_dispatch.envs, "MONO_ENABLE", True) + bad = _vllm_config(**{"parallel_config.tensor_parallel_size": 8}) + assert not mono_dispatch.MonoDecode(_model(), bad)._enabled + + +def test_enabled_dispatcher_reads_the_first_sparse_layer(mono): + assert mono._enabled + assert mono._layer_name == "attn" and mono._index_prefix == "idx" + assert mono._runner is None # built lazily, on the first eligible step + + +def test_runner_is_built_once_outside_capture(mono): + assert mono._ensure_runner() and _FakeRunner.built == 1 + assert mono._ensure_runner() and _FakeRunner.built == 1 + + +def test_runner_is_not_built_inside_capture(mono, monkeypatch): + monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: True) + assert not mono._ensure_runner() and _FakeRunner.built == 0 + assert mono._enabled # not a refusal: the next uncaptured step builds it + + +def test_stale_runner_is_rebuilt_after_a_kv_rebind(mono, monkeypatch): + first = _FakeRunner(None, None, stale=True) + mono._runner, mono._slots_verified = first, True + assert mono._ensure_runner() + assert first.closed and mono._runner is not first + assert not mono._slots_verified # the new cache's slots are checked again + + +def test_stale_runner_is_kept_while_capturing(mono, monkeypatch): + first = _FakeRunner(None, None, stale=True) + mono._runner = first + monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: True) + assert not mono._ensure_runner() and not first.closed + + +@pytest.mark.parametrize("exc", [MonoUnsupported("no CUs"), RuntimeError("boom")]) +def test_runner_build_failure_disables_mono(mono, monkeypatch, exc): + def boom(model, config): + raise exc + + monkeypatch.setattr(mono_dispatch, "MonoDecodeRunner", boom) + assert not mono._ensure_runner() + assert not mono._enabled and mono._runner is None + + +def test_slot_check_runs_once_and_caches(mono): + assert mono._slots_shared(_fwd_shared(4), 4) and mono._slots_verified + assert mono._slots_shared(_fwd_shared(4, shared=False), 4) # cached verdict + + +@pytest.mark.parametrize("missing", [True, False]) +def test_unshared_index_slots_disable_mono(mono, missing): + fwd = _fwd_shared(4, shared=False) # mismatched ids ... + if missing: + del fwd.slot_mapping["idx"] # ... or no index slots at all + assert not mono._slots_shared(fwd, 4) and not mono._enabled + + +def test_supports_routes_only_pure_decodes(mono, monkeypatch): + pos = torch.zeros(4, dtype=torch.int64) + monkeypatch.setattr(mono_dispatch, "get_forward_context", lambda: _fwd_shared(4)) + assert mono.supports(None, pos, None, None) and _FakeRunner.built == 1 + assert not mono.supports(None, pos, object(), None) # pipeline-parallel input + monkeypatch.setattr( + mono_dispatch, "get_forward_context", lambda: _fwd_shared(4, shared=True) + ) + fwd = _fwd(4, prefills=1) + monkeypatch.setattr(mono_dispatch, "get_forward_context", lambda: fwd) + assert not mono.supports(None, pos, None, None) and mono._enabled # just declined + + +def test_refused_step_does_not_build_the_runner(mono, monkeypatch): + fwd = _fwd(MAX_TOKENS + 1) + monkeypatch.setattr(mono_dispatch, "get_forward_context", lambda: fwd) + pos = torch.zeros(MAX_TOKENS + 1, dtype=torch.int64) + assert not mono.supports(None, pos, None, None) and _FakeRunner.built == 0 + + +def test_forward_runs_the_runner_or_the_self_check(mono, monkeypatch): + mono._ensure_runner() + pos = torch.zeros(2, dtype=torch.int64) + assert mono.forward(None, pos, None) == "mono-out" and mono._runner.calls == [2] + monkeypatch.setattr(mono_dispatch.envs, "MONO_CHECK", True) + monkeypatch.setattr( + mono_dispatch, "forward_checked", lambda runner, *a: ("checked", runner) + ) + assert mono.forward(None, pos, None) == ("checked", mono._runner) diff --git a/tests/models/minimax_m3/test_qkv_index_fused_epilogue.py b/tests/models/minimax_m3/test_qkv_index_fused_epilogue.py new file mode 100644 index 000000000000..4b949c04052e --- /dev/null +++ b/tests/models/minimax_m3/test_qkv_index_fused_epilogue.py @@ -0,0 +1,248 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MiniMax-M3 QKV+indexer MXFP8 GEMM with fused epilogue +(ops/qkv_index_fused_epilogue.py) vs the production chain: mxfp8_e4m3_quantize +-> flashinfer mm_mxfp8 -> fused_minimax_m3_qknorm_rope_kv_insert. + +Each case runs both tile configs (1-SM and 2-SM), which must match bitwise, +and compares them to the chain: bf16 q within tolerances, the quantized +outputs (fp8 q / index_q, NVFP4 caches) code by code. The chain rounds the +GEMM output to bf16 first, so values near a rounding boundary land one code +apart. +""" + +import pytest +import torch + +import vllm._custom_ops as ops +from vllm.platforms import current_platform + +pytestmark = pytest.mark.skipif( + not (current_platform.is_cuda() and current_platform.has_device_capability(100)), + reason="QKV+indexer MXFP8 GEMM is SM100+ CUDA only", +) + +HIDDEN = 6144 +HEAD_DIM = 128 +ROTARY_DIM = 64 +EPS = 1e-6 +MAX_POS = 8192 +Q_FP8_SCALE = 2.0 +# per-rank (q, kv, index_q) heads; N = (nq + 2 * nkv + niq + 1) * HEAD_DIM +TP_HEADS = {1: (64, 4, 4), 2: (32, 2, 2), 4: (16, 1, 1)} +# Caches start as 0xFF: never a scale byte (E4M3 scales saturate at 0x7E), so +# a stray or missing write shows up in the code comparison. +CACHE_FILL = 0xFF + +BF16_RTOL = 2**-6 +BF16_ATOL = 0.05 +# fp8 values near zero (RoPE cancellation, where an E4M3 step is 2^-7..2^-9) +# can land a few codes apart but stay within 2^-6. +FP8_MAX_MISMATCH_FRAC = 0.05 +FP8_SMALL_ABS = 2**-6 +NVFP4_MAX_MISMATCH_FRAC = 0.02 +NVFP4_SF_MAX_MISMATCH_FRAC = 0.05 + + +def _make_inputs(nq, nkv, niq, M, nb, bs, slots): + """MXFP8 activations / weight, norm weights, positions, the RoPE cache and + the KV / index-cache slots: random unique with ~3% -1 (no insert), the + last M of the cache, or all -1.""" + from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( + mxfp8_e4m3_quantize, + swizzle_mxfp8_scale, + ) + + gen = torch.Generator(device="cuda").manual_seed(M) + + def randn(*shape): + return torch.randn(*shape, device="cuda", generator=gen) + + n = (nq + 2 * nkv + niq + 1) * HEAD_DIM + # activations with a few outlier channels, like real hidden states + x = randn(M, HIDDEN) * 0.5 + x[:, torch.randperm(HIDDEN, device="cuda", generator=gen)[:16]] *= 20 + x = x.bfloat16() + w = (randn(n, HIDDEN) * 0.05).bfloat16() + xq, xsf = mxfp8_e4m3_quantize(x, is_sf_swizzled_layout=True) + wq, wsf = mxfp8_e4m3_quantize(w, is_sf_swizzled_layout=False) + wsf = swizzle_mxfp8_scale(wsf, M=n, K=HIDDEN) + # Gemma norm weights (scale 1 + w) as in the checkpoint: q / k near 0, + # index_q down to -1 (scale near 0), index_k up to ~2.5 + offset_std = torch.tensor( + [[0.1, 0.1], [0.2, 0.1], [-0.4, 0.25], [0.9, 0.5]], device="cuda" + ) + norm_weights = offset_std[:, :1] + offset_std[:, 1:] * randn(4, HEAD_DIM) + norm_weights = norm_weights.bfloat16() + positions = torch.randint(0, MAX_POS, (M,), device="cuda", generator=gen) + inv_freq = 1.0 / ( + 5e6 ** (torch.arange(0, ROTARY_DIM, 2, device="cuda").float() / ROTARY_DIM) + ) + freqs = torch.outer(torch.arange(MAX_POS, device="cuda").float(), inv_freq) + cos_sin = torch.cat((freqs.cos(), freqs.sin()), dim=-1).bfloat16() + + if slots == "none": + sm = ism = torch.full((M,), -1, device="cuda") + elif slots == "last_page": + sm = ism = torch.arange(nb * bs - M, nb * bs, device="cuda") + else: + sm, ism = ( + torch.randperm(nb * bs, device="cuda", generator=gen)[:M] for _ in range(2) + ) + sm[torch.rand(M, device="cuda", generator=gen) < 0.03] = -1 + ism[torch.rand(M, device="cuda", generator=gen) < 0.03] = -1 + return xq, xsf, wq, wsf, norm_weights, positions, cos_sin, sm, ism + + +def _ordered(codes, sign_bit): + """Sign-magnitude codes -> integers ordered like their values (+0 == -0), + so adjacent representable values differ by 1.""" + codes = codes.to(torch.int16) + mag = codes & (sign_bit - 1) + return torch.where(codes & sign_bit != 0, -mag, mag) + + +def _check_fp8(name, got, want): + """E4M3 codes: NaN masks exact, at most FP8_MAX_MISMATCH_FRAC differ, each + within one code or FP8_SMALL_ABS of the chain's value.""" + a, b = got.float(), want.float() + assert (a.isnan() == b.isnan()).all(), f"{name}: NaN masks differ" + fin = ~a.isnan() + d = _ordered(got.view(torch.uint8), 0x80) - _ordered(want.view(torch.uint8), 0x80) + d = d.abs()[fin] + mism = (d > 0).float().mean() + assert mism <= FP8_MAX_MISMATCH_FRAC, f"{name}: {mism:.2%} E4M3 codes differ" + far = (d > 1) & ((a - b).abs()[fin] > FP8_SMALL_ABS) + assert not far.any(), f"{name}: {far.sum()} E4M3 codes off by > 1 code" + + +def _check_cache(name, got, want, slots, bs): + """NVFP4 cache [nb, (nslots,) bs, 72] vs the chain's: pages without an + inserted token are byte-identical; in the others, E2M1 codes and E4M3 + scale bytes are each within one code, and few differ.""" + pages = torch.zeros(got.shape[0], dtype=torch.bool, device=got.device) + pages[slots[slots >= 0] // bs] = True + changed = (got != want).flatten(1).any(1) + assert not (changed & ~pages).any(), f"{name}: writes to pages with no token" + # each (page, slot) holds bs tokens' E2M1 data (64B each), then their + # E4M3 group scales (8B each) + got = got[pages].reshape(-1, bs * 72) + want = want[pages].reshape(-1, bs * 72) + + def nibbles(b): + return _ordered(torch.stack((b & 0xF, b >> 4), -1), 0x8) + + for part, frac in ( + (slice(0, bs * 64), NVFP4_MAX_MISMATCH_FRAC), + (slice(bs * 64, None), NVFP4_SF_MAX_MISMATCH_FRAC), + ): + g, w = got[:, part], want[:, part] + written = (g != CACHE_FILL) | (w != CACHE_FILL) + if part.start == 0: # packed E2M1 nibbles: compare per code + d = (nibbles(g) - nibbles(w)).abs() + written = written[..., None].expand_as(d) + else: # scale bytes: positive E4M3 + d = (g.to(torch.int16) - w.to(torch.int16)).abs() + assert (d <= 1).all(), f"{name}: codes off by > 1 code" + mism = (d[written] > 0).float().mean() if written.any() else 0.0 + assert mism <= frac, f"{name}: {mism:.2%} of written codes differ" + + +@pytest.mark.parametrize( + "case", + [ + pytest.param(dict(tp=1, M=1), id="tp1-m1"), + pytest.param(dict(tp=1, M=37), id="tp1-m37"), + pytest.param(dict(tp=1, M=1000), id="tp1-m1000"), + pytest.param(dict(tp=1, M=4096, q="fp8"), id="tp1-m4096-fp8q"), + pytest.param(dict(tp=1, M=32768, q="fp8"), id="tp1-m32768-fp8q"), + pytest.param(dict(tp=2, M=1024), id="tp2-m1024"), + pytest.param(dict(tp=4, M=1024, q="bf16"), id="tp4-m1024-bf16q"), + pytest.param(dict(tp=4, M=4100, q="fp8"), id="tp4-m4100-fp8q"), + pytest.param(dict(tp=4, M=1024, kv_scales=(0.5, 1.7)), id="tp4-kv-scales"), + pytest.param(dict(tp=4, M=1024, slots="none"), id="tp4-no-insert"), + pytest.param(dict(tp=1, M=1024, layers=3), id="tp1-cross-layer"), + pytest.param(dict(tp=4, M=1024, block_size=64), id="tp4-bs64"), + # > 2**31 bytes: writers in the last page exercise int64 byte offsets + pytest.param( + dict(tp=1, M=128, nb=30000, slots="last_page"), id="tp1-big-cache" + ), + ], +) +def test_qkv_index_fused_epilogue(case): + import flashinfer + + from vllm.models.minimax_m3.nvidia.ops.qkv_index_fused_epilogue import ( + minimax_m3_qkv_index_fused_epilogue, + ) + + tp, M = case["tp"], case["M"] + q_mode = case.get("q", "both") + kv_scales = case.get("kv_scales", (1.0, 1.0)) + bs, layers = case.get("block_size", 128), case.get("layers", 1) + nb = case.get("nb", (M + M // 2 + bs - 1) // bs + 1) + nq, nkv, niq = TP_HEADS[tp] + + xq, xsf, wq, wsf, norm_weights, positions, cos_sin, sm, ism = _make_inputs( + nq, nkv, niq, M, nb, bs, case.get("slots", "random") + ) + + def caches(): + # the last layer of [nb, layers, *page] buffers: page-strided if layers > 1 + kv = torch.full((nb, layers, 2 * nkv, bs, 72), CACHE_FILL, dtype=torch.uint8) + ic = torch.full((nb, layers, bs, 72), CACHE_FILL, dtype=torch.uint8) + return kv.cuda()[:, -1], ic.cuda()[:, -1] + + # the production chain + kv_ref, ic_ref = caches() + q_ref = torch.empty(M, nq * HEAD_DIM, dtype=torch.bfloat16, device="cuda") + q8_ref = torch.empty(M, nq * HEAD_DIM, dtype=torch.float8_e4m3fn, device="cuda") + iq_ref = torch.empty(M, niq * HEAD_DIM, dtype=torch.float8_e4m3fn, device="cuda") + qkv = flashinfer.mm_mxfp8( + xq, wq.t(), xsf, wsf, out_dtype=torch.bfloat16, backend="cute-dsl" + ) + ops.fused_minimax_m3_qknorm_rope_kv_insert( + qkv, norm_weights[0], norm_weights[1], cos_sin, positions, nq, nkv, + ROTARY_DIM, EPS, norm_weights[2], norm_weights[3], niq, sm, ism, + kv_ref, ic_ref, bs, q_ref, iq_ref, "nvfp4", + q_fp8_out=q8_ref, q_fp8_scale=Q_FP8_SCALE, + kv_k_scale=torch.tensor([kv_scales[0]], device="cuda"), + kv_v_scale=torch.tensor([kv_scales[1]], device="cuda"), + ) # fmt: skip + + outs = [] + for cta_group in (1, 2): + kv, ic = caches() + q = torch.empty_like(q_ref) if q_mode != "fp8" else None + q8 = torch.empty_like(q8_ref) if q_mode != "bf16" else None + iq = torch.empty_like(iq_ref) + minimax_m3_qkv_index_fused_epilogue( + xq, xsf, wq, wsf, positions, cos_sin, *norm_weights, EPS, + slot_mapping=sm, index_slot_mapping=ism, kv_cache=kv, index_cache=ic, + q_out=q, index_q_out=iq, q_fp8_out=q8, q_fp8_scale=Q_FP8_SCALE, + k_scale=kv_scales[0], v_scale=kv_scales[1], cta_group=cta_group, + ) # fmt: skip + outs.append((q, q8, iq, kv, ic)) + + # both tile configs write identical bytes + for a, b in zip(*outs): + if a is not None: + assert torch.equal(a.view(torch.uint8), b.view(torch.uint8)) + + q, q8, iq, kv, ic = outs[0] + if q is not None: + torch.testing.assert_close( + q, q_ref, rtol=BF16_RTOL, atol=BF16_ATOL, equal_nan=True + ) + if q8 is not None: + _check_fp8("q_fp8", q8, q8_ref) + _check_fp8("index_q", iq, iq_ref) + _check_cache("kv_cache", kv, kv_ref, sm, bs) + _check_cache("index_cache", ic, ic_ref, ism, bs) + # the other layers of a cross-layer buffer stay untouched + for c in (kv, ic): + storage = torch.empty(0, dtype=torch.uint8, device="cuda") + storage.set_(c.untyped_storage()) + outside = torch.ones_like(storage, dtype=torch.bool) + outside.as_strided(c.size(), c.stride(), c.storage_offset()).fill_(False) + assert (storage[outside] == CACHE_FILL).all(), "writes outside the view" diff --git a/tests/models/multimodal/processing/test_minimax_m3.py b/tests/models/multimodal/processing/test_minimax_m3.py index 04d6aa4778c3..b24ea2b803c6 100644 --- a/tests/models/multimodal/processing/test_minimax_m3.py +++ b/tests/models/multimodal/processing/test_minimax_m3.py @@ -1,138 +1,160 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""Unit tests for MiniMax-M3 VL ``max_long_side_pixel`` resize support. +"""Unit tests for MiniMax-M3 VL preprocessing (sglang-aligned size spec). -These exercise the vendored processor directly (no checkpoint / GPU needed), so -they validate the long-side resize spec and the resulting prompt-token counts -deterministically. +These exercise the vendored processor directly (no checkpoint / GPU needed) and +pin the ``compute_aligned_size`` / ``resolve_max_long_side_pixel`` contract +against the sglang reference algorithm +(``python/sglang/srt/multimodal/processors/minimax_m3_vl.py``). """ import pytest import torch from vllm.transformers_utils.processors.minimax_m3 import ( - IMAGE_MAX_TOTAL_PIXELS, MIN_SHORT_SIDE_PIXEL, - VIDEO_MAX_TOTAL_PIXELS, MiniMaxM3VLImageProcessor, MiniMaxM3VLVideoProcessor, - smart_resize, + compute_aligned_size, + resolve_max_long_side_pixel, ) -# Long sides are multiples of patch_size*merge_size (28) so the rounding is -# exact and the expected token counts are unambiguous. -LONG_SIDES = [252, 504, 1008] +FACTOR = 28 # patch_size * merge_size +PATCH_SIZE = 14 MERGE2 = 2**2 # merge_size ** 2 +# detail -> max_long_side_pixel, per the size spec. +IMAGE_DETAIL_CAPS = {"low": 672, "auto": 2016, "high": 3584} +VIDEO_DETAIL_CAPS = {"low": 504, "auto": 672, "high": 2188} -def _image_tokens(grid_thw) -> int: - g = list(grid_thw) - return int(g[0] * g[1] * g[2]) // MERGE2 + +def _merged_tokens(grid_thw) -> int: + return int(grid_thw.prod()) // MERGE2 # --------------------------------------------------------------------------- # -# smart_resize: the long-side spec (a) shrink / (b) enlarge / (c) hard cap +# compute_aligned_size: floor layers / ceil-align / long-side cap # --------------------------------------------------------------------------- # -def test_smart_resize_long_side_shrink(): - # (a) long side exceeds the cap -> shrink so the long side equals the cap. - h, w = smart_resize( - 2048, 1024, factor=28, max_long_side_pixel=1008, max_total_pixels=10**9 - ) - assert max(h, w) == 1008 - assert (h, w) == (1008, 504) # aspect ratio preserved +def test_compute_aligned_size_enlarges_short_side(): + # (200, 40) hits both floors: area 8000 < 168**2 scales to (376, 76); the + # short-side floor then scales by 168/76, where ceil(76 * 168/76) = 169 + # (float overshoot) aligns up to 196, and 832 aligns up to 840. + h, w = compute_aligned_size(200, 40, FACTOR, max_long_side_pixel=1008) + assert (h, w) == (840, 196) + assert h % FACTOR == 0 and w % FACTOR == 0 -def test_smart_resize_short_side_enlarge(): - # (b) long side within the cap but short side below the floor -> enlarge so - # the short side reaches min_short_side_pixel. - h, w = smart_resize( - 200, 40, factor=28, max_long_side_pixel=1008, max_total_pixels=10**9 - ) - assert min(h, w) == MIN_SHORT_SIDE_PIXEL # 112 +def test_compute_aligned_size_shrinks_over_cap_isotropically(): + # Long side 2048 ceil-aligns to 2072 > cap -> integer aspect-ratio + # scale-back to (1008, 504), already factor-aligned. + h, w = compute_aligned_size(2048, 1024, FACTOR, max_long_side_pixel=1008) + assert (h, w) == (1008, 504) -def test_smart_resize_total_pixels_raises(): - # (c) still over the area cap after resizing -> raise instead of inferring. - with pytest.raises(ValueError, match="max_total_pixels"): - smart_resize( - 5000, - 5000, - factor=28, - max_long_side_pixel=4000, - max_total_pixels=IMAGE_MAX_TOTAL_PIXELS, - ) +def test_compute_aligned_size_rejects_extreme_aspect_ratio(): + with pytest.raises(ValueError, match="aspect ratio"): + compute_aligned_size(20001, 100, FACTOR, max_long_side_pixel=1008) -def test_smart_resize_backward_compatible_area_bound(): - # Without max_long_side_pixel the original Qwen-style area bound is used. - assert smart_resize(2048, 2048, factor=28, max_pixels=451584) == (672, 672) +# --------------------------------------------------------------------------- # +# resolve_max_long_side_pixel: detail tiers and explicit override +# --------------------------------------------------------------------------- # +@pytest.mark.parametrize( + ("detail", "expected"), + [("low", 672), ("auto", 2016), ("high", 3584), (None, 2016)], +) +def test_resolve_max_long_side_pixel_image(detail, expected): + assert resolve_max_long_side_pixel(detail, None, modality="image") == expected + + +@pytest.mark.parametrize( + ("detail", "expected"), + [("low", 504), ("auto", 672), ("high", 2188), (None, 672)], +) +def test_resolve_max_long_side_pixel_video(detail, expected): + assert resolve_max_long_side_pixel(detail, None, modality="video") == expected + + +@pytest.mark.parametrize("modality", ["image", "video"]) +def test_resolve_max_long_side_pixel_explicit_overrides_detail(modality): + assert resolve_max_long_side_pixel("high", 1024, modality=modality) == 1024 + assert resolve_max_long_side_pixel(None, 1024, modality=modality) == 1024 + + +def test_processor_default_caps(): + assert MIN_SHORT_SIDE_PIXEL == 168 + assert MiniMaxM3VLImageProcessor().max_long_side_pixel == 2016 + assert MiniMaxM3VLVideoProcessor().max_long_side_pixel == 672 # --------------------------------------------------------------------------- # -# Image processor: monotonic prompt-token counts for 252 < 504 < 1008 +# Image processor end to end: grid/patch-counter consistency and token counts # --------------------------------------------------------------------------- # -def test_image_tokens_increase_with_max_long_side_pixel(): +@pytest.fixture(scope="module") +def square_image() -> torch.Tensor: + # 4096x4096 so detail="high" actually reaches the 3584 cap (a 2048x2048 + # image only ceil-aligns to 2072 and never upscales). + g = torch.Generator().manual_seed(0) + return torch.randint(0, 255, (3, 4096, 4096), dtype=torch.uint8, generator=g) + + +@pytest.mark.parametrize("detail", ["low", "auto", "high"]) +def test_image_preprocess_grid_matches_patch_counter(detail, square_image): proc = MiniMaxM3VLImageProcessor() - counts = [] - for long_side in LONG_SIDES: - patches = proc.get_number_of_image_patches( - 2048, 2048, images_kwargs={"max_long_side_pixel": long_side} - ) - counts.append(patches // MERGE2) + cap = IMAGE_DETAIL_CAPS[detail] - assert counts == [81, 324, 1296] - assert counts[0] < counts[1] < counts[2] + out = proc.preprocess([square_image], detail=detail, return_tensors="pt") + grid_thw = out["image_grid_thw"][0] + patches = proc.get_number_of_image_patches( + 4096, 4096, images_kwargs={"max_long_side_pixel": cap} + ) + assert int(grid_thw.prod()) == patches -def test_image_processor_defaults_match_spec(): - proc = MiniMaxM3VLImageProcessor() - assert proc.max_long_side_pixel is None # opt-in - assert proc.min_short_side_pixel == MIN_SHORT_SIDE_PIXEL - assert proc.max_total_pixels == IMAGE_MAX_TOTAL_PIXELS + # Cross-check against compute_aligned_size: the square long side lands + # exactly on the cap, giving (cap / patch_size) ** 2 patches. + assert compute_aligned_size(4096, 4096, FACTOR, max_long_side_pixel=cap) == ( + cap, + cap, + ) + assert patches == (cap // PATCH_SIZE) ** 2 -def test_image_preprocess_pipeline_monotonic(): +def test_image_tokens_increase_with_detail(square_image): proc = MiniMaxM3VLImageProcessor() - image = torch.randint(0, 255, (3, 2048, 2048), dtype=torch.uint8) - counts = [] - for long_side in LONG_SIDES: - out = proc.preprocess( - [image], - do_resize=True, - max_long_side_pixel=long_side, - return_tensors="pt", + counts = [ + _merged_tokens( + proc.preprocess([square_image], detail=detail, return_tensors="pt")[ + "image_grid_thw" + ][0] ) - counts.append(_image_tokens(out["image_grid_thw"][0])) - assert counts == [81, 324, 1296] + for detail in ("low", "auto", "high") + ] + # (cap / patch_size) ** 2 / merge_size**2 for caps 672 / 2016 / 3584. + assert counts == [576, 5184, 16384] + assert counts[0] < counts[1] < counts[2] -# --------------------------------------------------------------------------- # -# Video processor: same monotonic behavior + volumetric (w*h*frames) cap -# --------------------------------------------------------------------------- # -def test_video_tokens_increase_with_max_long_side_pixel(): - proc = MiniMaxM3VLVideoProcessor() - assert proc.max_total_pixels == VIDEO_MAX_TOTAL_PIXELS - video = torch.randint(0, 255, (4, 3, 2048, 2048), dtype=torch.uint8) - counts = [] - for long_side in LONG_SIDES: - out = proc.preprocess( - videos=[video], - do_resize=True, - max_long_side_pixel=long_side, - return_tensors="pt", - ) - counts.append(_image_tokens(out["video_grid_thw"][0])) - assert counts[0] < counts[1] < counts[2] +def test_image_preprocess_explicit_cap_overrides_detail(square_image): + proc = MiniMaxM3VLImageProcessor() + out = proc.preprocess( + [square_image], + detail="high", + max_long_side_pixel=672, + return_tensors="pt", + ) + # The explicit cap wins over detail="high" -> same grid as detail="low". + assert _merged_tokens(out["image_grid_thw"][0]) == 576 -def test_video_volumetric_cap_raises(): +# --------------------------------------------------------------------------- # +# Video processor: volumetric (frames * h * w) cap raises unconditionally +# --------------------------------------------------------------------------- # +def test_video_volume_cap_raises_by_default(): proc = MiniMaxM3VLVideoProcessor() - # 400 frames at a 1008-long-side square: 1008*1008*400 >> 301,056,000. - video = torch.randint(0, 255, (400, 3, 2048, 2048), dtype=torch.uint8) + # Default cap 672: 700 frames * 672 * 672 = 316,108,800 > 301,056,000. + # The volumetric cap raises even without any detail/max_long_side_pixel + # override. + video = torch.randint(0, 255, (700, 3, 672, 672), dtype=torch.uint8) with pytest.raises(ValueError, match="max_total_pixels"): - proc.preprocess( - videos=[video], - do_resize=True, - max_long_side_pixel=1008, - return_tensors="pt", - ) + proc.preprocess(videos=[video], return_tensors="pt") diff --git a/tests/models/registry.py b/tests/models/registry.py index 7b8223ccad97..3412b84cbefc 100644 --- a/tests/models/registry.py +++ b/tests/models/registry.py @@ -1580,6 +1580,11 @@ def check_available_online( is_available_online=False, use_original_num_layers=True, # DSpark has >1 draft block ), + "DSparkMiniMaxDraftModel": _HfExamplesInfo( + "MiniMaxAI/MiniMax-M3", + is_available_online=False, + use_original_num_layers=True, + ), "K3DSparkModel": _HfExamplesInfo( "moonshotai/Kimi-K3", speculative_model="Inferact/Kimi-K3-DSpark", diff --git a/tests/models/test_minimax_m3_mega_moe.py b/tests/models/test_minimax_m3_mega_moe.py new file mode 100644 index 000000000000..e4b834e3f832 --- /dev/null +++ b/tests/models/test_minimax_m3_mega_moe.py @@ -0,0 +1,295 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MiniMax-M3.1 on the DeepGEMM NVFP4 MegaMoE layer: gating, the checkpoint +adapter, and the fused block against a dequantized reference.""" + +import gc +from types import SimpleNamespace + +import pytest +import torch + +from vllm.model_executor.layers.fused_moe.deep_gemm_mega_moe import ( + DeepGemmMegaMoEExperts, +) +from vllm.models.minimax_m3.nvidia.model import ( + MEGA_MOE_FC2_INPUT_SCALE, + _mega_moe_expert_params_mapping, + _mega_moe_expert_weight, + _use_mega_moe, +) +from vllm.platforms import current_platform + +pytestmark = pytest.mark.skipif( + not current_platform.is_cuda(), reason="NVFP4 MegaMoE requires CUDA" +) + + +def _vllm_config(moe_backend: str, moe_quant_algo: str | None): + return SimpleNamespace( + kernel_config=SimpleNamespace(moe_backend=moe_backend), + quant_config=SimpleNamespace(moe_quant_algo=moe_quant_algo), + parallel_config=SimpleNamespace(enable_expert_parallel=True), + ) + + +@pytest.mark.parametrize( + ("moe_backend", "moe_quant_algo", "expected"), + [ + ("auto", "NVFP4", False), + ("deep_gemm_mega_moe", "NVFP4", True), + ("deep_gemm_mega_moe", None, NotImplementedError), + ], +) +def test_mega_moe_is_gated_on_nvfp4_checkpoints(moe_backend, moe_quant_algo, expected): + """MegaMoE is opt-in and refuses checkpoints whose experts are not NVFP4.""" + vllm_config = _vllm_config(moe_backend, moe_quant_algo) + if expected is NotImplementedError: + with pytest.raises(NotImplementedError, match="NVFP4 routed experts"): + _use_mega_moe(vllm_config) + else: + assert _use_mega_moe(vllm_config) is expected + + +def test_mega_moe_expert_weight_follows_the_qat_recipe(): + """Compressed-tensors quantization scales become ModelOpt dequantization + scales; the FC1 input scale is dropped (per-token) and the FC2 one is the + fixed QAT scale whatever the checkpoint holds.""" + prefix = "layers.3.block_sparse_moe.experts.7" + packed = torch.randint(0, 255, (4, 8), dtype=torch.uint8) + block_scale = torch.rand(4, 1).to(torch.float8_e4m3fn) + + assert _mega_moe_expert_weight(f"{prefix}.w1.weight_packed", packed) == ( + f"{prefix}.w1.weight", + packed, + ) + assert _mega_moe_expert_weight(f"{prefix}.w3.weight_scale", block_scale) == ( + f"{prefix}.w3.weight_scale", + block_scale, + ) + name, scale = _mega_moe_expert_weight( + f"{prefix}.w2.weight_global_scale", torch.tensor(448.0) + ) + assert name == f"{prefix}.w2.weight_scale_2" + assert torch.equal(scale, torch.tensor(1 / 448, dtype=torch.float32)) + for shard_id in ("w1", "w3"): + assert ( + _mega_moe_expert_weight( + f"{prefix}.{shard_id}.input_global_scale", torch.tensor(1.0) + ) + is None + ) + name, scale = _mega_moe_expert_weight( + f"{prefix}.w2.input_global_scale", torch.tensor(1.0) + ) + assert name == f"{prefix}.w2.input_scale" + assert scale.item() == MEGA_MOE_FC2_INPUT_SCALE + + +def _load_checkpoint(moe, tensors: dict[str, torch.Tensor]) -> None: + """``MiniMaxM3Model.load_weights`` for one MegaMoE block's tensors.""" + experts = moe.experts + mapping = _mega_moe_expert_params_mapping(experts.num_experts) + for name, tensor in tensors.items(): + if ".shared_experts." in name: + name = name.replace(".gate_proj.", ".w1.").replace(".up_proj.", ".w3.") + experts.load_shared_expert_weight(name, tensor) + continue + converted = _mega_moe_expert_weight(name, tensor) + if converted is None: + continue + name, tensor = converted + param_name, weight_name, expert_id, shard_id = next( + entry for entry in mapping if entry[1] in name + ) + name = name.replace(weight_name, param_name) + param = getattr(experts, name.rpartition(".")[2]) + param.weight_loader(param, tensor, name, shard_id=shard_id, expert_id=expert_id) + + +def _mega_moe_block(num_experts=8, top_k=2, hidden_size=512, intermediate_size=256): + """An SM100 MiniMax-M3.1 MoE block on MegaMoE with an MXFP8 shared expert.""" + if not current_platform.is_device_capability_family(100): + pytest.skip("DeepGEMM NVFP4 MegaMoE requires SM100") + from vllm.config import VllmConfig, set_current_vllm_config + from vllm.config.kernel import KernelConfig + from vllm.model_executor.layers.quantization.modelopt import ModelOptMxFp8Config + from vllm.models.minimax_m3.nvidia.model import MiniMaxM3MoE + + config = SimpleNamespace( + hidden_size=hidden_size, + intermediate_size=intermediate_size, + num_local_experts=num_experts, + num_experts_per_tok=top_k, + n_shared_experts=1, + scoring_func="sigmoid", + routed_scaling_factor=2.0, + use_routing_bias=False, + hidden_act="swigluoai", + swiglu_limit=7.0, + swiglu_alpha=1.702, + swiglu_beta=1.0, + ) + quant_config = ModelOptMxFp8Config( + is_checkpoint_mxfp8_serialized=True, + kv_cache_quant_algo=None, + exclude_modules=[], + moe_quant_algo="NVFP4", + ) + vllm_config = VllmConfig( + kernel_config=KernelConfig(moe_backend="deep_gemm_mega_moe") + ) + vllm_config.scheduler_config.max_num_batched_tokens = 256 + with set_current_vllm_config(vllm_config), torch.device("cuda"): + moe = MiniMaxM3MoE( + config, + layer_id=0, + quant_config=quant_config, + prefix="layers.0.block_sparse_moe", + use_mega_moe=True, + ) + assert isinstance(moe.experts, DeepGemmMegaMoEExperts) + return moe, config + + +@pytest.mark.parametrize("fused", [True, False]) +def test_mega_moe_allocates_the_shared_expert_once(dist_init, monkeypatch, fused): + """The block builds a real shared MLP only when MegaMoE does not fuse it + (e.g. an older DeepGEMM); a fused layer owns the only copy, and building + the block leaves no discarded weights for the garbage collector.""" + if not fused: + monkeypatch.setattr( + DeepGemmMegaMoEExperts, + "_kernel_fuses_shared_experts", + lambda self, spec: False, + ) + gc.collect() + gc.disable() + try: + moe, _ = _mega_moe_block() + allocated = torch.accelerator.memory_allocated() + gc.collect() + finally: + gc.enable() + assert torch.accelerator.memory_allocated() == allocated + assert moe.experts.has_fused_shared_experts is fused + assert (moe.shared_experts is None) is fused + assert all(param.is_cuda for param in moe.parameters()) + + +@pytest.mark.parametrize("num_tokens", [1, 45, 200]) +def test_mega_moe_block_matches_the_qat_reference(dist_init, num_tokens): + """A MiniMax-M3.1 MoE block on MegaMoE fuses its MXFP8 shared expert and, + loaded from a compressed-tensors checkpoint, reproduces the QAT recipe: + per-token FC1 input scales and the fixed FC2 input scale on the unweighted + SwiGLU output. Routing weights scale the BF16 expert outputs in combine.""" + from vllm.third_party.deep_gemm.utils import ( + cast_back_from_fp8, + per_token_cast_to_fp8, + ) + from vllm.third_party.deep_gemm.utils.nvfp4 import ( + cast_back_from_nvfp4, + per_token_cast_to_nvfp4, + ) + + torch.manual_seed(0) + moe, config = _mega_moe_block() + assert moe.experts.has_fused_shared_experts and moe.shared_experts is None + num_experts, top_k = config.num_local_experts, config.num_experts_per_tok + hidden_size, intermediate_size = config.hidden_size, config.intermediate_size + clamp, alpha, beta = config.swiglu_limit, config.swiglu_alpha, config.swiglu_beta + + def nvfp4(n, k): + weight = torch.randn(n, k, device="cuda") * k**-0.5 + global_scale = weight.abs().max().item() / (6 * 448) + packed, sf = per_token_cast_to_nvfp4(weight, global_scale) + dequant = cast_back_from_nvfp4(packed, sf, global_scale) + return ( + packed.view(torch.uint8), + sf.view(torch.float8_e4m3fn), + torch.tensor(1 / global_scale), + dequant, + ) + + def mxfp8(n, k): + weight = torch.randn(n, k, device="cuda") * k**-0.5 + fp8, sf = per_token_cast_to_fp8(weight, use_ue8m0=True, gran_k=32) + ue8m0 = (sf.view(torch.int32) >> 23).to(torch.uint8) + return fp8, ue8m0, cast_back_from_fp8(fp8, sf, gran_k=32) + + prefix = "layers.0.block_sparse_moe" + checkpoint: dict[str, torch.Tensor] = {} + ref_w13, ref_w2 = [], [] + for e in range(num_experts): + w13 = nvfp4(2 * intermediate_size, hidden_size) + w2 = nvfp4(hidden_size, intermediate_size) + for shard_id, rows, (packed, sf, global_scale, _) in ( + ("w1", slice(0, intermediate_size), w13), + ("w3", slice(intermediate_size, None), w13), + ("w2", slice(None), w2), + ): + name = f"{prefix}.experts.{e}.{shard_id}" + checkpoint[f"{name}.weight_packed"] = packed[rows] + checkpoint[f"{name}.weight_scale"] = sf[rows] + checkpoint[f"{name}.weight_global_scale"] = global_scale + # A placeholder the block must ignore. + checkpoint[f"{name}.input_global_scale"] = torch.tensor(0.25) + ref_w13.append(w13[3]) + ref_w2.append(w2[3]) + shared_ref = {} + for proj, (n, k) in ( + ("gate_proj", (intermediate_size, hidden_size)), + ("up_proj", (intermediate_size, hidden_size)), + ("down_proj", (hidden_size, intermediate_size)), + ): + fp8, ue8m0, shared_ref[proj] = mxfp8(n, k) + checkpoint[f"{prefix}.shared_experts.{proj}.weight"] = fp8 + checkpoint[f"{prefix}.shared_experts.{proj}.weight_scale"] = ue8m0 + _load_checkpoint(moe, checkpoint) + + # Rows span six decades, which one tensor-wide input scale cannot cover. + x = ( + torch.randn(num_tokens, hidden_size, device="cuda") + * torch.logspace(-4, 2, num_tokens, device="cuda")[:, None] + ).to(torch.bfloat16) + scores = torch.randn(num_tokens, num_experts, device="cuda").sigmoid() + topk_weights, topk_ids = scores.topk(top_k, dim=-1) + topk_weights *= config.routed_scaling_factor / topk_weights.sum(-1, keepdim=True) + out = moe.experts(x, topk_weights, topk_ids) + + def activation(h): + gate, up = h.to(torch.bfloat16).float().chunk(2, dim=-1) + gate = gate.clamp(max=clamp) + up = up.clamp(-clamp, clamp) + return gate * torch.sigmoid(alpha * gate) * (up + beta) + + def fp8_round_trip(h): + return cast_back_from_fp8( + *per_token_cast_to_fp8(h, use_ue8m0=True, gran_k=32, use_packed_ue8m0=True), + gran_k=32, + use_packed_ue8m0=True, + ) + + x_scales = x.float().abs().amax(-1, keepdim=True).clamp_min(1e-12) / 2688 + x_ref = cast_back_from_nvfp4(*per_token_cast_to_nvfp4(x.float() / x_scales)) + x_ref *= x_scales + ref = torch.zeros(num_tokens, hidden_size, device="cuda") + for e in range(num_experts): + rows, slots = torch.where(topk_ids == e) + if rows.numel() == 0: + continue + mid = activation(x_ref[rows] @ ref_w13[e].T) + mid = cast_back_from_nvfp4( + *per_token_cast_to_nvfp4(mid, MEGA_MOE_FC2_INPUT_SCALE), + MEGA_MOE_FC2_INPUT_SCALE, + ) + expert_out = (mid @ ref_w2[e].T).to(torch.bfloat16).float() + ref.index_add_(0, rows, topk_weights[rows, slots, None] * expert_out) + shared_w13 = torch.cat([shared_ref["gate_proj"], shared_ref["up_proj"]]) + shared_mid = fp8_round_trip(activation(fp8_round_trip(x) @ shared_w13.T)) + ref += (shared_mid @ shared_ref["down_proj"].T).to(torch.bfloat16).float() + + assert torch.isfinite(out).all() + # Per row: a missing per-token scale would only show in the small rows. + row_error = (out.float() - ref).norm(dim=-1) / ref.norm(dim=-1) + assert row_error.max() < 0.02, row_error diff --git a/tests/models/test_qwen3_dflash_mxfp8_context_kv.py b/tests/models/test_qwen3_dflash_mxfp8_context_kv.py new file mode 100644 index 000000000000..623c9ddb1ae4 --- /dev/null +++ b/tests/models/test_qwen3_dflash_mxfp8_context_kv.py @@ -0,0 +1,123 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""DFlash/DSpark context K/V projection with MXFP8 QKV weights.""" + +import pytest +import torch +from torch import nn + +from vllm.model_executor.layers.layernorm import RMSNorm +from vllm.model_executor.layers.linear import ( + QKVParallelLinear, + UnquantizedLinearMethod, +) +from vllm.model_executor.layers.quantization.modelopt import ModelOptMxFp8Config +from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( + _mxfp8_e4m3_quantize_torch, +) +from vllm.model_executor.models.qwen3_dflash import DFlashQwen3Model +from vllm.platforms import current_platform + +pytestmark = pytest.mark.skipif( + not current_platform.is_cuda() + or not current_platform.is_device_capability_family(100), + reason="Native MXFP8 kernels require SM100-family CUDA", +) + +HIDDEN, HEAD_DIM, NUM_HEADS, NUM_LAYERS, NUM_TOKENS = 256, 128, 2, 2, 7 +Q_SIZE, KV_SIZE = NUM_HEADS * HEAD_DIM, HEAD_DIM # one KV head + + +@pytest.fixture +def bf16_on_cuda(default_vllm_config, dist_init): + old_dtype = torch.get_default_dtype() + torch.set_default_dtype(torch.bfloat16) + with torch.device("cuda"): + yield + torch.set_default_dtype(old_dtype) + + +def _build_model(mode: str, has_bias: bool) -> tuple[DFlashQwen3Model, list]: + # MiniMax-style MXFP8 config; "mixed" leaves layer 1 in BF16. + quant_config = ( + None + if mode == "bf16" + else ModelOptMxFp8Config.from_config( + { + "quant_method": "mxfp8", + "activation_scheme": "dynamic", + "weight_block_size": [1, 32], + "ignored_layers": ( + ["layers.1.self_attn.qkv_proj"] if mode == "mixed" else [] + ), + } + ) + ) + model = DFlashQwen3Model.__new__(DFlashQwen3Model) + nn.Module.__init__(model) + model.hidden_norm = RMSNorm(HIDDEN) + model._rms_norm_eps = 1e-6 + attentions = [] + for i in range(NUM_LAYERS): + attn = nn.Module() + attn.q_size, attn.kv_size = Q_SIZE, KV_SIZE + attn.k_norm = RMSNorm(HEAD_DIM) + attn.qkv_proj = QKVParallelLinear( + HIDDEN, + HEAD_DIM, + NUM_HEADS, + 1, + bias=has_bias, + quant_config=quant_config, + prefix=f"layers.{i}.self_attn.qkv_proj", + disable_tp=True, + ) + weight = torch.randn(Q_SIZE + 2 * KV_SIZE, HIDDEN) / 16 + proj = attn.qkv_proj + if isinstance(proj.quant_method, UnquantizedLinearMethod): + proj.weight.data.copy_(weight) + else: + weight, scale = _mxfp8_e4m3_quantize_torch(weight) + proj.weight.data.copy_(weight) + proj.weight_scale.data.copy_(scale) + if has_bias: + proj.bias.data.normal_(std=0.1) + attentions.append(attn) + return model, attentions + + +@pytest.mark.parametrize("mode", ["bf16", "mxfp8", "mixed"]) +@pytest.mark.parametrize("has_bias", [False, True]) +@torch.inference_mode() +def test_context_kv_matches_qkv_projection(bf16_on_cuda, mode, has_bias): + """The context K/V must equal the K/V slice of each layer's own QKV output + after kernel repacking, eagerly and under CUDA graph replay.""" + torch.manual_seed(0) + model, attentions = _build_model(mode, has_bias) + # Load-time order: context buffers are built before kernels repack weights. + model._build_context_kv_buffers(attentions, has_bias=has_bias) + assert (model._fused_kv_weight is not None) == (mode == "bf16") + assert (model._context_kv_proj is not None) == (mode == "mxfp8") + for module in [*model.modules(), *(m for a in attentions for m in a.modules())]: + method = getattr(module, "quant_method", None) + if method is not None: + method.process_weights_after_loading(module) + + x = torch.randn(NUM_TOKENS, HIDDEN) + normed = model.hidden_norm(x) + expected = torch.cat( + [a.qkv_proj(normed)[0][:, Q_SIZE:] for a in attentions], dim=-1 + ) + + def project() -> torch.Tensor: + k, v = model._project_context_kv(x, NUM_TOKENS, NUM_LAYERS, 1, HEAD_DIM) + return torch.stack([k, v]).permute(2, 1, 0, 3, 4).reshape(NUM_TOKENS, -1) + + torch.testing.assert_close(project(), expected, rtol=0.02, atol=0.02) + + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + captured = project() + x.normal_() + graph.replay() + torch.testing.assert_close(captured, project(), rtol=0, atol=0) diff --git a/tests/quantization/test_auto_gptq.py b/tests/quantization/test_auto_gptq.py index 4f60a974caed..c2221b3f02c2 100644 --- a/tests/quantization/test_auto_gptq.py +++ b/tests/quantization/test_auto_gptq.py @@ -162,7 +162,7 @@ def test_routed_experts_loads_per_expert_biases(): class Loader: quant_config = None quant_method = object() - _fused_shared_expert_quantizer = None + shared_expert_online_loader = None moe_config = SimpleNamespace( is_act_and_mul=True, tp_rank=0, diff --git a/tests/quantization/test_fp8_per_channel.py b/tests/quantization/test_fp8_per_channel.py index d4f2fe264e6c..c0be76769ee1 100644 --- a/tests/quantization/test_fp8_per_channel.py +++ b/tests/quantization/test_fp8_per_channel.py @@ -9,6 +9,9 @@ `pytest tests/quantization/test_fp8_per_channel.py --forked`. """ +from types import SimpleNamespace +from unittest import mock + import pytest import torch @@ -28,10 +31,18 @@ Fp8PtpcOnlineMoEMethod, ) from vllm.model_executor.layers.quantization.utils.quant_utils import ( + get_fp8_min_max, kFp8StaticChannelSym, ) from vllm.platforms import current_platform +if current_platform.is_rocm(): + from vllm.platforms.rocm import on_gfx942 +else: + + def on_gfx942() -> bool: + return False + def test_fp8_per_channel_shorthand_registered() -> None: """The `fp8_per_channel` CLI shorthand must resolve to a config that @@ -56,6 +67,10 @@ def test_fp8_per_channel_shorthand_registered() -> None: not is_quant_method_supported("fp8"), reason="FP8 is not supported on this GPU type.", ) +@pytest.mark.skipif( + on_gfx942(), + reason="The dynamic per-token FP8 kernel can segfault on gfx942.", +) def test_scaled_fp8_quant_per_channel_shape() -> None: """Verify the kernel call per-channel quant depends on: passing a 2D weight to `ops.scaled_fp8_quant` with `use_per_token_if_dynamic=True` @@ -69,3 +84,63 @@ def test_scaled_fp8_quant_per_channel_shape() -> None: assert y.dtype == current_platform.fp8_dtype() assert s.shape == (96, 1) assert s.dtype == torch.float32 + + +@pytest.mark.skipif(not on_gfx942(), reason="Requires gfx942.") +def test_gfx942_moe_weight_quant_avoids_dynamic_per_token_op(monkeypatch) -> None: + """gfx942 load-time MoE quantization uses the torch per-channel path.""" + device = current_platform.device_type + torch.manual_seed(0) + w13_weight = torch.randn(2, 96, 128, device=device, dtype=torch.bfloat16) + w2_weight = torch.randn(2, 128, 48, device=device, dtype=torch.bfloat16) + + method = object.__new__(Fp8PtpcOnlineMoEMethod) + method.moe = SimpleNamespace(tp_size=1) + layer = SimpleNamespace(local_num_experts=2) + + def fail_dynamic_quant(*args, **kwargs): + raise AssertionError("gfx942 must not call dynamic per-token FP8 quant") + + monkeypatch.setattr(ops, "scaled_fp8_quant", fail_dynamic_quant) + with ( + mock.patch.object( + method, + "get_weights_for_quantization", + return_value=(w13_weight, w2_weight), + ) as get_weights, + mock.patch.object(method, "_setup_kernel") as setup_kernel, + mock.patch.object( + method, "release_requantization_source_weights" + ) as release_weights, + ): + method.process_weights_after_loading(layer) + + get_weights.assert_called_once_with(layer) + setup_kernel.assert_called_once() + release_weights.assert_called_once_with(layer) + _, got_w13, got_w2, got_w13_scale, got_w2_scale = setup_kernel.call_args.args + assert setup_kernel.call_args.kwargs == { + "w13_input_scale": None, + "w2_input_scale": None, + } + + fp8_min, fp8_max = get_fp8_min_max() + + def reference(weight: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + fp8_max_tensor = torch.tensor( + fp8_max, device=weight.device, dtype=torch.float32 + ) + scale = weight.abs().amax(dim=-1, keepdim=True).float() / fp8_max_tensor + scale.clamp_min_(1.0 / (fp8_max * 512)) + quantized = ( + (weight / scale).clamp(fp8_min, fp8_max).to(current_platform.fp8_dtype()) + ) + return quantized, scale + + expected_w13, expected_w13_scale = reference(w13_weight) + expected_w2, expected_w2_scale = reference(w2_weight) + assert torch.equal(got_w13_scale, expected_w13_scale) + assert torch.equal(got_w13, expected_w13) + assert torch.equal(got_w2_scale, expected_w2_scale) + assert torch.equal(got_w2, expected_w2) + assert layer._already_called_process_weights_after_loading diff --git a/tests/quantization/test_modelopt.py b/tests/quantization/test_modelopt.py index d489cb2b9acf..1cffd78714eb 100644 --- a/tests/quantization/test_modelopt.py +++ b/tests/quantization/test_modelopt.py @@ -154,6 +154,80 @@ def test_modelopt_mxfp8_preserves_per_row_checkpoint_scales(dist_init, monkeypat assert torch.equal(linear.weight_scale, scales) +_M31_QUANT_CONFIG = { + "quant_method": "mxfp8", + "ignored_layers": ["lm_head", "model.layers.3.block_sparse_moe.gate"], + "group_size": 16, + "moe_quant_algo": "NVFP4", + "moe_quant_format": "nvfp4-pack-quantized", +} + + +def test_modelopt_mxfp8_routes_nvfp4_experts_to_compressed_tensors(monkeypatch): + """MiniMax-M3.1 keeps MXFP8 linears but ships compressed-tensors NVFP4 + routed experts; loading them with the MXFP8 MoE method drops weights.""" + ct_method = Mock() + monkeypatch.setattr( + "vllm.model_executor.layers.quantization.compressed_tensors." + "compressed_tensors_moe.compressed_tensors_moe_w4a4_nvfp4." + "CompressedTensorsW4A4Nvfp4MoEMethod", + ct_method, + ) + config = ModelOptMxFp8Config.from_config(dict(_M31_QUANT_CONFIG)) + layer = Mock(spec=RoutedExperts) + layer.moe_config = Mock() + prefix = "model.layers.3.block_sparse_moe.experts" + + # MiniMax-M3.1 declares that it QAT'd the FC1 input per token, leaving a + # neutral 1.0 input_global_scale. A model that declares nothing keeps the + # checkpoint's per-tensor scale. + for declared, expected in ( + (kNvfp4DynamicToken, kNvfp4DynamicToken), + (None, kNvfp4Dynamic), + ): + ct_method.reset_mock() + layer.moe_config.qat_activation_key = declared + assert config.get_quant_method(layer, prefix) is ct_method.return_value + ct_method.assert_called_once_with( + layer.moe_config, layer_name=prefix, activation_key=expected + ) + + plain = ModelOptMxFp8Config.from_config({"quant_method": "mxfp8"}) + assert plain.moe_quant_algo is None + + +def test_per_token_nvfp4_moe_backends_match_the_experts_that_implement_it(): + """``make_nvfp4_moe_kernel`` dispatches unquantized inputs for a per-token + scheme and only forwards ``per_token_activation`` to this set, so it has to + be exactly the experts that take that argument. ``_supports_quant_scheme`` + cannot be used for the check: several NVFP4 backends match on the weight + key alone and accept any activation key.""" + import inspect + + from vllm.model_executor.layers.fused_moe.oracle.nvfp4 import ( + PER_TOKEN_NVFP4_MOE_BACKENDS, + NvFp4MoeBackend, + backend_to_kernel_cls, + ) + + implementing = { + backend + for backend in NvFp4MoeBackend + for cls in backend_to_kernel_cls(backend) + if "per_token_activation" in inspect.signature(cls.__init__).parameters + } + assert implementing == PER_TOKEN_NVFP4_MOE_BACKENDS + + +@pytest.mark.parametrize( + "override", + [{"moe_quant_algo": "MXFP4"}, {"moe_quant_format": "float-quantized"}], +) +def test_modelopt_mxfp8_rejects_unknown_expert_format(override): + with pytest.raises(ValueError, match="MoE quantization"): + ModelOptMxFp8Config.from_config({**_M31_QUANT_CONFIG, **override}) + + def test_modelopt_mxfp8_pre_processed_weights_follow_kernel(monkeypatch): """The weight cache daemon can only serve MXFP8 layers whose kernel needs no post-load state beyond the parameters it exports.""" @@ -1546,6 +1620,7 @@ def test_modelopt_block_quant_loads_expert_blocks_with_aligned_tp_slices( layer = torch.nn.Module() layer.layer_name = "model.layers.0.mlp.experts" layer.is_fused_checkpoint_transposed = False + layer.shared_expert_online_loader = None layer._orient_fused_weight = RoutedExperts._orient_fused_weight layer.get_expert_mapping = lambda **kwargs: ( RoutedExperts.build_expert_params_mapping( diff --git a/tests/quantization/test_online.py b/tests/quantization/test_online.py index b572bb425a6d..66214fad072a 100644 --- a/tests/quantization/test_online.py +++ b/tests/quantization/test_online.py @@ -881,7 +881,7 @@ def test_weight_loading_requantization_moe( for name, expected in tensors.items(): # Public loading must preserve all packed weights and scale conventions. torch.testing.assert_close(getattr(layer, name).cpu(), expected, rtol=0, atol=0) - actual_w13, actual_w2 = source.dequantize_weight(layer) + ((_, actual_w13, actual_w2),) = source.dequantize_weight(layer) # Gate/up ordering and distinct global scales must survive source loading. torch.testing.assert_close(actual_w13.cpu(), expected_w13, rtol=0, atol=0) @@ -921,9 +921,12 @@ def test_online_requantized_moe_padding( w13_num_shards=num_shards, is_act_and_mul=is_act_and_mul, has_bias=has_bias ) method.requantization_source = Mock() - method.requantization_source.dequantize_weight.return_value = (w13, w2) + method.requantization_source.dequantize_weight.return_value = iter( + [(slice(0, 2), w13, w2)] + ) layer = SimpleNamespace( local_num_experts=2, + expert_map_manager=SimpleNamespace(num_fused_shared_experts=0), moe_config=SimpleNamespace( hidden_dim_unpadded=16, intermediate_size_per_partition_unpadded=32, @@ -1075,6 +1078,7 @@ def create_layer() -> tuple[torch.nn.Module, Any]: layer = torch.nn.Module() layer.local_num_experts = 2 layer.num_experts = 2 + layer.expert_map_manager = SimpleNamespace(num_fused_shared_experts=0) layer._expert_routing_tables = lambda: None layer.moe_config = SimpleNamespace( hidden_dim_unpadded=size, @@ -2477,7 +2481,7 @@ def test_nvfp4_moe_dequantization_and_fp8_requantization_numerics( **checkpoint_tensors, params_dtype=torch.bfloat16, ) - w13_dequantized, w2_dequantized = source.dequantize_weight(source_layer) + ((_, w13_dequantized, w2_dequantized),) = source.dequantize_weight(source_layer) w13 = torch.cat((w1, w3), dim=1) torch.testing.assert_close(w13_dequantized, w13_reference, rtol=0, atol=0) diff --git a/tests/quantization/test_online_shared_expert_fusion.py b/tests/quantization/test_online_shared_expert_fusion.py index 394ba04a1b30..29fe15d5d89a 100644 --- a/tests/quantization/test_online_shared_expert_fusion.py +++ b/tests/quantization/test_online_shared_expert_fusion.py @@ -3,13 +3,16 @@ """Tests ROCm AITER fused shared experts with online quantization.""" import json +import logging from pathlib import Path from types import SimpleNamespace from typing import Any +from unittest.mock import Mock import pytest import torch +import vllm.envs as envs from tests.quantization.utils import load_model_without_vllm_runner from vllm._aiter_ops import rocm_aiter_ops from vllm.config.model import ModelConfig @@ -17,17 +20,37 @@ QuantizationConfigArgs, resolve_quantization_config, ) +from vllm.logger import _print_warning_once from vllm.model_executor.layers.fused_moe import FusedMoEFactory from vllm.model_executor.layers.fused_moe.experts import rocm_aiter_moe +from vllm.model_executor.layers.fused_moe.oracle import nvfp4 as nvfp4_oracle from vllm.model_executor.layers.fused_moe.oracle.mxfp4 import Mxfp4MoeBackend +from vllm.model_executor.layers.fused_moe.oracle.nvfp4 import NvFp4MoeBackend +from vllm.model_executor.layers.quantization.compressed_tensors.compressed_tensors_moe.compressed_tensors_moe_w4a4_nvfp4 import ( # noqa: E501 + CompressedTensorsW4A4Nvfp4MoEMethod, +) +from vllm.model_executor.layers.quantization.modelopt import ModelOptMxFp8Config from vllm.model_executor.layers.quantization.online.base import OnlineQuantizationConfig +from vllm.model_executor.layers.quantization.online.mxfp4 import Mxfp4OnlineMoEMethod +from vllm.model_executor.layers.quantization.online.mxfp8 import Mxfp8OnlineMoEMethod +from vllm.model_executor.layers.quantization.online.requantization import ( + is_requantization_source, +) from vllm.model_executor.layers.quantization.quark.quark import QuarkConfig from vllm.model_executor.layers.quantization.quark.quark_moe import ( + QuarkNvfp4MoEMethod, QuarkOCP_MX_MoEMethod, ) from vllm.model_executor.layers.quantization.utils.mxfp4_utils import ( mxfp4_quantize, ) +from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( + dequant_mxfp8_to_bf16, + mxfp8_e4m3_quantize, +) +from vllm.model_executor.layers.quantization.utils.nvfp4_emulation_utils import ( + dequantize_to_dtype, +) from vllm.model_executor.model_loader.dummy_loader import DummyModelLoader from vllm.model_executor.model_loader.reload.layerwise import ( finalize_layerwise_reload, @@ -123,17 +146,58 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.o_proj = SimpleNamespace(reduce_results=True) +class _SingleRankGroup: + """Minimal stand-in for a size-1 `GroupCoordinator`.""" + + world_size = 1 + rank_in_group = 0 + rank = 0 + local_rank = 0 + ranks = [0] + is_first_rank = True + is_last_rank = True + # Read at model construction, never used for communication here. + device_group = SimpleNamespace(size=lambda: 1, rank=lambda: 0) + cpu_group = None + + +@pytest.fixture +def single_rank_parallel_state(monkeypatch: pytest.MonkeyPatch): + """Single rank parallel groups without initializing a process group. + + This is faster than the `dist_init` fixture. + """ + for name in ("_WORLD", "_TP", "_ETP", "_DCP", "_PP", "_DP", "_EP", "_PCP"): + monkeypatch.setattr( + f"vllm.distributed.parallel_state.{name}", _SingleRankGroup() + ) + monkeypatch.setattr( + "vllm.model_executor.parameter.get_tensor_model_parallel_rank", lambda: 0 + ) + monkeypatch.setattr( + "vllm.model_executor.parameter.get_tensor_model_parallel_world_size", lambda: 1 + ) + + @pytest.fixture(autouse=True) def reset_aiter_shared_expert_topk_metadata(monkeypatch: pytest.MonkeyPatch): """Isolate AITER's process-global shared-expert routing buffer.""" + _print_warning_once.cache_clear() # `logger.warning_once` dedupes across tests monkeypatch.setattr(rocm_aiter_moe, "aiter_topK_meta_data", None) rocm_aiter_moe.init_aiter_topK_meta_data.cache_clear() yield rocm_aiter_moe.init_aiter_topK_meta_data.cache_clear() -def _write_minimal_moe_config(model_path: Path, architecture: str) -> None: - """Write a compact MoE config with one shared expert.""" +def _write_minimal_moe_config( + model_path: Path, + architecture: str, + quantization_config: dict[str, Any] | None = None, +) -> None: + """Write a compact MoE config with one shared expert. + + `quantization_config` overrides the checkpoint quantization of MiniMax-M3. + """ config = { "architectures": [architecture], "hidden_size": 256, @@ -170,13 +234,20 @@ def _write_minimal_moe_config(model_path: Path, architecture: str) -> None: text_config = { **config, "model_type": "minimax_m3_text", + "intermediate_size": 256, "dense_intermediate_size": 512, + "shared_intermediate_size": 256, "hidden_act": "swigluoai", + "swiglu_alpha": 1.702, + "swiglu_limit": 7.0, + "scoring_func": "sigmoid", + "use_routing_bias": True, + "routed_scaling_factor": 2.0, "num_local_experts": 4, - "n_shared_experts": 1, "moe_layer_freq": [1], "sparse_attention_config": None, - "quantization_config": { + "quantization_config": quantization_config + or { **_QUARK_MXFP4_CONFIG, "layer_quant_config": { "*block_sparse_moe.experts*": _QUARK_MXFP4_LAYER_CONFIG @@ -271,7 +342,7 @@ def _unpadded_block(padded: torch.Tensor, expected: torch.Tensor) -> torch.Tenso ) def test_online_shared_expert_loads_bf16_weights_into_mxfp4_slot( default_vllm_config, - dist_init, + single_rank_parallel_state, load_path: str, ) -> None: """A BF16 shared expert is quantized while routed MXFP4 weights are loaded. @@ -363,7 +434,7 @@ def test_online_shared_expert_loads_bf16_weights_into_mxfp4_slot( def test_online_shared_expert_reload_compatibility( default_vllm_config, - dist_init, + single_rank_parallel_state, monkeypatch: pytest.MonkeyPatch, ) -> None: """Reload a BF16 shared weight into its MXFP4 slot via meta staging.""" @@ -458,13 +529,12 @@ def test_online_quantization( architecture: str, tmp_path: Path, monkeypatch, - dist_init, + caplog_vllm, + single_rank_parallel_state, workspace_init, ) -> None: """Online MXFP4 fuses each architecture's shared expert into its MoE.""" - monkeypatch.setenv("VLLM_ROCM_USE_AITER", "1") - monkeypatch.setenv("VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS", "1") - rocm_aiter_ops.refresh_env_variables() + _enable_aiter(monkeypatch, fse=True) if architecture == "Glm5NextForCausalLM": from vllm.models.glm5next.common import model as glm5_next_model @@ -498,23 +568,6 @@ def test_online_quantization( ) target_pattern = f"*{expected_shared_expert_name}*" - logged_messages: list[str] = [] - logged_warnings: list[str] = [] - - def record_info(message: str, *args: object, **_kwargs: object) -> None: - if "Quantizing " in message and "of types" in message: - logged_messages.append(message % args) - - def record_warning(message: str, *args: object, **_kwargs: object) -> None: - logged_warnings.append(message % args) - - monkeypatch.setattr( - "vllm.model_executor.model_loader.base_loader.logger.info", record_info - ) - monkeypatch.setattr( - "vllm.model_executor.layers.fused_moe.utils.logger.warning", record_warning - ) - model, vllm_config = load_model_without_vllm_runner( str(tmp_path), dtype="bfloat16", @@ -551,7 +604,8 @@ def record_warning(message: str, *args: object, **_kwargs: object) -> None: shared_expert_prefix = routed_experts.moe_config.shared_expert_prefix assert shared_expert_prefix is not None assert shared_expert_prefix.endswith(shared_expert_name) - assert routed_experts._fused_shared_expert_quantizer is not None + assert routed_experts.shared_expert_online_loader is not None + assert routed_experts.shared_expert_online_loader.quantizer is not None expert_map_manager = routed_experts.expert_map_manager assert expert_map_manager.num_fused_shared_experts == 1 assert expert_map_manager.map_global_to_local( @@ -571,53 +625,547 @@ def record_warning(message: str, *args: object, **_kwargs: object) -> None: assert not any( "VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS is enabled but " "cannot be enabled" in warning - for warning in logged_warnings + for warning in _fse_warnings(caplog_vllm) + ) + parent_name = ( + "block_sparse_moe" if architecture == "MiniMaxM3SparseForCausalLM" else "mlp" ) - if architecture == "MiniMaxM3SparseForCausalLM": - # TODO: Use resolve_layer_fused_shared_expert in MiniMax M3 and remove - # this branch once its virtual fused projections are registered. - assert logged_messages == ["Quantizing 0 layers of types: "] + assert _online_quantization_logs(caplog_vllm) == [ + "Quantizing 2 layers of types: " + f"{parent_name}.{shared_expert_name}.down_proj: 1 " + f"(from targets: {target_pattern}, mxfp4); " + f"{parent_name}.{shared_expert_name}.gate_up_proj: 1 " + f"(from targets: {target_pattern}, mxfp4)" + ] + + +_MINIMAX_NVFP4_ROUTED_MXFP8_SHARED_QUANT_CONFIG: dict[str, Any] = { + # Mirrors MiniMax-M3.1's checkpoint: MXFP8 linears and shared experts, + # compressed-tensors NVFP4 routed experts. + "quant_method": "mxfp8", + "activation_scheme": "dynamic", + "weight_block_size": [1, 32], + "ignored_layers": [ + "lm_head", + "model.embed_tokens", + "vision_tower", + "multi_modal_projector", + "patch_merge_mlp", + "model.layers.0.block_sparse_moe.gate", + ], + "group_size": 16, + "moe_quant_algo": "NVFP4", + "moe_quant_format": "nvfp4-pack-quantized", +} + +def _quark_moe_config( + routed: dict[str, Any], shared: dict[str, Any] | None = None +) -> dict[str, Any]: + """Quark MiniMax checkpoint quantizing the routed experts as `routed` and the + shared experts as `shared` (excluded if None). Other layers are excluded.""" + modules = "experts" if shared is None else "(?:experts|shared_experts)" + return { + **_QUARK_MXFP4_CONFIG, + "global_quant_config": routed, + "layer_quant_config": ( + {} if shared in (None, routed) else {"*shared_experts*": shared} + ), + "exclude": [f"re:^(?!.*\\.block_sparse_moe\\.{modules}(?:\\.|$)).*$"], + } + + +# NVFP4: fp4 values with per-16 e4m3 scales, plus a per-tensor fp8_e4m3 scale. +_NVFP4_VALUES = { + "dtype": "fp4", + "is_dynamic": False, + "qscheme": "per_group", + "ch_axis": -1, + "group_size": 16, + "scale_format": "e4m3", + "observer_cls": "PerBlockMXObserver", +} +_NVFP4_GLOBAL_SCALE = { + "dtype": "fp8_e4m3", + "is_dynamic": False, + "qscheme": "per_tensor", + "observer_cls": "PerTensorMinMaxObserver", +} +_QUARK_NVFP4_LAYER_CONFIG: dict[str, Any] = { + "input_tensors": [{**_NVFP4_VALUES, "is_dynamic": True}, _NVFP4_GLOBAL_SCALE], + "output_tensors": None, + "weight": [_NVFP4_VALUES, _NVFP4_GLOBAL_SCALE], + "bias": None, + "target_device": None, +} +_QUARK_MXFP8_LAYER_CONFIG: dict[str, Any] = { + **_QUARK_MXFP4_LAYER_CONFIG, + **{ + name: {**_QUARK_MXFP4_LAYER_CONFIG[name], "dtype": "fp8_e4m3"} + for name in ("input_tensors", "weight") + }, +} +_QUARK_NVFP4_ROUTED_BF16_SHARED_QUANT_CONFIG = _quark_moe_config( + _QUARK_NVFP4_LAYER_CONFIG +) +_QUARK_NVFP4_ROUTED_NVFP4_SHARED_QUANT_CONFIG = _quark_moe_config( + _QUARK_NVFP4_LAYER_CONFIG, _QUARK_NVFP4_LAYER_CONFIG +) +_QUARK_MXFP4_ROUTED_MXFP8_SHARED_QUANT_CONFIG = _quark_moe_config( + _QUARK_MXFP4_LAYER_CONFIG, _QUARK_MXFP8_LAYER_CONFIG +) +# BF16 (excluded) routed experts, MXFP8 shared experts. +_QUARK_BF16_ROUTED_MXFP8_SHARED_QUANT_CONFIG = { + **_QUARK_MXFP4_CONFIG, + "global_quant_config": _QUARK_MXFP8_LAYER_CONFIG, + "layer_quant_config": {}, + "exclude": ["re:^(?!.*\\.block_sparse_moe\\.shared_experts(?:\\.|$)).*$"], +} + +_FSE_ROUTED_SHARED_TARGETS = { + "*block_sparse_moe.experts*": "mxfp4", + "*shared_experts*": "mxfp4", +} + +_ONLINE_QUANTIZATION_LOGGER = "vllm.model_executor.model_loader.base_loader" +_FSE_LOGGER = "vllm.model_executor.layers.fused_moe.utils" + + +def _enable_aiter( + monkeypatch: pytest.MonkeyPatch, *, moe: bool = True, fse: bool | None = None +) -> None: + """Enable AITER; `fse` sets or unsets fused shared experts, None keeps it.""" + # Other tests reload `envs`, which can leave these flags pinned as attributes + # that shadow the environment variables. + for name in ( + "VLLM_ROCM_USE_AITER", + "VLLM_ROCM_USE_AITER_MOE", + "VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS", + ): + monkeypatch.delitem(vars(envs), name, raising=False) + monkeypatch.setenv("VLLM_ROCM_USE_AITER", "1") + if moe: + monkeypatch.setenv("VLLM_ROCM_USE_AITER_MOE", "1") + if fse is not None: + monkeypatch.setenv("VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS", str(int(fse))) + rocm_aiter_ops.refresh_env_variables() + + +def _use_checkpoint_quantization(monkeypatch: pytest.MonkeyPatch) -> None: + """Only resolve the user's quantization config, as the CLI does. + + The checkpoint's own "mxfp8" method is detected into `model_config.quantization`, + which the helper would otherwise resolve as the online MXFP8 shorthand. + """ + monkeypatch.setattr( + "tests.quantization.utils.resolve_quantization_config", + lambda _quantization, quantization_config: quantization_config, + ) + + +def _logged_messages( + caplog: pytest.LogCaptureFixture, logger: str, level: int +) -> list[str]: + return [ + r.getMessage() + for r in caplog.records + if r.name == logger and r.levelno == level + ] + + +def _online_quantization_logs(caplog: pytest.LogCaptureFixture) -> list[str]: + return [ + message + for message in _logged_messages( + caplog, _ONLINE_QUANTIZATION_LOGGER, logging.INFO + ) + if "Quantizing " in message and "of types" in message + ] + + +def _fse_warnings(caplog: pytest.LogCaptureFixture) -> list[str]: + return _logged_messages(caplog, _FSE_LOGGER, logging.WARNING) + + +_ROUTED_MXFP4 = {"*block_sparse_moe.experts*": "mxfp4"} +_ROUTED_SHARED_MXFP4 = {**_ROUTED_MXFP4, "*shared_expert*": "mxfp4"} +# (targets, fse_requested, routed_method_cls, id) of routed experts requantization. +_ROUTED_TARGET_CASES = [ + (_ROUTED_SHARED_MXFP4, True, Mxfp4OnlineMoEMethod, "fse_routed_shared_mxfp4"), + ({"*block_sparse_moe.experts*": "mxfp8"}, False, Mxfp8OnlineMoEMethod, "routed_mxfp8"), + (_ROUTED_MXFP4, False, Mxfp4OnlineMoEMethod, "routed_mxfp4"), + (_ROUTED_SHARED_MXFP4, False, Mxfp4OnlineMoEMethod, "routed_shared_mxfp4"), + # FSE refused: the shared expert, kept as stored, does not match. + (_ROUTED_MXFP4, True, Mxfp4OnlineMoEMethod, "fse_refused_routed_mxfp4"), +] + + +@pytest.mark.parametrize( + "checkpoint_quant_config, source_cls, targets, fse_requested, routed_method_cls", + [ + *( + pytest.param( + config, + source_cls, + targets, + fse, + method_cls, + id=f"{config_id}-{case_id}", + marks=pytest.mark.skip( + # TODO: enable once `QuarkLinearMethod` implements + # `dequantize_weight`. + reason="Requantizing Quark NVFP4 shared experts is not supported." + ) + if config is _QUARK_NVFP4_ROUTED_NVFP4_SHARED_QUANT_CONFIG + and "*shared_expert*" in targets + else (), + ) + for config, source_cls, config_id in [ + ( + _MINIMAX_NVFP4_ROUTED_MXFP8_SHARED_QUANT_CONFIG, + CompressedTensorsW4A4Nvfp4MoEMethod, + "nvfp4_routed_mxfp8_shared", + ), + ( + _QUARK_NVFP4_ROUTED_BF16_SHARED_QUANT_CONFIG, + QuarkNvfp4MoEMethod, + "quark_nvfp4_routed_bf16_shared", + ), + ( + _QUARK_NVFP4_ROUTED_NVFP4_SHARED_QUANT_CONFIG, + QuarkNvfp4MoEMethod, + "quark_nvfp4_routed_nvfp4_shared", + ), + ] + for targets, fse, method_cls, case_id in _ROUTED_TARGET_CASES + ), + # Routed experts are not requantized. With FSE, the MXFP8 shared expert is + # staged and quantized to MXFP4 into its slot after loading. Without, the + # shared expert linears are requantized from Quark MXFP8. + *( + pytest.param( + _QUARK_MXFP4_ROUTED_MXFP8_SHARED_QUANT_CONFIG, + None, + {"*shared_expert*": "mxfp4"}, + fse, + QuarkOCP_MX_MoEMethod, + id=f"quark_mxfp4_routed_mxfp8_shared-{case_id}", + ) + for fse, case_id in ((True, "fse_shared_mxfp4"), (False, "shared_mxfp4")) + ), + ], +) +def test_fse_online_quantization_routed_shared( + checkpoint_quant_config: dict[str, Any], + source_cls: type, + targets: dict[str, str], + fse_requested: bool, + routed_method_cls: type, + tmp_path: Path, + monkeypatch, + caplog_vllm, + single_rank_parallel_state, + workspace_init, +) -> None: + """Routed and/or shared experts are (re)quantized online. The shared experts + are fused into the routed experts only with + `VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS=1`. + """ + architecture = "MiniMaxM3SparseForCausalLM" + _enable_aiter(monkeypatch, fse=fse_requested) + _write_minimal_moe_config(tmp_path, architecture, checkpoint_quant_config) + _use_checkpoint_quantization(monkeypatch) + model, vllm_config = load_model_without_vllm_runner( + str(tmp_path), + dtype="bfloat16", + model_config_kwargs={ + "quantization_config": QuantizationConfigArgs(targets=targets) + }, + model_loader_cls=DummyModelLoader, + ) + expected_model_cls, resolved_architecture = get_model_architecture( + vllm_config.model_config + ) + assert resolved_architecture == architecture + assert isinstance(model, expected_model_cls) + + # FSE requested with only the routed experts online quantized: FSE is + # rightfully refused, as the shared expert (kept as stored) does not run with + # the routed experts' online keys. + if fse_requested and "*shared_expert*" not in targets: + assert any( + "VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS is enabled but " + "cannot be enabled" in warning + and "do not match the routed expert keys" in warning + for warning in _fse_warnings(caplog_vllm) + ), _fse_warnings(caplog_vllm) + return + + assert not any( + "VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS is enabled but " + "cannot be enabled" in warning + for warning in _fse_warnings(caplog_vllm) + ), _fse_warnings(caplog_vllm) + + moes = [ + module + for module in model.modules() + if hasattr(module, "is_fused_shared_expert_enabled") + and hasattr(module, "experts") + ] + assert len(moes) == 1 + moe = moes[0] + assert moe.is_fused_shared_expert_enabled == fse_requested, architecture + assert (moe.shared_experts is None) == fse_requested + + routed_experts = moe.experts.routed_experts + assert isinstance(routed_experts.quant_method, routed_method_cls) + # Without source, the routed experts are not requantized: the MXFP8 shared + # expert is staged, and quantized to MXFP4 into its slot after loading. + assert isinstance( + getattr(routed_experts.quant_method, "requantization_source", None), + source_cls or type(None), + ) + num_fused_shared_experts = 1 if fse_requested else 0 + assert ( + routed_experts.expert_map_manager.num_fused_shared_experts + == num_fused_shared_experts + ) + num_slots = routed_experts.moe_config.num_logical_experts + num_fused_shared_experts + assert routed_experts.w13_weight.shape[0] == num_slots + assert routed_experts.w2_weight.shape[0] == num_slots + if routed_method_cls is Mxfp8OnlineMoEMethod: + # MXFP8 scales are stored flattened as [num_slots * rows, K // 32]. + assert routed_experts.w13_weight_scale.shape[0] == ( + num_slots * routed_experts.w13_weight.shape[1] + ) + assert routed_experts.w2_weight_scale.shape[0] == ( + num_slots * routed_experts.w2_weight.shape[1] + ) else: - assert logged_messages == [ - "Quantizing 2 layers of types: " - f"mlp.{shared_expert_name}.down_proj: 1 " - f"(from targets: {target_pattern}, mxfp4); " - f"mlp.{shared_expert_name}.gate_up_proj: 1 " - f"(from targets: {target_pattern}, mxfp4)" + assert routed_experts.w13_weight_scale.shape[0] == num_slots + assert routed_experts.w2_weight_scale.shape[0] == num_slots + # Staging and source parameters are released after requantization. + for name in ( + "online_w13_weight", + "online_w2_weight", + "online_w13_weight_scale", + "online_w2_weight_scale", + "w13_weight_packed", + "w2_weight_packed", + "w13_weight_global_scale", + "w2_weight_global_scale", + ): + assert not hasattr(routed_experts, name), name + + routed_target = "*block_sparse_moe.experts*" + shared_target = "*shared_expert*" + quantized = [] + if routed_target in targets: + quantized += [ + f"block_sparse_moe.experts: 1 " + f"(from targets: {routed_target}, {targets[routed_target]})" ] + if shared_target in targets: + quantized += [ + f"block_sparse_moe.shared_experts.{projection}: 1 " + f"(from targets: {shared_target}, {targets[shared_target]})" + for projection in ("down_proj", "gate_up_proj") + ] + assert _online_quantization_logs(caplog_vllm) == [ + f"Quantizing {len(quantized)} layers of types: " + "; ".join(quantized) + ] + + if fse_requested: + # The staged shared experts were quantized into their slots once. + with pytest.raises(NotImplementedError, match="Reloading fused shared"): + routed_experts.weight_loader( + routed_experts.w2_weight, + torch.zeros(1), + f"{routed_experts.layer_name}.w2_weight", + "w2", + routed_experts.moe_config.num_logical_experts, + ) + if fse_requested and source_cls is None: + # Requantized routed experts parameters are replaced after processing, and + # are restored for reloads by the layerwise reload machinery only. + shared_prefix = routed_experts.moe_config.shared_expert_prefix + with pytest.raises(NotImplementedError, match="Reloading fused shared"): + model.load_weights( + [(f"{shared_prefix}.down_proj.weight", routed_experts.w2_weight[0])] + ) -def test_online_gate_up_proj_target_disables_fse( +def test_fse_online_quantization_bf16_routed_quantized_shared_raises( tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, - dist_init, + monkeypatch, + single_rank_parallel_state, workspace_init, ) -> None: - """A partial shared-expert target quantizes while disabling FSE.""" - architecture = "DeepseekForCausalLM" - target_pattern = "*shared_experts.gate_up_proj*" - monkeypatch.setenv("VLLM_ROCM_USE_AITER", "1") - monkeypatch.setenv("VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS", "1") - rocm_aiter_ops.refresh_env_variables() - _write_minimal_moe_config(tmp_path, architecture) + """Routed experts quantized online from BF16 can not take a staged shared + expert stored quantized (MXFP8).""" + architecture = "MiniMaxM3SparseForCausalLM" + _enable_aiter(monkeypatch, fse=True) + _write_minimal_moe_config( + tmp_path, architecture, _QUARK_BF16_ROUTED_MXFP8_SHARED_QUANT_CONFIG + ) + _use_checkpoint_quantization(monkeypatch) + with pytest.raises(NotImplementedError, match="quantized online from high"): + load_model_without_vllm_runner( + str(tmp_path), + dtype="bfloat16", + model_config_kwargs={ + "quantization_config": QuantizationConfigArgs( + targets=_ROUTED_SHARED_MXFP4 + ) + }, + model_loader_cls=DummyModelLoader, + ) - logged_messages: list[str] = [] - logged_warnings: list[str] = [] - def record_info(message: str, *args: object, **_kwargs: object) -> None: - if "Quantizing " in message and "of types" in message: - logged_messages.append(message % args) +def test_fse_online_quantization_routed_shared_loads_checkpoint_weights( + default_vllm_config, + single_rank_parallel_state, +) -> None: + """Routed NVFP4 and shared MXFP8 weights land in their MXFP4 expert slots. - def record_warning(message: str, *args: object, **_kwargs: object) -> None: - logged_warnings.append(message % args) + The weights are loaded through `MiniMaxM3Model.load_weights` with checkpoint names + (`w1/w2/w3`, `shared_experts.*`, `weight_scale_inv`), as the model loader does. + """ + from vllm.models.minimax_m3.amd.model import MiniMaxM3Model - monkeypatch.setattr( - "vllm.model_executor.model_loader.base_loader.logger.info", record_info + default_vllm_config.model_config = ModelConfig() + hidden_size = intermediate_size = 64 + num_routed_experts = 2 + shared_slot = num_routed_experts + device = current_platform.device_type + quant_config = ModelOptMxFp8Config( + is_checkpoint_mxfp8_serialized=True, + kv_cache_quant_algo=None, + exclude_modules=[], + moe_quant_algo="NVFP4", ) - monkeypatch.setattr( - "vllm.model_executor.layers.fused_moe.utils.logger.warning", record_warning + quant_config.online_quantization_config = OnlineQuantizationConfig( + QuantizationConfigArgs(targets=_FSE_ROUTED_SHARED_TARGETS) + ) + + def nvfp4_weight(rows: int, cols: int): + packed = torch.randint(0, 256, (rows, cols // 2), dtype=torch.uint8) + scale = (torch.rand(rows, cols // 16) * 4 + 0.5).to(torch.float8_e4m3fn) + global_scale = torch.rand(1, dtype=torch.float32) + 0.5 + return packed, scale, global_scale + + def dequantize_nvfp4(packed, scale, global_scale): + return dequantize_to_dtype( + packed[None], + scale[None], + (1.0 / global_scale).reshape(1), + torch.bfloat16, + block_size=16, + swizzle=False, + )[0] + + with torch.device(device): + runner = FusedMoEFactory( + num_experts=num_routed_experts, + top_k=1, + hidden_size=hidden_size, + intermediate_size=intermediate_size, + params_dtype=torch.bfloat16, + n_shared_experts=1, + fuse_shared_experts=True, + shared_expert_prefix="model.layers.0.block_sparse_moe.shared_experts", + prefix="model.layers.0.block_sparse_moe.experts", + quant_config=quant_config, + ) + layer = runner.routed_experts + assert isinstance(layer.quant_method, Mxfp4OnlineMoEMethod) + + shapes = { + "gate_proj": (intermediate_size, hidden_size), + "up_proj": (intermediate_size, hidden_size), + "down_proj": (hidden_size, intermediate_size), + } + routed = { + (expert, projection): nvfp4_weight(*shape) + for expert in range(num_routed_experts) + for projection, shape in shapes.items() + } + shared = { + projection: mxfp8_e4m3_quantize( + torch.randn(*shape, dtype=torch.bfloat16), + is_sf_swizzled_layout=False, + ) + for projection, shape in shapes.items() + } + + ckpt_names = {"gate_proj": "w1", "up_proj": "w3", "down_proj": "w2"} + weights = [] + for (expert, projection), (packed, scale, global_scale) in routed.items(): + prefix = f"block_sparse_moe.experts.{expert}.{ckpt_names[projection]}" + weights += [ + (f"{prefix}.weight_packed", packed), + (f"{prefix}.weight_scale", scale), + (f"{prefix}.weight_global_scale", global_scale), + (f"{prefix}.input_global_scale", torch.ones(1)), + ] + for projection, (weight, scale) in shared.items(): + prefix = f"block_sparse_moe.shared_experts.{projection}" + weights += [ + (f"{prefix}.weight", weight), + (f"{prefix}.weight_scale_inv", scale), + ] + + # Only the parts of `MiniMaxM3Model` that `load_weights` uses. + class ModelStub(torch.nn.Module): + get_expert_mapping = MiniMaxM3Model.get_expert_mapping + load_weights = MiniMaxM3Model.load_weights + + model = ModelStub() + model.config = SimpleNamespace( + num_local_experts=num_routed_experts, n_shared_experts=1 + ) + model.is_fused_shared_expert_enabled = True + model.block_sparse_moe = torch.nn.Module() + model.block_sparse_moe.experts = runner + model.load_weights(weights) + layer.quant_method.process_weights_after_loading(layer) + + def check_slot(slot: int, gate, up, down) -> None: + for rows, reference in ( + (slice(0, intermediate_size), gate), + (slice(intermediate_size, 2 * intermediate_size), up), + ): + expected, expected_scale = mxfp4_quantize(reference) + assert torch.equal(layer.w13_weight[slot, rows], expected) + assert torch.equal(layer.w13_weight_scale[slot, rows], expected_scale) + expected, expected_scale = mxfp4_quantize(down) + assert torch.equal(layer.w2_weight[slot], expected) + assert torch.equal(layer.w2_weight_scale[slot], expected_scale) + + for expert in range(num_routed_experts): + check_slot( + expert, + *(dequantize_nvfp4(*routed[expert, projection]) for projection in shapes), + ) + check_slot( + shared_slot, + *(dequant_mxfp8_to_bf16(*shared[projection]) for projection in shapes), ) + +def test_online_gate_up_proj_target_disables_fse( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog_vllm, + single_rank_parallel_state, + workspace_init, +) -> None: + """A partial shared-expert target quantizes while disabling FSE.""" + architecture = "DeepseekForCausalLM" + target_pattern = "*shared_experts.gate_up_proj*" + _enable_aiter(monkeypatch, fse=True) + _write_minimal_moe_config(tmp_path, architecture) + model, _ = load_model_without_vllm_runner( str(tmp_path), dtype="bfloat16", @@ -638,13 +1186,235 @@ def record_warning(message: str, *args: object, **_kwargs: object) -> None: ) assert not moe.is_fused_shared_expert_enabled assert moe.shared_experts is not None - assert logged_messages == [ + assert _online_quantization_logs(caplog_vllm) == [ "Quantizing 1 layers of types: " "mlp.shared_experts.gate_up_proj: 1 " f"(from targets: {target_pattern}, mxfp4)" ] - assert logged_warnings == [ + # The untargeted down_proj is unquantized: its keys do not match. + [warning] = _fse_warnings(caplog_vllm) + assert warning.startswith( "VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS is enabled but cannot be " - "enabled - skipping for this layer: online quantization targets only " - "part of the shared expert at model.layers.0.mlp.shared_experts." + "enabled - skipping for this layer: shared expert (weight, activation) keys " + ) + assert ( + "at model.layers.0.mlp.shared_experts do not match the routed expert keys" + in warning + ) + + +@pytest.mark.parametrize("num_shared", [0, 1, 2]) +@pytest.mark.parametrize("experts_per_chunk", [1, 3, 4]) +def test_online_moe_quantize_weights_places_routed_then_shared_experts( + num_shared: int, experts_per_chunk: int +): + """Chunked routed experts come first and the staged shared experts last.""" + import types + + from vllm.model_executor.layers.quantization.online.moe_base import ( + OnlineMoEMethodBase, + ) + + num_routed, w13_shape, w2_shape = 4, (6, 8), (8, 3) + num_experts = num_routed + num_shared + + def expert_values(shape: tuple[int, ...]) -> torch.Tensor: + # Every element of expert `e` is `e`, so the slot is recoverable. + values = torch.arange(num_experts, dtype=torch.float32) + return values.view(-1, 1, 1).expand(num_experts, *shape).contiguous() + + w13_all, w2_all = expert_values(w13_shape), expert_values(w2_shape) + + def dequantize_weight(layer): + for start in range(0, num_routed, experts_per_chunk): + experts = slice(start, min(start + experts_per_chunk, num_routed)) + yield experts, w13_all[experts], w2_all[experts] + + method = SimpleNamespace( + requantization_source=SimpleNamespace( + dequantize_weight=dequantize_weight, + ), + _pad_requantized_weights=lambda layer, w13, w2, n: (w13, w2), + ) + method.iter_weights_for_quantization = types.MethodType( + OnlineMoEMethodBase.iter_weights_for_quantization, method + ) + layer = SimpleNamespace( + local_num_experts=num_experts, + expert_map_manager=SimpleNamespace(num_fused_shared_experts=num_shared), + orig_dtype=torch.float32, + shared_expert_online_loader=SimpleNamespace( + dequantize_staging=lambda layer: ( + w13_all[num_routed:], + w2_all[num_routed:], + ), + release_staging=lambda layer: None, + ), + ) + + def quantize(w13, w2): + return w13 * 2, w13.mean(-1), w2 * 2, w2.mean(-1) + + w13_q, w13_scale, w2_q, w2_scale = OnlineMoEMethodBase.quantize_weights( + method, layer, quantize + ) + + assert torch.equal(w13_q, w13_all * 2) + assert torch.equal(w13_scale, w13_all.mean(-1)) + assert torch.equal(w2_q, w2_all * 2) + assert torch.equal(w2_scale, w2_all.mean(-1)) + + +if current_platform.is_rocm(): + from vllm.platforms.rocm import on_gfx950 + + ROCM_GFX950 = on_gfx950() +else: + ROCM_GFX950 = False + + +@pytest.mark.parametrize("requantize", [False, True], ids=["no_requant", "requant"]) +def test_nvfp4_moe_requantization_on_rocm( + requantize: bool, + tmp_path: Path, + default_vllm_config, + single_rank_parallel_state, + workspace_init, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """NVFP4 routed experts must be requantized online on ROCm. + + NVFP4 -> MXFP4 requantization with `--moe-backend aiter` skips the NVFP4 oracle: + `aiter` is not an NVFP4 backend. + """ + _enable_aiter(monkeypatch) + if not requantize: + _write_minimal_moe_config( + tmp_path, + "MiniMaxM3SparseForCausalLM", + _MINIMAX_NVFP4_ROUTED_MXFP8_SHARED_QUANT_CONFIG, + ) + _use_checkpoint_quantization(monkeypatch) + with pytest.raises( + NotImplementedError, + match="NVFP4 MoE experts .* is not supported on ROCm", + ): + load_model_without_vllm_runner( + str(tmp_path), + dtype="bfloat16", + model_loader_cls=DummyModelLoader, + ) + return + + if not ROCM_GFX950: + pytest.skip("AITER MXFP4 MoE requires gfx950") + default_vllm_config.model_config = ModelConfig() + default_vllm_config.kernel_config.moe_backend = "aiter" + + nvfp4_oracle_logger = Mock() + monkeypatch.setattr( + "vllm.model_executor.layers.fused_moe.oracle.nvfp4.logger", nvfp4_oracle_logger + ) + + hidden_size = intermediate_size = 256 + num_experts, top_k = 8, 2 + device = current_platform.device_type + quant_config = ModelOptMxFp8Config( + is_checkpoint_mxfp8_serialized=True, + kv_cache_quant_algo=None, + exclude_modules=[], + moe_quant_algo="NVFP4", + ) + quant_config.online_quantization_config = OnlineQuantizationConfig( + QuantizationConfigArgs(targets={"*block_sparse_moe.experts*": "mxfp4"}) + ) + + with torch.device(device): + runner = FusedMoEFactory( + num_experts=num_experts, + top_k=top_k, + hidden_size=hidden_size, + intermediate_size=intermediate_size, + params_dtype=torch.bfloat16, + router_logits_dtype=torch.float32, + prefix="model.layers.0.block_sparse_moe.experts", + quant_config=quant_config, + ) + layer = runner.routed_experts + assert layer.moe_config.moe_backend == "aiter" + + # The requantization target selected the AITER MXFP4 backend, and the NVFP4 + # oracle did not run for the checkpoint method: no log from it. + assert isinstance(layer.quant_method, Mxfp4OnlineMoEMethod) + assert "AITER" in layer.quant_method.mxfp4_backend.name + assert isinstance( + layer.quant_method.requantization_source, CompressedTensorsW4A4Nvfp4MoEMethod + ) + assert nvfp4_oracle_logger.mock_calls == [] + + +def test_nvfp4_oracle_only_skipped_for_requantized_layers( + default_vllm_config, + single_rank_parallel_state, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Only the targeted layer's NVFP4 checkpoint method skips backend selection.""" + _enable_aiter(monkeypatch) + default_vllm_config.model_config = ModelConfig() + quant_config = ModelOptMxFp8Config( + is_checkpoint_mxfp8_serialized=True, + kv_cache_quant_algo=None, + exclude_modules=[], + moe_quant_algo="NVFP4", + ) + quant_config.online_quantization_config = OnlineQuantizationConfig( + QuantizationConfigArgs( + targets={"*layers.0.block_sparse_moe.experts*": "mxfp4"} + ) + ) + + real_select = nvfp4_oracle.select_nvfp4_moe_backend + selected: list[tuple[str, NvFp4MoeBackend]] = [] + + def select(config, weight_key, activation_key): + skipped = is_requantization_source() + if skipped: + backend, experts_cls = real_select(config, weight_key, activation_key) + else: + # No native NVFP4 MoE backend on ROCm: pretend one was selected. + backend, experts_cls = NvFp4MoeBackend.VLLM_CUTLASS, Mock() + selected.append(("skipped" if skipped else "selected", backend)) + return backend, experts_cls + + monkeypatch.setattr( + "vllm.model_executor.layers.quantization.compressed_tensors." + "compressed_tensors_moe.compressed_tensors_moe_w4a4_nvfp4." + "select_nvfp4_moe_backend", + select, + ) + + layers = [] + with torch.device(current_platform.device_type): + for layer_idx in range(2): + runner = FusedMoEFactory( + num_experts=4, + top_k=1, + hidden_size=64, + intermediate_size=64, + params_dtype=torch.bfloat16, + prefix=f"model.layers.{layer_idx}.block_sparse_moe.experts", + quant_config=quant_config, + ) + layers.append(runner.routed_experts) + + assert selected == [ + ("skipped", NvFp4MoeBackend.EMULATION), + ("selected", NvFp4MoeBackend.VLLM_CUTLASS), ] + assert isinstance(layers[0].quant_method, Mxfp4OnlineMoEMethod) + assert isinstance( + layers[0].quant_method.requantization_source, + CompressedTensorsW4A4Nvfp4MoEMethod, + ) + assert isinstance(layers[1].quant_method, CompressedTensorsW4A4Nvfp4MoEMethod) + assert not is_requantization_source() diff --git a/tests/v1/attention/test_attention_backends.py b/tests/v1/attention/test_attention_backends.py index 0f911594931b..bac201fe1593 100644 --- a/tests/v1/attention/test_attention_backends.py +++ b/tests/v1/attention/test_attention_backends.py @@ -864,6 +864,79 @@ def causal_mask_mod( ) +@pytest.mark.skipif( + not current_platform.is_device_capability_family(100), + reason="FA4 takes FP8 Q/K/V with descales on Blackwell.", +) +def test_flash_attn_fa4_unit_fp8_descale_is_exact(default_vllm_config): + """FlashAttentionImpl passes FA4 no descale for a per-tensor scale of 1.0, + which FA4 reads as exactly 1.0; calibrated scales keep their descale.""" + from vllm.v1.attention.backends.fa_utils import ( + flash_attn_varlen_func, + is_fa_version_supported, + ) + from vllm.v1.attention.backends.flash_attn import FlashAttentionImpl + + if not is_fa_version_supported(4): + pytest.skip("FA4 is not supported.") + set_random_seed(0) + device = torch.device(f"{DEVICE_TYPE}:0") + fp8 = current_platform.fp8_dtype() + seq_lens, q_len = [1328, 523, 2011], 3 + num_heads, num_kv_heads, head_size = 64, 4, 128 + impl = FlashAttentionImpl( + num_heads=num_heads, + head_size=head_size, + scale=head_size**-0.5, + num_kv_heads=num_kv_heads, + alibi_slopes=None, + sliding_window=None, + kv_cache_dtype="fp8", + ) + assert impl.vllm_flash_attn_version == 4 + + q = torch.randn(len(seq_lens) * q_len, num_heads, head_size, device=device) + k_cache, v_cache = ( + torch.randn(64, 128, num_kv_heads, head_size, device=device).to(fp8) + for _ in range(2) + ) + block_table = torch.randperm(64, dtype=torch.int32, device=device)[:48] + + def run(descale: torch.Tensor | None) -> torch.Tensor: + return flash_attn_varlen_func( + q=q.to(fp8), + k=k_cache, + v=v_cache, + cu_seqlens_q=torch.arange( + 0, q.shape[0] + 1, q_len, dtype=torch.int32, device=device + ), + seqused_k=torch.tensor(seq_lens, dtype=torch.int32, device=device), + max_seqlen_q=q_len, + max_seqlen_k=max(seq_lens), + softmax_scale=head_size**-0.5, + causal=True, + block_table=block_table.view(len(seq_lens), -1), + fa_version=4, + q_descale=descale, + k_descale=descale, + v_descale=descale, + ) + + shape = (len(seq_lens), num_kv_heads) + unit = torch.ones(1, device=device) + assert impl._descale(unit, 1.0, shape) is None + expanded = unit.expand(shape) # What FA4 got for a unit scale before. + output = run(impl._descale(unit, 1.0, shape)) + torch.testing.assert_close(output, run(expanded), atol=0, rtol=0) + # Descales are applied when given, so the comparison above is not vacuous. + assert not torch.equal(output, run(2 * expanded)) + # Calibrated and per-head scales (whose float holds the max) keep theirs. + calibrated = impl._descale(0.5 * unit, 0.5, shape) + assert calibrated is not None and torch.equal(calibrated, 0.5 * expanded) + per_head = torch.tensor([1.0, 0.5, 1.0, 0.25], device=device) + assert impl._descale(per_head, 1.0, shape) is not None + + @pytest.mark.skipif( AttentionBackendEnum.FLASHINFER not in BACKENDS_TO_TEST, reason="FlashInfer is not available.", diff --git a/tests/v1/attention/test_flashinfer_ts.py b/tests/v1/attention/test_flashinfer_ts.py new file mode 100644 index 000000000000..a0249456f887 --- /dev/null +++ b/tests/v1/attention/test_flashinfer_ts.py @@ -0,0 +1,227 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""FLASHINFER_TS: the non-causal draft-block decode path. + +Covers the two things that are easy to get wrong and silently produce plausible +output: the K/V plane layout the kernel validates, and the page-aligned window +restriction that stands in for a window the kernel cannot take with a dense +mask. +""" + +import pytest +import torch + +from vllm.platforms import current_platform +from vllm.v1.attention.backend import AttentionType +from vllm.v1.attention.backends.flashinfer_ts import ( + FlashInferTSMetadataBuilder, +) + +HEAD_DIM = 128 +PAGE = 128 +WINDOW = 4096 + + +def _sm100_family() -> bool: + cap = current_platform.get_device_capability() + return cap is not None and (cap.major, cap.minor) in ((10, 0), (10, 3), (10, 7)) + + +requires_kernel = pytest.mark.skipif( + not current_platform.is_cuda() or not _sm100_family(), + reason="prims_ts decode runs on SM100a/SM103a/SM107a only", +) + + +@pytest.mark.parametrize("num_kv_heads", [1, 4]) +def test_reads_vllms_existing_interleaved_page(num_kv_heads): + """No layout change: K/V are the halves of vLLM's [pages, Hkv, page, 2*D] + page, whose token stride is 2*D. The kernel takes its TMA strides from the + tensor, so this must stay a pure view with head_dim contiguous. + """ + page = torch.zeros(8, num_kv_heads, PAGE, 2 * HEAD_DIM, dtype=torch.uint8) + k, v = page[..., :HEAD_DIM], page[..., HEAD_DIM:] + + assert k.shape == (8, num_kv_heads, PAGE, HEAD_DIM) + assert k.stride(-1) == 1 and v.stride(-1) == 1 # the one hard requirement + assert k.stride(2) == 2 * HEAD_DIM # interleaved, not compact + assert k.data_ptr() == page.data_ptr() # views, never a repack + assert v.data_ptr() == page.data_ptr() + HEAD_DIM + + +@pytest.mark.parametrize("query_len", [1, 3, 7]) +def test_window_restriction_is_a_superset_of_the_true_window(query_len): + """The restricted page table must never drop a token the symmetric window + can reach, and must overshoot by less than one page. + """ + builder = FlashInferTSMetadataBuilder.__new__(FlashInferTSMetadataBuilder) + builder.sliding_window = WINDOW + builder.page_size = PAGE + builder.query_len = query_len + # The builder writes metadata into persistent buffers so a replayed CUDA + # graph keeps reading the same addresses; the window math is exercised + # through them, not around them. + pages = builder._window_pages(query_len) + builder._buf_seq_lens = torch.zeros(6, dtype=torch.int32) + builder._buf_block_table = torch.zeros((6, pages), dtype=torch.int32) + + seq_lens = torch.tensor( + [1, PAGE, WINDOW - 1, WINDOW + query_len, 8192, 120_000], dtype=torch.int32 + ) + block_table = torch.arange( + seq_lens.numel() * (int(seq_lens.max()) // PAGE + 1), dtype=torch.int32 + ).view(seq_lens.numel(), -1) + + new_lens, new_bt = FlashInferTSMetadataBuilder._restrict_to_window( + builder, seq_lens, block_table, query_len + ) + + span = WINDOW + query_len - 1 + reachable = torch.minimum(seq_lens, torch.full_like(seq_lens, span)) + assert torch.all(new_lens >= reachable), "window restriction dropped live tokens" + assert int((new_lens - reachable).max()) < PAGE, "overshoot exceeds one page" + # The kept pages must be the tail of each row, so the last token of the + # sequence is still addressable. + last_page = (seq_lens.long() - 1) // PAGE + assert torch.all(new_bt.long().max(dim=1).values >= last_page) + + +def test_impl_accepts_the_arguments_the_attention_layer_passes(): + """Attention() calls impl_cls positionally and forwards extra_impl_args + (``sinks`` among them); a signature that only matches AttentionImpl's + abstract __init__ raises TypeError at engine init, not at import. + """ + from vllm.v1.attention.backends.flashinfer_ts import FlashInferTSImpl + + impl = FlashInferTSImpl( + 16, + HEAD_DIM, + HEAD_DIM**-0.5, + 1, + None, + WINDOW, + "fp8", + None, + AttentionType.DECODER, + None, + sinks=None, + ) + # FP8 KV reads an FP8 query; the layer's own quant is skipped via + # query_pre_quantized because the fused QK-norm/RoPE kernel emits it. + assert impl.supports_quant_query_input + + with pytest.raises(NotImplementedError): + FlashInferTSImpl( + 16, + HEAD_DIM, + HEAD_DIM**-0.5, + 1, + None, + WINDOW, + "fp8", + None, + AttentionType.DECODER, + None, + sinks=torch.zeros(16), + ) + + +@requires_kernel +def test_dense_plan_matches_flash_attention_non_causal(): + """A dense prims_ts plan is the non-causal draft block FA4 produces.""" + pytest.importorskip("flashinfer.attention.prims_ts") + from flashinfer.attention.prims_ts import BatchDecodePagedTSWrapper + + from vllm.vllm_flash_attn.cute.interface import _flash_attn_fwd + + torch.manual_seed(0) + b, sq, hq, hkv, kv = 2, 3, 16, 1, PAGE + dev = torch.device("cuda") + scale = HEAD_DIM**-0.5 + pages = b * (kv // PAGE) + 1 + + page = torch.randn(pages, 2 * hkv, PAGE, HEAD_DIM, dtype=torch.bfloat16, device=dev) + k_plane, v_plane = page[:, :hkv].contiguous(), page[:, hkv:].contiguous() + interleaved = torch.cat([k_plane, v_plane], dim=-1).contiguous() + k_fa, v_fa = interleaved.transpose(1, 2).split(HEAD_DIM, dim=-1) + + q = torch.randn(b * sq, hq, HEAD_DIM, dtype=torch.bfloat16, device=dev) + bt = torch.arange(1, pages, dtype=torch.int32, device=dev).view(b, -1).contiguous() + lens = torch.full((b,), kv, dtype=torch.int32, device=dev) + cu_q = torch.arange(0, (b + 1) * sq, sq, dtype=torch.int32, device=dev) + + ref = torch.empty(b * sq, hq, HEAD_DIM, dtype=torch.bfloat16, device=dev) + _flash_attn_fwd( + q, + k_fa, + v_fa, + cu_seqlens_q=cu_q, + seqused_k=lens, + max_seqlen_q=sq, + max_seqlen_k=kv, + page_table=bt, + softmax_scale=scale, + causal=False, + window_size_left=WINDOW - 1, + window_size_right=WINDOW - 1, + num_splits=0, + out=ref, + ) + + wrapper = BatchDecodePagedTSWrapper(kv_layout="HND") + wrapper.plan( + device=dev, + batch_size=b, + num_qo_heads=hq, + num_kv_heads=hkv, + head_dim=HEAD_DIM, + page_size=PAGE, + max_kv_len=kv, + max_seq_len_q=sq, + packed_query=False, + q_data_type=torch.bfloat16, + kv_data_type=torch.bfloat16, + o_data_type=torch.bfloat16, + mask_type="dense", + window_left=-1, + ) + out = torch.empty(b, sq, hq, HEAD_DIM, dtype=torch.bfloat16, device=dev) + wrapper.run( + q=q.view(b, sq, hq, HEAD_DIM), + paged_kv_cache=(k_plane, v_plane), + seq_lens=lens, + block_tables=bt, + bmm1_scale=scale, + bmm2_scale=1.0, + out=out, + ) + + # One page of KV reduces in the same order in both kernels. + torch.testing.assert_close(out.reshape(b * sq, hq, HEAD_DIM), ref, rtol=0, atol=0) + + +def test_metadata_tensors_keep_their_addresses_across_builds(): + """A captured CUDA graph replays the ADDRESS of seq_lens and the page table. + + Returning freshly allocated tensors per step leaves a replayed graph reading + memory the allocator has since handed to someone else, which shows up as an + engine that pins every GPU and never retires a step. + """ + builder = FlashInferTSMetadataBuilder.__new__(FlashInferTSMetadataBuilder) + builder.sliding_window = WINDOW + builder.page_size = PAGE + builder.query_len = 4 + pages = builder._window_pages(4) + builder._buf_seq_lens = torch.zeros(4, dtype=torch.int32) + builder._buf_block_table = torch.zeros((4, pages), dtype=torch.int32) + + block_table = torch.arange(4 * 1024, dtype=torch.int32).view(4, -1) + ptrs = set() + for step in range(3): + seq_lens = torch.tensor([512, 8192, 40_000 + step, 120_000], dtype=torch.int32) + lens, table = FlashInferTSMetadataBuilder._restrict_to_window( + builder, seq_lens, block_table, 4 + ) + ptrs.add((lens.data_ptr(), table.data_ptr(), tuple(table.shape))) + + assert len(ptrs) == 1, f"metadata moved between builds: {ptrs}" diff --git a/tests/v1/core/test_kv_cache_utils.py b/tests/v1/core/test_kv_cache_utils.py index 917ed57c0ae7..fda2c164e46a 100644 --- a/tests/v1/core/test_kv_cache_utils.py +++ b/tests/v1/core/test_kv_cache_utils.py @@ -1411,6 +1411,21 @@ def test_draft_layer_tag_is_not_part_of_the_cache_format(target): assert type(target).merge([target, draft]) == target +@pytest.mark.parametrize( + "spec", + [ + new_kv_cache_spec(), + SinkFullAttentionSpec( + block_size=16, num_kv_heads=1, head_size=64, dtype=torch.float32, sink_len=4 + ), + ], +) +def test_attention_merge_preserves_kv_head_major_slots(spec): + # NIXL re-shards NVFP4 pages by KV head only if the group spec keeps the flag. + spec = replace(spec, num_head_slots=2 * spec.num_kv_heads, kv_head_major_slots=True) + assert type(spec).merge([spec, spec]).kv_head_major_slots + + @pytest.mark.parametrize( "layer_type,dcp_size,expected_width", [ diff --git a/tests/v1/kv_connector/unit/test_nixl_connector.py b/tests/v1/kv_connector/unit/test_nixl_connector.py index 2889a8bf36b8..e5566ec8602c 100644 --- a/tests/v1/kv_connector/unit/test_nixl_connector.py +++ b/tests/v1/kv_connector/unit/test_nixl_connector.py @@ -1788,14 +1788,24 @@ def test_handshake_rejects_wrong_block_len_without_gqa_replication( worker.add_remote_agent(bad_meta, remote_tp_size=2) @pytest.mark.parametrize( - ("kv_quant_mode", "local_tp", "remote_tp", "num_kv_heads", "rejected"), + ( + "kv_quant_mode", + "local_tp", + "remote_tp", + "num_kv_heads", + "kv_head_major_slots", + "rejected", + ), [ - (KVQuantMode.NVFP4, 2, 1, 8, True), - (KVQuantMode.NVFP4, 1, 2, 8, True), - (KVQuantMode.NVFP4, 2, 2, 8, False), + (KVQuantMode.NVFP4, 2, 1, 8, False, True), + (KVQuantMode.NVFP4, 1, 2, 8, False, True), + (KVQuantMode.NVFP4, 2, 2, 8, False, False), # Both sides hold one replicated head per rank: no head split. - (KVQuantMode.NVFP4, 16, 8, 8, False), - (KVQuantMode.NONE, 2, 1, 8, False), + (KVQuantMode.NVFP4, 16, 8, 8, False, False), + (KVQuantMode.NONE, 2, 1, 8, False, False), + # H2ND pages: each head's K and V slots are one contiguous run. + (KVQuantMode.NVFP4, 4, 1, 4, True, False), + (KVQuantMode.NVFP4, 1, 4, 4, True, False), ], ) @patch( @@ -1810,10 +1820,12 @@ def test_handshake_rejects_nvfp4_kv_head_split( local_tp, remote_tp, num_kv_heads, + kv_head_major_slots, rejected, ): """NVFP4 pages keep all heads' data before all heads' scales, so - heterogeneous-TP head splitting would silently corrupt the KV. + heterogeneous-TP head splitting would silently corrupt the KV unless the + spec lays out the page by KV head. """ block_size = maybe_update_block_size(16) vllm_config = create_vllm_config(block_size=block_size) @@ -1829,6 +1841,7 @@ def test_handshake_rejects_nvfp4_kv_head_split( head_size=16, dtype=torch.uint8, kv_quant_mode=kv_quant_mode, + kv_head_major_slots=kv_head_major_slots, ), ) ], @@ -1855,6 +1868,11 @@ def test_handshake_rejects_nvfp4_kv_head_split( worker.block_len_per_layer = [local_len] worker.num_blocks = 1 worker.dst_num_blocks[worker.engine_id] = worker.num_blocks + worker.src_blocks_data = np.array( + [(0, local_len, worker.tp_rank, local_len, worker.num_blocks)], + dtype=np.uint64, + ) + worker.num_descs = worker.num_blocks meta = NixlAgentMetadata( engine_id=FakeNixlConnectorWorker.REMOTE_ENGINE_ID, agent_metadata=FakeNixlWrapper.AGENT_METADATA, diff --git a/tests/v1/kv_connector/unit/test_nixl_desc_geometry.py b/tests/v1/kv_connector/unit/test_nixl_desc_geometry.py index 384f5d76739b..eaebc44f1a24 100644 --- a/tests/v1/kv_connector/unit/test_nixl_desc_geometry.py +++ b/tests/v1/kv_connector/unit/test_nixl_desc_geometry.py @@ -33,6 +33,7 @@ NixlPushConnectorWorker, ) from vllm.v1.kv_cache_interface import ( + FullAttentionSpec, KVCacheConfig, KVCacheGroupSpec, KVCacheLayout, @@ -132,18 +133,30 @@ def _make_packed_mla_view_worker( pp_size=1, backend_names=("FLASHMLA",), worker_cls=NixlPushConnectorWorker, + gqa_layers=(), ): - """Register real strided views; only NIXL and distributed runtime are fake.""" + """Register real strided views; only NIXL and distributed runtime are fake. + + Layers named in `gqa_layers` get a K/V spec and make the model non-MLA. + """ block_size = 16 raw = torch.zeros(num_blocks * block_stride, dtype=torch.int8) tensors, groups, caches = [], [], {} for name, (offset, page_size) in layouts.items(): - spec = MLAAttentionSpec( - block_size=block_size, - num_kv_heads=1, - head_size=page_size // block_size, - dtype=torch.uint8, - ) + if name in gqa_layers: + spec = FullAttentionSpec( + block_size=block_size, + num_kv_heads=1, + head_size=page_size // block_size // 2, + dtype=torch.uint8, + ) + else: + spec = MLAAttentionSpec( + block_size=block_size, + num_kv_heads=1, + head_size=page_size // block_size, + dtype=torch.uint8, + ) tensor = KVCacheTensor( size=raw.nbytes, layers=[name], @@ -180,7 +193,7 @@ def _make_packed_mla_view_worker( "producer" if pp_size > 1 else "consumer", KVCacheConfig(num_blocks, tensors, groups), ) - worker.use_mla = True + worker.use_mla = not gqa_layers worker.register_kv_caches(caches) return worker, raw @@ -208,6 +221,46 @@ def test_packed_mla_pp1_transfers_whole_rows(num_layers, worker_cls): assert metadata.packed_member_layouts == layouts +# MiniMax-M3-like row: each layer's K/V page (head-sharded) and indexer page. +_GQA_ROW = { + "L0.kv": (0, 128), + "L0.ix": (128, 64), + "L1.kv": (192, 128), + "L1.ix": (320, 64), +} + + +@pytest.mark.cpu_test +@pytest.mark.parametrize( + "worker_cls", [NixlPullConnectorWorker, NixlPushConnectorWorker] +) +def test_packed_gqa_pp1_transfers_whole_rows(worker_cls): + # Head-sharded pages still travel as whole rows when P and D shard alike. + worker, raw = _make_packed_mla_view_worker( + _GQA_ROW, 384, worker_cls=worker_cls, gqa_layers=("L0.kv", "L1.kv") + ) + assert not worker.use_mla + assert worker.num_regions == 1 + assert worker.src_blocks_data.tolist() == [[raw.data_ptr(), 384, 0, 384, 4]] + metadata = msgspec.msgpack.decode( + worker.xfer_handshake_metadata.agent_metadata_bytes, type=NixlAgentMetadata + ) + assert metadata.packed_member_layouts == _GQA_ROW + + +@pytest.mark.cpu_test +def test_packed_gqa_rows_reject_heterogeneous_tp(): + gqa = ("L0.kv", "L1.kv") + producer, _ = _make_packed_mla_view_worker(_GQA_ROW, 384, gqa_layers=gqa) + consumer, _ = _make_packed_mla_view_worker(_GQA_ROW, 384, gqa_layers=gqa) + metadata = msgspec.msgpack.decode( + producer.xfer_handshake_metadata.agent_metadata_bytes, type=NixlAgentMetadata + ) + metadata.engine_id = "remote" + with pytest.raises(RuntimeError, match="need the same TP"): + consumer.add_remote_agent(metadata, remote_tp_size=2) + + @pytest.mark.cpu_test def test_per_layer_peer_addresses_pages_inside_packed_rows(): # E.g. a HiSparse decoder reading a BLHNC prefiller's whole-row region. diff --git a/tests/v1/sample/test_topk_topp_sampler.py b/tests/v1/sample/test_topk_topp_sampler.py index 924f0703d3e5..262ebc553ff8 100644 --- a/tests/v1/sample/test_topk_topp_sampler.py +++ b/tests/v1/sample/test_topk_topp_sampler.py @@ -395,6 +395,27 @@ def test_extreme_p_values(self): p = torch.tensor([0.1, 0.5, 0.9, 1.0] * 4, dtype=torch.float32) self._compare_results(logits.clone(), k=None, p=p) + @pytest.mark.parametrize("k_val", [None, 50]) + def test_tiny_p_keeps_max_token(self, k_val: int | None): + """Above 64 rows, a top-p below the fp32 resolution of the kept mass + must still keep a max token instead of masking the whole row.""" + from vllm.v1.sample.ops.topk_topp_triton import apply_top_k_top_p_triton + + batch_size = 156 + logits = ( + 3.0 + * torch.randn( + batch_size, 32000, generator=self.generator, dtype=torch.float32 + ) + ).bfloat16() + logits[1::4, :2] = logits[1::4].amax(dim=-1, keepdim=True) # tied max + logits = logits.float() + is_max = logits == logits.amax(dim=-1, keepdim=True) + k = None if k_val is None else torch.full((batch_size,), k_val) + p = torch.full((batch_size,), 1e-9, dtype=torch.float32) + kept = apply_top_k_top_p_triton(logits.clone(), k, p) != float("-inf") + assert (kept & is_max).any(dim=-1).all() + def test_large_batch(self): """Test with a large batch size.""" batch_size, vocab_size = 512, 32000 diff --git a/tests/v1/simple_kv_offload/test_host_buffer.py b/tests/v1/simple_kv_offload/test_host_buffer.py new file mode 100644 index 000000000000..48161dabf33a --- /dev/null +++ b/tests/v1/simple_kv_offload/test_host_buffer.py @@ -0,0 +1,87 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""HostBuffer for SimpleCPUOffloadConnector (CPU only, Linux).""" + +import mmap +import sys + +import pytest + +from vllm.v1.simple_kv_offload.host_buffer import HostBuffer, parse_hugepage_size + +pytestmark = pytest.mark.skipif(sys.platform != "linux", reason="Linux mm APIs") + + +def free_hugepages(page: int) -> int: + path = f"/sys/kernel/mm/hugepages/hugepages-{page >> 10}kB/free_hugepages" + try: + with open(path) as f: + return int(f.read()) + except OSError: + return -1 + + +def hugepage_with_free(n: int) -> int: + for page in (2 << 20, 1 << 30): + if free_hugepages(page) >= n: + return page + pytest.skip(f"needs {n} free hugepages of some size") + raise AssertionError("unreachable") + + +def mapping_info(addr: int) -> tuple[set[str], str]: + """(smaps VmFlags, numa_maps policy) of the mapping starting at ``addr``.""" + flags: set[str] = set() + with open("/proc/self/smaps") as f: + inside = False + for line in f: + head = line.split()[0] + if "-" in head and not head.endswith(":"): + inside = int(head.split("-")[0], 16) == addr + elif inside and line.startswith("VmFlags:"): + flags = set(line.split()[1:]) + break + with open("/proc/self/numa_maps") as f: + policy = next(ln.split()[1] for ln in f if int(ln.split()[0], 16) == addr) + return flags, policy + + +@pytest.mark.parametrize( + "value,expected", + [ + (None, None), + ("none", None), + ("2MB", 2 << 20), + ("1GiB", 1 << 30), + ("1g", 1 << 30), + ], +) +def test_parse_hugepage_size(value, expected): + assert parse_hugepage_size(value) == expected + + +def test_parse_hugepage_size_rejects_unknown(): + with pytest.raises(ValueError, match="cpu_hugepage_block_size"): + parse_hugepage_size("4KB") + + +@pytest.mark.parametrize("hugepages", [False, True]) +def test_buffer_rounds_up_populates_and_skips_fork(hugepages: bool): + page = hugepage_with_free(2) if hugepages else mmap.PAGESIZE + buf = HostBuffer(page + 1, page if hugepages else None, numa_node=0) + assert buf.nbytes == 2 * page + assert buf.tensor.data_ptr() % page == 0 + assert int(buf.tensor[::4096].abs().sum()) == 0 # kernel-zeroed + flags, policy = mapping_info(buf.tensor.data_ptr()) + assert "dc" in flags # MADV_DONTFORK sets VM_DONTCOPY + assert ("ht" in flags) == hugepages + assert policy == "prefer:0" + + +def test_hugepage_buffer_fails_closed_when_pool_is_short(): + page = 1 << 30 + free = free_hugepages(page) + if free < 0: + pytest.skip("no 1 GiB hugepage pool") + with pytest.raises(RuntimeError, match="Cannot map"): + HostBuffer((free + 1) * page, page) diff --git a/tests/v1/spec_decode/test_dflash2.py b/tests/v1/spec_decode/test_dflash2.py index aba910901d08..37bfb852cd59 100644 --- a/tests/v1/spec_decode/test_dflash2.py +++ b/tests/v1/spec_decode/test_dflash2.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project -from types import SimpleNamespace +from types import MethodType, SimpleNamespace import pytest import torch @@ -762,6 +762,12 @@ def forward(self, hidden_states): hidden_norm=SimpleNamespace(weight=nn.Parameter(torch.ones(2))), _rms_norm_eps=1e-6, ) + model._normalize_context_states = MethodType( + qwen3_dflash.DFlashQwen3Model._normalize_context_states, model + ) + model._project_context_kv_token_major = MethodType( + qwen3_dflash.DFlashQwen3Model._project_context_kv_token_major, model + ) layers_attn = [ SimpleNamespace( qkv_proj=projection, diff --git a/tests/v1/spec_decode/test_draft_attention_backend_override.py b/tests/v1/spec_decode/test_draft_attention_backend_override.py index 26bcd68fea8f..33ec7f7b551c 100644 --- a/tests/v1/spec_decode/test_draft_attention_backend_override.py +++ b/tests/v1/spec_decode/test_draft_attention_backend_override.py @@ -12,13 +12,15 @@ import pytest -from vllm.config import LoadConfig, SpeculativeConfig +from vllm.config import CacheConfig, LoadConfig, SpeculativeConfig +from vllm.v1.worker.gpu.spec_decode.dflash.speculator import DFlashSpeculator from vllm.v1.worker.gpu.spec_decode.eagle.utils import load_eagle_model @dataclass class _AttentionConfig: backend: str | None = None + use_non_causal: bool = False @dataclass @@ -98,3 +100,32 @@ def test_override_does_not_mutate_the_target_config(): cfg = _config("FLASHINFER", "TRITON_ATTN") _capture_draft_config(cfg) assert cfg.attention_config.backend == "FLASHINFER" + + +def test_draft_attn_builders_get_overrides_and_keep_resolved_cache_state(): + """The draft's metadata builders read the same kernel overrides as its + layers, without losing state the engine core resolved on the target, e.g. + an fp8 draft next to an NVFP4 target with a resolved KV cache layout.""" + cache_config = CacheConfig(cache_dtype="nvfp4") + cache_config.kv_cache_layout = "HND" + cfg = _VllmConfig( + attention_config=_AttentionConfig(backend="FLASHINFER"), + kernel_config=_KernelConfig(), + cache_config=cache_config, + speculative_config=_SpeculativeConfig( + attention_backend="TRITON_ATTN", kv_cache_dtype="fp8" + ), + ) + speculator = object.__new__(DFlashSpeculator) + speculator.vllm_config = cfg + speculator.speculative_config = cfg.speculative_config + speculator.requires_non_causal = True + + used = speculator.attn_vllm_config + + assert used.attention_config.backend == "TRITON_ATTN" + assert used.attention_config.use_non_causal + assert used.cache_config.cache_dtype == "fp8" + assert used.cache_config.kv_cache_layout == "HND" + assert cfg.attention_config.backend == "FLASHINFER" + assert cfg.cache_config.cache_dtype == "nvfp4" diff --git a/tests/v1/spec_decode/test_dspark_sharded_sampling.py b/tests/v1/spec_decode/test_dspark_sharded_sampling.py new file mode 100644 index 000000000000..eeedba9599cf --- /dev/null +++ b/tests/v1/spec_decode/test_dspark_sharded_sampling.py @@ -0,0 +1,408 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Batch-sharded DSpark draft sampling must reproduce the replicated path bit +for bit: the same draft ids on every rank and, on each request's owner rank, +the same cached draft-logits rows the rejection sampler reads next step. + +Every TP rank is simulated in-process: each rank stages its vocab shard, the +all-to-all and the draft-id all-gather are emulated from the staged buffers. +The LM-head, Markov embedding and Markov bias run the real layers (and the +platform's GEMM dispatch). +""" + +from types import SimpleNamespace +from unittest import mock + +import numpy as np +import pytest +import torch +from torch import nn + +from vllm.model_executor.layers.logits_processor import LogitsProcessor +from vllm.model_executor.layers.vocab_parallel_embedding import ( + UnquantizedEmbeddingMethod, +) +from vllm.model_executor.models.qwen3_dspark import ( + DSparkMarkovHead, + Qwen3DSparkForCausalLM, +) +from vllm.utils.math_utils import cdiv +from vllm.v1.worker.gpu.sample import batch_shard +from vllm.v1.worker.gpu.spec_decode.dspark import speculator as dspark_speculator +from vllm.v1.worker.gpu.spec_decode.dspark.speculator import DSparkSpeculator + +DEVICE = "cuda" +TP_SIZE = 4 +HIDDEN = 128 +# M3.1's rank: the Markov GEMM's rows then depend on its row count, so a GEMM +# over only the owned rows fails these tests. +MARKOV_RANK = 256 +NUM_STEPS = 3 +MAX_NUM_REQS = 64 +SHARD_WIDTH = 2048 +# The draft vocab is smaller than TP_SIZE * SHARD_WIDTH: the last shard ends +# in vocab padding, as with a padded LM head. +DRAFT_VOCAB = 8000 +DTYPE = torch.bfloat16 + +pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs GPU") + + +class _LMHeadShard(nn.Module): + def __init__(self, weight: torch.Tensor): + super().__init__() + self.weight = nn.Parameter(weight, requires_grad=False) + self.quant_method = UnquantizedEmbeddingMethod() + self.tp_size = TP_SIZE + self.num_embeddings_per_partition = weight.shape[0] + + +class _DraftModel(nn.Module): + """One rank's view of a vocab-parallel Qwen3 DSpark draft head.""" + + compute_draft_logits_local = Qwen3DSparkForCausalLM.compute_draft_logits_local + markov_embed = Qwen3DSparkForCausalLM.markov_embed + markov_bias = Qwen3DSparkForCausalLM.markov_bias + map_draft_to_target = Qwen3DSparkForCausalLM.map_draft_to_target + + def __init__(self, shards, rank, markov_head, d2t): + super().__init__() + self.shards = shards + self.lm_head = shards[rank] + self.model = SimpleNamespace(markov_head=markov_head) + self.logits_processor = LogitsProcessor(DRAFT_VOCAB) + self.draft_id_to_target_id = d2t + + def compute_draft_logits(self, hidden_states: torch.Tensor) -> torch.Tensor: + # The replicated path: every shard (each rank's GEMM), all-gathered + # along the vocab, then the vocab padding dropped. + shards = [ + self.logits_processor(shard, hidden_states, skip_gather=True) + for shard in self.shards + ] + return torch.cat(shards, dim=-1)[..., :DRAFT_VOCAB] + + +def _make_weights(reduced_vocab: bool): + g = torch.Generator(device=DEVICE).manual_seed(0) + lm_head = torch.randn( + TP_SIZE * SHARD_WIDTH, HIDDEN, generator=g, device=DEVICE, dtype=DTYPE + ) + shards = [_LMHeadShard(w) for w in lm_head.split(SHARD_WIDTH)] + target_vocab = DRAFT_VOCAB + 500 if reduced_vocab else DRAFT_VOCAB + markov_head = DSparkMarkovHead( + target_vocab, DRAFT_VOCAB, MARKOV_RANK, prefix="markov_head" + ).to(device=DEVICE, dtype=DTYPE) + with torch.no_grad(): + markov_head.markov_w1.weight.normal_(generator=g) + markov_head.markov_w2.weight.normal_(generator=g) + d2t = None + if reduced_vocab: + # Draft id i maps to target id i + d2t[i] (sorted, unique targets). + target_ids = torch.randperm(target_vocab, generator=g, device=DEVICE) + target_ids = target_ids[:DRAFT_VOCAB].sort().values + d2t = target_ids - torch.arange(DRAFT_VOCAB, device=DEVICE) + return shards, markov_head, d2t, target_vocab + + +def _make_speculator( + shards, markov_head, d2t, target_vocab, rank, probabilistic, inputs +) -> DSparkSpeculator: + spec = DSparkSpeculator.__new__(DSparkSpeculator) + spec.model = _DraftModel(shards, rank, markov_head, d2t) + spec.num_speculative_steps = NUM_STEPS + spec.max_num_reqs = MAX_NUM_REQS + spec.device = torch.device(DEVICE) + spec.dtype = DTYPE + spec.use_fp64_gumbel = False + spec.draft_watermarker = None + spec.acceptance_estimator = None + spec.use_confidence_head = False + spec._draft_topk = None + spec._draft_sharder = None + spec.draft_logits_num_shards = 1 + spec.draft_logits_shard_idx = 0 + spec.draft_logits = ( + torch.zeros(MAX_NUM_REQS, NUM_STEPS, target_vocab, dtype=DTYPE, device=DEVICE) + if probabilistic + else None + ) + spec._d2t_scatter_index = None + spec._draft_scatter_buf = None + if probabilistic and d2t is not None: + spec._d2t_scatter_index = torch.arange(DRAFT_VOCAB, device=DEVICE) + d2t + spec._draft_scatter_buf = torch.full( + (MAX_NUM_REQS, target_vocab), float("-inf"), dtype=DTYPE, device=DEVICE + ) + spec._step_cols = torch.arange(NUM_STEPS, dtype=torch.int32, device=DEVICE) + spec._anchor_idx = ( + torch.arange(MAX_NUM_REQS, dtype=torch.int64, device=DEVICE) * NUM_STEPS + ) + spec._req_rows = torch.arange(MAX_NUM_REQS, dtype=torch.int64, device=DEVICE) + spec.draft_tokens = torch.zeros( + MAX_NUM_REQS, NUM_STEPS, dtype=torch.int64, device=DEVICE + ) + # Per-step inputs, shared by value: the same prepared buffers on all ranks. + spec.temperature = inputs["temperature"].clone() + spec.seeds = inputs["seeds"].clone() + spec.sample_indices = inputs["sample_indices"].clone() + spec.sample_pos = inputs["sample_pos"].clone() + spec.sample_idx_mapping = inputs["sample_idx_mapping"].clone() + spec.input_buffers = SimpleNamespace(input_ids=inputs["input_ids"].clone()) + return spec + + +def _make_inputs(rng: np.random.Generator, slots: np.ndarray, target_vocab: int): + """Buffers as prepare_dflash_inputs leaves them for `slots` (the batch).""" + num_reqs = len(slots) + max_rows = MAX_NUM_REQS * NUM_STEPS + sample_idx_mapping = np.full(max_rows, -1, dtype=np.int32) + sample_idx_mapping[: num_reqs * NUM_STEPS] = np.repeat(slots, NUM_STEPS) + sample_indices = np.zeros(max_rows, dtype=np.int64) + sample_indices[: num_reqs * NUM_STEPS] = np.arange(num_reqs * NUM_STEPS) + sample_pos = np.zeros(max_rows, dtype=np.int64) + last_pos = rng.integers(10, 5000, size=num_reqs) + sample_pos[: num_reqs * NUM_STEPS] = ( + last_pos[:, None] + 2 + np.arange(NUM_STEPS) + ).ravel() + temperature = np.zeros(MAX_NUM_REQS, dtype=np.float32) + # A mix of greedy and seeded random requests. + temperature[slots] = rng.choice([0.0, 0.6, 1.0, 1.3], size=num_reqs) + seeds = rng.integers(0, 2**62, size=MAX_NUM_REQS, dtype=np.int64) + input_ids = rng.integers(0, target_vocab, size=max_rows, dtype=np.int32) + + def dev(a): + return torch.from_numpy(np.ascontiguousarray(a)).to(DEVICE) + + return { + "sample_idx_mapping": dev(sample_idx_mapping), + "sample_indices": dev(sample_indices), + "sample_pos": dev(sample_pos), + "temperature": dev(temperature), + "seeds": dev(seeds), + "input_ids": dev(input_ids), + } + + +def _fake_group(rank: int): + return SimpleNamespace(rank_in_group=rank, world_size=TP_SIZE, device_group=None) + + +def _run_sharded_tails(specs, slots: np.ndarray, num_reqs_padded: int) -> None: + """Run _sample_after_forward on every simulated rank, emulating the + all-to-all from the staged send buffers and the all-gather in two passes + (gather the owners' ids, then rerun with the gathered result).""" + input_batch = SimpleNamespace(idx_mapping_np=slots, num_reqs=len(slots)) + sends = [spec._draft_sharder.send for spec in specs] + + def run(rank, gathered): + def fake_all_to_all( + output, input, output_split_sizes, input_split_sizes, group + ): + bounds = np.concatenate([[0], np.cumsum(input_split_sizes)]) + output.copy_(torch.cat([s[bounds[rank] : bounds[rank + 1]] for s in sends])) + + def fake_all_gather(tensor, dim): + local_ids.append(tensor.clone()) + return gathered if gathered is not None else tensor.repeat(TP_SIZE, 1) + + local_ids: list[torch.Tensor] = [] + with ( + mock.patch.object( + batch_shard, "get_tp_group", return_value=_fake_group(rank) + ), + mock.patch.object( + batch_shard.torch.distributed, "all_to_all_single", fake_all_to_all + ), + mock.patch.object( + batch_shard, "tensor_model_parallel_all_gather", fake_all_gather + ), + ): + specs[rank]._sample_after_forward(input_batch, num_reqs_padded) + return local_ids[0] + + local = [run(rank, None) for rank in range(TP_SIZE)] + gathered = torch.cat(local) + for rank in range(TP_SIZE): + run(rank, gathered) + + +def _enable_sharding(spec, rank: int) -> None: + with ( + mock.patch.object(batch_shard, "get_tp_group", return_value=_fake_group(rank)), + mock.patch.object( + dspark_speculator, "get_tp_group", return_value=_fake_group(rank) + ), + ): + spec.enable_batch_sharded_sampling() + assert spec._draft_sharder is not None + if spec.draft_logits is not None: + # As _init_draft_logits sizes it: this rank's requests only, one row + # per owned slot. + spec.draft_logits_num_shards = TP_SIZE + spec.draft_logits_shard_idx = rank + spec.draft_logits = spec.draft_logits.new_zeros( + cdiv(MAX_NUM_REQS, TP_SIZE), *spec.draft_logits.shape[1:] + ) + + +def _check_against_replicated(ref, specs, slots: np.ndarray) -> None: + num_reqs = len(slots) + for rank, spec in enumerate(specs): + assert torch.equal(spec.draft_tokens[:num_reqs], ref.draft_tokens[:num_reqs]) + if ref.draft_logits is None: + continue + owned_rows = set() + for slot in slots: + assert ref.draft_logits[slot].any() + if slot % TP_SIZE == rank: + row = slot // TP_SIZE + owned_rows.add(row) + assert torch.equal(spec.draft_logits[row], ref.draft_logits[slot]) + # Only the owner (the verifying rank) caches a request's rows. + for row in range(spec.draft_logits.shape[0]): + if row not in owned_rows: + assert not spec.draft_logits[row].any() + + +# (slots, padded batch size). The Markov bias GEMM keeps the padded batch's +# row count; 4 rows pick the skinny GEMM on ROCm, more rows the library GEMM. +_BATCHES = [ + ([5, 9, 13], 4), # rank 1 owns every request, the others none + ([0, 7, 2, 33, 41, 12, 63, 18, 22, 3, 50, 44, 29], 16), + (None, 40), # 37 random slots +] + + +@pytest.mark.parametrize("probabilistic", [True, False]) +@pytest.mark.parametrize("reduced_vocab", [False, True]) +@pytest.mark.parametrize("batch", range(len(_BATCHES))) +def test_sharded_draft_sampling_matches_replicated( + default_vllm_config, probabilistic: bool, reduced_vocab: bool, batch: int +): + rng = np.random.default_rng(batch) + slots, num_reqs_padded = _BATCHES[batch] + if slots is None: + slots = rng.choice(MAX_NUM_REQS, size=37, replace=False) + slots = np.asarray(slots, dtype=np.int64) + shards, markov_head, d2t, target_vocab = _make_weights(reduced_vocab) + inputs = _make_inputs(rng, slots, target_vocab) + head_hidden = torch.randn( + num_reqs_padded * NUM_STEPS, HIDDEN, device=DEVICE, dtype=DTYPE + ) + + def make(rank): + spec = _make_speculator( + shards, markov_head, d2t, target_vocab, rank, probabilistic, inputs + ) + spec._run_model = lambda *args, **kwargs: head_hidden + return spec + + ref = make(0) + ref._generate_draft(num_reqs_padded, num_reqs_padded * NUM_STEPS, None, None, None) + + specs = [make(rank) for rank in range(TP_SIZE)] + for rank, spec in enumerate(specs): + _enable_sharding(spec, rank) + spec._generate_draft( + num_reqs_padded, num_reqs_padded * NUM_STEPS, None, None, None + ) + _run_sharded_tails(specs, slots, num_reqs_padded) + _check_against_replicated(ref, specs, slots) + + +def test_sharded_draft_stage_replays_in_cuda_graph(default_vllm_config): + """The staged half of the draft step is captured once and replayed for a + different batch of the same padded size, like the drafter's FULL graph.""" + num_reqs_padded = 16 + rng = np.random.default_rng(3) + shards, markov_head, d2t, target_vocab = _make_weights(reduced_vocab=False) + capture_slots = np.arange(num_reqs_padded, dtype=np.int64) + capture_inputs = _make_inputs(rng, capture_slots, target_vocab) + head_hidden = torch.zeros( + num_reqs_padded * NUM_STEPS, HIDDEN, device=DEVICE, dtype=DTYPE + ) + + specs = [] + graphs = [] + for rank in range(TP_SIZE): + spec = _make_speculator( + shards, markov_head, d2t, target_vocab, rank, True, capture_inputs + ) + spec._run_model = lambda *args, **kwargs: head_hidden + _enable_sharding(spec, rank) + args = (num_reqs_padded, num_reqs_padded * NUM_STEPS, None, None, None) + spec._generate_draft(*args) # warm up outside the capture + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + spec._generate_draft(*args) + specs.append(spec) + graphs.append(graph) + + # A smaller batch with skewed ownership replays the same graphs. + slots = np.array([4, 8, 12, 1, 31, 60, 2, 16, 20], dtype=np.int64) + inputs = _make_inputs(rng, slots, target_vocab) + head_hidden.copy_(torch.randn_like(head_hidden)) + for spec, graph in zip(specs, graphs): + for name in ("sample_idx_mapping", "sample_indices", "sample_pos"): + getattr(spec, name).copy_(inputs[name]) + spec.temperature.copy_(inputs["temperature"]) + spec.seeds.copy_(inputs["seeds"]) + spec.input_buffers.input_ids.copy_(inputs["input_ids"]) + graph.replay() + _run_sharded_tails(specs, slots, num_reqs_padded) + + ref = _make_speculator(shards, markov_head, d2t, target_vocab, 0, True, inputs) + ref._run_model = lambda *args, **kwargs: head_hidden + ref._generate_draft(num_reqs_padded, num_reqs_padded * NUM_STEPS, None, None, None) + _check_against_replicated(ref, specs, slots) + + +def _sample_sequential_unfused(spec, num_reqs: int, head_hidden: torch.Tensor): + """The replicated Markov loop with the bias added outside the Gumbel kernel.""" + num_sample = num_reqs * NUM_STEPS + sample_hidden = head_hidden[spec.sample_indices[:num_sample]] + base_logits = spec.model.compute_draft_logits(sample_hidden) + base_logits = base_logits.view(num_reqs, NUM_STEPS, -1) + idx_map = spec.sample_idx_mapping[:num_sample].view(num_reqs, NUM_STEPS) + sample_pos = spec.sample_pos[:num_sample].view(num_reqs, NUM_STEPS) + prev = spec.input_buffers.input_ids[spec._anchor_idx[:num_reqs]] + for i in range(NUM_STEPS): + bias = spec.model.markov_bias(spec.model.markov_embed(prev)) + prev = spec._sample_logits( + base_logits[:, i] + bias, idx_map[:, i], sample_pos[:, i], i + ) + spec.draft_tokens[:num_reqs, i] = prev + + +@pytest.mark.parametrize("probabilistic", [True, False]) +@pytest.mark.parametrize("reduced_vocab", [False, True]) +@pytest.mark.parametrize("batch", range(len(_BATCHES))) +def test_replicated_markov_sampling_matches_unfused( + default_vllm_config, probabilistic: bool, reduced_vocab: bool, batch: int +): + """In every mode, the replicated loop gives the draft ids and cached draft + logits of adding the Markov bias first. Probabilistic full-vocab drafting + adds it inside the Gumbel kernel.""" + rng = np.random.default_rng(batch) + slots, num_reqs_padded = _BATCHES[batch] + if slots is None: + slots = rng.choice(MAX_NUM_REQS, size=37, replace=False) + shards, markov_head, d2t, target_vocab = _make_weights(reduced_vocab) + inputs = _make_inputs(rng, np.asarray(slots, dtype=np.int64), target_vocab) + head_hidden = torch.randn( + num_reqs_padded * NUM_STEPS, HIDDEN, device=DEVICE, dtype=DTYPE + ) + specs = [ + _make_speculator( + shards, markov_head, d2t, target_vocab, 0, probabilistic, inputs + ) + for _ in range(2) + ] + specs[0]._sample_sequential(num_reqs_padded, head_hidden) + _sample_sequential_unfused(specs[1], num_reqs_padded, head_hidden) + assert torch.equal(specs[0].draft_tokens, specs[1].draft_tokens) + if probabilistic: + draft_logits = specs[0].draft_logits + assert draft_logits is not None and draft_logits.any() + assert torch.equal(draft_logits, specs[1].draft_logits) diff --git a/tests/v1/spec_decode/test_rejection_sampler_utils.py b/tests/v1/spec_decode/test_rejection_sampler_utils.py index fd282f434624..68236d6c59bb 100644 --- a/tests/v1/spec_decode/test_rejection_sampler_utils.py +++ b/tests/v1/spec_decode/test_rejection_sampler_utils.py @@ -1241,6 +1241,78 @@ def test_block_verification_accepts_at_least_as_many(num_speculative_steps: int) ) +def test_block_verification_is_unbiased_across_steps(): + """Consecutive block verification steps must keep the target distribution. + + Block verification observes the draft and the acceptance draw of every row, + and after a partial accept the next step verifies the same positions again. + If those draws are keyed by position alone, the next step reuses draws that + verification has already observed, which biases the output. The single-step + tests above give every trial fresh positions and cannot see this, so here + each request decodes many steps from its own advancing position, drafting + with gumbel_sample the way the speculators do. + """ + torch.manual_seed(0) + device = "cuda" + num_reqs, num_steps, k = 2048, 32, 5 + vocab_size = NARROW_VOCAB_SIZE + + target_logits_1d = torch.randn(vocab_size, device=device) + # A draft close to the target accepts most proposals, so steps often revisit + # positions the previous step verified past its accepted prefix. + draft_logits_1d = target_logits_1d + torch.randn(vocab_size, device=device) + + reqs = torch.arange(num_reqs, dtype=torch.int32, device=device) + rows = torch.arange(k + 1, device=device) + draft_cols = rows[:k].to(torch.int32).repeat(num_reqs) + temperature = torch.ones(num_reqs, dtype=torch.float32, device=device) + seed = torch.arange(num_reqs, dtype=torch.int64, device=device) + draft_logits = torch.empty(num_reqs, k, vocab_size, device=device) + target_logits = target_logits_1d.expand(num_reqs * (k + 1), -1).contiguous() + cu_num_logits = torch.arange(num_reqs + 1, dtype=torch.int32, device=device) * ( + k + 1 + ) + + start = torch.zeros(num_reqs, dtype=torch.int64, device=device) + emitted = [] + for _ in range(num_steps): + pos = start.unsqueeze(1) + rows + # A draft is keyed by the position before it, i.e. its verifying row. + drafts = gumbel_sample( + draft_logits_1d.expand(num_reqs * k, -1), + reqs.repeat_interleave(k), + temperature, + seed, + pos[:, :k].reshape(-1), + apply_temperature=True, + is_drafting=True, + logits_cache=draft_logits, + logits_cache_col=draft_cols, + ) + draft_sampled = torch.zeros(num_reqs, k + 1, dtype=torch.int64, device=device) + draft_sampled[:, 1:] = drafts.view(num_reqs, k) + sampled, num_sampled = rejection_sample( + target_logits=target_logits, + draft_logits=draft_logits, + draft_sampled=draft_sampled.view(-1), + cu_num_logits=cu_num_logits, + pos=pos.reshape(-1), + idx_mapping=reqs, + expanded_idx_mapping=reqs.repeat_interleave(k + 1), + expanded_local_pos=rows.to(torch.int32).repeat(num_reqs), + temperature=temperature, + seed=seed, + num_speculative_steps=k, + use_block_verification=True, + ) + emitted.append(sampled[rows < num_sampled.unsqueeze(1)]) + start += num_sampled + + _assert_distribution_match( + torch.cat(emitted), torch.softmax(target_logits_1d, dim=0), device + ) + + @pytest.mark.parametrize("has_draft_logits", [True, False]) @pytest.mark.parametrize("fly_window_size", [0, 2]) def test_chunked_requests_match_full_batch( diff --git a/tests/v1/worker/test_dbo_pure_tp.py b/tests/v1/worker/test_dbo_pure_tp.py new file mode 100644 index 000000000000..ae3fb50d2387 --- /dev/null +++ b/tests/v1/worker/test_dbo_pure_tp.py @@ -0,0 +1,186 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""DBO under pure tensor parallelism (one DP rank, no EP), without GPUs.""" + +import threading +from types import SimpleNamespace + +import pytest +import torch + +import vllm.distributed.parallel_state as parallel_state +import vllm.v1.worker.ubatching as ubatching +import vllm.v1.worker.workspace as workspace +from vllm.config import CUDAGraphMode, ParallelConfig, VllmConfig +from vllm.sequence import IntermediateTensors +from vllm.v1.worker.gpu.dp_utils import dispatch_cg_and_sync_dp +from vllm.v1.worker.gpu.ubatch_utils import merge_ubatch_outputs + + +def test_merge_tensors_concatenates_along_tokens(): + a, b = torch.arange(6.0).view(3, 2), torch.arange(6.0, 10.0).view(2, 2) + assert torch.equal(merge_ubatch_outputs([a, b]), torch.cat([a, b])) + + +def test_merge_recurses_into_tuples_and_lists(): + # EAGLE3 returns (hidden, aux); DSpark returns (hidden, [aux, ...]). + h = [torch.full((2, 4), float(i)) for i in range(2)] + aux = [ + [torch.full((2, 3), 10.0 + i), torch.full((2, 5), 20.0 + i)] for i in range(2) + ] + merged = merge_ubatch_outputs([(h[0], aux[0]), (h[1], aux[1])]) + assert isinstance(merged, tuple) and isinstance(merged[1], list) + assert torch.equal(merged[0], torch.cat(h)) + assert torch.equal(merged[1][0], torch.cat([aux[0][0], aux[1][0]])) + assert torch.equal(merged[1][1], torch.cat([aux[0][1], aux[1][1]])) + + +def test_merge_keeps_none_and_intermediate_tensors(): + assert merge_ubatch_outputs([None, None]) is None + parts = [ + IntermediateTensors({"hidden_states": torch.ones(2, 4) * i}) for i in range(2) + ] + merged = merge_ubatch_outputs(parts) + assert merged["hidden_states"].shape == (4, 4) + + +def _parallel_config(tp=4, dp=1, ep=False): + return ParallelConfig( + tensor_parallel_size=tp, + data_parallel_size=dp, + enable_expert_parallel=ep, + enable_dbo=True, + ) + + +@pytest.mark.parametrize( + ("tp", "dp", "ep", "tp_only"), + [ + (4, 1, False, True), + (4, 2, False, False), + (4, 1, True, False), + (1, 1, False, False), + ], +) +def test_dbo_tp_only(tp, dp, ep, tp_only): + assert _parallel_config(tp, dp, ep).dbo_tp_only is tp_only + assert not ParallelConfig(tensor_parallel_size=tp).dbo_tp_only # DBO off + + +def _config(tp=4, dp=1, ep=False, spec=False, mm=False, enc_dec=False): + return SimpleNamespace( + model_config=SimpleNamespace( + is_multimodal_model=mm, is_encoder_decoder=enc_dec, is_hybrid=False + ), + parallel_config=_parallel_config(tp, dp, ep), + lora_config=None, + speculative_config=object() if spec else None, + compilation_config=SimpleNamespace(cudagraph_mode=CUDAGraphMode.FULL), + is_mm_encoder_only=False, + ) + + +@pytest.mark.parametrize( + ("kwargs", "rejected"), + [ + # pure TP: the drafter and the vision encoder run outside the split + (dict(spec=True), None), + (dict(mm=True), None), + (dict(spec=True, mm=True), None), + # anything that is not pure TP keeps the old restrictions + (dict(spec=True, dp=2), "speculative decoding"), + (dict(spec=True, ep=True), "speculative decoding"), + (dict(spec=True, tp=1), "speculative decoding"), + (dict(mm=True, dp=2), "multimodal"), + # encoder-decoder models stay out under pure TP too + (dict(enc_dec=True), "multimodal"), + ], +) +def test_dbo_unsupported_features(monkeypatch, kwargs, rejected): + monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1") + unsupported = VllmConfig._get_dbo_unsupported_features(_config(**kwargs)) + if rejected is None: + assert unsupported == [] + else: + assert any(rejected in u for u in unsupported), unsupported + + +def _parallel(threshold_prefill=8192, threshold_decode=32768): + return SimpleNamespace( + use_ubatching=True, + num_ubatches=2, + dbo_prefill_token_threshold=threshold_prefill, + dbo_decode_token_threshold=threshold_decode, + ) + + +@pytest.mark.parametrize( + ("num_tokens", "uniform_decode", "allow", "expected_ubatches"), + [ + (16384, False, True, 2), # prefill above its threshold: split + (4096, False, True, 1), # below: whole + (16384, True, True, 1), # a decode step uses the decode threshold + (16384, False, False, 1), # the caller did not allow a split + ], +) +def test_single_dp_rank_splits_on_its_own( + num_tokens, uniform_decode, allow, expected_ubatches +): + desc, sync = dispatch_cg_and_sync_dp( + None, + num_reqs=2, + num_tokens=num_tokens, + uniform_token_count=None, + dp_size=1, + dp_rank=0, + need_eager=True, + parallel_config=_parallel(), + allow_ubatching=allow, + uniform_decode=uniform_decode, + ) + assert sync is None + assert desc.num_ubatches == expected_ubatches + if expected_ubatches > 1: + # a split step runs eager + assert desc.cg_mode == CUDAGraphMode.NONE + + +@pytest.mark.parametrize(("num_ubatches", "expected"), [(1, 0), (2, 1)]) +def test_workspace_id_shared_across_microbatches(monkeypatch, num_ubatches, expected): + # TP-only DBO on the V2 runner keeps one workspace set. + monkeypatch.setattr(workspace, "dbo_current_ubatch_id", lambda: 1) + manager = workspace.WorkspaceManager( + torch.device("cpu"), num_ubatches=num_ubatches, num_lanes=1 + ) + assert manager._get_workspace_id() == expected + + +@pytest.mark.parametrize( + "kwargs", + [dict(dp=2), dict(ep=True), dict(dbo=False)], +) +def test_hook_not_installed_outside_pure_tp_dbo(monkeypatch, kwargs): + monkeypatch.setattr(parallel_state, "_dbo_tp_all_reduce_hook", None) + monkeypatch.setattr(ubatching, "_TP_UBATCH_COMMS", None) + dbo = kwargs.pop("dbo", True) + pc = _parallel_config(**kwargs) if dbo else ParallelConfig(tensor_parallel_size=4) + ubatching.init_dbo_tp_comms(pc) + assert parallel_state._dbo_tp_all_reduce_hook is None + assert ubatching._TP_UBATCH_COMMS is None + + +def test_hook_is_inert_outside_a_microbatch(monkeypatch): + # Outside a microbatch thread or for a non-TP group the hook returns None. + monkeypatch.setattr(ubatching, "_THREAD_ID_TO_CONTEXT", {}) + assert ubatching._dbo_tp_all_reduce(object(), torch.ones(2)) is None + monkeypatch.setattr(ubatching, "_THREAD_ID_TO_CONTEXT", {threading.get_ident(): 0}) + monkeypatch.setattr(parallel_state, "_TP", object()) + assert ubatching._dbo_tp_all_reduce(object(), torch.ones(2)) is None + + +@pytest.mark.parametrize(("rocm", "priority"), [(True, -1), (False, 0)]) +def test_comm_stream_priority(monkeypatch, rocm, priority): + from vllm.platforms import current_platform + + monkeypatch.setattr(current_platform, "is_rocm", lambda: rocm) + assert ubatching.dbo_comm_stream_priority() == priority diff --git a/tests/v1/worker/test_eagle3_aux_hidden_states_pp.py b/tests/v1/worker/test_eagle3_aux_hidden_states_pp.py index 89bfc6a53d50..567e460dc083 100644 --- a/tests/v1/worker/test_eagle3_aux_hidden_states_pp.py +++ b/tests/v1/worker/test_eagle3_aux_hidden_states_pp.py @@ -57,29 +57,39 @@ def test_mimo_does_not_inherit_aux_hidden_state_pp_support(): class _PPAuxLayer(torch.nn.Module): - """Aliases and mutates residual in place like MiniMaxM3DecoderLayer.""" + """Aliases and mutates residual in place like MiniMaxM3DecoderLayer. - ffn_all_reduce_deferred = False + With ``deferred``, the FFN output is this rank's half of a 2-way TP sum, and + the next input norm completes the all-reduce. + """ - def __init__(self, index): + def __init__(self, index, deferred): super().__init__() self.index = index + self.ffn_all_reduce_deferred = deferred + self.fuse_input_allreduce = False - def forward(self, positions, hidden_states, residual): - total = hidden_states if residual is None else hidden_states + residual - residual = hidden_states if residual is None else residual - residual.copy_(total + self.index + 1) - return torch.full_like(hidden_states, 10 * (self.index + 1)), residual + def forward_input_norm(self, hidden_states, residual): + if residual is None: + return hidden_states, hidden_states + if self.fuse_input_allreduce: + hidden_states = hidden_states * 2 + residual.add_(hidden_states) + return hidden_states, residual + + def forward_after_input_norm(self, positions, hidden_states, residual): + residual.add_(self.index + 1) + output = torch.full_like(hidden_states, 10 * (self.index + 1)) + return output / 2 if self.ffn_all_reduce_deferred else output, residual class _PPAuxNorm(torch.nn.Module): - """Clobbers its inputs so aux taps that alias them would fail.""" + """Fused add + norm (identity scaling) that overwrites its inputs in place.""" def forward(self, hidden_states, residual): - output = hidden_states + residual - hidden_states.fill_(-101) - residual.fill_(-103) - return output, residual + residual.add_(hidden_states) + hidden_states.copy_(residual) + return hidden_states, residual @pytest.fixture @@ -98,10 +108,18 @@ def minimax_pp_stage(monkeypatch): monkeypatch.setattr( minimax_m3, "MiniMAXGemmaRMSNorm", lambda *args, **kwargs: _PPAuxNorm() ) + deferred = [False] monkeypatch.setattr( minimax_m3, "MiniMaxM3DecoderLayer", - lambda **kwargs: _PPAuxLayer(int(kwargs["prefix"].rsplit(".", 1)[1])), + lambda **kwargs: _PPAuxLayer( + int(kwargs["prefix"].rsplit(".", 1)[1]), deferred[0] + ), + ) + monkeypatch.setattr( + minimax_m3, + "fused_allreduce_gemma_rms_norm", + lambda hidden_states, residual, norm: norm(hidden_states * 2, residual), ) def make_layers(num_layers, build, prefix): @@ -117,8 +135,9 @@ def make_layers(num_layers, build, prefix): monkeypatch.setattr(minimax_m3, "make_layers", make_layers) - def make_stage(start, end, taps, world_size=2): + def make_stage(start, end, taps, world_size=2, deferred_all_reduce=False): bounds[:] = [start, end] + deferred[0] = deferred_all_reduce group.world_size = world_size group.is_first_rank = start == 0 group.is_last_rank = end == 6 @@ -204,3 +223,15 @@ def test_minimax_pp2_without_aux_keeps_hidden_and_residual_transport(minimax_pp_ ) == {"hidden_states", "residual"} output = last(None, None, sent) torch.testing.assert_close(output, _pp_aux_state(_expected_aux_value(6))) + + +@pytest.mark.parametrize("taps", [(0, 3, 6), (1, 2, 5)]) +def test_minimax_aux_taps_follow_deferred_tp_all_reduce(minimax_pp_stage, taps): + """Under TP each FFN output stays a partial sum until the next input norm or + the final norm all-reduces it, so aux taps must read the reduced stream.""" + model, _ = minimax_pp_stage(0, 6, taps, world_size=1, deferred_all_reduce=True) + assert model.fuse_final_norm_allreduce + output, aux = model(None, None, None, _pp_aux_state(7)) + for hidden, tap in zip(aux, taps, strict=True): + torch.testing.assert_close(hidden, _pp_aux_state(_expected_aux_value(tap))) + torch.testing.assert_close(output, _pp_aux_state(_expected_aux_value(6))) diff --git a/tests/v1/worker/test_gpu_batch_shard.py b/tests/v1/worker/test_gpu_batch_shard.py index 4ee76818df4f..9a45b9349a2d 100644 --- a/tests/v1/worker/test_gpu_batch_shard.py +++ b/tests/v1/worker/test_gpu_batch_shard.py @@ -21,6 +21,7 @@ from vllm.v1.worker.gpu.sample import batch_shard from vllm.v1.worker.gpu.sample.batch_shard import ( BatchSharder, + DraftBatchSharder, _shard_grammar_output, ) @@ -655,6 +656,76 @@ def fake_all_gather(x: torch.Tensor, dim: int = 0) -> torch.Tensor: assert lp.cu_num_generated_tokens is None +@requires_gpu +@pytest.mark.parametrize("tp_size", [2, 4, 8]) +@pytest.mark.parametrize( + "num_reqs,num_reqs_padded", [(1, 1), (3, 4), (5, 8), (23, 24), (40, 40)] +) +def test_draft_shard_plan(tp_size: int, num_reqs: int, num_reqs_padded: int): + """A drafter's staged (req, step) rows are owner-sorted like the target's + logits (batch order within an owner, padded requests last), and the local + views and gather sources address exactly each rank's requests.""" + rng = np.random.default_rng(num_reqs * 10 + tp_size) + max_num_reqs, num_steps, width = 64, 3, 8 + slots = rng.choice(max_num_reqs, size=num_reqs, replace=False).astype(np.int32) + sample_idx_mapping = np.full(max_num_reqs * num_steps, -1, dtype=np.int32) + sample_idx_mapping[: num_reqs * num_steps] = np.repeat(slots, num_steps) + sample_pos = rng.integers(0, 10_000, size=max_num_reqs * num_steps) + num_rows = num_reqs_padded * num_steps + # Row r of the vocab shard holds the value r in every column. + local_logits = ( + torch.arange(num_rows, dtype=torch.float32, device=DEVICE) + .unsqueeze(1) + .repeat(1, width) + ) + sample_idx_mapping_gpu = torch.from_numpy(sample_idx_mapping).to(DEVICE) + sample_pos_gpu = torch.from_numpy(sample_pos).to(DEVICE) + + owners = slots % tp_size + order = np.argsort(owners, kind="stable") + send_reqs = np.concatenate([order, np.arange(num_reqs, num_reqs_padded)]) + expected_rows = (send_reqs[:, None] * num_steps + np.arange(num_steps)).ravel() + + local_ids = [] + gathered_src = None + for rank in range(tp_size): + fake_group = SimpleNamespace(rank_in_group=rank, world_size=tp_size) + with mock.patch.object(batch_shard, "get_tp_group", return_value=fake_group): + sharder = DraftBatchSharder( + max_num_reqs, num_steps, width, torch.float32, torch.device(DEVICE) + ) + # Stale entries must never survive into a smaller batch. + sharder.send_rows.fill_(10**9) + sharder.stage( + local_logits, sample_idx_mapping_gpu, sample_pos_gpu, num_reqs_padded + ) + assert _np(sharder.send_rows[:num_rows]).tolist() == expected_rows.tolist() + assert (_np(sharder.send[:num_rows])[:, 0] == expected_rows).all() + + owned = np.flatnonzero(owners == rank) + num_owned = len(owned) + assert _np(sharder.local_rows[:num_owned]).tolist() == owned.tolist() + # Step-major: [step, owned request]. + owned_rows = owned[None, :] * num_steps + np.arange(num_steps)[:, None] + assert ( + _np(sharder.local_idx_mapping[:, :num_owned]) + == sample_idx_mapping[owned_rows] + ).all() + assert ( + _np(sharder.local_sample_pos[:, :num_owned]) == sample_pos[owned_rows] + ).all() + src = _np(sharder.gathered_src[:num_reqs]) + if gathered_src is None: + gathered_src = src + assert (src == gathered_src).all() + # This rank's gather block: its owned slots, then padding. + block = np.full(num_reqs_padded, -1, dtype=np.int64) + block[:num_owned] = slots[owned] + local_ids.append(block) + # Indexing the rank-major gather with gathered_src restores batch order. + assert (np.concatenate(local_ids)[gathered_src] == slots).all() + + def test_finish_requests_frees_slots_in_sorted_order(): """Request slots must be freed in the same order on every TP rank: ownership derives from slot indices, and `finished_req_ids` is a set diff --git a/tests/v1/worker/test_gpu_gumbel_sample.py b/tests/v1/worker/test_gpu_gumbel_sample.py index b3c4128bfc73..6d5075cf9614 100644 --- a/tests/v1/worker/test_gpu_gumbel_sample.py +++ b/tests/v1/worker/test_gpu_gumbel_sample.py @@ -528,3 +528,33 @@ def test_logits_cache_narrower_than_logits_is_rejected(): logits_cache=cache, logits_cache_col=torch.tensor(0, dtype=torch.int32, device=DEVICE), ) + + +@pytest.mark.parametrize("dtype", [torch.float32, torch.float64]) +def test_gumbel_combine_preserves_first_nan_and_maximum(dtype): + """Combining block partials preserves argmax/gather's tie and NaN ordering.""" + from vllm.v1.worker.gpu.sample.gumbel import _gumbel_combine_kernel + + # Padded rows exercise strides; 197 blocks exercise the masked reduction tail. + maxima = torch.randn(6, 211, dtype=dtype, device=DEVICE)[:, :197] + maxima[0].fill_(-torch.inf) + maxima[1].fill_(1) + maxima[2, 7] = maxima[2, 9] = torch.nan + maxima[3, 5] = maxima[3, 6] = torch.inf + maxima[4].fill_(-torch.inf) + maxima[4, 196] = 0 + token_ids = torch.arange(197, dtype=torch.int64, device=DEVICE).expand(6, -1) + sampled = torch.empty(6, dtype=torch.int64, device=DEVICE) + + _gumbel_combine_kernel[(6,)]( + token_ids, + token_ids.stride(0), + maxima, + maxima.stride(0), + sampled, + 197, + PADDED_NUM_BLOCKS=256, + ) + + expected = token_ids.gather(1, maxima.argmax(-1, keepdim=True)).view(-1) + assert torch.equal(sampled, expected) diff --git a/tests/v1/worker/test_gpu_input_batch_v2.py b/tests/v1/worker/test_gpu_input_batch_v2.py index 5e1a3972e257..76cbb3a95cf0 100644 --- a/tests/v1/worker/test_gpu_input_batch_v2.py +++ b/tests/v1/worker/test_gpu_input_batch_v2.py @@ -162,3 +162,60 @@ def test_prepare_dcp_local_seq_lens_matches_reference( ) assert batch.dcp_local_seq_lens is not None assert torch.equal(batch.dcp_local_seq_lens.cpu(), expected.to(torch.int32)) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="triton kernel needs CUDA") +@pytest.mark.parametrize("write_padding", [False, True]) +@pytest.mark.parametrize( + "query_lens,gap,tail", [([3, 1, 2], 0, 5), ([3, 1, 2], 3, 5), ([1025], 7, 1030)] +) +def test_prepare_positions_preserves_padding_after_compaction( + write_padding: bool, query_lens: list[int], gap: int, tail: int +): + """Dropped real rows stay unpadded; only the graph tail is padding.""" + from vllm.v1.worker.gpu.input_batch import prepare_pos_seq_lens + + device = "cuda" + num_reqs = len(query_lens) + mapping = torch.arange(num_reqs - 1, -1, -1, dtype=torch.int32, device=device) + computed = torch.arange(num_reqs, dtype=torch.int32, device=device) * 10 + starts = np.concatenate(([0], np.cumsum(query_lens))) + query_start_loc = torch.tensor(starts, dtype=torch.int32, device=device) + num_tokens = int(starts[-1]) + pad_start = num_tokens + gap + padded_tokens = pad_start + tail + positions = torch.full((padded_tokens + 1,), -1, dtype=torch.int64, device=device) + seq_lens = torch.full((num_reqs + 2,), -1, dtype=torch.int32, device=device) + padding = torch.ones(padded_tokens + 1, dtype=torch.bool, device=device) + padding[-1] = False + if write_padding: + padding[pad_start:padded_tokens] = False + + prepare_pos_seq_lens( + mapping, + query_start_loc, + computed, + positions, + seq_lens, + is_padding=padding if write_padding else None, + num_tokens_padded=padded_tokens, + pad_start=pad_start, + ) + + expected_positions = torch.cat( + [ + torch.arange(query_len, device=device) + (num_reqs - 1 - i) * 10 + for i, query_len in enumerate(query_lens) + ] + ) + assert torch.equal(positions[:num_tokens], expected_positions) + assert (positions[num_tokens:] == -1).all() + expected_lens = computed.flip(0) + torch.tensor(query_lens, device=device) + assert torch.equal(seq_lens[:num_reqs], expected_lens) + assert not seq_lens[num_reqs:].any() + if write_padding: + assert not padding[:pad_start].any() + assert padding[pad_start:padded_tokens].all() + else: + assert padding[:padded_tokens].all() + assert not padding[-1] diff --git a/vllm/_custom_ops.py b/vllm/_custom_ops.py index 09a459826988..4aae7fee98c6 100644 --- a/vllm/_custom_ops.py +++ b/vllm/_custom_ops.py @@ -2782,6 +2782,7 @@ def fused_minimax_m3_qknorm_rope_kv_insert( q_fp8_scale: float = 1.0, kv_k_scale: torch.Tensor | None = None, kv_v_scale: torch.Tensor | None = None, + write_qkv: bool = True, ) -> None: """Fused MiniMax-M3 attention pre-processing (in-place). @@ -2792,11 +2793,13 @@ def fused_minimax_m3_qknorm_rope_kv_insert( - sparse layer (``num_index_heads > 0``): ``[q | k | v | index_q | index_k]`` — the index branch is read straight out of ``qkv``. - When ``kv_cache`` is given (sparse serving), also scatter-inserts the - normed/roped k & v into the paged KV cache by ``slot_mapping`` and the - index key into ``index_cache`` by ``index_slot_mapping``. ``kv_cache_dtype`` - selects the cache storage/conversion path. If - ``index_slot_mapping`` is omitted, ``slot_mapping`` is used for both caches. + When ``kv_cache`` is given, also scatter-inserts the normed/roped k & v + into the paged KV cache by ``slot_mapping`` and, on sparse layers, the + index key into ``index_cache`` by ``index_slot_mapping``. + ``kv_cache_dtype`` selects the cache storage/conversion path; a dense + layer's insert stores exactly what ``reshape_and_cache_flash`` would with + unit k/v scales. If ``index_slot_mapping`` is omitted, ``slot_mapping`` is + used for both caches. If ``q_out`` / ``index_q_out`` (contiguous ``[N, nq*128]`` / ``[N, niq*128]``) are given, the normed/roped q / index_q are written there @@ -2818,6 +2821,11 @@ def fused_minimax_m3_qknorm_rope_kv_insert( ``[index_q | index_k]`` tail, but the kernel only processes the main q/k/v branches and main KV cache. This is used by MiniMax-M3 index-topk reuse layers that consume top-k block ids selected by an earlier sparse layer. + + ``write_qkv=False`` needs ``q_fp8_out`` without ``q_out``, for callers that + read only the FP8 q, ``index_q_out`` and the caches: k and index_k need not + be rewritten in ``qkv``. The persistent kernel (SM80+, ``rotary_dim`` 64) + skips those stores; the fallback kernel may still make them. """ torch.ops._C.fused_minimax_m3_qknorm_rope_kv_insert( qkv, @@ -2845,6 +2853,47 @@ def fused_minimax_m3_qknorm_rope_kv_insert( q_fp8_scale, kv_k_scale, kv_v_scale, + write_qkv, + ) + + +def fused_minimax_m3_dspark_context_kv( + all_kv: torch.Tensor, + k_norm_weight: torch.Tensor, + cos_sin_cache: torch.Tensor, + positions: torch.Tensor, + slot_mapping: torch.Tensor, + kv_cache: torch.Tensor, + cache_offsets: torch.Tensor, + k_scale: torch.Tensor, + scale_offsets: torch.Tensor, + rotary_dim: int, + eps: float, + kv_cache_dtype: str, +) -> None: + """Store the MiniMax-M3 DSpark draft's context K/V for every layer. + + ``all_kv`` ``[N, L, 2, nkv, 128]`` holds each layer's K and V. K gets the + layer's Gemma RMSNorm (``k_norm_weight[L, 128]``) and partial NeoX RoPE; + both are stored like ``reshape_and_cache_flash`` into the layers' caches. + Layer ``l``'s cache is ``kv_cache`` (layer 0, ``[nb, nkv, bs, 2 * 128]``) + shifted by ``cache_offsets[l]`` elements; its fp8 k/v scales are + ``k_scale`` (layer 0's) shifted by ``scale_offsets[0, l]`` / + ``scale_offsets[1, l]`` floats. Slots < 0 are skipped. + """ + torch.ops._C.fused_minimax_m3_dspark_context_kv( + all_kv, + k_norm_weight, + cos_sin_cache, + positions, + slot_mapping, + kv_cache, + cache_offsets, + k_scale, + scale_offsets, + rotary_dim, + eps, + kv_cache_dtype, ) diff --git a/vllm/config/attention.py b/vllm/config/attention.py index f812ca57bd7e..b6af50db33be 100644 --- a/vllm/config/attention.py +++ b/vllm/config/attention.py @@ -40,8 +40,10 @@ class AttentionConfig: backend: AttentionBackendEnum | None = None """Attention backend to use. Use "auto" or None for automatic selection.""" - minimax_m3_msa_decode_backend: MiniMaxM3MSADecodeBackend = "triton" - """Sparse decode kernel used by the MiniMax M3 MSA backend.""" + minimax_m3_msa_decode_backend: MiniMaxM3MSADecodeBackend = "cutlass" + """Sparse decode kernel used by the MiniMax M3 MSA backend. "cutlass" falls + back to Triton where the CUTLASS kernel does not support the platform, KV + cache dtype, or head layout.""" backend_per_kind: dict[str, AttentionBackendEnum] = field(default_factory=dict) """Per-KV-cache-group attention backend overrides, keyed by @@ -95,7 +97,20 @@ class AttentionConfig: model's default (bf16 for MiniMax M3, fp8 for the DeepSeek sparse indexer, mxfp4 for DeepSeek-V4 on ROCm CDNA4 with aiter). Quantized formats (fp8, mxfp4, nvfp4) require indexer kernel support in the - backend.""" + backend; MiniMax M3 supports nvfp4 on SM100/SM103/SM107 with at most 8 + decode queries per request.""" + + indexer_decode_cp: bool = False + """Split the sparse-attention indexer's decode scoring across the + tensor-parallel ranks by context instead of by index head: each rank scores + a 1/TP slice of the index-K pages for every head and the ranks exchange + their local top-k, so each reads 1/TP of the index-K cache per sparse + layer. The index-K cache stays replicated, so this is unrelated to + `--decode-context-parallel-size`, which shards the KV cache itself; the two + cannot be combined. Implemented for the MiniMax M3 NVFP4 indexer, which + needs `indexer_kv_dtype="nvfp4"` and TP 4 (one index head per rank); it is + ignored with a warning where it does not apply. It pays off from about 4 + concurrent decodes at 128K context and grows with batch and context.""" indexer_sparse_logits: bool = False """DeepSeek V4.1 two-level indexer: score only the candidate blocks with diff --git a/vllm/config/parallel.py b/vllm/config/parallel.py index f51a35c5c4a9..7f8deb57a972 100644 --- a/vllm/config/parallel.py +++ b/vllm/config/parallel.py @@ -649,6 +649,16 @@ def use_ubatching(self) -> bool: def num_ubatches(self) -> int: return 2 if self.enable_dbo else self.ubatch_size + @property + def dbo_tp_only(self) -> bool: + """DBO with one DP rank and no EP: microbatches overlap TP all-reduces.""" + return ( + self.use_ubatching + and self.data_parallel_size == 1 + and not self.enable_expert_parallel + and self.tensor_parallel_size > 1 + ) + @property def local_engines_only(self) -> bool: """Client manages local+remote EngineCores in pure internal LB case. diff --git a/vllm/config/speculative.py b/vllm/config/speculative.py index 9a6f1a8afc7b..e2413491f993 100644 --- a/vllm/config/speculative.py +++ b/vllm/config/speculative.py @@ -3,6 +3,7 @@ import copy import functools +import os from collections.abc import Callable, Mapping from typing import TYPE_CHECKING, Any, Literal, Self, get_args @@ -16,6 +17,7 @@ from vllm.config.utils import config, replace from vllm.logger import init_logger from vllm.transformers_utils.config import get_hf_text_config, iter_rope_parameters +from vllm.transformers_utils.repo_utils import get_subfolder_path from vllm.utils.hashing import safe_hash from vllm.utils.import_utils import LazyLoader, has_arctic_inference from vllm.v1.attention.backends.registry import AttentionBackendEnum @@ -113,6 +115,31 @@ def _rope_only_sizes_cache(hf_config: PreTrainedConfig) -> bool: ) +_MINIMAX_M3_MODEL_TYPES = ("minimax_m3_vl", "minimax_m3_text") +_MINIMAX_M3_DSPARK_SUBFOLDER = "dspark" + + +def _get_minimax_m3_dspark_draft( + target_model_config: ModelConfig, cache_dir: str | None +) -> str: + """MiniMax-M3 checkpoints ship the DSpark draft as a standalone checkpoint + in their `dspark/` subfolder.""" + draft = get_subfolder_path( + target_model_config.model, + _MINIMAX_M3_DSPARK_SUBFOLDER, + revision=target_model_config.revision, + cache_dir=cache_dir, + ) + if not os.path.isfile(os.path.join(draft, "config.json")): + raise ValueError( + f"MiniMax-M3 DSpark found no draft checkpoint in the " + f"'{_MINIMAX_M3_DSPARK_SUBFOLDER}/' subfolder of " + f"{target_model_config.model}. Set speculative_config.model to the " + "draft checkpoint." + ) + return draft + + def _is_qwen3_omni_target(model_config: ModelConfig) -> bool: hf_config = model_config.hf_config architectures = set(getattr(model_config, "architectures", ()) or ()) @@ -1106,7 +1133,25 @@ def hf_config_override(hf_config: PreTrainedConfig) -> PreTrainedConfig: text_config.num_kv_shared_layers = 0 hf_config.update({"n_predict": 1, "architectures": ["Gemma4MTPModel"]}) - if ( + if initial_architecture == "DSparkMiniMaxDraftModel": + quantization_config = getattr(hf_config, "quantization_config", None) + hf_config = getattr(hf_config, "text_config", hf_config) + if ( + quantization_config is not None + and getattr(hf_config, "quantization_config", None) is None + ): + hf_config.update({"quantization_config": quantization_config}) + dflash_config = dict(getattr(hf_config, "dflash_config", None) or {}) + dflash_config.setdefault("causal", False) + hf_config.model_type = "minimax_m3_dspark" + hf_config.update( + { + "architectures": ["DSparkMiniMaxDraftModel"], + "dflash_config": dflash_config, + "markov_rank": hf_config.dspark_markov_rank, + } + ) + elif ( hf_config.model_type == "minimax_m3_vl" or initial_architecture == "MiniMaxM3SparseForConditionalGeneration" ): @@ -1232,7 +1277,11 @@ def __post_init__(self): ) self.method = "mtp" - if self.model is None and self.num_speculative_tokens is not None: + # DSpark drafts carry their own width (block size), so the default + # draft is resolved even without num_speculative_tokens. + if self.model is None and ( + self.num_speculative_tokens is not None or self.method == "dspark" + ): if self.method == "mtp": if self.target_model_config is None: raise ValueError("target_model_config must be present for mtp") @@ -1250,12 +1299,24 @@ def __post_init__(self): if not self.quantization: self.quantization = self.target_model_config.quantization elif self.method == "dspark": - # DeepSeek DSpark can ship the weights inside the target checkpoint if self.target_model_config is None: raise ValueError("target_model_config must be present for dspark") - self.model = self.target_model_config.model - if not self.quantization: - self.quantization = self.target_model_config.quantization + if ( + self.target_model_config.hf_config.model_type + in _MINIMAX_M3_MODEL_TYPES + ): + self.model = _get_minimax_m3_dspark_draft( + self.target_model_config, + self.draft_load_config.download_dir + if self.draft_load_config + else None, + ) + else: + # DeepSeek DSpark can ship the weights inside the target + # checkpoint + self.model = self.target_model_config.model + if not self.quantization: + self.quantization = self.target_model_config.quantization elif self.method in ("ngram", "[ngram]"): self.model = "ngram" elif self.method == "ngram_gpu": @@ -1510,6 +1571,8 @@ def __post_init__(self): not in self.draft_model_config.architectures and "Gemma4DSparkModel" not in self.draft_model_config.architectures and "K3DSparkModel" not in self.draft_model_config.architectures + and "DSparkMiniMaxDraftModel" + not in self.draft_model_config.architectures ): # DeepSeek-V4(.1) DSpark reuses the full target config # and its weights ship in the target checkpoint. diff --git a/vllm/config/vllm.py b/vllm/config/vllm.py index bbeb12c20cba..8013ee18392b 100644 --- a/vllm/config/vllm.py +++ b/vllm/config/vllm.py @@ -2178,7 +2178,7 @@ def has_blocked_weights(): f"cudagraph_mode={self.compilation_config.cudagraph_mode}" ) - if self.parallel_config.use_ubatching: + if self.parallel_config.use_ubatching and not self.parallel_config.dbo_tp_only: a2a_backend = self.parallel_config.all2all_backend if current_platform.is_rocm(): supported_backends = [ @@ -3237,9 +3237,10 @@ def _get_dbo_unsupported_features(self) -> list[str]: model_config = self.model_config parallel_config = self.parallel_config + tp_only_dbo = parallel_config.dbo_tp_only if self.lora_config is not None: unsupported.append("dual batch overlap with LoRA") - if self.speculative_config is not None: + if self.speculative_config is not None and not tp_only_dbo: unsupported.append("dual batch overlap with speculative decoding") if parallel_config.pipeline_parallel_size > 1: unsupported.append("dual batch overlap with pipeline parallelism") @@ -3249,7 +3250,8 @@ def _get_dbo_unsupported_features(self) -> list[str]: ): unsupported.append("dual batch overlap with context parallelism") if model_config is not None and ( - model_config.is_multimodal_model or model_config.is_encoder_decoder + (model_config.is_multimodal_model and not tp_only_dbo) + or model_config.is_encoder_decoder ): unsupported.append("dual batch overlap with multimodal models") if model_config is not None and model_config.is_hybrid: diff --git a/vllm/cute_utils/__init__.py b/vllm/cute_utils/__init__.py index 033533a5c9a0..2cc4564efa26 100644 --- a/vllm/cute_utils/__init__.py +++ b/vllm/cute_utils/__init__.py @@ -60,11 +60,15 @@ def to_cta0_smem(ptr: cute.Pointer, *, loc=None, ip=None): ) -def simple_tma_copy(atom, src, dst, mbar=None, cache_policy=None): +def simple_tma_copy(atom, src, dst, mbar=None, cache_policy=None, mcast_mask=None): """A simple helper that wraps group_modes() and tma_partition() NOTE: this should be called WITHOUT cute.elect_one() """ - if isinstance(atom.op, cpasync.CopyBulkTensorTileG2SOp): + g2s_ops = ( + cpasync.CopyBulkTensorTileG2SOp, + cpasync.CopyBulkTensorTileG2SMulticastOp, + ) + if isinstance(atom.op, g2s_ops): gmem = src smem = dst elif isinstance(atom.op, cpasync.CopyBulkTensorTileS2GOp): @@ -81,8 +85,13 @@ def simple_tma_copy(atom, src, dst, mbar=None, cache_policy=None): cute.group_modes(gmem, 0), ) - if isinstance(atom.op, cpasync.CopyBulkTensorTileG2SOp): - cute.copy(atom, g_part, s_part, tma_bar_ptr=mbar, cache_policy=cache_policy) + if isinstance(atom.op, g2s_ops): + kwargs = {} + if mcast_mask is not None: + kwargs["mcast_mask"] = mcast_mask + cute.copy( + atom, g_part, s_part, tma_bar_ptr=mbar, cache_policy=cache_policy, **kwargs + ) elif isinstance(atom.op, cpasync.CopyBulkTensorTileS2GOp): cute.copy(atom, s_part, g_part, cache_policy=cache_policy) else: diff --git a/vllm/cute_utils/cvt.py b/vllm/cute_utils/cvt.py index 8bb4ad95198b..ce103ee741b8 100644 --- a/vllm/cute_utils/cvt.py +++ b/vllm/cute_utils/cvt.py @@ -38,6 +38,12 @@ def bf16x2_to_fp32x2(data, *, loc=None, ip=None) -> tuple[Float32, Float32]: ) elif isinstance(data, (cute.Tensor, cute.TensorSSA)): + # TensorSSA in, TensorSSA out (it can't be recast: stage it in rmem) + is_ssa = isinstance(data, cute.TensorSSA) + if is_ssa: + frag = cute.make_rmem_tensor(data.shape, data.dtype) + frag.store(data) + data = frag # recast to 32-bit registers if needed if data.element_type == BFloat16: data = cute.recast_tensor(data, Uint32) @@ -48,7 +54,7 @@ def bf16x2_to_fp32x2(data, *, loc=None, ip=None) -> tuple[Float32, Float32]: out = cute.make_rmem_tensor(size * 2, Float32) for i in range(size): out[i * 2], out[i * 2 + 1] = bf16x2_to_fp32x2(data[i]) - return out + return out.load() if is_ssa else out else: raise ValueError(f"Unsupported type {type(data)}") diff --git a/vllm/distributed/kv_transfer/kv_connector/v1/nixl/base_worker.py b/vllm/distributed/kv_transfer/kv_connector/v1/nixl/base_worker.py index 37075775b66c..c6a69dc884a4 100644 --- a/vllm/distributed/kv_transfer/kv_connector/v1/nixl/base_worker.py +++ b/vllm/distributed/kv_transfer/kv_connector/v1/nixl/base_worker.py @@ -1546,12 +1546,12 @@ def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]): self._ple_block_len = None self._ple_region_index = None - # A shared packed row may transfer whole only if every page in it is - # replicated across TP ranks: MLA without SSM state. Head-sharded - # attention or SSM state (e.g. Qwen3.8-Flash-Next) must stay split. + # A shared packed row may transfer whole if every page in it is + # replicated across TP ranks (MLA), or if P and D shard heads alike + # (non-MLA, equal TP checked at handshake). SSM state (e.g. + # Qwen3.8-Flash-Next) must stay split. packed_storage = ( _share_storage_and_block_stride(list(xfer_buffers.values())) - and self.use_mla and not self._has_mamba ) if route_packed_layers and any( @@ -1677,13 +1677,14 @@ def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]): and cache[0].is_contiguous() and cache[0].nbytes == physical_page_size ) - # Block-outermost MLA: one block row holds every layer's page. + # Block-outermost: one block row holds every layer's page (in an + # MLA model, only its MLA layers' pages travel as rows). packed_mla = ( self._has_packed_cache and not self._has_mamba and packed_storage and storage_is_block_major - and is_mla_region + and (is_mla_region or not self.use_mla) ) if packed_mla and use_layer_name_routing: # PP>1 prefill stage: register only this layer's page of each row. @@ -2860,13 +2861,16 @@ def _validate_remote_agent_handshake( ) # NVFP4 pages store all heads' data before all heads' scales, so a - # head's bytes are not a contiguous slice of the page. + # head's bytes are not a contiguous slice of the page, unless the + # backend lays out the page by KV head. if ( not self.use_mla and self.transfer_topo.local_physical_heads != max(1, self.transfer_topo.total_num_kv_heads // remote_tp_size) and any( - isinstance(spec, AttentionSpec) and spec.kv_quant_mode.is_nvfp4 + isinstance(spec, AttentionSpec) + and spec.kv_quant_mode.is_nvfp4 + and not spec.kv_head_major_slots for spec in self._layer_specs.values() ) ): @@ -2875,6 +2879,13 @@ def _validate_remote_agent_handshake( f"(local TP {self.transfer_topo.tp_size}, remote TP " f"{remote_tp_size}). Use matching TP sizes on prefill and decode." ) + # A whole row holds this rank's heads of every layer: no re-sharding. + if self._packed_member_layouts and not self.use_mla and tp_ratio != 1: + raise RuntimeError( + "Packed KV rows of a non-MLA model need the same TP on prefill " + f"and decode (local TP {self.transfer_topo.tp_size}, remote TP " + f"{remote_tp_size}). Use LBHNC for heterogeneous TP." + ) # Per-region block_len validation enforcing the P/D invariant. # REPLICATE regions (MLA, or a whole-model MLA / replicated-KV transfer) diff --git a/vllm/distributed/kv_transfer/kv_connector/v1/simple_cpu_offload_connector.py b/vllm/distributed/kv_transfer/kv_connector/v1/simple_cpu_offload_connector.py index c36936c92e3c..e70b53d395bf 100644 --- a/vllm/distributed/kv_transfer/kv_connector/v1/simple_cpu_offload_connector.py +++ b/vllm/distributed/kv_transfer/kv_connector/v1/simple_cpu_offload_connector.py @@ -25,6 +25,7 @@ from vllm.v1.core.sched.output import SchedulerOutput from vllm.v1.metrics.cache_hit_source import CacheHitSource from vllm.v1.outputs import KVConnectorOutput +from vllm.v1.simple_kv_offload.host_buffer import parse_hugepage_size from vllm.v1.simple_kv_offload.manager import ( BoundaryStoreStats, SimpleCPUOffloadScheduler, @@ -144,6 +145,11 @@ def __init__( ) disk_buffer_slots = max(1, int(extra_config.get("disk_buffer_slots", 2))) use_page_cache = bool(extra_config.get("use_page_cache", False)) + # "1GB"/"2MB": back the CPU buffer with explicit HugeTLB pages. The + # key matches OffloadingConnector's hugetlbfs option. + cpu_hugepage_size = parse_hugepage_size( + extra_config.get("cpu_hugepage_block_size") + ) if disk_mode: if disk_path is None: @@ -163,6 +169,10 @@ def __init__( ", ".join(ignored), ) disk_path = None + if disk_mode and cpu_hugepage_size is not None: + raise ValueError( + 'cpu_hugepage_block_size applies only to kv_offload_backend="cpu".' + ) self.scheduler_manager: SimpleCPUOffloadScheduler | None = None self.worker_handler: SimpleCPUOffloadWorker | None = None @@ -224,6 +234,7 @@ def __init__( disk_buffer_slots=disk_buffer_slots, use_page_cache=use_page_cache, num_cpu_blocks=num_cpu_blocks, + cpu_hugepage_size=cpu_hugepage_size, ) # --- Worker-side methods --- diff --git a/vllm/distributed/parallel_state.py b/vllm/distributed/parallel_state.py index 897518247f13..f58e5fa39516 100644 --- a/vllm/distributed/parallel_state.py +++ b/vllm/distributed/parallel_state.py @@ -747,6 +747,11 @@ def all_reduce(self, input_: torch.Tensor) -> torch.Tensor: return self._all_reduce_out_place(input_) def _all_reduce_out_place(self, input_: torch.Tensor) -> torch.Tensor: + # Under the vllm.all_reduce custom op, so compiled graphs reach it too. + if _dbo_tp_all_reduce_hook is not None and not torch.compiler.is_compiling(): + out = _dbo_tp_all_reduce_hook(self, input_) + if out is not None: + return out if self.device_communicator is None: raise ValueError("No device communicator found") return self.device_communicator.all_reduce(input_) @@ -1588,6 +1593,16 @@ def _replace_active_groups( return old_groups +# Set by vllm.v1.worker.ubatching.init_dbo_tp_comms. +_DboTpAllReduceHook = Callable[[GroupCoordinator, torch.Tensor], torch.Tensor | None] +_dbo_tp_all_reduce_hook: _DboTpAllReduceHook | None = None + + +def set_dbo_tp_all_reduce_hook(hook: _DboTpAllReduceHook | None) -> None: + global _dbo_tp_all_reduce_hook + _dbo_tp_all_reduce_hook = hook + + _TP: GroupCoordinator | None = None diff --git a/vllm/envs.py b/vllm/envs.py index a7bde6b336fa..0cd5ea8db560 100755 --- a/vllm/envs.py +++ b/vllm/envs.py @@ -160,6 +160,7 @@ VLLM_ROCM_FP8_PADDING: bool = True VLLM_ROCM_MOE_PADDING: bool = True VLLM_ROCM_SHUFFLE_KV_CACHE_LAYOUT: bool = False + VLLM_ROCM_MINIMAX_M3_SP_PREFILL: bool = False VLLM_ENABLE_V1_MULTIPROCESSING: bool = True VLLM_LOG_BATCHSIZE_INTERVAL: float = -1 VLLM_DISABLE_COMPILE_CACHE: bool = False @@ -1406,6 +1407,11 @@ def _resolve_rust_cli_path() -> str | None: "VLLM_ROCM_SHUFFLE_KV_CACHE_LAYOUT": lambda: ( os.getenv("VLLM_ROCM_SHUFFLE_KV_CACHE_LAYOUT", "False").lower() in ("true", "1") ), + # MiniMax-M3 sequence-parallel prefill under pure TP (TP4, gfx950). + # By default is disabled. + "VLLM_ROCM_MINIMAX_M3_SP_PREFILL": lambda: ( + os.getenv("VLLM_ROCM_MINIMAX_M3_SP_PREFILL", "False").lower() in ("true", "1") + ), # Custom quick allreduce kernel for MI3* cards # Choice of quantization level: FP, INT8, INT6, INT4, INT3 or NONE # Recommended for large models to get allreduce diff --git a/vllm/model_executor/kernels/linear/mxfp8/flashinfer.py b/vllm/model_executor/kernels/linear/mxfp8/flashinfer.py index c3b99fc36ec3..f21d0bf37360 100644 --- a/vllm/model_executor/kernels/linear/mxfp8/flashinfer.py +++ b/vllm/model_executor/kernels/linear/mxfp8/flashinfer.py @@ -99,7 +99,7 @@ def apply_weights( out_dtype, input_shape = qa.orig_dtype, qa.orig_shape else: assert isinstance(x, torch.Tensor) - out_dtype, input_shape = x.dtype, x.shape + out_dtype, input_shape = layer.params_dtype, x.shape input_mxfp8, input_scale = mxfp8_e4m3_quantize( x.view(-1, K), is_sf_swizzled_layout=True ) @@ -177,7 +177,7 @@ def apply_weights( out_dtype, input_shape = qa.orig_dtype, qa.orig_shape else: assert isinstance(x, torch.Tensor) - out_dtype, input_shape = x.dtype, x.shape + out_dtype, input_shape = layer.params_dtype, x.shape input_mxfp8, input_scale = mxfp8_e4m3_quantize( x.view(-1, K), is_sf_swizzled_layout=True ) diff --git a/vllm/model_executor/kernels/linear/mxfp8/rocm_native.py b/vllm/model_executor/kernels/linear/mxfp8/rocm_native.py index e46b61275c66..7ee4944783fd 100644 --- a/vllm/model_executor/kernels/linear/mxfp8/rocm_native.py +++ b/vllm/model_executor/kernels/linear/mxfp8/rocm_native.py @@ -35,7 +35,7 @@ def _mxfp8_linear_kernel( out_ptr, M, N, - K, + K: tl.constexpr, stride_xm, stride_xk, stride_xsm, @@ -87,10 +87,20 @@ def _mxfp8_dot_scaled_linear( w: torch.Tensor, # [N, K] fp8 e4m3 w_scale: torch.Tensor, # [N, K//32] uint8 (E8M0) ) -> torch.Tensor: - M, K = x.shape - N = w.shape[0] x_q, x_scale = mxfp8_e4m3_quantize(x) - out = torch.empty((M, N), dtype=x.dtype, device=x.device) + return _mxfp8_dot_scaled_gemm(x_q, x_scale, w, w_scale, x.dtype) + + +def _mxfp8_dot_scaled_gemm( + x_q: torch.Tensor, # [M, K] fp8 e4m3 + x_scale: torch.Tensor, # [M, K//32] uint8 (E8M0) + w: torch.Tensor, + w_scale: torch.Tensor, + out_dtype: torch.dtype, +) -> torch.Tensor: + M, K = x_q.shape + N = w.shape[0] + out = torch.empty((M, N), dtype=out_dtype, device=x_q.device) BLOCK_M, BLOCK_N, BLOCK_K, num_warps, num_stages = _select_cfg(M, N, K) grid = (triton.cdiv(M, BLOCK_M), triton.cdiv(N, BLOCK_N)) _mxfp8_linear_kernel[grid]( @@ -124,10 +134,12 @@ def _mxfp8_dot_scaled_linear( # gfx950's async-copy LDS (default in the triton 3.8 this branch pins) leaves no # room for num_stages=3 at BLOCK_K=256; use 2 there. _BK256_STAGES = 3 +_ON_GFX950 = False if current_platform.is_rocm(): from vllm.platforms.rocm import on_gfx950 - if on_gfx950(): + _ON_GFX950 = on_gfx950() + if _ON_GFX950: _BK256_STAGES = 2 @@ -142,6 +154,11 @@ def _select_cfg(M, N, K): (the K-loop is unmasked), so every BLOCK_K below is guarded to be K-divisible (served K: 384/768/1024/2048/6144). """ + if _ON_GFX950 and M <= 16: + if K == 6144 and N in (1536, 2560): + return 16, 16, 1024, 2, 3 + if K == 768 and N == 6144: + return 16, 16, 256, 2, 3 if M <= 64: # decode (M in {1,32,64}): tiny-M GEMV is weight-BW + GPU-OCCUPANCY bound. The # lever is NARROW BLOCK_N=16 (maximize N-tiles so more CUs stream the weight in @@ -261,6 +278,30 @@ def process_weights_after_loading(self, layer: torch.nn.Module) -> None: replace_parameter(layer, "weight", weight.contiguous()) replace_parameter(layer, "weight_scale", weight_scale) + @staticmethod + def supports_quantized_input(layer: torch.nn.Module) -> bool: + """Whether ``apply_quantized`` serves ``layer`` (fp8 weights).""" + return layer.weight.element_size() == 1 and ( + layer.weight_scale.shape[0] != layer.weight.shape[0] + or layer.weight.shape[1] % _DOT_SCALED_K_ALIGN == 0 + ) + + def apply_quantized( + self, + layer: torch.nn.Module, + x_q: torch.Tensor, + x_scale: torch.Tensor, + out_dtype: torch.dtype, + ) -> torch.Tensor: + """``apply_weights`` on ``mxfp8_e4m3_quantize``'s fp8 + e8m0 output.""" + if layer.weight_scale.shape[0] != layer.weight.shape[0]: + return rocm_mxfp8_block32_gemm( + x_q, x_scale, layer.weight, layer.weight_scale, out_dtype + ) + return _mxfp8_dot_scaled_gemm( + x_q, x_scale, layer.weight, layer.weight_scale, out_dtype + ) + def apply_weights( self, layer: torch.nn.Module, diff --git a/vllm/model_executor/layers/attention/attention.py b/vllm/model_executor/layers/attention/attention.py index 93958bb12782..98b7f6509303 100644 --- a/vllm/model_executor/layers/attention/attention.py +++ b/vllm/model_executor/layers/attention/attention.py @@ -256,6 +256,7 @@ def __init__( mm_prefix_clamp_sliding_window: bool = False, attn_backend: type[AttentionBackend] | None = None, head_size_v: int | None = None, + query_pre_quantized: bool = False, **extra_impl_args, ) -> None: """The KV cache is stored inside this class and is accessed via @@ -469,7 +470,11 @@ def __init__( # for attn backends supporting query quantization self.query_quant = None if ( - self.impl.supports_quant_query_input + # A model whose fused QK-norm/RoPE kernel already emits the + # quantized query (MiniMax-M3's DSpark draft) passes + # query_pre_quantized and skips this second quantization. + not query_pre_quantized + and self.impl.supports_quant_query_input and ( self.kv_cache_dtype.startswith("fp8") or self.kv_cache_dtype.startswith("nvfp4") diff --git a/vllm/model_executor/layers/fused_allreduce_gemma_rms_norm.py b/vllm/model_executor/layers/fused_allreduce_gemma_rms_norm.py index 7046bfc991b9..7abad9cae919 100644 --- a/vllm/model_executor/layers/fused_allreduce_gemma_rms_norm.py +++ b/vllm/model_executor/layers/fused_allreduce_gemma_rms_norm.py @@ -24,6 +24,7 @@ ) from vllm.model_executor.layers.layernorm import GemmaRMSNorm from vllm.platforms import current_platform +from vllm.v1.worker.ubatching import dbo_enabled MiB = 1024 * 1024 @@ -153,8 +154,9 @@ def fused_allreduce_gemma_rms_norm( # No all-reduce needed; identical to the unfused path. return norm(hidden_states, residual) + # Under DBO every all-reduce must reach the microbatch hand-off hook. ok, max_token_num = _can_use_flashinfer(hidden_states, tp_size) - if ok: + if ok and not dbo_enabled(): norm_out = torch.empty_like(hidden_states) # With norm_out provided, the kernel writes the new residual # (all_reduce(hidden_states) + residual) into the hidden_states buffer @@ -174,7 +176,7 @@ def fused_allreduce_gemma_rms_norm( ) return norm_out, hidden_states - if _can_use_aiter_fused_ar_rms(hidden_states): + if not dbo_enabled() and _can_use_aiter_fused_ar_rms(hidden_states): from vllm._aiter_ops import rocm_aiter_ops return rocm_aiter_ops.get_fused_allreduce_rmsnorm_op()( diff --git a/vllm/model_executor/layers/fused_moe/config.py b/vllm/model_executor/layers/fused_moe/config.py index e8bd822becab..55a86a2f8d06 100644 --- a/vllm/model_executor/layers/fused_moe/config.py +++ b/vllm/model_executor/layers/fused_moe/config.py @@ -16,7 +16,10 @@ OCP_MX_DTYPES, OCP_MX_Scheme, ) -from vllm.model_executor.layers.quantization.utils.quant_utils import GroupShape +from vllm.model_executor.layers.quantization.utils.quant_utils import ( + GroupShape, + QuantKey, +) from vllm.platforms import current_platform from vllm.utils.import_utils import get_triton_kernels_version from vllm.utils.math_utils import cdiv @@ -1339,6 +1342,12 @@ class FusedMoEConfig: tp_shard_with_padding: bool = False rocm_aiter_fmoe_enabled: bool = False aiter_fmoe_shared_expert_enabled: bool = False + # Activation scheme the routed experts were trained (QAT) against, when the + # checkpoint does not record it. Quant methods use it in place of their + # default: MiniMax-M3.1 quantizes the FC1 input per token and ships a 1.0 + # ``input_global_scale`` placeholder, which is indistinguishable from a + # calibrated per-tensor scale of 1.0. + qat_activation_key: QuantKey | None = None # Whether to force MXFP4 (a4w4) MoE activations for DeepSeek V4.1 on # ROCm/AITER. Opt-in via VLLM_ROCM_USE_AITER_MOE_A4W4_DSV4=1; rejected # for any other model type. Resolved here, not in the forward path, diff --git a/vllm/model_executor/layers/fused_moe/layer.py b/vllm/model_executor/layers/fused_moe/layer.py index 3b3e2aa39973..cbe6d0ce8938 100644 --- a/vllm/model_executor/layers/fused_moe/layer.py +++ b/vllm/model_executor/layers/fused_moe/layer.py @@ -40,6 +40,7 @@ from vllm.model_executor.layers.quantization.base_config import ( QuantizationConfig, ) +from vllm.model_executor.layers.quantization.utils.quant_utils import QuantKey logger = init_logger(__name__) @@ -114,6 +115,7 @@ def FusedMoEFactory( swiglu_beta: float | None = None, activation_situ_beta: float | None = None, activation_situ_linear_beta: float | None = None, + qat_activation_key: QuantKey | None = None, e_score_correction_bias: torch.Tensor | None = None, apply_router_weight_on_input: bool = False, activation: str = "silu", @@ -186,6 +188,8 @@ def FusedMoEFactory( swiglu_limit: SwiGLU activation limit activation_situ_beta: SituGLU activation beta activation_situ_linear_beta: SituGLU linear beta + qat_activation_key: Activation quantization scheme the experts were + trained against, for checkpoints that do not record it e_score_correction_bias: Expert score correction bias tensor apply_router_weight_on_input: Whether to apply router weights on input activation: Activation function name ("silu", "gelu", etc.) @@ -387,6 +391,7 @@ def FusedMoEFactory( swiglu_beta=swiglu_beta, activation_situ_beta=activation_situ_beta, activation_situ_linear_beta=activation_situ_linear_beta, + qat_activation_key=qat_activation_key, max_capture_size=vllm_config.compilation_config.max_cudagraph_capture_size, skip_final_all_reduce=skip_final_all_reduce, ) diff --git a/vllm/model_executor/layers/fused_moe/oracle/nvfp4.py b/vllm/model_executor/layers/fused_moe/oracle/nvfp4.py index 80aa9122f447..a1b9b6ee80b6 100644 --- a/vllm/model_executor/layers/fused_moe/oracle/nvfp4.py +++ b/vllm/model_executor/layers/fused_moe/oracle/nvfp4.py @@ -1,6 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from enum import Enum +from typing import Any import torch @@ -54,6 +55,15 @@ class NvFp4MoeBackend(Enum): FLASHINFER_MOE_EP_CUTEDSL = "FLASHINFER_MOE_EP_CUTEDSL" +# Backends whose experts quantize the MoE input themselves, with one scale per +# token. ``make_nvfp4_moe_kernel`` only hands ``per_token_activation`` to these. +PER_TOKEN_NVFP4_MOE_BACKENDS = frozenset( + { + NvFp4MoeBackend.FLASHINFER_CUTEDSL, + NvFp4MoeBackend.FLASHINFER_TRTLLM, + } +) + FLASHINFER_NVFP4_MOE_BACKENDS = [ NvFp4MoeBackend.FLASHINFER_TRTLLM, NvFp4MoeBackend.FLASHINFER_CUTLASS, @@ -196,6 +206,18 @@ def select_nvfp4_moe_backend( """Select the primary NvFP4 MoE backend Note: Shape-specific fallbacks may still occur at runtime. """ + from vllm.model_executor.layers.quantization.online.requantization import ( + is_requantization_source, + ) + + # TODO: remove and let the oracles have an option to skip init. + if is_requantization_source(): + from vllm.model_executor.layers.fused_moe.experts.nvfp4_emulation_moe import ( + Nvfp4QuantizationEmulationTritonExperts, + ) + + return NvFp4MoeBackend.EMULATION, Nvfp4QuantizationEmulationTritonExperts + # NOTE: the kernels are selected in the following order. # FLASHINFER_B12X is intentionally excluded from auto-selection until # the upstream CUTLASS SM121 MMA op guard is resolved; use @@ -615,6 +637,10 @@ def make_nvfp4_moe_kernel( routing_tables: tuple[torch.Tensor, torch.Tensor, torch.Tensor] | None = None, per_token_activation: bool = False, ) -> mk.FusedMoEKernel: + # Marlin consumes A16 and must not receive per-token A4 metadata. + if backend == NvFp4MoeBackend.MARLIN and moe_quant_config.use_nvfp4_w4a16: + per_token_activation = False + # Create Prepare/Finalize. prepare_finalize = maybe_make_prepare_finalize( moe=moe_config, @@ -628,15 +654,17 @@ def make_nvfp4_moe_kernel( logger.info_once("Using %s", prepare_finalize.__class__.__name__) - extra_kwargs = {} - if ( - backend - in ( - NvFp4MoeBackend.FLASHINFER_TRTLLM, - NvFp4MoeBackend.FLASHINFER_CUTEDSL, - ) - and per_token_activation - ): + extra_kwargs: dict[str, Any] = {} + if per_token_activation: + # Prepare dispatched the input unquantized, so an expert that does + # not quantize it itself would read garbage. The backend selection + # does not catch this: several NVFP4 experts match on the weight key + # alone and accept any activation key. + if backend not in PER_TOKEN_NVFP4_MOE_BACKENDS: + raise ValueError( + f"Per-token NVFP4 activation scales are not supported by " + f"{backend.value}." + ) extra_kwargs["per_token_activation"] = True # Create Experts. diff --git a/vllm/model_executor/layers/fused_moe/prepare_finalize/no_dp_ep.py b/vllm/model_executor/layers/fused_moe/prepare_finalize/no_dp_ep.py index fe5d518cf337..f63bb843d5fd 100644 --- a/vllm/model_executor/layers/fused_moe/prepare_finalize/no_dp_ep.py +++ b/vllm/model_executor/layers/fused_moe/prepare_finalize/no_dp_ep.py @@ -39,6 +39,10 @@ def _quantize_input( class MoEPrepareAndFinalizeNoDPEPModular(mk.FusedMoEPrepareAndFinalizeModular): + def supports_dbo(self) -> bool: + # No all2all: the DBO hand-offs are the TP all-reduces. + return True + def supports_deferred_moe_finalize(self) -> bool: # finalize() here is the top-k weight-and-reduce and nothing else, # which is exactly the work a deferring consumer takes over. diff --git a/vllm/model_executor/layers/fused_moe/prepare_megamoe.py b/vllm/model_executor/layers/fused_moe/prepare_megamoe.py index 5e8d8cde9a62..e1297e8380b6 100644 --- a/vllm/model_executor/layers/fused_moe/prepare_megamoe.py +++ b/vllm/model_executor/layers/fused_moe/prepare_megamoe.py @@ -300,52 +300,75 @@ def _prepare_megamoe_nvfp4_inputs_kernel( hidden_size: tl.constexpr, top_k: tl.constexpr, num_local_experts: tl.constexpr, - BLOCK_M: tl.constexpr, + BLOCK_H: tl.constexpr, BLOCK_K: tl.constexpr, + NUM_SPLITS: tl.constexpr, BLOCK_TOPK: tl.constexpr, BLOCK_E: tl.constexpr, SHARED_BLOCK_M: tl.constexpr, SHARED_MXFP8: tl.constexpr, ) -> None: + # Grid (token, split): each program quantizes the BLOCK_K chunks split, + # split + NUM_SPLITS, ... of one token's row. + token = tl.program_id(0) + split = tl.program_id(1) if l2_alpha is not None: experts = tl.arange(0, BLOCK_E) - expert_mask = (experts < num_local_experts) & (tl.program_id(0) == 0) + expert_mask = (experts < num_local_experts) & (token == 0) & (split == 0) alpha = tl.load(w2_global_scale + experts, mask=expert_mask) tl.store(l2_alpha + experts, alpha * l2_activation_scale, mask=expert_mask) + if token >= num_tokens: + return - token_id = tl.program_id(0) * BLOCK_M + tl.arange(0, BLOCK_M) - token_mask = token_id < num_tokens - k_offsets = tl.arange(0, BLOCK_K) - hidden_ptrs = hidden_states + token_id[:, None] * hidden_stride_m - - amax = tl.zeros((BLOCK_M,), tl.float32) - for k_block_id in range(hidden_size // BLOCK_K): - hidden = tl.load( - hidden_ptrs + (k_block_id * BLOCK_K + k_offsets[None, :]) * hidden_stride_k, - mask=token_mask[:, None], - other=0.0, - ).to(tl.float32) - amax = tl.maximum(amax, tl.max(tl.abs(hidden), axis=1)) - x_scale = tl.maximum(amax, 1.0e-12) * _INV_NVFP4_MAX - tl.store(x_scales + token_id, x_scale, mask=token_mask) - - for k_block_id in range(hidden_size // BLOCK_K): - k_ids = k_block_id * BLOCK_K + k_offsets - hidden = tl.load( - hidden_ptrs + k_ids[None, :] * hidden_stride_k, - mask=token_mask[:, None], - other=0.0, + if split == 0: + token_ids = token + tl.zeros([1], dtype=tl.int32) + _store_topk( + token_ids, + token_ids < num_tokens, + topk_ids, + topk_weights, + is_padding, + topk_idx_out, + topk_weights_out, + topk_ids_stride_m, + topk_ids_stride_k, + topk_weights_stride_m, + topk_weights_stride_k, + is_padding_stride_m, + topk_idx_stride_m, + topk_idx_stride_k, + topk_weights_out_stride_m, + topk_weights_out_stride_k, + top_k, + 1, + BLOCK_TOPK, ) + # Every program reads the whole row for the token scale. + row = hidden_states + token.to(tl.int64) * hidden_stride_m + cols = tl.arange(0, BLOCK_H) + hidden_row = tl.load( + row + cols * hidden_stride_k, mask=cols < hidden_size, other=0.0 + ) + amax = tl.max(tl.abs(hidden_row.to(tl.float32)), axis=0) + x_scale = tl.maximum(amax, 1.0e-12) * _INV_NVFP4_MAX + if split == 0: + tl.store(x_scales + token, x_scale) + + shared_sf_row = _shared_sf_row(token, SHARED_BLOCK_M) + for k0 in tl.range(split * BLOCK_K, hidden_size, NUM_SPLITS * BLOCK_K): + k_ids = k0 + tl.arange(0, BLOCK_K) + k_mask = k_ids < hidden_size + hidden = tl.load(row + k_ids * hidden_stride_k, mask=k_mask, other=0.0) + # E2M1 values with one E4M3 scale per 16, relative to the token scale. values = tl.reshape( - tl.div_rn(hidden.to(tl.float32), x_scale[:, None]), - [BLOCK_M, BLOCK_K // 16, 16], + tl.div_rn(hidden.to(tl.float32), x_scale), [BLOCK_K // 16, 16] ) - block_scale = tl.max(tl.abs(values), axis=2) * (1.0 / 6.0) + block_scale = tl.max(tl.abs(values), axis=1) * (1.0 / 6.0) block_scale = tl.minimum(tl.maximum(block_scale, 2.0**-9), 448.0) block_scale = block_scale.to(tl.float8e4nv) - values = tl.div_rn(values, block_scale.to(tl.float32)[:, :, None]) + values = tl.div_rn(values, block_scale.to(tl.float32)[:, None]) magnitude = tl.abs(values) # Round to nearest even on the grid {0, 0.5, 1, 1.5, 2, 3, 4, 6}. code = ( @@ -358,61 +381,45 @@ def _prepare_megamoe_nvfp4_inputs_kernel( + (magnitude > 5.0).to(tl.int32) ) code = tl.where((values < 0) & (code != 0), code | 8, code) - low, high = tl.split(tl.reshape(code, [BLOCK_M, BLOCK_K // 2, 2])) - packed_offsets = k_block_id * (BLOCK_K // 2) + tl.arange(0, BLOCK_K // 2) + low, high = tl.split(tl.reshape(code, [BLOCK_K // 2, 2])) + packed_ids = k0 // 2 + tl.arange(0, BLOCK_K // 2) tl.store( - x_out + token_id[:, None] * x_stride_m + packed_offsets[None, :], + x_out + token * x_stride_m + packed_ids, (low | (high << 4)).to(tl.uint8), - mask=token_mask[:, None], + mask=packed_ids < hidden_size // 2, ) - sf_offsets = k_block_id * (BLOCK_K // 64) + tl.arange(0, BLOCK_K // 64) + # Four E4M3 scales per little-endian int32 word, one word per 64 values. + sf_ids = k0 // 64 + tl.arange(0, BLOCK_K // 64) sf_bytes = tl.reshape( - block_scale.to(tl.uint8, bitcast=True), [BLOCK_M, BLOCK_K // 64, 4] + block_scale.to(tl.uint8, bitcast=True), [BLOCK_K // 64, 4] ) tl.store( - x_sf + token_id[:, None] * x_sf_stride_m + sf_offsets[None, :], + x_sf + token * x_sf_stride_m + sf_ids, _pack_bytes(sf_bytes, 4), - mask=token_mask[:, None], + mask=sf_ids < hidden_size // 64, ) if shared_x is not None: - shared_ptrs = shared_x + token_id[:, None] * shared_x_stride_m + shared_ptrs = shared_x + token * shared_x_stride_m + k_ids if SHARED_MXFP8: fp8, _, scale_exp = _quantize_fp8_groups( - hidden.to(tl.float32), BLOCK_M, BLOCK_K, 32, True + tl.reshape(hidden.to(tl.float32), (1, BLOCK_K)), + 1, + BLOCK_K, + 32, + True, ) - tl.store(shared_ptrs + k_ids[None, :], fp8, mask=token_mask[:, None]) + tl.store(shared_ptrs, tl.reshape(fp8, [BLOCK_K]), mask=k_mask) + word_ids = k0 // 128 + tl.arange(0, BLOCK_K // 128) tl.store( shared_x_sf - + _shared_sf_row(token_id, SHARED_BLOCK_M) * shared_x_sf_stride_m - + k_block_id * shared_x_sf_stride_k, - _pack_bytes(scale_exp, BLOCK_K // 32), - mask=token_mask, + + shared_sf_row * shared_x_sf_stride_m + + word_ids * shared_x_sf_stride_k, + _pack_bytes(tl.reshape(scale_exp, [BLOCK_K // 128, 4]), 4), + mask=word_ids < hidden_size // 128, ) else: - tl.store(shared_ptrs + k_ids[None, :], hidden, mask=token_mask[:, None]) - - _store_topk( - token_id, - token_mask, - topk_ids, - topk_weights, - is_padding, - topk_idx_out, - topk_weights_out, - topk_ids_stride_m, - topk_ids_stride_k, - topk_weights_stride_m, - topk_weights_stride_k, - is_padding_stride_m, - topk_idx_stride_m, - topk_idx_stride_k, - topk_weights_out_stride_m, - topk_weights_out_stride_k, - top_k, - BLOCK_M, - BLOCK_TOPK, - ) + tl.store(shared_ptrs, hidden, mask=k_mask) def _resolve_hidden_quant(hidden_quant: QuantKey, block_k: int) -> tuple[int, bool]: @@ -632,11 +639,19 @@ def prepare_megamoe_nvfp4_inputs( if tensor is not None and tensor.stride(-1) != 1: raise ValueError(f"MegaMoE NVFP4 staging requires a row-major {name}.") - block_m = 8 if num_tokens >= 64 else 1 top_k = topk_ids.shape[1] num_local_experts = 0 if l2_alpha is None else l2_alpha.numel() + # Up to 512 tokens each row is split over programs; larger batches fill the + # GPU with one program per row looping over wider chunks. + block_h = triton.next_power_of_2(hidden_size) + if num_tokens <= 512: + block_k = min(1024, block_h) + num_splits = triton.cdiv(hidden_size, block_k) + else: + block_k = min(2048, block_h) + num_splits = 1 # One program even without tokens, to write l2_alpha. - grid = (max(triton.cdiv(num_tokens, block_m), 1),) + grid = (max(num_tokens, 1), num_splits) _prepare_megamoe_nvfp4_inputs_kernel[grid]( hidden_states, x.view(torch.uint8), @@ -672,8 +687,9 @@ def prepare_megamoe_nvfp4_inputs( hidden_size, top_k, num_local_experts, - BLOCK_M=block_m, - BLOCK_K=128, + BLOCK_H=block_h, + BLOCK_K=block_k, + NUM_SPLITS=num_splits, BLOCK_TOPK=triton.next_power_of_2(top_k), BLOCK_E=triton.next_power_of_2(max(num_local_experts, 1)), SHARED_BLOCK_M=shared_block_m or 1, diff --git a/vllm/model_executor/layers/fused_moe/routed_experts.py b/vllm/model_executor/layers/fused_moe/routed_experts.py index 59aea0599b4e..5c3f91a51d98 100644 --- a/vllm/model_executor/layers/fused_moe/routed_experts.py +++ b/vllm/model_executor/layers/fused_moe/routed_experts.py @@ -26,7 +26,6 @@ from vllm.model_executor.layers.fused_moe.unquantized_fused_moe_method import ( UnquantizedFusedMoEMethod, ) -from vllm.model_executor.layers.linear import LinearBase from vllm.model_executor.layers.quantization.base_config import ( QuantizationConfig, resolve_quant_method, @@ -160,7 +159,6 @@ def __init__( object.__setattr__(self, "hash_indices_table", hash_indices_table) # End random parameters self._loaded_expert_biases: set[str] = set() - self._fused_shared_expert_quantizer = self._get_fused_shared_expert_quantizer() self.quant_method = self._get_quant_method( self.layer_name, @@ -168,6 +166,26 @@ def __init__( self.moe_config, ) + # Only set when FSE go through online quantization, with pre-quantized routed. + self.shared_expert_online_loader = None + online_config = getattr(self.quant_config, "online_quantization_config", None) + if ( + online_config is not None + and self.expert_map_manager.num_fused_shared_experts > 0 + ): + from vllm.model_executor.layers.quantization.online.shared_expert import ( + OnlineSharedExpertLoader, + ) + + self.shared_expert_online_loader = OnlineSharedExpertLoader( + self.quant_config, + online_config, + self.quant_method, + self.moe_config.shared_expert_prefix, + self.moe_config.num_logical_experts, + self.expert_map_manager.num_fused_shared_experts, + ) + # Round up hidden size and update moe_config. # TODO: move roundup to _get_quant_method? self.hidden_size, self.intermediate_size_per_partition = ( @@ -212,6 +230,10 @@ def __init__( self.quant_method.create_weights(layer=self, **moe_quant_params) + loader = self.shared_expert_online_loader + if loader is not None and loader.stages_shared_experts: + loader.create_staging(self, params_dtype, weight_loader=self.weight_loader) + self.lora_base_layer_prefix = "" # TODO(bnell): Temporary hack. Get rid of this. @@ -638,31 +660,6 @@ def _load_single_value( # _to_scalar's reshape(()) would reject the size-2 weight_shape. param_data[expert_id] = loaded_weight - def _get_fused_shared_expert_quantizer( - self, - ) -> Callable[[torch.Tensor], tuple[torch.Tensor, torch.Tensor]] | None: - """Return the quantizer for an online-quantized fused shared expert.""" - online_config = getattr(self.quant_config, "online_quantization_config", None) - prefix = self.moe_config.shared_expert_prefix - if ( - online_config is None - or prefix is None - or self.expert_map_manager.num_fused_shared_experts == 0 - ): - return None - # FSE compatibility checks require every shared-expert projection to - # use the routed experts' weight key. - resolved = online_config.resolve_quant_method_cls( - LinearBase, f"{prefix}.down_proj" - ) - if resolved is None: - return None - from vllm.model_executor.layers.quantization.online.base import ( - ONLINE_SHARED_EXPERT_QUANTIZERS, - ) - - return ONLINE_SHARED_EXPERT_QUANTIZERS[resolved[3].weight] - @overload def weight_loader( self, @@ -737,34 +734,18 @@ def weight_loader( return False if return_success else None # Hereafter, `expert_id` is local physical id - # A full-precision fused shared expert is quantized into the checkpoint - # layout, then loaded like a pre-quantized expert weight and scale. - if ( - self._fused_shared_expert_quantizer is not None - and self.moe_config.num_logical_experts - <= global_expert_id - < self.moe_config.num_logical_experts - + self.expert_map_manager.num_fused_shared_experts - and weight_name.endswith("_weight") - and loaded_weight.is_floating_point() - and loaded_weight.dtype != param.dtype - ): - weight, weight_scale = self._fused_shared_expert_quantizer( - loaded_weight.to(self.moe_config.device) - ) - stem = "w2" if shard_id == "w2" else "w13" - self.weight_loader( - getattr(self, f"{stem}_weight_scale"), - weight_scale, - f"{weight_name}_scale", + if self.shared_expert_online_loader is not None: + param, expert_id, loaded = self.shared_expert_online_loader.load( + self, + param, + loaded_weight, + weight_name, shard_id, global_expert_id, - return_success=True, - ) - loaded = self.weight_loader( - param, weight, weight_name, shard_id, global_expert_id, True + expert_id, ) - return loaded if return_success else None + if loaded is not None: + return loaded if return_success else None # is_transposed: if the dim to shard the weight # should be flipped. Required by GPTQ/AWQ (K-first format). @@ -1042,6 +1023,10 @@ def load_weights( ) weight_name = qual_name.replace(weight_name, param_name) param_name = weight_name.removeprefix(f"{self.layer_name}.") + if self.shared_expert_online_loader is not None: + param_name = self.shared_expert_online_loader.redirect_param_name( + param_name, shard_id, expert_id + ) param = getattr(self, param_name, None) if param is None: if param_name.endswith(("w13_bias", "w2_bias")): @@ -1147,7 +1132,7 @@ def make_expert_params_mapping( has_base_layer = any(".base_layer." in n for n, _ in model.named_parameters()) prefix = "base_layer." if has_base_layer else "" # These loaders index ``params_dict[full_name]``, so both sides get it. - return RoutedExperts.build_expert_params_mapping( + mapping = RoutedExperts.build_expert_params_mapping( ckpt_gate_proj_name, ckpt_down_proj_name, ckpt_up_proj_name, @@ -1158,6 +1143,14 @@ def make_expert_params_mapping( lora_base_layer_prefix_on_param_name=prefix, ) + # All MoE layers of a model share the same FSE and quantization setup. + routed_experts = next( + (m for m in model.modules() if isinstance(m, RoutedExperts)), None + ) + if routed_experts is None or routed_experts.shared_expert_online_loader is None: + return mapping + return routed_experts.shared_expert_online_loader.redirect_mapping(mapping) + @staticmethod def build_expert_params_mapping( ckpt_gate_proj_name: str, diff --git a/vllm/model_executor/layers/fused_moe/utils.py b/vllm/model_executor/layers/fused_moe/utils.py index 27df12668584..bb3f25d3e99b 100644 --- a/vllm/model_executor/layers/fused_moe/utils.py +++ b/vllm/model_executor/layers/fused_moe/utils.py @@ -75,17 +75,24 @@ def resolve_layer_fused_shared_expert( """ # NOTE: is_fusion_moe_shared_experts_enabled is decorated with @if_aiter_supported # that returns None if AITER is not available. - fse_requested = bool(rocm_aiter_ops.is_fusion_moe_shared_experts_enabled()) - fse_compatible, fse_reason = ( - is_shared_expert_quant_fse_compatible( + aiter_enabled = bool(rocm_aiter_ops.is_fusion_moe_shared_experts_enabled()) + fse_requested = aiter_enabled or envs.VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS + if not fse_requested: + fse_compatible, fse_reason = True, None + elif not aiter_enabled: + fse_compatible = False + fse_reason = ( + "AITER fused MoE is not enabled, which requires VLLM_ROCM_USE_AITER=1 " + f"(currently {envs.VLLM_ROCM_USE_AITER}) and " + f"VLLM_ROCM_USE_AITER_MOE=1 (currently {envs.VLLM_ROCM_USE_AITER_MOE})" + ) + else: + fse_compatible, fse_reason = is_shared_expert_quant_fse_compatible( quant_config, f"{prefix}.experts", f"{prefix}.{shared_expert_name}", moe_backend=moe_backend, ) - if fse_requested - else (True, None) - ) is_fused_shared_expert_enabled = fse_requested and fse_compatible # In online shared_expert quantization is used, register it to @@ -122,7 +129,7 @@ def resolve_layer_fused_shared_expert( target_pattern, ) if fse_requested and not is_fused_shared_expert_enabled: - logger.warning( + logger.warning_once( "VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS is enabled but " "cannot be enabled - skipping for this layer: %s.", fse_reason, @@ -164,7 +171,14 @@ def get_moe_layer(layer: nn.Module) -> nn.Module | None: "Per-layer fused shared experts is not yet supported. Please open " "an issue." ) - return enabled_count > 0 and disabled_count == 0 + is_enabled = enabled_count > 0 and disabled_count == 0 + if is_enabled: + logger.info_once( + "Fused shared experts enabled for all %d MoE layers of %s.", + enabled_count, + moe_cls.__name__, + ) + return is_enabled @triton.jit diff --git a/vllm/model_executor/layers/quantization/base_config.py b/vllm/model_executor/layers/quantization/base_config.py index 5bc1e42aa5da..0c289519bb2b 100644 --- a/vllm/model_executor/layers/quantization/base_config.py +++ b/vllm/model_executor/layers/quantization/base_config.py @@ -3,6 +3,8 @@ import inspect from abc import ABC, abstractmethod +from collections.abc import Iterator +from contextlib import nullcontext from typing import TYPE_CHECKING, Any import regex as re @@ -86,8 +88,16 @@ def process_weights_after_loading(self, layer: nn.Module) -> None: def dequantize_weight( self, layer: nn.Module - ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: - """Materialize a serialized quantized weight for requantization.""" + ) -> torch.Tensor | Iterator[tuple[slice, torch.Tensor, torch.Tensor]]: + """Materialize a serialized quantized weight for requantization. + + Args: + layer: Layer holding the serialized weights. + + Returns: + The dequantized weight for linear layers. For MoE layers, an + iterator of ``(experts, w13, w2)`` over groups of experts. + """ raise NotImplementedError( f"The quantization method {type(self)} does not implement " "dequantize_weight, so re-quantization from this checkpoint is " @@ -308,26 +318,37 @@ def resolve_quant_method( from vllm.model_executor.layers.quantization.online.moe_base import ( OnlineMoEMethodBase, ) + from vllm.model_executor.layers.quantization.online.requantization import ( + requantization_source_scope, + ) - base_quant_method = quant_config.get_quant_method(layer, prefix) - if quant_config.online_quantization_config is None: - # No online configuration: retain the checkpoint method. - return base_quant_method + online_config = quant_config.online_quantization_config # Online quantization currently supports only LinearBase and RoutedExperts. # Embeddings and ParallelLMHead retain their checkpoint quantization method. - if not isinstance(layer, (LinearBase, RoutedExperts)): + is_online_supported_layer = isinstance(layer, (LinearBase, RoutedExperts)) + + online_target = None + if online_config is not None and is_online_supported_layer: + online_config.packed_modules_mapping = quant_config.packed_modules_mapping + online_target = online_config.resolve_quant_method_cls(type(layer), prefix) + + # The checkpoint method of requantized experts is only a dequantization source. + with ( + requantization_source_scope() + if online_target is not None and isinstance(layer, RoutedExperts) + else nullcontext() + ): + base_quant_method = quant_config.get_quant_method(layer, prefix) + if online_config is None: + # No online configuration: retain the checkpoint method. + return base_quant_method + if not is_online_supported_layer: # Online quantization only supports linear and routed MoE layers. return base_quant_method - quant_config.online_quantization_config.packed_modules_mapping = ( - quant_config.packed_modules_mapping - ) checkpoint_is_quantized = base_quant_method is not None and not isinstance( base_quant_method, (UnquantizedLinearMethod, UnquantizedFusedMoEMethod) ) - online_target = quant_config.online_quantization_config.resolve_quant_method_cls( - type(layer), prefix - ) if checkpoint_is_quantized: if online_target is None: diff --git a/vllm/model_executor/layers/quantization/compressed_tensors/compressed_tensors_moe/compressed_tensors_moe_w4a4_nvfp4.py b/vllm/model_executor/layers/quantization/compressed_tensors/compressed_tensors_moe/compressed_tensors_moe_w4a4_nvfp4.py index e7fc3f1df365..a08f59dc05f5 100644 --- a/vllm/model_executor/layers/quantization/compressed_tensors/compressed_tensors_moe/compressed_tensors_moe_w4a4_nvfp4.py +++ b/vllm/model_executor/layers/quantization/compressed_tensors/compressed_tensors_moe/compressed_tensors_moe_w4a4_nvfp4.py @@ -1,6 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project +from collections.abc import Iterator import torch @@ -26,10 +27,15 @@ from vllm.model_executor.layers.quantization.compressed_tensors.compressed_tensors_moe import ( # noqa E501 CompressedTensorsMoEMethod, ) +from vllm.model_executor.layers.quantization.utils.flashinfer_utils import ( + trtllm_nvfp4_hidden_alignment, +) from vllm.model_executor.layers.quantization.utils.nvfp4_emulation_utils import ( dequantize_nvfp4_moe_weights, ) from vllm.model_executor.layers.quantization.utils.quant_utils import ( + QuantKey, + is_dynamic_per_token_outer_scale, kNvfp4Dynamic, kNvfp4Static, ) @@ -54,16 +60,24 @@ def __init__( moe: FusedMoEConfig, layer_name: str | None = None, use_a16: bool = False, + activation_key: QuantKey = kNvfp4Dynamic, ): super().__init__(moe) self.group_size = 16 self.use_a16 = use_a16 + # FC1 input scheme; a per-token one (``kNvfp4DynamicToken``) replaces + # the checkpoint's static input scales. Only the backends that quantize + # the input themselves accept it, so selection enforces the invariant. + self.activation_key: QuantKey | None = None if use_a16 else activation_key + self.per_token_activation = is_dynamic_per_token_outer_scale( + self.activation_key + ) # Select experts implementation. self.nvfp4_backend, self.experts_cls = select_nvfp4_moe_backend( config=self.moe, weight_key=kNvfp4Static, - activation_key=None if use_a16 else kNvfp4Dynamic, + activation_key=self.activation_key, ) self.use_global_sf = is_global_sf_supported_for_nvfp4_backend( self.nvfp4_backend @@ -190,8 +204,8 @@ def create_weights( def dequantize_weight( self, layer: torch.nn.Module - ) -> tuple[torch.Tensor, torch.Tensor]: - """Materialize serialized NVFP4 expert weights for requantization.""" + ) -> Iterator[tuple[slice, torch.Tensor, torch.Tensor]]: + """Yield ``(experts, w13, w2)`` dequantized NVFP4 experts.""" return dequantize_nvfp4_moe_weights( layer.w13_weight_packed, layer.w13_weight_scale, @@ -230,6 +244,14 @@ def process_weights_after_loading(self, layer: RoutedExperts) -> None: ) w13_weight_global_scale = layer.w13_weight_global_scale[:, 0].contiguous() + a13_scale = 1.0 / layer.w13_input_global_scale + a2_scale = 1.0 / layer.w2_input_global_scale + if self.per_token_activation: + # Per-token scales cover the FC1 input, and the per-token kernel + # requantizes the FC2 input per token: static scales are neutral. + a13_scale = torch.ones_like(a13_scale) + a2_scale = torch.ones_like(a2_scale) + # Shuffle weights into the NvFp4 kernel format. ( w13, @@ -246,13 +268,17 @@ def process_weights_after_loading(self, layer: RoutedExperts) -> None: w13=layer.w13_weight, w13_scale=layer.w13_weight_scale, w13_scale_2=(1.0 / w13_weight_global_scale), - a13_scale=(1.0 / layer.w13_input_global_scale), + a13_scale=a13_scale, w2=layer.w2_weight, w2_scale=layer.w2_weight_scale, w2_scale_2=(1.0 / layer.w2_weight_global_scale), - a2_scale=(1.0 / layer.w2_input_global_scale), + a2_scale=a2_scale, is_act_and_mul=self.moe.is_act_and_mul, use_a16=self.use_a16, + trtllm_hidden_alignment=trtllm_nvfp4_hidden_alignment( + per_token_activation=self.per_token_activation, + is_act_and_mul=self.moe.is_act_and_mul, + ), ) replace_parameter(layer, "w13_weight", w13) @@ -273,6 +299,7 @@ def process_weights_after_loading(self, layer: RoutedExperts) -> None: experts_cls=self.experts_cls, backend=self.nvfp4_backend, routing_tables=layer._expert_routing_tables(), + per_token_activation=self.per_token_activation, ) self.moe_kernel.fused_experts.process_weights_after_loading(layer) diff --git a/vllm/model_executor/layers/quantization/modelopt.py b/vllm/model_executor/layers/quantization/modelopt.py index 29db26053521..409240effdd5 100644 --- a/vllm/model_executor/layers/quantization/modelopt.py +++ b/vllm/model_executor/layers/quantization/modelopt.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project -from collections.abc import Callable +from collections.abc import Callable, Iterator from dataclasses import dataclass from enum import Enum from fnmatch import fnmatch @@ -895,8 +895,8 @@ def uses_weight_scale_2_pattern(self) -> bool: def dequantize_weight( self, layer: torch.nn.Module - ) -> tuple[torch.Tensor, torch.Tensor]: - """Materialize serialized ModelOpt NVFP4 expert weights.""" + ) -> Iterator[tuple[slice, torch.Tensor, torch.Tensor]]: + """Yield ``(experts, w13, w2)`` dequantized ModelOpt NVFP4 experts.""" return dequantize_nvfp4_moe_weights( layer.w13_weight, layer.w13_weight_scale, @@ -1208,10 +1208,14 @@ def __init__( is_checkpoint_mxfp8_serialized: bool, kv_cache_quant_algo: str | None, exclude_modules: list[str], + moe_quant_algo: str | None = None, ) -> None: super().__init__(exclude_modules) self.quant_method = "MXFP8" self.is_checkpoint_mxfp8_serialized = is_checkpoint_mxfp8_serialized + # MiniMax-M3.1 checkpoints keep MXFP8 linears but store routed experts + # as compressed-tensors NVFP4 (`moe_quant_algo: NVFP4`). + self.moe_quant_algo = moe_quant_algo if not is_checkpoint_mxfp8_serialized: raise ValueError( @@ -1247,12 +1251,25 @@ def from_config(cls, config: dict[str, Any]) -> "ModelOptMxFp8Config": # (same on-disk format as ModelOpt MXFP8); normalize to the ModelOpt # schema and reuse the shared parser. if "quantization" not in config and not config.get("quant_algo"): + moe_quant_algo = (config.get("moe_quant_algo") or "").upper() or None + if moe_quant_algo is not None and ( + moe_quant_algo != "NVFP4" + or config.get("moe_quant_format") != "nvfp4-pack-quantized" + or config.get("group_size") != 16 + ): + raise ValueError( + "Unsupported MXFP8 checkpoint MoE quantization: " + f"moe_quant_algo={config.get('moe_quant_algo')!r}, " + f"moe_quant_format={config.get('moe_quant_format')!r}, " + f"group_size={config.get('group_size')!r}." + ) config = { "quant_method": "modelopt", "quantization": { "quant_algo": "MXFP8", "kv_cache_quant_algo": config.get("kv_cache_quant_algo"), "exclude_modules": config.get("ignored_layers", []) or [], + "moe_quant_algo": moe_quant_algo, }, } return cast("ModelOptMxFp8Config", super().from_config(config)) @@ -1286,8 +1303,41 @@ def _from_config( is_checkpoint_mxfp8_serialized, kv_cache_quant_method, exclude_modules, + moe_quant_algo=original_config.get("quantization", {}).get( + "moe_quant_algo" + ), ) + def routed_expert_weight_key(self) -> QuantKey: + """The weight format the routed experts are stored in. + + MXFP8, or NVFP4 (``moe_quant_algo: NVFP4``). + """ + if self.moe_quant_algo != "NVFP4": + return kMxfp8Static + return kNvfp4Static + + def get_quant_method( + self, layer: torch.nn.Module, prefix: str + ) -> "QuantizeMethodBase | None": + if ( + self.moe_quant_algo == "NVFP4" + and isinstance(layer, RoutedExperts) + and not self.is_layer_excluded(prefix) + ): + from vllm.model_executor.layers.quantization.compressed_tensors.compressed_tensors_moe.compressed_tensors_moe_w4a4_nvfp4 import ( # noqa: E501 + CompressedTensorsW4A4Nvfp4MoEMethod, + ) + + # Nothing in the checkpoint says how its FC1 input was + # quantized during QAT, so the model declares it. + return CompressedTensorsW4A4Nvfp4MoEMethod( + layer.moe_config, + layer_name=prefix, + activation_key=(layer.moe_config.qat_activation_key or kNvfp4Dynamic), + ) + return super().get_quant_method(layer, prefix) + class ModelOptMxFp8FusedMoE(FusedMoEMethodBase): """FlashInfer TRTLLM MXFP8 block-scale MoE for ModelOpt checkpoints.""" diff --git a/vllm/model_executor/layers/quantization/online/base.py b/vllm/model_executor/layers/quantization/online/base.py index 511714837faa..9ac99e6c04f7 100644 --- a/vllm/model_executor/layers/quantization/online/base.py +++ b/vllm/model_executor/layers/quantization/online/base.py @@ -61,6 +61,9 @@ get_layer_name_after_index, ) from vllm.model_executor.layers.quantization.utils.mxfp4_utils import mxfp4_quantize +from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( + dequant_mxfp8_to_bf16, +) from vllm.model_executor.layers.quantization.utils.quant_utils import ( QuantKey, kFp8Static128BlockSym, @@ -70,6 +73,7 @@ kInt8StaticChannelSym, kMxfp4Static, kMxfp8Dynamic, + kMxfp8Static, kNvfp4Static, ) @@ -114,6 +118,14 @@ class OnlineQuantizationSource(str, Enum): kMxfp4Static: mxfp4_quantize, } +# Dequantizers `(weight, weight_scale) -> high precision weight` of quantized fused +# shared-expert checkpoint weights, keyed by the checkpoint weight QuantKey. +ONLINE_SHARED_EXPERT_DEQUANTIZERS: dict[ + QuantKey, Callable[[torch.Tensor, torch.Tensor], torch.Tensor] +] = { + kMxfp8Static: dequant_mxfp8_to_bf16, +} + def _find_matching_targets( prefix: str, diff --git a/vllm/model_executor/layers/quantization/online/fp8.py b/vllm/model_executor/layers/quantization/online/fp8.py index f4a327192108..c636403fd458 100644 --- a/vllm/model_executor/layers/quantization/online/fp8.py +++ b/vllm/model_executor/layers/quantization/online/fp8.py @@ -817,26 +817,43 @@ def process_weights_after_loading(self, layer: Module) -> None: fp8_dtype = current_platform.fp8_dtype() w13 = torch.empty_like(w13_weight, dtype=fp8_dtype) w2 = torch.empty_like(w2_weight, dtype=fp8_dtype) - # Scale's leading dim is taken from the fp8 weight tensor by - # construction, so it cannot drift from the weight's expert count - # under EP / padded MoE. - n_w13 = w13_weight.shape[1] - w13_scale = torch.ones( - w13.shape[0], n_w13, 1, device=w13.device, dtype=torch.float32 - ) layer.w13_input_scale = None layer.w2_input_scale = None + use_torch_w13_quant = False + if current_platform.is_rocm(): + from vllm.platforms.rocm import on_gfx942 + + use_torch_w13_quant = on_gfx942() + + if use_torch_w13_quant: + # dynamic_per_token_scaled_fp8_quant can hard-crash on gfx942. + w13_amax = weight_amax(w13_weight, dim=-1, keepdim=True) + w13_scale = _fp8_channel_scale(w13_amax) + else: + # Scale's leading dim is taken from the fp8 weight tensor by + # construction, so it cannot drift from the weight's expert count + # under EP / padded MoE. + n_w13 = w13_weight.shape[1] + w13_scale = torch.ones( + w13.shape[0], n_w13, 1, device=w13.device, dtype=torch.float32 + ) + w2_amax = weight_amax(w2_weight, dim=-1, keepdim=True) w2_amax = amax_for_moe_weight_quant(w2_amax, self.moe.tp_size) w2_scale = _fp8_channel_scale(w2_amax) for expert in range(layer.local_num_experts): - w13[expert], w13_scale[expert] = ops.scaled_fp8_quant( - w13_weight[expert], - scale=None, - use_per_token_if_dynamic=True, - ) + if use_torch_w13_quant: + w13[expert] = _fp8_quant_per_channel( + w13_weight[expert], w13_scale[expert] + ) + else: + w13[expert], w13_scale[expert] = ops.scaled_fp8_quant( + w13_weight[expert], + scale=None, + use_per_token_if_dynamic=True, + ) w2[expert] = _fp8_quant_per_channel(w2_weight[expert], w2_scale[expert]) self._setup_kernel( diff --git a/vllm/model_executor/layers/quantization/online/moe_base.py b/vllm/model_executor/layers/quantization/online/moe_base.py index eb175ebd33d8..e691f64cafc8 100644 --- a/vllm/model_executor/layers/quantization/online/moe_base.py +++ b/vllm/model_executor/layers/quantization/online/moe_base.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from abc import abstractmethod +from collections.abc import Callable, Iterator import torch @@ -46,14 +47,17 @@ def create_weights( layer.weight_block_size = None if self.requantization_source is not None: + # In case FSE is used, shared experts slots are initialized on RoutedExperts + # online quant method, the source only holds the routed experts. self.create_requantization_source_weights( layer, - num_experts, + num_experts - layer.expert_map_manager.num_fused_shared_experts, layer.moe_config.hidden_dim_unpadded, layer.moe_config.intermediate_size_per_partition_unpadded, params_dtype, **extra_weight_attrs, ) + layer.num_experts = num_experts return # Fused gate_up_proj (column parallel) — full precision on meta device @@ -118,22 +122,95 @@ def create_weights( def get_weights_for_quantization( self, layer: torch.nn.Module ) -> tuple[torch.Tensor, torch.Tensor]: + """Return the high precision ``(w13, w2)`` of all local experts.""" if self.requantization_source is None: return layer.w13_weight, layer.w2_weight + w13, w2 = self.quantize_weights(layer, lambda w13, w2: (w13, w2)) + return w13, w2 + + def iter_weights_for_quantization( + self, layer: torch.nn.Module + ) -> Iterator[tuple[slice, torch.Tensor, torch.Tensor]]: + """Yield ``(experts, w13, w2)`` for groups of experts to quantize. + + The source dequantizes in chunks to bound staging memory. Without a source, + all routed experts are yielded at once. Fused shared experts come last. + """ + num_shared = layer.expert_map_manager.num_fused_shared_experts + num_routed = layer.local_num_experts - num_shared + + source = self.requantization_source + if source is None: + # These include the fused shared experts slots, never staged here. + yield slice(0, num_routed), layer.w13_weight, layer.w2_weight + else: + chunks = source.dequantize_weight(layer) + if isinstance(chunks, torch.Tensor): + raise TypeError("MoE requantization requires w13 and w2 weights.") + for experts, w13, w2 in chunks: + yield ( + experts, + *self._pad_requantized_weights( + layer, w13, w2, experts.stop - experts.start + ), + ) + + if num_shared > 0: + loader = layer.shared_expert_online_loader + shared_w13, shared_w2 = loader.dequantize_staging(layer) + loader.release_staging(layer) + yield ( + slice(num_routed, num_routed + num_shared), + *self._pad_requantized_weights( + layer, + shared_w13.to(layer.orig_dtype), + shared_w2.to(layer.orig_dtype), + num_shared, + ), + ) + + def quantize_weights( + self, + layer: torch.nn.Module, + quantize: Callable[[torch.Tensor, torch.Tensor], tuple[torch.Tensor, ...]], + ) -> tuple[torch.Tensor, ...]: + """Quantize the layer's weights one group of experts at a time. - weights = self.requantization_source.dequantize_weight(layer) - if not isinstance(weights, tuple): - raise TypeError("MoE requantization requires w13 and w2 weight tensors.") + Args: + layer: Layer to quantize. + quantize: Maps ``(w13, w2)`` of a group of experts to tensors, e.g. + ``(w13, w13_scale, w2, w2_scale)``. - w13, w2 = weights + Returns: + The ``quantize`` outputs for all local experts. + """ + num_experts = layer.local_num_experts + outputs: list[torch.Tensor] | None = None + for experts, w13, w2 in self.iter_weights_for_quantization(layer): + quantized = quantize(w13, w2) + if outputs is None: + if w13.shape[0] == num_experts: + return quantized + outputs = [t.new_empty((num_experts, *t.shape[1:])) for t in quantized] + for output, tensor in zip(outputs, quantized): + output[experts] = tensor + assert outputs is not None + return tuple(outputs) + + def _pad_requantized_weights( + self, + layer: torch.nn.Module, + w13: torch.Tensor, + w2: torch.Tensor, + num_experts: int, + ) -> tuple[torch.Tensor, torch.Tensor]: config = layer.moe_config hidden_size = config.hidden_dim_unpadded intermediate_size = config.intermediate_size_per_partition_unpadded target_hidden_size = config.hidden_dim target_intermediate_size = config.intermediate_size_per_partition - num_experts = layer.local_num_experts num_shards = self.moe.w13_num_shards if w13.shape != (num_experts, num_shards * intermediate_size, hidden_size): diff --git a/vllm/model_executor/layers/quantization/online/mxfp4.py b/vllm/model_executor/layers/quantization/online/mxfp4.py index 70a64340f694..655fa5276518 100644 --- a/vllm/model_executor/layers/quantization/online/mxfp4.py +++ b/vllm/model_executor/layers/quantization/online/mxfp4.py @@ -296,18 +296,23 @@ def process_weights_after_loading(self, layer: Module) -> None: if getattr(layer, "_already_called_process_weights_after_loading", False): return - w13_weight, w2_weight = self.get_weights_for_quantization(layer) - self._zero_padding(layer, w13_weight, w2_weight) - if self.mxfp4_backend == Mxfp4MoeBackend.NONE: + w13_weight, w2_weight = self.get_weights_for_quantization(layer) + self._zero_padding(layer, w13_weight, w2_weight) layer._already_called_process_weights_after_loading = True return layer.w13_input_scale = None layer.w2_input_scale = None - w13, w13_scale = _quantize_mxfp4_moe_weight(w13_weight) - w2, w2_scale = _quantize_mxfp4_moe_weight(w2_weight) + def quantize(w13_weight: torch.Tensor, w2_weight: torch.Tensor): + self._zero_padding(layer, w13_weight, w2_weight) + return ( + *_quantize_mxfp4_moe_weight(w13_weight), + *_quantize_mxfp4_moe_weight(w2_weight), + ) + + w13, w13_scale, w2, w2_scale = self.quantize_weights(layer, quantize) self._setup_kernel( layer, diff --git a/vllm/model_executor/layers/quantization/online/mxfp8.py b/vllm/model_executor/layers/quantization/online/mxfp8.py index f16f2b9fbf24..d405e76c2cde 100644 --- a/vllm/model_executor/layers/quantization/online/mxfp8.py +++ b/vllm/model_executor/layers/quantization/online/mxfp8.py @@ -237,12 +237,16 @@ def process_weights_after_loading(self, layer: Module) -> None: if getattr(layer, "_already_called_process_weights_after_loading", False): return - w13_weight, w2_weight = self.get_weights_for_quantization(layer) layer.w13_input_scale = None layer.w2_input_scale = None - w13, w13_scale = self._quantize_mxfp8_moe_weight(w13_weight) - w2, w2_scale = self._quantize_mxfp8_moe_weight(w2_weight) + def quantize(w13_weight: torch.Tensor, w2_weight: torch.Tensor): + return ( + *self._quantize_mxfp8_moe_weight(w13_weight), + *self._quantize_mxfp8_moe_weight(w2_weight), + ) + + w13, w13_scale, w2, w2_scale = self.quantize_weights(layer, quantize) self._setup_kernel( layer, diff --git a/vllm/model_executor/layers/quantization/online/requantization.py b/vllm/model_executor/layers/quantization/online/requantization.py index 01260342178b..72fb0a2718b6 100644 --- a/vllm/model_executor/layers/quantization/online/requantization.py +++ b/vllm/model_executor/layers/quantization/online/requantization.py @@ -1,10 +1,35 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project +from collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar + import torch from vllm.model_executor.layers.quantization.base_config import QuantizeMethodBase +_requantization_source: ContextVar[bool] = ContextVar( + "requantization_source", default=False +) + + +@contextmanager +def requantization_source_scope() -> Iterator[None]: + """Mark quantization methods created in this scope as requantization sources. + + Their weights are only dequantized, so oracles can skip backend selection. + """ + token = _requantization_source.set(True) + try: + yield + finally: + _requantization_source.reset(token) + + +def is_requantization_source() -> bool: + return _requantization_source.get() + class OnlineRequantizationMixin: """Shared lifecycle for converting serialized weights before quantization.""" diff --git a/vllm/model_executor/layers/quantization/online/shared_expert.py b/vllm/model_executor/layers/quantization/online/shared_expert.py new file mode 100644 index 000000000000..b23a7b693802 --- /dev/null +++ b/vllm/model_executor/layers/quantization/online/shared_expert.py @@ -0,0 +1,340 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from collections.abc import Callable +from typing import Any + +import torch + +from vllm.model_executor.layers.fused_moe import FusedMoeWeightScaleSupported +from vllm.model_executor.layers.linear import LinearBase +from vllm.model_executor.layers.quantization.online.requantization import ( + OnlineRequantizationMixin, +) +from vllm.model_executor.layers.quantization.utils.config_utils import ( + get_checkpoint_quant_keys, +) +from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( + MXFP8_BLOCK_SIZE, + MXFP8_SCALE_DTYPE, + MXFP8_VALUE_DTYPE, +) +from vllm.model_executor.layers.quantization.utils.quant_utils import ( + QuantKey, + kMxfp8Static, +) +from vllm.model_executor.utils import set_weight_attrs + +SharedExpertQuantizer = Callable[[torch.Tensor], tuple[torch.Tensor, torch.Tensor]] + + +def _param_stem(shard_id: str) -> str: + return "w2" if shard_id == "w2" else "w13" + + +class OnlineSharedExpertLoader: + """Loads the fused shared experts (FSE) of a ``RoutedExperts`` layer with online + quantization. + + - Staged shared experts: the shared experts are loaded as stored in temporary + slots (``online_w{13,2}_weight[_scale]``), dequantized after loading, and + quantized into the routed experts slots: with the routed experts when they + are requantized, else by ``finalize``. + - Unquantized shared experts with pre-quantized routed experts: the shared + experts are quantized on arrival by ``quantizer``, and loaded in the routed + experts slots. + """ + + def __init__( + self, + quant_config, + online_config, + quant_method: Any, + shared_expert_prefix: str | None, + num_logical_experts: int, + num_fused_shared_experts: int, + ): + self.shared_expert_prefix = shared_expert_prefix + self.num_logical_experts = num_logical_experts + self.num_fused_shared_experts = num_fused_shared_experts + # The routed experts are requantized online from their checkpoint format. + self.routed_requantized = ( + isinstance(quant_method, OnlineRequantizationMixin) + and quant_method.requantization_source is not None + ) + # Requantized routed experts quantize the staged shared experts with them. + self.stages_shared_experts = self.routed_requantized + self.quantizer: SharedExpertQuantizer | None = None + target_key = self._get_shared_target_key(online_config) + # Format the shared experts are stored in (None: unquantized). FSE + # compatibility checks require every projection to share it. + self.stored_key: QuantKey | None = None + if self.routed_requantized or target_key is not None: + self.stored_key = get_checkpoint_quant_keys( + quant_config, f"{shared_expert_prefix}.down_proj", LinearBase + )[0] + if not self.routed_requantized and target_key is not None: + if self.stored_key != target_key: + from vllm.model_executor.layers.quantization.online.base import ( + ONLINE_SHARED_EXPERT_QUANTIZERS, + ) + + if target_key not in ONLINE_SHARED_EXPERT_QUANTIZERS: + raise NotImplementedError( + "Online quantization of fused shared experts is not " + f"supported for weight key {target_key}. Disable FSE or " + "open an issue." + ) + self.quantizer = ONLINE_SHARED_EXPERT_QUANTIZERS[target_key] + # Quantized shared experts are staged, as their weight and scale + # are needed together to be dequantized. + self.stages_shared_experts = self.stored_key is not None + from vllm.model_executor.layers.quantization.online.moe_base import ( + OnlineMoEMethodBase, + ) + + if self.stages_shared_experts and isinstance( + quant_method, OnlineMoEMethodBase + ): + # `finalize` writes into pre-quantized routed experts slots. + raise NotImplementedError( + "Fused shared experts stored quantized are not supported " + "with routed experts quantized online from high " + "precision. Disable FSE or open an issue." + ) + self.staging_parameters: dict[str, torch.nn.Parameter] = {} + + def _get_shared_target_key(self, online_config) -> QuantKey | None: + if self.shared_expert_prefix is None: + return None + # FSE compatibility checks require every shared-expert projection to + # use the routed experts' weight key. + resolved = online_config.resolve_quant_method_cls( + LinearBase, f"{self.shared_expert_prefix}.down_proj" + ) + return None if resolved is None else resolved[3].weight + + def create_staging( + self, + layer: torch.nn.Module, + params_dtype: torch.dtype, + **extra_weight_attrs, + ) -> None: + """Create parameters holding the fused shared experts as stored. + + The checkpoint shared experts are loaded as stored into + ``online_w{13,2}_weight`` (plus ``online_w{13,2}_weight_scale`` for + quantized shared experts), which are separate from the routed experts' + parameters. They are dequantized by ``dequantize_staging``. + """ + from vllm.model_executor.layers.quantization.online.base import ( + ONLINE_SHARED_EXPERT_DEQUANTIZERS, + ) + + moe_config = layer.moe_config + hidden_size = moe_config.hidden_dim_unpadded + intermediate_size = moe_config.intermediate_size_per_partition_unpadded + checkpoint_key = self.stored_key + if ( + checkpoint_key is not None + and checkpoint_key not in ONLINE_SHARED_EXPERT_DEQUANTIZERS + ): + raise NotImplementedError( + "Fused shared experts (FSE) with online quantization only support " + "shared experts stored unquantized or as " + f"{list(ONLINE_SHARED_EXPERT_DEQUANTIZERS)}, got {checkpoint_key}. " + "Disable FSE or open an issue." + ) + # NOTE: The staging layout is MXFP8's, the only quantized format in + # ONLINE_SHARED_EXPERT_DEQUANTIZERS. + is_mxfp8 = checkpoint_key == kMxfp8Static + if is_mxfp8 and ( + hidden_size % MXFP8_BLOCK_SIZE or intermediate_size % MXFP8_BLOCK_SIZE + ): + raise ValueError( + "MXFP8 shared experts require hidden/intermediate sizes " + f"divisible by {MXFP8_BLOCK_SIZE}." + ) + + def register(name: str, shape: tuple[int, ...], dtype: torch.dtype, **attrs): + param = torch.nn.Parameter( + torch.empty(shape, dtype=dtype), requires_grad=False + ) + layer.register_parameter(name, param) + set_weight_attrs(param, extra_weight_attrs | attrs) + self.staging_parameters[name] = param + + w13_rows = moe_config.w13_num_shards * intermediate_size + for stem, rows, cols in ( + ("w13", w13_rows, hidden_size), + ("w2", hidden_size, intermediate_size), + ): + shape = (self.num_fused_shared_experts, rows) + weight_dtype = MXFP8_VALUE_DTYPE if is_mxfp8 else params_dtype + register(f"online_{stem}_weight", (*shape, cols), weight_dtype) + if is_mxfp8: + register( + f"online_{stem}_weight_scale", + (*shape, cols // MXFP8_BLOCK_SIZE), + MXFP8_SCALE_DTYPE, + quant_method=FusedMoeWeightScaleSupported.GROUP.value, + ) + + def dequantize_staging( + self, layer: torch.nn.Module + ) -> tuple[torch.Tensor, torch.Tensor]: + """Return the staged ``(w13, w2)`` shared experts, dequantized if needed.""" + w13 = layer.online_w13_weight.data + w2 = layer.online_w2_weight.data + if self.stored_key is not None: + from vllm.model_executor.layers.quantization.online.base import ( + ONLINE_SHARED_EXPERT_DEQUANTIZERS, + ) + + dequantize = ONLINE_SHARED_EXPERT_DEQUANTIZERS[self.stored_key] + w13 = dequantize(w13, layer.online_w13_weight_scale.data) + w2 = dequantize(w2, layer.online_w2_weight_scale.data) + return w13, w2 + + def release_staging(self, layer: torch.nn.Module) -> None: + for name, param in self.staging_parameters.items(): + if layer._parameters.get(name) is param: + delattr(layer, name) + self.staging_parameters.clear() + + def finalize(self, layer: torch.nn.Module) -> None: + """Quantize the staged shared experts into the pre-quantized routed experts + slots. To call after loading, before the routed experts' processing. + + Requantized routed experts quantize the staged shared experts themselves. + """ + if self.routed_requantized or not self.staging_parameters: + return + assert self.quantizer is not None + shared_w13, shared_w2 = self.dequantize_staging(layer) + for shared_id in range(self.num_fused_shared_experts): + expert_id = layer._map_global_expert_id_to_local_expert_id( + self.num_logical_experts + shared_id + ) + if expert_id == -1: + continue + for stem, weight in (("w13", shared_w13), ("w2", shared_w2)): + weight, weight_scale = self.quantizer(weight[shared_id]) + for name, tensor in ( + (f"{stem}_weight", weight), + (f"{stem}_weight_scale", weight_scale), + ): + rows, cols = tensor.shape + getattr(layer, name).data[expert_id, :rows, :cols].copy_(tensor) + self.release_staging(layer) + + def is_fused_shared_expert(self, global_expert_id: int) -> bool: + return ( + self.num_logical_experts + <= global_expert_id + < self.num_logical_experts + self.num_fused_shared_experts + ) + + @staticmethod + def _staging_param_name(weight_name: str, shard_id: str) -> str | None: + """Staging parameter (``online_w{13,2}_weight[_scale]``) of a shared expert + tensor. They are separate from the routed experts' parameters. None for + other tensors. + """ + stem = f"online_{_param_stem(shard_id)}" + if weight_name.endswith("_weight_scale"): + return f"{stem}_weight_scale" + if weight_name.endswith("_weight"): + return f"{stem}_weight" + return None + + def redirect_param_name( + self, param_name: str, shard_id: str, expert_id: int + ) -> str: + """Parameter name a checkpoint tensor of expert `expert_id` loads into.""" + # Once the staging is released, reloads go to `load`, which raises. + if self.staging_parameters and self.is_fused_shared_expert(expert_id): + return self._staging_param_name(param_name, shard_id) or param_name + return param_name + + def redirect_mapping( + self, mapping: list[tuple[str, str, int, str]] + ) -> list[tuple[str, str, int, str]]: + """Point the expert params mapping of the shared experts to the staging + parameters, as e.g. ``w13_`` -> ``online_w13_``.""" + if not self.staging_parameters: + return mapping + redirected = [] + for param_name, weight_name, expert_id, shard_id in mapping: + if self.is_fused_shared_expert(expert_id) and weight_name.startswith( + f"experts.{expert_id}." + ): + stem = "w2_" if param_name.endswith("w2_") else "w13_" + param_name = f"{param_name.removesuffix(stem)}online_{stem}" + redirected.append((param_name, weight_name, expert_id, shard_id)) + return redirected + + def load( + self, + layer: Any, + param: torch.nn.Parameter, + loaded_weight: torch.Tensor, + weight_name: str, + shard_id: str, + global_expert_id: int, + expert_id: int, + ) -> tuple[torch.nn.Parameter, int, bool | None]: + """Prepare the load of a fused shared expert tensor in + ``RoutedExperts.weight_loader``. + + Returns: + The parameter and local expert id to load into, and the load result if + the tensor was already loaded (None to let the caller load it). + """ + if not self.is_fused_shared_expert(global_expert_id): + return param, expert_id, None + + if self.stages_shared_experts: + if not self.staging_parameters: + # The staged shared experts were already quantized and released. + raise NotImplementedError( + "Reloading fused shared experts staged for online quantization " + "is not supported." + ) + staging_name = self._staging_param_name(weight_name, shard_id) + if staging_name is None: + raise NotImplementedError( + f"Fused shared expert tensor {weight_name!r} has no online " + "staging parameter: only *_weight and *_weight_scale are " + "supported when staging shared experts." + ) + return ( + getattr(layer, staging_name), + global_expert_id - self.num_logical_experts, + None, + ) + + # Only quantize high-precision shared expert weights, load anything else as is. + if ( + self.quantizer is None + or not weight_name.endswith("_weight") + or not loaded_weight.is_floating_point() + or loaded_weight.dtype == param.dtype + ): + return param, expert_id, None + + # Full-precision shared expert: quantize it, then load the weight and + # scale like a pre-quantized expert. + weight, weight_scale = self.quantizer(loaded_weight.to(layer.moe_config.device)) + layer.weight_loader( + getattr(layer, f"{_param_stem(shard_id)}_weight_scale"), + weight_scale, + f"{weight_name}_scale", + shard_id, + global_expert_id, + return_success=True, + ) + loaded = layer.weight_loader( + param, weight, weight_name, shard_id, global_expert_id, True + ) + return param, expert_id, loaded diff --git a/vllm/model_executor/layers/quantization/quark/quark.py b/vllm/model_executor/layers/quantization/quark/quark.py index 2951f578b001..01c1172e85ad 100644 --- a/vllm/model_executor/layers/quantization/quark/quark.py +++ b/vllm/model_executor/layers/quantization/quark/quark.py @@ -968,6 +968,23 @@ def __init__(self, quantization_config: QuarkConfig): def process_weights_after_loading(self, layer: torch.nn.Module) -> None: layer.scheme.process_weights_after_loading(layer) + def dequantize_weight(self, layer: torch.nn.Module) -> torch.Tensor: + """Reconstruct serialized weights for online requantization.""" + from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( + dequant_mxfp8_to_bf16, + ) + from vllm.model_executor.layers.quantization.utils.quant_utils import ( + kMxfp8Static, + ) + + if getattr(layer.scheme, "weight_quant_key", None) != kMxfp8Static: + raise NotImplementedError( + "Quark weight dequantization is only supported for MXFP8." + ) + return dequant_mxfp8_to_bf16( + layer.weight.contiguous(), layer.weight_scale.contiguous() + ) + def create_weights( self, layer: torch.nn.Module, diff --git a/vllm/model_executor/layers/quantization/quark/quark_moe.py b/vllm/model_executor/layers/quantization/quark/quark_moe.py index a17f7b28da87..1672c338d2dc 100644 --- a/vllm/model_executor/layers/quantization/quark/quark_moe.py +++ b/vllm/model_executor/layers/quantization/quark/quark_moe.py @@ -1,6 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project +from collections.abc import Iterator from typing import TYPE_CHECKING, Any import torch @@ -2319,8 +2320,8 @@ def create_weights( def dequantize_weight( self, layer: torch.nn.Module - ) -> tuple[torch.Tensor, torch.Tensor]: - """Dequantize Quark NVFP4 expert weights for requantization.""" + ) -> Iterator[tuple[slice, torch.Tensor, torch.Tensor]]: + """Yield ``(experts, w13, w2)`` dequantized Quark NVFP4 experts.""" return dequantize_nvfp4_moe_weights( layer.w13_weight, layer.w13_weight_scale, diff --git a/vllm/model_executor/layers/quantization/utils/config_utils.py b/vllm/model_executor/layers/quantization/utils/config_utils.py index 0c802e7af0db..f8efc6bc0cc8 100644 --- a/vllm/model_executor/layers/quantization/utils/config_utils.py +++ b/vllm/model_executor/layers/quantization/utils/config_utils.py @@ -11,7 +11,10 @@ from vllm.logger import init_logger if TYPE_CHECKING: + import torch + from vllm.model_executor.layers.quantization.base_config import QuantizationConfig + from vllm.model_executor.layers.quantization.utils.quant_utils import QuantKey logger = init_logger(__name__) @@ -56,6 +59,70 @@ def get_quark_ocp_mx_group_size( return int(group_size) if group_size is not None else None +def _get_effective_quant_keys( + quant_config: "QuantizationConfig", + prefix: str, + layer_type: "type[torch.nn.Module]", +) -> tuple["QuantKey | None", "QuantKey | None"]: + """Return the (weight, activation) keys a layer runs with: its online + quantization target if any, else its checkpoint format. ``None`` denotes an + unquantized weight, or an unknown/unquantized activation. + + Raises: + NotImplementedError: If the checkpoint format can not be determined. + """ + from vllm.model_executor.layers.linear import UnquantizedLinearMethod + + online_quant_config = quant_config.online_quantization_config + target = ( + online_quant_config.resolve_quant_method_cls(layer_type, prefix) + if online_quant_config is not None + else None + ) + if target is not None: + _, _, _, quant_spec, method_cls = target + if method_cls in (None, UnquantizedLinearMethod): + return None, None + # NOTE: The online shorthands' `QuantSpec` (`_ONLINE_SHORTHANDS` in + # quantization.py) do not define the activation key: use the method's. + return quant_spec.weight, getattr(method_cls, "activation_quant_key", None) + return get_checkpoint_quant_keys(quant_config, prefix, layer_type) + + +def get_checkpoint_quant_keys( + quant_config: "QuantizationConfig", + prefix: str, + layer_type: "type[torch.nn.Module]", +) -> tuple["QuantKey | None", "QuantKey | None"]: + """Return the (weight, activation) keys a layer is stored with in the + checkpoint. ``None`` denotes an unquantized weight, or an unknown/unquantized + activation. + + Raises: + NotImplementedError: If the checkpoint format can not be determined. + """ + from vllm.model_executor.layers.fused_moe import RoutedExperts + from vllm.model_executor.layers.quantization.modelopt import ModelOptMxFp8Config + from vllm.model_executor.layers.quantization.quark.quark import QuarkConfig + from vllm.model_executor.layers.quantization.utils.quant_utils import kMxfp8Static + + if isinstance(quant_config, QuarkConfig): + weight_key, activation_key, _ = quant_config.get_quant_method_target( + prefix, layer_type + ) + return weight_key, activation_key + if isinstance(quant_config, ModelOptMxFp8Config): + # Non-excluded linears are MXFP8. TODO: activation keys are left unknown. + if quant_config.is_layer_excluded(prefix): + return None, None + if issubclass(layer_type, RoutedExperts): + return quant_config.routed_expert_weight_key(), None + return kMxfp8Static, None + raise NotImplementedError( + f"Cannot determine the checkpoint format of {type(quant_config).__name__}." + ) + + def is_shared_expert_quant_fse_compatible( quant_config: "QuantizationConfig | None", expert_prefix: str, @@ -78,11 +145,11 @@ def is_shared_expert_quant_fse_compatible( """ from vllm.model_executor.layers.quantization.fp8 import Fp8Config from vllm.model_executor.layers.quantization.modelopt import ModelOptMxFp8Config - from vllm.model_executor.layers.quantization.online.fp8 import OnlineLinearBase from vllm.model_executor.layers.quantization.quark.quark import QuarkConfig from vllm.model_executor.layers.quantization.utils.quant_utils import ( is_layer_skipped, kMxfp4Static, + kMxfp8Static, ) from vllm.models.deepseek_v4.quant_config import DeepseekV4FP8Config from vllm.models.deepseek_v41.quant_config import ( @@ -95,93 +162,60 @@ def is_shared_expert_quant_fse_compatible( if quant_config is None: return True, None + # Re-quantization of a pre-quantized checkpoint. online_quant_config = quant_config.online_quantization_config - shared_expert_targets = None if online_quant_config is not None: + from vllm.model_executor.layers.fused_moe import RoutedExperts from vllm.model_executor.layers.linear import LinearBase online_quant_config.packed_modules_mapping = quant_config.packed_modules_mapping - shared_expert_targets = [ - online_quant_config.resolve_quant_method_cls( - LinearBase, f"{shared_expert_prefix}.{projection_name}" - ) + shared_prefixes = [ + f"{shared_expert_prefix}.{projection_name}" for projection_name in projection_names ] - if all(target is None for target in shared_expert_targets): - shared_expert_targets = None - - if shared_expert_targets is not None: - from vllm.model_executor.layers.fused_moe import RoutedExperts - from vllm.model_executor.layers.linear import UnquantizedLinearMethod - from vllm.model_executor.layers.quantization.online.base import ( - ONLINE_SHARED_EXPERT_QUANTIZERS, + is_online_quantized = any( + online_quant_config.resolve_quant_method_cls(layer_type, prefix) is not None + for layer_type, prefix in [ + (RoutedExperts, expert_prefix), + *((LinearBase, prefix) for prefix in shared_prefixes), + ] ) - - # NOTE: online shared experts quantization check is only implemented for quark - # quant method at the moment. This can be extended here for other quant methods. - # Requirement is: - # - Retrieve routed weight quant key - # - Retrieve routed activation quant key - # and ensure the online quantization set on shared expert match them. - if isinstance(quant_config, QuarkConfig): - routed_weight_key, routed_activation_key, _ = ( - quant_config.get_quant_method_target(expert_prefix, RoutedExperts) - ) - elif ( - isinstance(quant_config, (DeepseekV4FP8Config, DeepseekV41FP8Config)) - and quant_config.expert_dtype == "fp4" - and moe_backend == "aiter_mega_moe" - ): - # AITER MegaMoE quantizes the activations of every slot itself. - routed_weight_key, routed_activation_key = kMxfp4Static, None - else: - reason = ( - "online quantization FSE compatibility check is not implemented for " - f"{type(quant_config).__name__}" - ) - logger.warning_once(reason) - return False, reason - - if routed_weight_key not in ONLINE_SHARED_EXPERT_QUANTIZERS: - return ( - False, - "online shared-expert quantization is not supported for routed " - f"expert weight key {routed_weight_key}", - ) - - for shared_expert_target in shared_expert_targets: - if shared_expert_target is None: - return ( - False, - "online quantization targets only part of the shared expert at " - f"{shared_expert_prefix}", - ) - - _, _, _, shared_quant_spec, shared_method_cls = shared_expert_target - if shared_method_cls in (None, UnquantizedLinearMethod): - return ( - False, - "online quantization excludes FSE weights at " - f"{shared_expert_prefix}", - ) - assert issubclass(shared_method_cls, OnlineLinearBase) - - # NOTE: We can not rely on shared_quant_spec.activation_quant_key - # as _ONLINE_SHORTHANDS: dict[str, QuantSpec] in quantization.py - # does not define the default activation quant key. - # `online_quant_config.resolve_quant_method_cls` should return the - # activation quant key as well. Only some online methods define it - # on the class, so compare the weight key first. - if shared_quant_spec.weight != routed_weight_key or ( - moe_backend != "aiter_mega_moe" - and shared_method_cls.activation_quant_key != routed_activation_key - ): + if is_online_quantized: + # Only check that the routed and shared experts run with the same + # keys. Unsupported loading paths (e.g. the format the shared expert + # is stored in) raise NotImplementedError at weight loading. + try: + if ( + isinstance( + quant_config, (DeepseekV4FP8Config, DeepseekV41FP8Config) + ) + and quant_config.expert_dtype == "fp4" + and moe_backend == "aiter_mega_moe" + ): + routed_keys = (kMxfp4Static, None) + else: + routed_keys = _get_effective_quant_keys( + quant_config, expert_prefix, RoutedExperts + ) + shared_keys = { + _get_effective_quant_keys(quant_config, prefix, LinearBase) + for prefix in shared_prefixes + } + except NotImplementedError as e: + logger.warning_once(str(e)) + return False, str(e) + if moe_backend == "aiter_mega_moe": + # AITER MegaMoE quantizes the activations of every slot itself. + routed_keys = (routed_keys[0], None) + shared_keys = {(weight_key, None) for weight_key, _ in shared_keys} + if shared_keys != {routed_keys}: return ( False, - "online shared-expert quantization keys do not match the " - "routed expert keys", + f"shared expert (weight, activation) keys {shared_keys} at " + f"{shared_expert_prefix} do not match the routed expert keys " + f"{routed_keys}", ) - return True, None + return True, None if moe_backend == "aiter_mega_moe": return ( @@ -367,6 +401,17 @@ def is_ignored(layer_name: str) -> bool: "MXFP8 excludes routed and shared experts inconsistently at " f"{shared_expert_prefix}", ) + # The shared expert is stored as MXFP8, so it can take an expert slot + # only when the routed experts are MXFP8 too (not NVFP4-routed hybrids). + if ( + not expert_excluded + and quant_config.routed_expert_weight_key() != kMxfp8Static + ): + return ( + False, + "routed experts do not run as MXFP8 like the shared expert at " + f"{shared_expert_prefix}", + ) return True, None diff --git a/vllm/model_executor/layers/quantization/utils/mxfp8_utils.py b/vllm/model_executor/layers/quantization/utils/mxfp8_utils.py index bfcc69e4b1de..6567eeb86242 100644 --- a/vllm/model_executor/layers/quantization/utils/mxfp8_utils.py +++ b/vllm/model_executor/layers/quantization/utils/mxfp8_utils.py @@ -145,6 +145,7 @@ def _kernel( _MXFP8_QUANT_KERNEL = None +_MXFP8_M1_BLOCK_M = {2048: 4, 3072: 4, 6144: 2} def _mxfp8_e4m3_quantize_triton( @@ -163,7 +164,7 @@ def _mxfp8_e4m3_quantize_triton( scales = torch.empty( (M, K // MXFP8_BLOCK_SIZE), dtype=MXFP8_SCALE_DTYPE, device=x.device ) - BLOCK_M = 64 + BLOCK_M = _MXFP8_M1_BLOCK_M.get(K, 64) if M == 1 else 64 grid = (triton.cdiv(M, BLOCK_M), K // MXFP8_BLOCK_SIZE) _MXFP8_QUANT_KERNEL[grid]( x, @@ -180,6 +181,7 @@ def _mxfp8_e4m3_quantize_triton( BLOCK_M=BLOCK_M, FP8_MAX=float(torch.finfo(MXFP8_VALUE_DTYPE).max), TINY=float(torch.finfo(torch.float32).tiny), + num_warps=4, ) return xq, scales diff --git a/vllm/model_executor/layers/quantization/utils/nvfp4_emulation_utils.py b/vllm/model_executor/layers/quantization/utils/nvfp4_emulation_utils.py index cad141206678..fed8b4adbc6f 100644 --- a/vllm/model_executor/layers/quantization/utils/nvfp4_emulation_utils.py +++ b/vllm/model_executor/layers/quantization/utils/nvfp4_emulation_utils.py @@ -1,5 +1,6 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project +from collections.abc import Iterator from types import SimpleNamespace import torch @@ -17,6 +18,9 @@ "ref_nvfp4_quant", ] +# Target size of the dequantized expert chunks yielded for requantization. +_DEQUANT_CHUNK_BYTES = 1 << 30 + FLOAT4_E2M1_MAX = scalar_types.float4_e2m1f.max() FLOAT4_E2M1_MAX_RECIPROCAL = 1 / FLOAT4_E2M1_MAX @@ -630,7 +634,7 @@ def dequantize_to_dtype( return out.to(dtype) -def dequantize_nvfp4_moe_weights( +def _dequantize_nvfp4_moe_experts( w13_weight_packed: torch.Tensor, w13_weight_scale: torch.Tensor, w13_weight_global_scale: torch.Tensor, @@ -638,16 +642,9 @@ def dequantize_nvfp4_moe_weights( w2_weight_scale: torch.Tensor, w2_weight_global_scale: torch.Tensor, dtype: torch.dtype, - group_size: int = 16, - *, - invert_global_scales: bool = True, + group_size: int, + invert_global_scales: bool, ) -> tuple[torch.Tensor, torch.Tensor]: - """Materialize serialized NVFP4 MoE weights for requantization. - - Compressed-tensors stores global encode scales, while ModelOpt stores - ``weight_scale_2`` as the corresponding decode multiplier. Set - ``invert_global_scales`` according to the source checkpoint convention. - """ if invert_global_scales: w13_weight_global_scale = 1.0 / w13_weight_global_scale w2_weight_global_scale = 1.0 / w2_weight_global_scale @@ -682,6 +679,53 @@ def dequantize_nvfp4_moe_weights( return w13, w2 +@torch.no_grad() +def dequantize_nvfp4_moe_weights( + w13_weight_packed: torch.Tensor, + w13_weight_scale: torch.Tensor, + w13_weight_global_scale: torch.Tensor, + w2_weight_packed: torch.Tensor, + w2_weight_scale: torch.Tensor, + w2_weight_global_scale: torch.Tensor, + dtype: torch.dtype, + group_size: int = 16, + *, + invert_global_scales: bool = True, +) -> Iterator[tuple[slice, torch.Tensor, torch.Tensor]]: + """Dequantize serialized NVFP4 MoE weights for requantization. + + Compressed-tensors stores global encode scales, while ModelOpt stores + ``weight_scale_2`` as the corresponding decode multiplier. Set + ``invert_global_scales`` according to the source checkpoint convention. + + Returns: + An iterator of ``(experts, w13, w2)`` over groups of experts, so that + the dequantized staging tensors stay around ``_DEQUANT_CHUNK_BYTES``. + """ + num_experts = w13_weight_packed.shape[0] + # Two fp4 values per packed byte. + expert_bytes = ( + dtype.itemsize + * 2 + * (w13_weight_packed[0].numel() + w2_weight_packed[0].numel()) + ) + experts_per_chunk = max(1, _DEQUANT_CHUNK_BYTES // expert_bytes) + for start in range(0, num_experts, experts_per_chunk): + experts = slice(start, min(start + experts_per_chunk, num_experts)) + w13, w2 = _dequantize_nvfp4_moe_experts( + w13_weight_packed[experts], + w13_weight_scale[experts], + w13_weight_global_scale[experts], + w2_weight_packed[experts], + w2_weight_scale[experts], + w2_weight_global_scale[experts], + dtype, + group_size, + invert_global_scales, + ) + yield experts, w13, w2 + + def get_reciprocal(x): if isinstance(x, torch.Tensor): # torch.where yields operation not permitted when stream is capturing. diff --git a/vllm/model_executor/layers/quantization/utils/quant_utils.py b/vllm/model_executor/layers/quantization/utils/quant_utils.py index 8cdbb3e596ae..557034f3e3d7 100644 --- a/vllm/model_executor/layers/quantization/utils/quant_utils.py +++ b/vllm/model_executor/layers/quantization/utils/quant_utils.py @@ -217,6 +217,17 @@ def __str__(self): FP4_DTYPE, scale=kNvfp4DynamicGroupScale, scale2=kDynamicTokenScale ) + +def is_dynamic_per_token_outer_scale(key: QuantKey | None) -> bool: + """Whether ``key``'s second-level scale is computed per token at runtime.""" + return ( + key is not None + and key.scale2 is not None + and not key.scale2.static + and key.scale2.group_shape == GroupShape.PER_TOKEN + ) + + kNvfp4StaticGroupScale = ScaleDesc(FP8_DTYPE, True, GroupShape(1, 16)) kNvfp4Static = QuantKey( FP4_DTYPE, scale=kNvfp4StaticGroupScale, scale2=kStaticTensorScale diff --git a/vllm/model_executor/model_loader/utils.py b/vllm/model_executor/model_loader/utils.py index 8a236941002b..31faf4a4e169 100644 --- a/vllm/model_executor/model_loader/utils.py +++ b/vllm/model_executor/model_loader/utils.py @@ -183,6 +183,12 @@ def process_weights_after_loading( else nullcontext() ) with loading_context, timing_context: + # Quantize the staged fused shared experts into their slots. + shared_expert_loader = getattr( + module, "shared_expert_online_loader", None + ) + if shared_expert_loader is not None: + shared_expert_loader.finalize(module) quant_method.process_weights_after_loading(module) # process_weights_after_loading may swap in freshly-created # Parameters (e.g. FP8 requantization), which are stamped with the diff --git a/vllm/model_executor/models/config.py b/vllm/model_executor/models/config.py index 91379e1e8f79..af938e710759 100644 --- a/vllm/model_executor/models/config.py +++ b/vllm/model_executor/models/config.py @@ -86,6 +86,30 @@ def verify_and_update_config(cls, vllm_config: "VllmConfig") -> None: logger.info("Using bfloat16 kv-cache for DeepSeekV3.2") +class MiniMaxM3SparseConfig(VerifyAndUpdateConfig): + @staticmethod + def verify_and_update_config(vllm_config: "VllmConfig") -> None: + from vllm.v1.kv_cache_interface import get_kv_quant_mode + + if not get_kv_quant_mode(vllm_config.cache_config.cache_dtype).is_nvfp4: + return + # The NVFP4 KV attention kernels (MSA's CUTLASS Q8KV4 prefill) need 16 + # query heads per KV head on each rank; fail before the workers start. + text_config = vllm_config.model_config.hf_text_config + tp_size = vllm_config.parallel_config.tensor_parallel_size + num_heads = text_config.num_attention_heads // tp_size + num_kv_heads = max(1, text_config.num_key_value_heads // tp_size) + if num_heads != 16 * num_kv_heads: + raise ValueError( + "MiniMax-M3 does not support an NVFP4 KV cache with " + f"tensor_parallel_size={tp_size} yet: each rank holds {num_heads} " + f"query heads over {num_kv_heads} KV head(s), and the NVFP4 " + "attention kernels need 16 per KV head. Use a smaller " + "tensor_parallel_size (with data/expert parallelism) or another " + "kv_cache_dtype." + ) + + class GlmMoeDsaForCausalLM(VerifyAndUpdateConfig): @staticmethod def verify_and_update_config(vllm_config: "VllmConfig") -> None: @@ -787,7 +811,7 @@ def verify_and_update_config(cls, vllm_config: "VllmConfig") -> None: cache_config.mamba_block_size = model_config.max_model_len -class MiniMaxM3SparseForConditionalGenerationConfig(VerifyAndUpdateConfig): +class MiniMaxM3SparseForConditionalGenerationConfig(MiniMaxM3SparseConfig): INDEX_CACHE_KEYS = ("use_index_cache", "index_topk_freq", "index_skip_topk_offset") @classmethod @@ -1243,6 +1267,7 @@ def verify_and_update_config(vllm_config: "VllmConfig") -> None: "LlamaBidirectionalModel": LlamaBidirectionalConfig, "LlamaNemotronVLForSequenceClassification": LlamaNemotronVLConfig, "LlamaNemotronVLModel": LlamaNemotronVLConfig, + "MiniMaxM3SparseForCausalLM": MiniMaxM3SparseConfig, "Mamba2ForCausalLM": MambaModelConfig, "MambaForCausalLM": MambaModelConfig, "MiniMaxM3SparseForConditionalGeneration": ( diff --git a/vllm/model_executor/models/qwen3_dflash.py b/vllm/model_executor/models/qwen3_dflash.py index b7959cfc856b..e5eb0959ac97 100644 --- a/vllm/model_executor/models/qwen3_dflash.py +++ b/vllm/model_executor/models/qwen3_dflash.py @@ -27,12 +27,17 @@ ) from vllm.model_executor.layers.logits_processor import LogitsProcessor from vllm.model_executor.layers.quantization.base_config import QuantizationConfig +from vllm.model_executor.layers.quantization.modelopt import ModelOptMxFp8Config from vllm.model_executor.layers.rotary_embedding import get_rope from vllm.model_executor.layers.vocab_parallel_embedding import ( ParallelLMHead, VocabParallelEmbedding, ) from vllm.model_executor.model_loader.weight_utils import make_attention_sink +from vllm.model_executor.utils import ( + is_weights_pre_processed, + weights_already_processed, +) from vllm.multimodal.inputs import NestedTensors from vllm.platforms import current_platform from vllm.transformers_utils.config import set_default_rope_theta @@ -59,6 +64,12 @@ _SLIDING_ATTENTION = "sliding_attention" +def _is_mxfp8_linear(layer: nn.Module) -> bool: + return isinstance( + getattr(layer, "quant_config", None), ModelOptMxFp8Config + ) and not isinstance(layer.quant_method, UnquantizedLinearMethod) + + def _dflash_layer_causal(config: Qwen3Config, layer_idx: int) -> bool: """Resolve explicit causality before falling back to legacy layer defaults.""" is_causal = getattr(config, "is_causal", None) @@ -182,6 +193,7 @@ def __init__( quant_config: QuantizationConfig | None = None, prefix: str = "", attn_type: str = AttentionType.DECODER, + query_pre_quantized: bool = False, ) -> None: super().__init__() self.layer_name = prefix @@ -242,6 +254,7 @@ def __init__( prefix=f"{prefix}.attn", attn_type=attn_type, sinks=self.attention_sink_bias, + query_pre_quantized=query_pre_quantized, ) self.causal = causal if current_platform.is_rocm(): @@ -408,6 +421,9 @@ class DFlashQwen3Model(nn.Module): ".up_proj": (".gate_up_proj", 1), }, ) + # Maps module paths in the draft checkpoint's quantization exclusions to + # this model's module paths. + quant_config_mapper: WeightsMapper | None = None def __init__( self, @@ -422,6 +438,8 @@ def __init__( self.config = speculative_config.draft_model_config.hf_config self.vocab_size = self.config.vocab_size self.quant_config = get_draft_quant_config(vllm_config) + if self.quant_config is not None and self.quant_config_mapper is not None: + self.quant_config.apply_vllm_mapper(self.quant_config_mapper) map_draft_quant_config( self.quant_config, self.hf_to_vllm_mapper, @@ -510,6 +528,7 @@ def _build_context_kv_buffers( self._hidden_norm_weight = self.hidden_norm.weight.data self._context_qkv_projs = [a.qkv_proj for a in layers_attn] self._context_q_sizes = [a.q_size for a in layers_attn] + self._context_kv_proj: ReplicatedLinear | None = None if all( isinstance(proj.quant_method, UnquantizedLinearMethod) @@ -528,6 +547,12 @@ def _build_context_kv_buffers( # consumed by F.linear. Run each projection through its quant method. self._fused_kv_weight = None self._fused_kv_bias = None + if not is_weights_pre_processed() and all( + _is_mxfp8_linear(proj) for proj in self._context_qkv_projs + ): + self._context_kv_proj = self._build_mxfp8_context_kv_proj( + layers_attn, has_bias + ) # K-norm weights stacked into one contiguous [num_layers, head_dim] # tensor so the per-layer K-norm runs as a single grouped kernel. @@ -535,6 +560,35 @@ def _build_context_kv_buffers( [a.k_norm.weight.data for a in layers_attn], dim=0 ).contiguous() + @staticmethod + def _build_mxfp8_context_kv_proj( + layers_attn: list[nn.Module], has_bias: bool + ) -> ReplicatedLinear: + """One MXFP8 GEMM over the K/V rows of every layer's QKV projection. + + MXFP8 block scales are per output row, so the K/V rows and their scales + are copied as-is. Must run before process_weights_after_loading repacks + the weights and scales into kernel layouts. + """ + first = layers_attn[0].qkv_proj + with torch.device(first.weight.device): + proj = ReplicatedLinear( + first.input_size, + sum(2 * a.kv_size for a in layers_attn), + bias=has_bias, + params_dtype=first.params_dtype, + quant_config=first.quant_config, + prefix=first.prefix, + return_bias=False, + disable_tp=True, # QKV weights are already sharded on this rank. + ) + names = ["weight", "weight_scale"] + (["bias"] if has_bias else []) + for name in names: + getattr(proj, name).data.copy_( + torch.cat([getattr(a.qkv_proj, name)[a.q_size :] for a in layers_attn]) + ) + return proj + def _build_fused_kv_buffers(self) -> None: """Build fused weight buffers for precompute_and_store_context_kv. @@ -578,15 +632,7 @@ def _build_fused_kv_buffers(self) -> None: # References to inner Attention layers for direct cache writes self._attn_layers = [layer.self_attn.attn for layer in self.layers] - def _project_context_kv( - self, - context_states: torch.Tensor, - num_ctx: int, - num_layers: int, - num_kv_heads: int, - head_dim: int, - ) -> tuple[torch.Tensor, torch.Tensor]: - # --- Fused KV projection (one GEMM for all layers) --- + def _normalize_context_states(self, context_states: torch.Tensor) -> torch.Tensor: normed_context_states = torch.empty_like(context_states) ops.rms_norm( normed_context_states, @@ -594,11 +640,28 @@ def _project_context_kv( self._hidden_norm_weight, self._rms_norm_eps, ) + return normed_context_states + + def _project_context_kv_token_major( + self, + context_states: torch.Tensor, + num_ctx: int, + num_layers: int, + num_kv_heads: int, + head_dim: int, + ) -> torch.Tensor: + """Context K/V of every layer, ``[num_ctx, L, 2, nkv, hd]``.""" + # --- Fused KV projection (one GEMM for all layers) --- + normed_context_states = self._normalize_context_states(context_states) if self._fused_kv_weight is not None: all_kv_flat = F.linear( normed_context_states, self._fused_kv_weight, self._fused_kv_bias ) all_kv = all_kv_flat.view(num_ctx, num_layers, 2, num_kv_heads, head_dim) + elif self._context_kv_proj is not None: + all_kv = self._context_kv_proj(normed_context_states).view( + num_ctx, num_layers, 2, num_kv_heads, head_dim + ) else: layer_kv = [] for proj, q_size in zip( @@ -609,7 +672,19 @@ def _project_context_kv( qkv[:, q_size:].view(num_ctx, 2, num_kv_heads, head_dim) ) all_kv = torch.stack(layer_kv, dim=1) + return all_kv + def _project_context_kv( + self, + context_states: torch.Tensor, + num_ctx: int, + num_layers: int, + num_kv_heads: int, + head_dim: int, + ) -> tuple[torch.Tensor, torch.Tensor]: + all_kv = self._project_context_kv_token_major( + context_states, num_ctx, num_layers, num_kv_heads, head_dim + ) # Single contiguous copy that separates K/V and transposes to # layer-major layout. Result: [2, L, num_ctx, nkv, hd] contiguous. # Indexing dim-0 gives contiguous [L, num_ctx, nkv, hd] for K and V. @@ -653,7 +728,8 @@ def precompute_and_store_context_kv( "DFlash buffer initialization was skipped. If dummy weights are not " "in use, this may indicate an error in weight loading." ) - self._build_fused_kv_buffers() + with weights_already_processed(): + self._build_fused_kv_buffers() num_ctx = context_states.shape[0] L = self._num_attn_layers diff --git a/vllm/model_executor/models/qwen3_dspark.py b/vllm/model_executor/models/qwen3_dspark.py index 156f55c373ad..d3f8e48c0cc1 100644 --- a/vllm/model_executor/models/qwen3_dspark.py +++ b/vllm/model_executor/models/qwen3_dspark.py @@ -231,6 +231,8 @@ def __init__( class Qwen3DSparkForCausalLM(DFlashQwen3ForCausalLM): + model_cls = Qwen3DSparkModel + def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None: nn.Module.__init__(self) speculative_config = vllm_config.speculative_config @@ -240,7 +242,7 @@ def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None: if getattr(self.config, "draft_vocab_size", None) is None: self.config.draft_vocab_size = getattr(self.config, "vocab_size", None) target_layer_num = vllm_config.model_config.get_total_num_hidden_layers() - self.model = Qwen3DSparkModel( + self.model = self.model_cls( vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model"), start_layer_id=target_layer_num, @@ -275,6 +277,10 @@ def compute_draft_logits(self, hidden_states: torch.Tensor) -> torch.Tensor: # Markov bias in draft space, then remaps via map_draft_to_target. return self.logits_processor(self.lm_head, hidden_states) + def compute_draft_logits_local(self, hidden_states: torch.Tensor) -> torch.Tensor: + # This rank's vocab shard, vocab padding included. + return self.logits_processor(self.lm_head, hidden_states, skip_gather=True) + def map_draft_to_target(self, draft_ids: torch.Tensor) -> torch.Tensor: # Map draft-vocab ids to target ids (identity for full-vocab drafts). if self.draft_id_to_target_id is None: diff --git a/vllm/model_executor/models/registry.py b/vllm/model_executor/models/registry.py index d7f3c3bbf4a2..b7b0d3c562fe 100644 --- a/vllm/model_executor/models/registry.py +++ b/vllm/model_executor/models/registry.py @@ -678,6 +678,10 @@ "vllm.models.deepseek_v41", "DSparkDeepseekV4ForCausalLM", ), + "DSparkMiniMaxDraftModel": ( + "vllm.models.minimax_m3.common.dspark", + "MiniMaxM3DSparkForCausalLM", + ), "Qwen3DSparkModel": ("qwen3_dspark", "Qwen3DSparkForCausalLM"), "Qwen3OmniDSparkModel": ("qwen3_dspark", "Qwen3DSparkForCausalLM"), # Serving under method="dflash" means EAGLEConfig rewrites the draft diff --git a/vllm/model_executor/warmup/kernel_warmup.py b/vllm/model_executor/warmup/kernel_warmup.py index 0f1058a98661..3191b0af25fa 100644 --- a/vllm/model_executor/warmup/kernel_warmup.py +++ b/vllm/model_executor/warmup/kernel_warmup.py @@ -162,9 +162,6 @@ def _autotune_kimi_k3_kda_qkvg(model: torch.nn.Module) -> None: def kernel_warmup(worker: "Worker", *, process_local_only: bool = False): - from vllm.model_executor.warmup.minimax_m3_msa_warmup import ( - minimax_m3_msa_warmup, - ) from vllm.model_executor.warmup.step5_dsa_warmup import step5_dsa_warmup if not worker.use_v2_model_runner: @@ -249,7 +246,13 @@ def kernel_warmup(worker: "Worker", *, process_local_only: bool = False): b12x_warmup(worker, cudagraph_capture_sizes) - minimax_m3_msa_warmup(worker) + if current_platform.is_cuda(): + # The MSA kernels, and the CuTe DSL their modules import, are CUDA-only. + from vllm.model_executor.warmup.minimax_m3_msa_warmup import ( + minimax_m3_msa_warmup, + ) + + minimax_m3_msa_warmup(worker) # Allocate the exact decode-sized workspace, autotune cache misses, and # resolve every CUDA Graph bucket before capture begins. diff --git a/vllm/model_executor/warmup/minimax_m3_msa_warmup.py b/vllm/model_executor/warmup/minimax_m3_msa_warmup.py index 2c8996a93341..699cad10af08 100644 --- a/vllm/model_executor/warmup/minimax_m3_msa_warmup.py +++ b/vllm/model_executor/warmup/minimax_m3_msa_warmup.py @@ -1,21 +1,83 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any + +import torch from vllm.logger import init_logger from vllm.model_executor.warmup.attention_warmup import ( mixed_batch_attention_warmup, ) +from vllm.models.minimax_m3.nvidia.indexer_msa import MiniMaxM3IndexerMSAImpl +from vllm.models.minimax_m3.nvidia.indexer_nvfp4 import MiniMaxM3IndexerNvfp4Impl from vllm.models.minimax_m3.nvidia.model import MiniMaxM3SparseAttention +from vllm.models.minimax_m3.nvidia.msa_cutlass_sparse_decode import ( + NVFP4_BLOCK_SCALE_SHIFT, + uses_q8kv4_decode, +) +from vllm.models.minimax_m3.nvidia.sparse_attention_msa import ( + MiniMaxM3SparseMSABaseImpl, +) from vllm.platforms import current_platform from vllm.tracing import instrument if TYPE_CHECKING: + from vllm.config import VllmConfig from vllm.v1.worker.gpu_worker import Worker logger = init_logger(__name__) +# KV-cache dtypes fmha_sm100.warmup plans attention kernels for. +_MSA_KV_CACHE_DTYPES = ("auto", "bfloat16", "fp8", "fp8_e4m3", "nvfp4") + + +def _msa_prebuild_kwargs( + vllm_config: "VllmConfig", module: MiniMaxM3SparseAttention +) -> dict[str, Any] | None: + """``fmha_sm100.warmup`` arguments for the kernels this rank can request.""" + impl = module.impl + indexer = module.indexer.impl + msa = ( + impl + if isinstance(impl, MiniMaxM3SparseMSABaseImpl) + and module.kv_cache_dtype in _MSA_KV_CACHE_DTYPES + else None + ) + attention = msa is not None + if isinstance(indexer, MiniMaxM3IndexerNvfp4Impl): + index_cache_dtype = "nvfp4" + elif isinstance(indexer, MiniMaxM3IndexerMSAImpl): + index_cache_dtype = module.indexer_kv_dtype + else: + index_cache_dtype = None + if not attention and index_cache_dtype is None: + return None + + spec_config = vllm_config.speculative_config + num_spec = spec_config.num_speculative_tokens if spec_config is not None else 0 + q8kv4_decode = attention and uses_q8kv4_decode( + kv_cache_dtype=module.kv_cache_dtype, + num_q_heads=module.num_heads, + num_kv_heads=module.num_kv_heads, + ) + return dict( + kv_cache_dtype=module.kv_cache_dtype if attention else "auto", + index_cache_dtype=index_cache_dtype, + num_q_heads=module.num_heads, + num_kv_heads=module.num_kv_heads, + topk=impl.topk_blocks, + decode_query_lens=range(1, num_spec + 2), + num_index_heads=indexer.num_index_heads, + page_size=impl.block_size, + decode_backend="q8kv4" if q8kv4_decode else "kv_mode3", + block_scale_shift=NVFP4_BLOCK_SCALE_SHIFT, + sparse_decode=msa is not None and msa.use_cutlass_decode, + sparse_prefill=attention, + prefill_backend=msa.prefill_backend if msa is not None else "cute_dsl", + device=torch.device("cuda", torch.accelerator.current_device_index()), + ) + @instrument(span_name="MiniMax M3 MSA warmup") def minimax_m3_msa_warmup(worker: "Worker") -> None: @@ -36,5 +98,14 @@ def minimax_m3_msa_warmup(worker: "Worker") -> None: logger.info("Warming up MiniMax M3 MSA kernels.") - # Cover sparse prefill through the normal model path. + # Build every native kernel the configuration can request at once instead + # of compiling each one serially on first use. + kwargs = _msa_prebuild_kwargs(worker.vllm_config, sparse_module) + if kwargs is not None: + from vllm.third_party.fmha_sm100 import warmup + + logger.info("MiniMax M3 MSA kernels: %s", warmup(**kwargs)) + + # Cover sparse prefill (and its CuTe-DSL kernels) through the normal model + # path. mixed_batch_attention_warmup(worker) diff --git a/vllm/models/common/ops/moe_tail_fusion/__init__.py b/vllm/models/common/ops/moe_tail_fusion/__init__.py new file mode 100644 index 000000000000..3a391caf17df --- /dev/null +++ b/vllm/models/common/ops/moe_tail_fusion/__init__.py @@ -0,0 +1,5 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +"""Building blocks shared by the CuTe DSL kernels that fuse a MoE layer's tail +(top-k finalize, TP all-reduce, norms) across models.""" diff --git a/vllm/models/common/ops/moe_tail_fusion/primitives.py b/vllm/models/common/ops/moe_tail_fusion/primitives.py new file mode 100644 index 000000000000..53a2384bf265 --- /dev/null +++ b/vllm/models/common/ops/moe_tail_fusion/primitives.py @@ -0,0 +1,671 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +# Adapted from FlashInfer's flashinfer/comm/mnnvl_cutedsl/cute_dsl_primitives.py +# and runtime.py (flashinfer-ai/flashinfer@139af6f6). + +"""CuTe DSL primitives shared by the fused MoE-tail kernels: PTX loads and +stores, NVLS multicast stores, Lamport mailbox helpers, BF16 packing, block +reductions and launch helpers. This module defines no kernel.""" + +import cuda.bindings.driver as cuda +import cutlass +import cutlass.cute as cute +import torch +from cutlass import BFloat16, Float32, Int32, Int64, Uint16, Uint32 +from cutlass._mlir import ir +from cutlass._mlir.dialects import llvm, vector +from cutlass.cute.runtime import from_dlpack, make_fake_compact_tensor +from cutlass.cutlass_dsl import T, dsl_user_op + +WARP_SIZE = 32 +VEC_BF16 = 8 +QUAD_BF16 = 4 +PACKED_BYTES = 16 +NEGATIVE_ZERO_BF16_BITS = 0x8000 +NEGATIVE_ZERO_BF16_PAIR = 0x80008000 +NEGATIVE_ZERO_F32_BITS = 0x80000000 + +# Lamport mailboxes rotate through three generations; the stage-state words +# hold the next generation to publish into and the one being consumed. +LAMPORT_GENERATIONS = 3 +NEXT_STAGE = 0 +ACTIVE_STAGE = 1 + + +def _asm(result, operands, text, constraints, *, side_effects, loc, ip): + return llvm.inline_asm( + result, + operands, + text, + constraints, + has_side_effects=side_effects, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + + +# --------------------------------------------------------------------------- +# Global memory +# --------------------------------------------------------------------------- + + +@dsl_user_op +def load_global_u32x4( + pointer: cute.Pointer, + *, + volatile: cutlass.Constexpr[bool] = False, + loc=None, + ip=None, +): + """Load one 128-bit fragment as four u32 registers. + + The volatile form is the Lamport polling load. Marking the asm + side-effecting prevents loop-invariant motion and common-subexpression + elimination across polling iterations. + """ + address = pointer.toint(loc=loc, ip=ip) + opcode = "ld.volatile.global.v4.u32" if volatile else "ld.global.v4.u32" + loaded = _asm( + llvm.StructType.get_literal([T.i32()] * 4), + [address.ir_value(loc=loc, ip=ip)], + f"{opcode} {{$0, $1, $2, $3}}, [$4];", + "=r,=r,=r,=r,l", + side_effects=volatile, + loc=loc, + ip=ip, + ) + packed = vector.from_elements( + ir.VectorType.get([4], T.i32(), loc=loc), + [ + llvm.extractvalue(T.i32(), loaded, [index], loc=loc, ip=ip) + for index in range(4) + ], + loc=loc, + ip=ip, + ) + return cute.TensorSSA(packed, 4, Uint32) + + +@dsl_user_op +def load_global_u32x2(pointer: cute.Pointer, *, loc=None, ip=None): + address = pointer.toint(loc=loc, ip=ip) + loaded = _asm( + llvm.StructType.get_literal([T.i32()] * 2), + [address.ir_value(loc=loc, ip=ip)], + "ld.global.v2.u32 {$0, $1}, [$2];", + "=r,=r,l", + side_effects=False, + loc=loc, + ip=ip, + ) + packed = vector.from_elements( + ir.VectorType.get([2], T.i32(), loc=loc), + [ + llvm.extractvalue(T.i32(), loaded, [index], loc=loc, ip=ip) + for index in range(2) + ], + loc=loc, + ip=ip, + ) + return cute.TensorSSA(packed, 2, Uint32) + + +@dsl_user_op +def load_global_bf16_as_f32(address: Int64, *, loc=None, ip=None) -> Float32: + return Float32( + _asm( + T.f32(), + [address.ir_value(loc=loc, ip=ip)], + "{\n\t.reg .b16 bits;\n\tld.global.b16 bits, [$1];\n\t" + "cvt.f32.bf16 $0, bits;\n\t}", + "=f,l", + side_effects=False, + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def load_volatile_u32(pointer: cute.Pointer, *, loc=None, ip=None) -> Uint32: + address = pointer.toint(loc=loc, ip=ip) + return Uint32( + _asm( + T.i32(), + [address.ir_value(loc=loc, ip=ip)], + "ld.volatile.global.u32 $0, [$1];", + "=r,l", + side_effects=True, + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def store_global_u32x4( + address: Int64, + packed, + *, + volatile: cutlass.Constexpr[bool] = False, + loc=None, + ip=None, +) -> None: + """Store four packed words to an ordinary or NVLS multicast global VA.""" + words = [packed[index].ir_value(loc=loc, ip=ip) for index in range(4)] + opcode = "st.volatile.global.v4.u32" if volatile else "st.global.v4.u32" + _asm( + None, + [address.ir_value(loc=loc, ip=ip), *words], + f"{opcode} [$0], {{$1, $2, $3, $4}};", + "l,r,r,r,r", + side_effects=True, + loc=loc, + ip=ip, + ) + + +@dsl_user_op +def store_global_u32x2(address: Int64, packed, *, loc=None, ip=None) -> None: + words = [packed[index].ir_value(loc=loc, ip=ip) for index in range(2)] + _asm( + None, + [address.ir_value(loc=loc, ip=ip), *words], + "st.global.v2.u32 [$0], {$1, $2};", + "l,r,r", + side_effects=True, + loc=loc, + ip=ip, + ) + + +@dsl_user_op +def store_global_u32(address: Int64, word: Uint32, *, loc=None, ip=None) -> None: + _asm( + None, + [address.ir_value(loc=loc, ip=ip), word.ir_value(loc=loc, ip=ip)], + "st.global.u32 [$0], $1;", + "l,r", + side_effects=True, + loc=loc, + ip=ip, + ) + + +@dsl_user_op +def red_async_release_gpu_add_u32( + pointer: cute.Pointer, value: Uint32, *, loc=None, ip=None +) -> None: + """The SM100 arrival primitive FlashInfer's LamportFlags use.""" + address = pointer.toint(loc=loc, ip=ip) + _asm( + None, + [address.ir_value(loc=loc, ip=ip), value.ir_value(loc=loc, ip=ip)], + "red.async.release.global.gpu.add.u32 [$0], $1;", + "l,r", + side_effects=True, + loc=loc, + ip=ip, + ) + + +# --------------------------------------------------------------------------- +# NVLS multicast stores +# --------------------------------------------------------------------------- + + +@dsl_user_op +def stmc_bf16x2(address: Int64, packed: Uint32, *, loc=None, ip=None) -> None: + _asm( + None, + [address.ir_value(loc=loc, ip=ip), packed.ir_value(loc=loc, ip=ip)], + "multimem.st.relaxed.sys.global.bf16x2 [$0], $1;", + "l,r", + side_effects=True, + loc=loc, + ip=ip, + ) + + +@dsl_user_op +def stmc_bf16x4(address: Int64, packed, *, loc=None, ip=None) -> None: + words = [packed[index].ir_value(loc=loc, ip=ip) for index in range(2)] + _asm( + None, + [address.ir_value(loc=loc, ip=ip), *words], + "multimem.st.relaxed.sys.global.v2.bf16x2 [$0], {$1, $2};", + "l,r,r", + side_effects=True, + loc=loc, + ip=ip, + ) + + +@dsl_user_op +def stmc_bf16x8(address: Int64, packed, *, loc=None, ip=None) -> None: + """Publish eight BF16 values (four packed words) through NVLS multicast.""" + words = [packed[index].ir_value(loc=loc, ip=ip) for index in range(4)] + _asm( + None, + [address.ir_value(loc=loc, ip=ip), *words], + "multimem.st.relaxed.sys.global.v4.bf16x2 [$0], {$1, $2, $3, $4};", + "l,r,r,r,r", + side_effects=True, + loc=loc, + ip=ip, + ) + + +# --------------------------------------------------------------------------- +# Lamport sentinels +# +# A BF16 mailbox marks an empty slot with BF16 negative zero in every lane; an +# FP32 mailbox marks it with FP32 negative zero in every word. Senders replace +# real negative zeros with positive zeros so they never read as empty. +# --------------------------------------------------------------------------- + + +@dsl_user_op +def store_lamport_sentinel_u32x4(address: Int64, *, loc=None, ip=None) -> None: + """Reset one BF16 Lamport fragment to BF16 negative zeros.""" + sentinel = Uint32(NEGATIVE_ZERO_BF16_PAIR).ir_value(loc=loc, ip=ip) + _asm( + None, + [address.ir_value(loc=loc, ip=ip), sentinel, sentinel, sentinel, sentinel], + "st.global.v4.u32 [$0], {$1, $2, $3, $4};", + "l,r,r,r,r", + side_effects=True, + loc=loc, + ip=ip, + ) + + +@dsl_user_op +def store_lamport_sentinel_128(pointer: cute.Pointer, *, loc=None, ip=None) -> None: + """Reset one FP32 Lamport fragment to four FP32 negative-zero bit patterns.""" + address = pointer.toint(loc=loc, ip=ip) + sentinel = Uint32(NEGATIVE_ZERO_F32_BITS).ir_value(loc=loc, ip=ip) + _asm( + None, + [address.ir_value(loc=loc, ip=ip), sentinel, sentinel, sentinel, sentinel], + "st.global.v4.u32 [$0], {$1, $2, $3, $4};", + "l,r,r,r,r", + side_effects=True, + loc=loc, + ip=ip, + ) + + +@cute.jit +def sanitize_negative_zero_u32(word: Uint32) -> Uint32: + low = Uint16(word & Uint32(0xFFFF)) + high = Uint16(word >> Uint32(16)) + if low == Uint16(NEGATIVE_ZERO_BF16_BITS): + word = word & Uint32(0xFFFF0000) + if high == Uint16(NEGATIVE_ZERO_BF16_BITS): + word = word & Uint32(0x0000FFFF) + return word + + +@cute.jit +def sanitize_negative_zero_u32x2(packed): + sanitized = cute.make_rmem_tensor(cute.make_layout((2,)), Uint32) + for index in cutlass.range_constexpr(2): + sanitized[index] = sanitize_negative_zero_u32(packed[index]) + return sanitized.load() + + +@cute.jit +def sanitize_negative_zero_u32x4(packed): + """Turn real BF16 -0 into +0 so it cannot equal the empty sentinel.""" + sanitized = cute.make_rmem_tensor(cute.make_layout((4,)), Uint32) + for index in cutlass.range_constexpr(4): + sanitized[index] = sanitize_negative_zero_u32(packed[index]) + return sanitized.load() + + +@cute.jit +def fragment_has_negative_zero(packed): + """Whether a BF16 fragment still holds the BF16 sentinel in any lane.""" + dirty = False + for index in cutlass.range_constexpr(4): + word = packed[index] + dirty = ( + dirty + | (Uint16(word & Uint32(0xFFFF)) == Uint16(NEGATIVE_ZERO_BF16_BITS)) + | (Uint16(word >> Uint32(16)) == Uint16(NEGATIVE_ZERO_BF16_BITS)) + ) + return dirty + + +@cute.jit +def fragment_is_dirty(packed): + """Whether an FP32 fragment still holds the FP32 sentinel in any word.""" + dirty = packed[0] == Uint32(NEGATIVE_ZERO_F32_BITS) + for index in cutlass.range_constexpr(1, 4): + dirty = dirty | (packed[index] == Uint32(NEGATIVE_ZERO_F32_BITS)) + return dirty + + +# --------------------------------------------------------------------------- +# Shared and distributed shared memory +# --------------------------------------------------------------------------- + + +@dsl_user_op +def map_shared_to_peer( + smem_pointer: cute.Pointer, peer_rank: Int32, *, loc=None, ip=None +) -> Int32: + """Map a local shared-memory slot to the same slot in a peer CTA.""" + address = smem_pointer.toint(loc=loc, ip=ip).ir_value(loc=loc, ip=ip) + return Int32( + _asm( + T.i32(), + [address, peer_rank.ir_value(loc=loc, ip=ip)], + "mapa.shared::cluster.u32 $0, $1, $2;", + "=r,r,r", + side_effects=False, + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def store_shared_cluster_f32( + remote_address: Int32, value: Float32, *, loc=None, ip=None +) -> None: + _asm( + None, + [remote_address.ir_value(loc=loc, ip=ip), value.ir_value(loc=loc, ip=ip)], + "st.shared::cluster.f32 [$0], $1;", + "r,f", + side_effects=True, + loc=loc, + ip=ip, + ) + + +@dsl_user_op +def load_shared_f32x2(pointer: cute.Pointer, *, loc=None, ip=None): + """Load two aligned FP32 partials from local shared memory.""" + address = Int32(pointer.toint(loc=loc, ip=ip)) + loaded = _asm( + llvm.StructType.get_literal([T.f32()] * 2), + [address.ir_value(loc=loc, ip=ip)], + "ld.shared.v2.f32 {$0, $1}, [$2];", + "=f,=f,r", + side_effects=True, + loc=loc, + ip=ip, + ) + return tuple( + Float32(llvm.extractvalue(T.f32(), loaded, [index], loc=loc, ip=ip)) + for index in range(2) + ) + + +@dsl_user_op +def load_shared_f32x4(pointer: cute.Pointer, *, loc=None, ip=None): + """Load four aligned FP32 partials from local shared memory.""" + address = Int32(pointer.toint(loc=loc, ip=ip)) + loaded = _asm( + llvm.StructType.get_literal([T.f32()] * 4), + [address.ir_value(loc=loc, ip=ip)], + "ld.shared.v4.f32 {$0, $1, $2, $3}, [$4];", + "=f,=f,=f,=f,r", + side_effects=True, + loc=loc, + ip=ip, + ) + return tuple( + Float32(llvm.extractvalue(T.f32(), loaded, [index], loc=loc, ip=ip)) + for index in range(4) + ) + + +# --------------------------------------------------------------------------- +# BF16 packing and arithmetic +# --------------------------------------------------------------------------- + + +@dsl_user_op +def packed_u32x4_to_bf16x8(packed, *, loc=None, ip=None): + values = llvm.bitcast( + ir.VectorType.get([VEC_BF16], BFloat16.mlir_type, loc=loc), + packed.ir_value(loc=loc, ip=ip), + loc=loc, + ip=ip, + ) + return cute.TensorSSA(values, VEC_BF16, BFloat16) + + +@dsl_user_op +def packed_u32x2_to_bf16x4(packed, *, loc=None, ip=None): + values = llvm.bitcast( + ir.VectorType.get([QUAD_BF16], BFloat16.mlir_type, loc=loc), + packed.ir_value(loc=loc, ip=ip), + loc=loc, + ip=ip, + ) + return cute.TensorSSA(values, QUAD_BF16, BFloat16) + + +@dsl_user_op +def bf16x8_to_packed_u32x4(values, *, loc=None, ip=None): + packed = llvm.bitcast( + ir.VectorType.get([4], T.i32(), loc=loc), + values.ir_value(loc=loc, ip=ip), + loc=loc, + ip=ip, + ) + return cute.TensorSSA(packed, 4, Uint32) + + +@dsl_user_op +def bf16x4_to_packed_u32x2(values, *, loc=None, ip=None): + packed = llvm.bitcast( + ir.VectorType.get([2], T.i32(), loc=loc), + values.ir_value(loc=loc, ip=ip), + loc=loc, + ip=ip, + ) + return cute.TensorSSA(packed, 2, Uint32) + + +@dsl_user_op +def bf16x2_to_u32(values, *, loc=None, ip=None) -> Uint32: + return Uint32( + llvm.bitcast(T.i32(), values.ir_value(loc=loc, ip=ip), loc=loc, ip=ip) + ) + + +@dsl_user_op +def f32_to_bf16_bits(value: Float32, *, loc=None, ip=None) -> Uint32: + return Uint32( + _asm( + T.i32(), + [value.ir_value(loc=loc, ip=ip)], + "{\n\t.reg .b16 bits;\n\tcvt.rn.bf16.f32 bits, $1;\n\t" + "cvt.u32.u16 $0, bits;\n\t}", + "=r,f", + side_effects=False, + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def fma_f32_bf16( + a: BFloat16, b: BFloat16, acc: Float32, *, loc=None, ip=None +) -> Float32: + a_bits = llvm.bitcast(T.i16(), a.ir_value(loc=loc, ip=ip), loc=loc, ip=ip) + b_bits = llvm.bitcast(T.i16(), b.ir_value(loc=loc, ip=ip), loc=loc, ip=ip) + return Float32( + _asm( + T.f32(), + [a_bits, b_bits, acc.ir_value(loc=loc, ip=ip)], + "fma.rn.f32.bf16 $0, $1, $2, $3;", + "=f,h,h,f", + side_effects=False, + loc=loc, + ip=ip, + ) + ) + + +# --------------------------------------------------------------------------- +# Warp and block reductions +# --------------------------------------------------------------------------- + + +@dsl_user_op +def shuffle_sync_idx_u32( + value: Uint32, source_lane: Int32, *, loc=None, ip=None +) -> Uint32: + return Uint32( + _asm( + T.i32(), + [value.ir_value(loc=loc, ip=ip), source_lane.ir_value(loc=loc, ip=ip)], + "shfl.sync.idx.b32 $0, $1, $2, 0x1f, 0xffffffff;", + "=r,r,r", + # Preserve full-warp execution across later divergent consumers. + side_effects=True, + loc=loc, + ip=ip, + ) + ) + + +@cute.jit +def group_leader_block_sum( + value: Float32, + warp_sums: cute.Tensor, + warps: cutlass.Constexpr[int], + leader_stride: cutlass.Constexpr[int], +) -> Float32: + """Block sum of the values held by every ``leader_stride``-th lane.""" + lane = cute.arch.lane_idx() + warp = cute.arch.warp_idx() + for offset in cutlass.range_constexpr(1, WARP_SIZE): + if cutlass.const_expr(offset >= leader_stride and (offset & (offset - 1)) == 0): + value = value + cute.arch.shuffle_sync_bfly( + value, + offset=offset, + mask=-1, + mask_and_clamp=31, + ) + if lane == 0: + cute.arch.store((warp_sums + warp).llvm_ptr, value) + cute.arch.barrier() + + result = Float32(0.0) + if warp == 0: + if lane < Int32(warps): + result = cute.arch.load( + (warp_sums + lane).llvm_ptr, + Float32, + ) + result = cute.arch.warp_reduction_sum(result) + if lane == 0: + cute.arch.store(warp_sums.llvm_ptr, result) + cute.arch.barrier() + return cute.arch.load(warp_sums.llvm_ptr, Float32) + + +@cute.jit +def warp_sum_specialized( + value: Float32, + warp_idx: Int32, + lane: Int32, + warps: cutlass.Constexpr[int], + last_warp_lanes: cutlass.Constexpr[int], + last_warp_mask: cutlass.Constexpr[int], +) -> Float32: + """Warp sum supporting a compile-time partial final warp.""" + if warp_idx == Int32(warps - 1) and cutlass.const_expr(last_warp_lanes < 32): + for offset in cutlass.range_constexpr(16, 0, -1): + # range_constexpr does not provide powers-of-two stepping. + if cutlass.const_expr(offset in (16, 8, 4, 2, 1)): + other = cute.arch.shuffle_sync_bfly( + value, + offset=offset, + mask=last_warp_mask, + mask_and_clamp=31, + ) + if (lane ^ Int32(offset)) < Int32(last_warp_lanes): + value = value + other + else: + for offset in cutlass.range_constexpr(16, 0, -1): + if cutlass.const_expr(offset in (16, 8, 4, 2, 1)): + value = value + cute.arch.shuffle_sync_bfly( + value, + offset=offset, + mask=-1, + mask_and_clamp=31, + ) + return value + + +# --------------------------------------------------------------------------- +# Launch helpers +# --------------------------------------------------------------------------- + + +class CUDAGraphCompatibleWrapper: + """DLPack view that does not synchronize with the producer stream.""" + + __slots__ = ("tensor",) + + def __init__(self, tensor: torch.Tensor) -> None: + self.tensor = tensor + + def __dlpack__(self, stream=None): + # stream=-1 skips producer sync; CuTe launches on the current stream, + # which is the capturing one under CUDA graphs. + return self.tensor.__dlpack__(stream=-1) + + def __dlpack_device__(self): + return self.tensor.__dlpack_device__() + + +def to_cute(tensor: torch.Tensor, assumed_align: int = 16) -> cute.Tensor: + return from_dlpack( + CUDAGraphCompatibleWrapper(tensor.detach()), assumed_align=assumed_align + ) + + +def to_cute_dynamic( + tensor: torch.Tensor, alignment: int, *, divisibility: int +) -> cute.Tensor: + """A 1-D view whose length is a runtime shape divisible by ``divisibility``.""" + return to_cute(tensor, alignment).mark_compact_shape_dynamic( + mode=0, divisibility=divisibility + ) + + +def to_cute_dynamic_m( + tensor: torch.Tensor, *, mode: int, assumed_align: int = 16 +) -> cute.Tensor: + """Expose exactly one compact tensor mode as a runtime shape. + + Model dimensions remain part of the compiled tensor type. Only the token + mode is symbolic, so changing M within an op's capacity reuses the same + compiled kernel. + """ + return to_cute(tensor, assumed_align).mark_compact_shape_dynamic( + mode=mode, stride_order=tensor.dim_order() + ) + + +def make_fake_dynamic_compact_tensor(dtype, *, alignment: int, divisibility: int): + return make_fake_compact_tensor( + dtype, (cute.sym_int32(divisibility=divisibility),), assumed_align=alignment + ) + + +def current_cu_stream() -> cuda.CUstream: + return cuda.CUstream(torch.cuda.current_stream().cuda_stream) diff --git a/vllm/models/deepseek_v41/nvidia/ops/cute_dsl/all_reduce_mhc.py b/vllm/models/deepseek_v41/nvidia/ops/cute_dsl/all_reduce_mhc.py index 191a928fe2e9..3bbd13cf2f49 100644 --- a/vllm/models/deepseek_v41/nvidia/ops/cute_dsl/all_reduce_mhc.py +++ b/vllm/models/deepseek_v41/nvidia/ops/cute_dsl/all_reduce_mhc.py @@ -34,10 +34,11 @@ from cutlass.cute.runtime import make_fake_compact_tensor from vllm.distributed import get_tp_group -from vllm.models.deepseek_v41.common.ops.query_quant import mxfp8_scale_bytes - -from .primitives import ( +from vllm.models.common.ops.moe_tail_fusion.primitives import ( + ACTIVE_STAGE, + LAMPORT_GENERATIONS, NEGATIVE_ZERO_BF16_BITS, + NEXT_STAGE, QUAD_BF16, VEC_BF16, WARP_SIZE, @@ -46,6 +47,7 @@ current_cu_stream, f32_to_bf16_bits, fragment_has_negative_zero, + group_leader_block_sum, load_global_bf16_as_f32, load_global_u32x2, load_global_u32x4, @@ -67,10 +69,8 @@ to_cute, to_cute_dynamic, ) +from vllm.models.deepseek_v41.common.ops.query_quant import mxfp8_scale_bytes -LAMPORT_GENERATIONS = 3 -NEXT_STAGE = 0 -ACTIVE_STAGE = 1 # One UE8M0 scale per 32 values: four adjacent threads' BF16 fragments. MXFP8_BLOCK = 32 FRAGMENTS_PER_MXFP8_BLOCK = MXFP8_BLOCK // VEC_BF16 @@ -79,41 +79,6 @@ SCALE_TILE_COLS = 4 -@cute.jit -def _group_leader_block_sum( - value: Float32, - warp_sums: cute.Tensor, - warps: cutlass.Constexpr[int], - leader_stride: cutlass.Constexpr[int], -) -> Float32: - lane = cute.arch.lane_idx() - warp = cute.arch.warp_idx() - for offset in cutlass.range_constexpr(1, WARP_SIZE): - if cutlass.const_expr(offset >= leader_stride and (offset & (offset - 1)) == 0): - value = value + cute.arch.shuffle_sync_bfly( - value, - offset=offset, - mask=-1, - mask_and_clamp=31, - ) - if lane == 0: - cute.arch.store((warp_sums + warp).llvm_ptr, value) - cute.arch.barrier() - - result = Float32(0.0) - if warp == 0: - if lane < Int32(warps): - result = cute.arch.load( - (warp_sums + lane).llvm_ptr, - Float32, - ) - result = cute.arch.warp_reduction_sum(result) - if lane == 0: - cute.arch.store(warp_sums.llvm_ptr, result) - cute.arch.barrier() - return cute.arch.load(warp_sums.llvm_ptr, Float32) - - class _SharedOnlyPublishDeviceKernel: def __init__( self, @@ -227,7 +192,7 @@ def kernel( if cutlass.const_expr(self.release_before_store): if block == 0 and tidx == 0: store_global_u32( - stage_state.iterator + ACTIVE_STAGE, + (stage_state.iterator + ACTIVE_STAGE).toint(), stage, ) cute.arch.barrier() @@ -270,7 +235,7 @@ def kernel( if cutlass.const_expr(not self.release_before_store): if block == 0 and tidx == 0: store_global_u32( - stage_state.iterator + ACTIVE_STAGE, + (stage_state.iterator + ACTIVE_STAGE).toint(), stage, ) cute.arch.barrier() @@ -523,7 +488,7 @@ def kernel( if block == 0 and tidx == 0: store_global_u32( - stage_state.iterator + ACTIVE_STAGE, + (stage_state.iterator + ACTIVE_STAGE).toint(), stage, ) cute.arch.barrier() @@ -826,7 +791,7 @@ def kernel( if token == 0 and cluster_rank == 0 and tidx == 0: store_global_u32( - stage_state.iterator + NEXT_STAGE, + (stage_state.iterator + NEXT_STAGE).toint(), (active_stage + Uint32(1)) % Uint32(LAMPORT_GENERATIONS), ) if cutlass.const_expr(self.enable_pdl): @@ -861,7 +826,7 @@ def kernel( smem = cutlass.utils.SmemAllocator() warp_sums = smem.allocate_array(Float32, self.warps) cluster_sums = smem.allocate_array(Float32, self.cluster_size) - cta_sum = _group_leader_block_sum( + cta_sum = group_leader_block_sum( thread_sum, warp_sums, self.warps, diff --git a/vllm/models/deepseek_v41/nvidia/ops/cute_dsl/primitives.py b/vllm/models/deepseek_v41/nvidia/ops/cute_dsl/primitives.py deleted file mode 100644 index 16d5f4721a33..000000000000 --- a/vllm/models/deepseek_v41/nvidia/ops/cute_dsl/primitives.py +++ /dev/null @@ -1,396 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -# Adapted from FlashInfer's flashinfer/comm/mnnvl_cutedsl/cute_dsl_primitives.py -# and runtime.py (flashinfer-ai/flashinfer@139af6f6). - -"""PTX building blocks and launch helpers for the DSV4.1 LL all-reduce.""" - -import cuda.bindings.driver as cuda -import cutlass -import cutlass.cute as cute -import torch -from cutlass import Float32, Int32, Int64, Uint16, Uint32 -from cutlass._mlir import ir -from cutlass._mlir.dialects import llvm, vector -from cutlass.cute.runtime import from_dlpack, make_fake_compact_tensor -from cutlass.cutlass_dsl import T, dsl_user_op - -WARP_SIZE = 32 -VEC_BF16 = 8 -QUAD_BF16 = 4 -NEGATIVE_ZERO_BF16_BITS = 0x8000 -NEGATIVE_ZERO_BF16_PAIR = 0x80008000 - - -def _asm(result, operands, text, constraints, *, side_effects, loc, ip): - return llvm.inline_asm( - result, - operands, - text, - constraints, - has_side_effects=side_effects, - is_align_stack=False, - asm_dialect=llvm.AsmDialect.AD_ATT, - loc=loc, - ip=ip, - ) - - -@dsl_user_op -def load_global_u32x4( - pointer: cute.Pointer, - *, - volatile: cutlass.Constexpr[bool] = False, - loc=None, - ip=None, -): - address = pointer.toint(loc=loc, ip=ip) - opcode = "ld.volatile.global.v4.u32" if volatile else "ld.global.v4.u32" - loaded = _asm( - llvm.StructType.get_literal([T.i32()] * 4), - [address.ir_value(loc=loc, ip=ip)], - f"{opcode} {{$0, $1, $2, $3}}, [$4];", - "=r,=r,=r,=r,l", - side_effects=volatile, - loc=loc, - ip=ip, - ) - packed = vector.from_elements( - ir.VectorType.get([4], T.i32(), loc=loc), - [ - llvm.extractvalue(T.i32(), loaded, [index], loc=loc, ip=ip) - for index in range(4) - ], - loc=loc, - ip=ip, - ) - return cute.TensorSSA(packed, 4, Uint32) - - -@dsl_user_op -def load_global_u32x2(pointer: cute.Pointer, *, loc=None, ip=None): - address = pointer.toint(loc=loc, ip=ip) - loaded = _asm( - llvm.StructType.get_literal([T.i32()] * 2), - [address.ir_value(loc=loc, ip=ip)], - "ld.global.v2.u32 {$0, $1}, [$2];", - "=r,=r,l", - side_effects=False, - loc=loc, - ip=ip, - ) - packed = vector.from_elements( - ir.VectorType.get([2], T.i32(), loc=loc), - [ - llvm.extractvalue(T.i32(), loaded, [index], loc=loc, ip=ip) - for index in range(2) - ], - loc=loc, - ip=ip, - ) - return cute.TensorSSA(packed, 2, Uint32) - - -@dsl_user_op -def load_global_bf16_as_f32(address: Int64, *, loc=None, ip=None) -> Float32: - return Float32( - _asm( - T.f32(), - [address.ir_value(loc=loc, ip=ip)], - "{\n\t.reg .b16 bits;\n\tld.global.b16 bits, [$1];\n\t" - "cvt.f32.bf16 $0, bits;\n\t}", - "=f,l", - side_effects=False, - loc=loc, - ip=ip, - ) - ) - - -@dsl_user_op -def store_global_u32x4(address: Int64, packed, *, loc=None, ip=None) -> None: - words = [packed[index].ir_value(loc=loc, ip=ip) for index in range(4)] - _asm( - None, - [address.ir_value(loc=loc, ip=ip), *words], - "st.global.v4.u32 [$0], {$1, $2, $3, $4};", - "l,r,r,r,r", - side_effects=True, - loc=loc, - ip=ip, - ) - - -@dsl_user_op -def store_lamport_sentinel_u32x4(address: Int64, *, loc=None, ip=None) -> None: - sentinel = Uint32(NEGATIVE_ZERO_BF16_PAIR).ir_value(loc=loc, ip=ip) - _asm( - None, - [address.ir_value(loc=loc, ip=ip), sentinel, sentinel, sentinel, sentinel], - "st.global.v4.u32 [$0], {$1, $2, $3, $4};", - "l,r,r,r,r", - side_effects=True, - loc=loc, - ip=ip, - ) - - -@dsl_user_op -def load_volatile_u32(pointer: cute.Pointer, *, loc=None, ip=None) -> Uint32: - address = pointer.toint(loc=loc, ip=ip) - return Uint32( - _asm( - T.i32(), - [address.ir_value(loc=loc, ip=ip)], - "ld.volatile.global.u32 $0, [$1];", - "=r,l", - side_effects=True, - loc=loc, - ip=ip, - ) - ) - - -@dsl_user_op -def store_global_u32( - pointer: cute.Pointer, value: Uint32, *, loc=None, ip=None -) -> None: - address = pointer.toint(loc=loc, ip=ip) - _asm( - None, - [address.ir_value(loc=loc, ip=ip), value.ir_value(loc=loc, ip=ip)], - "st.global.u32 [$0], $1;", - "l,r", - side_effects=True, - loc=loc, - ip=ip, - ) - - -@dsl_user_op -def packed_u32x4_to_bf16x8(packed, *, loc=None, ip=None): - values = llvm.bitcast( - ir.VectorType.get([VEC_BF16], cutlass.BFloat16.mlir_type, loc=loc), - packed.ir_value(loc=loc, ip=ip), - loc=loc, - ip=ip, - ) - return cute.TensorSSA(values, VEC_BF16, cutlass.BFloat16) - - -@dsl_user_op -def packed_u32x2_to_bf16x4(packed, *, loc=None, ip=None): - values = llvm.bitcast( - ir.VectorType.get([QUAD_BF16], cutlass.BFloat16.mlir_type, loc=loc), - packed.ir_value(loc=loc, ip=ip), - loc=loc, - ip=ip, - ) - return cute.TensorSSA(values, QUAD_BF16, cutlass.BFloat16) - - -@dsl_user_op -def bf16x4_to_packed_u32x2(values, *, loc=None, ip=None): - packed = llvm.bitcast( - ir.VectorType.get([2], T.i32(), loc=loc), - values.ir_value(loc=loc, ip=ip), - loc=loc, - ip=ip, - ) - return cute.TensorSSA(packed, 2, Uint32) - - -@dsl_user_op -def bf16x8_to_packed_u32x4(values, *, loc=None, ip=None): - packed = llvm.bitcast( - ir.VectorType.get([4], T.i32(), loc=loc), - values.ir_value(loc=loc, ip=ip), - loc=loc, - ip=ip, - ) - return cute.TensorSSA(packed, 4, Uint32) - - -@cute.jit -def sanitize_negative_zero_u32(word: Uint32) -> Uint32: - low = Uint16(word & Uint32(0xFFFF)) - high = Uint16(word >> Uint32(16)) - if low == Uint16(NEGATIVE_ZERO_BF16_BITS): - word = word & Uint32(0xFFFF0000) - if high == Uint16(NEGATIVE_ZERO_BF16_BITS): - word = word & Uint32(0x0000FFFF) - return word - - -@cute.jit -def sanitize_negative_zero_u32x4(packed): - sanitized = cute.make_rmem_tensor(cute.make_layout((4,)), Uint32) - for index in cutlass.range_constexpr(4): - sanitized[index] = sanitize_negative_zero_u32(packed[index]) - return sanitized.load() - - -@cute.jit -def sanitize_negative_zero_u32x2(packed): - sanitized = cute.make_rmem_tensor(cute.make_layout((2,)), Uint32) - for index in cutlass.range_constexpr(2): - sanitized[index] = sanitize_negative_zero_u32(packed[index]) - return sanitized.load() - - -@cute.jit -def fragment_has_negative_zero(packed): - dirty = False - for index in cutlass.range_constexpr(4): - word = packed[index] - dirty = ( - dirty - | (Uint16(word & Uint32(0xFFFF)) == Uint16(NEGATIVE_ZERO_BF16_BITS)) - | (Uint16(word >> Uint32(16)) == Uint16(NEGATIVE_ZERO_BF16_BITS)) - ) - return dirty - - -@dsl_user_op -def map_shared_to_peer( - smem_pointer: cute.Pointer, peer_rank: Int32, *, loc=None, ip=None -) -> Int32: - address = smem_pointer.toint(loc=loc, ip=ip).ir_value(loc=loc, ip=ip) - return Int32( - _asm( - T.i32(), - [address, peer_rank.ir_value(loc=loc, ip=ip)], - "mapa.shared::cluster.u32 $0, $1, $2;", - "=r,r,r", - side_effects=False, - loc=loc, - ip=ip, - ) - ) - - -@dsl_user_op -def store_shared_cluster_f32( - remote_address: Int32, value: Float32, *, loc=None, ip=None -) -> None: - _asm( - None, - [remote_address.ir_value(loc=loc, ip=ip), value.ir_value(loc=loc, ip=ip)], - "st.shared::cluster.f32 [$0], $1;", - "r,f", - side_effects=True, - loc=loc, - ip=ip, - ) - - -@dsl_user_op -def f32_to_bf16_bits(value: Float32, *, loc=None, ip=None) -> Uint32: - return Uint32( - _asm( - T.i32(), - [value.ir_value(loc=loc, ip=ip)], - "{\n\t.reg .b16 bits;\n\tcvt.rn.bf16.f32 bits, $1;\n\t" - "cvt.u32.u16 $0, bits;\n\t}", - "=r,f", - side_effects=False, - loc=loc, - ip=ip, - ) - ) - - -@dsl_user_op -def shuffle_sync_idx_u32( - value: Uint32, source_lane: Int32, *, loc=None, ip=None -) -> Uint32: - return Uint32( - _asm( - T.i32(), - [value.ir_value(loc=loc, ip=ip), source_lane.ir_value(loc=loc, ip=ip)], - "shfl.sync.idx.b32 $0, $1, $2, 0x1f, 0xffffffff;", - "=r,r,r", - # Preserve full-warp execution across later divergent consumers. - side_effects=True, - loc=loc, - ip=ip, - ) - ) - - -@dsl_user_op -def stmc_bf16x2(address: Int64, packed: Uint32, *, loc=None, ip=None) -> None: - _asm( - None, - [address.ir_value(loc=loc, ip=ip), packed.ir_value(loc=loc, ip=ip)], - "multimem.st.relaxed.sys.global.bf16x2 [$0], $1;", - "l,r", - side_effects=True, - loc=loc, - ip=ip, - ) - - -@dsl_user_op -def stmc_bf16x4(address: Int64, values, *, loc=None, ip=None) -> None: - words = [values[index].ir_value(loc=loc, ip=ip) for index in range(2)] - _asm( - None, - [address.ir_value(loc=loc, ip=ip), *words], - "multimem.st.relaxed.sys.global.v2.bf16x2 [$0], {$1, $2};", - "l,r,r", - side_effects=True, - loc=loc, - ip=ip, - ) - - -@dsl_user_op -def stmc_bf16x8(address: Int64, values, *, loc=None, ip=None) -> None: - words = [values[index].ir_value(loc=loc, ip=ip) for index in range(4)] - _asm( - None, - [address.ir_value(loc=loc, ip=ip), *words], - "multimem.st.relaxed.sys.global.v4.bf16x2 [$0], {$1, $2, $3, $4};", - "l,r,r,r,r", - side_effects=True, - loc=loc, - ip=ip, - ) - - -class _GraphSafeDLPack: - __slots__ = ("tensor",) - - def __init__(self, tensor: torch.Tensor) -> None: - self.tensor = tensor - - def __dlpack__(self, stream=None): - # stream=-1 skips producer sync; CuTe launches on the current stream, - # which is the capturing one under CUDA graphs. - return self.tensor.__dlpack__(stream=-1) - - def __dlpack_device__(self): - return self.tensor.__dlpack_device__() - - -def to_cute(tensor: torch.Tensor, alignment: int) -> cute.Tensor: - return from_dlpack(_GraphSafeDLPack(tensor.detach()), assumed_align=alignment) - - -def to_cute_dynamic( - tensor: torch.Tensor, alignment: int, *, divisibility: int -) -> cute.Tensor: - return to_cute(tensor, alignment).mark_compact_shape_dynamic( - mode=0, divisibility=divisibility - ) - - -def make_fake_dynamic_compact_tensor(dtype, *, alignment: int, divisibility: int): - return make_fake_compact_tensor( - dtype, (cute.sym_int32(divisibility=divisibility),), assumed_align=alignment - ) - - -def current_cu_stream() -> cuda.CUstream: - return cuda.CUstream(torch.cuda.current_stream().cuda_stream) diff --git a/vllm/models/deepseek_v41/nvidia/specialized_decode/boundary/publishing_gemm.py b/vllm/models/deepseek_v41/nvidia/specialized_decode/boundary/publishing_gemm.py index 87e7e45fa099..3677a3432b3c 100644 --- a/vllm/models/deepseek_v41/nvidia/specialized_decode/boundary/publishing_gemm.py +++ b/vllm/models/deepseek_v41/nvidia/specialized_decode/boundary/publishing_gemm.py @@ -101,10 +101,7 @@ QuantizedActivation, as_quantized_activation, ) -from vllm.models.deepseek_v41.common.ops.query_quant import mxfp8_scale_bytes - -from ...ops.cute_dsl.all_reduce_mhc import ACTIVE_STAGE, NEXT_STAGE -from ...ops.cute_dsl.primitives import ( +from vllm.models.common.ops.moe_tail_fusion.primitives import ( VEC_BF16, _asm, current_cu_stream, @@ -113,6 +110,9 @@ shuffle_sync_idx_u32, stmc_bf16x8, ) +from vllm.models.deepseek_v41.common.ops.query_quant import mxfp8_scale_bytes + +from ...ops.cute_dsl.all_reduce_mhc import ACTIVE_STAGE, NEXT_STAGE from .. import LOW_BATCH_MAX_ROWS from ..attention.mxfp8 import Tactic, mxfp8_eligible from .all_reduce import BoundaryAllReduce diff --git a/vllm/models/deepseek_v41/nvidia/specialized_decode/moe/routed_expert_front_cute.py b/vllm/models/deepseek_v41/nvidia/specialized_decode/moe/routed_expert_front_cute.py index 99a87c22bcc7..871b3032ddef 100644 --- a/vllm/models/deepseek_v41/nvidia/specialized_decode/moe/routed_expert_front_cute.py +++ b/vllm/models/deepseek_v41/nvidia/specialized_decode/moe/routed_expert_front_cute.py @@ -74,7 +74,8 @@ from cutlass._mlir.dialects import llvm from cutlass.cutlass_dsl import T, dsl_user_op -from ...ops.cute_dsl.primitives import load_global_u32x4 +from vllm.models.common.ops.moe_tail_fusion.primitives import load_global_u32x4 + from .routed_expert_route_cute import ( MAX_EXPERTS, WORDS, diff --git a/vllm/models/deepseek_v41/nvidia/specialized_decode/moe/routed_expert_gemm.py b/vllm/models/deepseek_v41/nvidia/specialized_decode/moe/routed_expert_gemm.py index f7120d8948dc..590fe2675a2a 100644 --- a/vllm/models/deepseek_v41/nvidia/specialized_decode/moe/routed_expert_gemm.py +++ b/vllm/models/deepseek_v41/nvidia/specialized_decode/moe/routed_expert_gemm.py @@ -55,8 +55,8 @@ from vllm.logger import init_logger from vllm.model_executor.layers.fused_moe.moe_output import UnfinalizedMoEOutput +from vllm.models.common.ops.moe_tail_fusion.primitives import current_cu_stream -from ...ops.cute_dsl.primitives import current_cu_stream from .routed_expert_front_cute import RoutedExpertFront from .routed_expert_gemm_cute import ( RoutedExpertGemm1, diff --git a/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/allreduce_rmsnorm_reduce_scatter_early_exit.py b/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/allreduce_rmsnorm_reduce_scatter_early_exit.py index 67d5cfdf081d..41b10f7d1dc9 100644 --- a/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/allreduce_rmsnorm_reduce_scatter_early_exit.py +++ b/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/allreduce_rmsnorm_reduce_scatter_early_exit.py @@ -15,15 +15,16 @@ import torch.distributed as dist import torch.distributed._symmetric_memory as symm_mem from cutlass import BFloat16, Float32, Int32, Int64, Uint32 +from cutlass._mlir import ir +from cutlass._mlir.dialects import llvm, vector +from cutlass.cutlass_dsl import T, dsl_user_op from vllm.model_executor.layers.fused_moe.moe_output import UnfinalizedMoEOutput - -from .primitives import ( - NUM_LAMPORT_BUFFERS, +from vllm.models.common.ops.moe_tail_fusion.primitives import ( + LAMPORT_GENERATIONS, PACKED_BYTES, VEC_BF16, bf16x8_to_packed_u32x4, - finalize_top16_bf16, fragment_is_dirty, load_global_u32x4, load_shared_f32x2, @@ -32,7 +33,7 @@ map_shared_to_peer, packed_u32x4_to_bf16x8, red_async_release_gpu_add_u32, - sanitize_negative_zero, + sanitize_negative_zero_u32x4, stmc_bf16x8, store_global_u32x4, store_lamport_sentinel_128, @@ -45,6 +46,103 @@ _SEVEN_CTA_MAX_M = 4 +def _make_top16_bf16_finalize_asm() -> str: + lines = [ + "{", + ".reg .pred _valid<16>;", + ".reg .s32 _index<16>;", + ".reg .b32 _weight_words<8>;", + ".reg .b16 _weights<16>;", + ".reg .b32 _data<64>;", + ".reg .b16 _lo, _hi;", + ".reg .f32 _acc<8>;", + ".reg .u64 _address<16>;", + "ld.global.v4.u32 {_index0, _index1, _index2, _index3}, [$5];", + "ld.global.v4.u32 {_index4, _index5, _index6, _index7}, [$5+16];", + "ld.global.v4.u32 {_index8, _index9, _index10, _index11}, [$5+32];", + "ld.global.v4.u32 {_index12, _index13, _index14, _index15}, [$5+48];", + "ld.global.v4.u32 " + "{_weight_words0, _weight_words1, _weight_words2, " + "_weight_words3}, [$6];", + "ld.global.v4.u32 " + "{_weight_words4, _weight_words5, _weight_words6, " + "_weight_words7}, [$6+16];", + ] + for pair in range(8): + lines.append( + f"mov.b32 {{_weights{2 * pair}, _weights{2 * pair + 1}}}, " + f"_weight_words{pair};" + ) + for element in range(8): + lines.append(f"mov.f32 _acc{element}, 0f00000000;") + for route in range(16): + data = 4 * route + lines.extend( + [ + f"setp.ge.s32 _valid{route}, _index{route}, 0;", + f"@_valid{route} mad.wide.s32 _address{route}, " + f"_index{route}, 7168, $4;", + f"@_valid{route} ld.global.v4.u32 " + f"{{_data{data}, _data{data + 1}, _data{data + 2}, " + f"_data{data + 3}}}, [_address{route}];", + ] + ) + for route in range(16): + for pair in range(4): + data = 4 * route + pair + element = 2 * pair + lines.extend( + [ + f"@_valid{route} mov.b32 {{_lo, _hi}}, _data{data};", + f"@_valid{route} fma.rn.f32.bf16 _acc{element}, _lo, " + f"_weights{route}, _acc{element};", + f"@_valid{route} fma.rn.f32.bf16 _acc{element + 1}, _hi, " + f"_weights{route}, _acc{element + 1};", + ] + ) + for pair in range(4): + lines.append(f"cvt.rn.bf16x2.f32 ${pair}, _acc{2 * pair + 1}, _acc{2 * pair};") + lines.append("}") + return "\n".join(lines) + + +_TOP16_BF16_FINALIZE_ASM = _make_top16_bf16_finalize_asm() + + +@dsl_user_op +def finalize_top16_bf16( + gemm2_vector: cute.Pointer, + route_indices: cute.Pointer, + route_weights: cute.Pointer, + *, + loc=None, + ip=None, +): + """Finalize one Kimi K3 top-16 vector with wide metadata loads.""" + addresses = [ + pointer.toint(loc=loc, ip=ip).ir_value(loc=loc, ip=ip) + for pointer in (gemm2_vector, route_indices, route_weights) + ] + out = llvm.inline_asm( + llvm.StructType.get_literal([T.i32()] * 4), + addresses, + _TOP16_BF16_FINALIZE_ASM, + "=r,=r,=r,=r,l,l,l", + has_side_effects=False, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + packed = vector.from_elements( + ir.VectorType.get([4], T.i32(), loc=loc), + [llvm.extractvalue(T.i32(), out, [i], loc=loc, ip=ip) for i in range(4)], + loc=loc, + ip=ip, + ) + return cute.TensorSSA(packed, 4, Uint32) + + def _mapping( tp_size: int, latent_dim: int, @@ -367,7 +465,7 @@ def _token_device( cute.AddressSpace.gmem, assumed_align=16, ) - local_packed = sanitize_negative_zero( + local_packed = sanitize_negative_zero_u32x4( finalize_top16_bf16( gemm2_vector, route_indices, @@ -402,7 +500,7 @@ def _token_device( local_values[element] + values[element].to(Float32) * weight ) - local_packed = sanitize_negative_zero( + local_packed = sanitize_negative_zero_u32x4( bf16x8_to_packed_u32x4(local_values.load().to(BFloat16)) ) else: @@ -412,7 +510,7 @@ def _token_device( cute.AddressSpace.gmem, assumed_align=16, ) - local_packed = sanitize_negative_zero( + local_packed = sanitize_negative_zero_u32x4( load_global_u32x4(local_ptr, volatile=False) ) multicast_offset = ( @@ -592,7 +690,7 @@ def _token_device( arrived = load_volatile_u32(access_counter) while arrived < Uint32(m): arrived = load_volatile_u32(access_counter) - next_index = (current_index + Uint32(1)) % Uint32(NUM_LAMPORT_BUFFERS) + next_index = (current_index + Uint32(1)) % Uint32(LAMPORT_GENERATIONS) actual_bytes = Uint32(m) * Uint32(self.tp_size * self.latent_dim * 2) cute.arch.store((latent_flags.iterator + 0).llvm_ptr, next_index) cute.arch.store((latent_flags.iterator + 1).llvm_ptr, current_index) @@ -653,7 +751,7 @@ def _token_device( cute.AddressSpace.gmem, assumed_align=16, ) - local_packed = sanitize_negative_zero( + local_packed = sanitize_negative_zero_u32x4( load_global_u32x4(source_ptr, volatile=False) ) destination_element = current_elements + ( @@ -771,7 +869,7 @@ def _token_device( target = Uint32(m) * Uint32(self.shared_roles) while arrived < target: arrived = load_volatile_u32(access_counter) - next_index = (current_index + Uint32(1)) % Uint32(NUM_LAMPORT_BUFFERS) + next_index = (current_index + Uint32(1)) % Uint32(LAMPORT_GENERATIONS) actual_bytes = Uint32(m) * Uint32(self.tp_size * self.shard_dim * 2) cute.arch.store((shared_flags.iterator + 0).llvm_ptr, next_index) cute.arch.store((shared_flags.iterator + 1).llvm_ptr, current_index) @@ -1071,7 +1169,7 @@ def __init__( ) bytes_per_routed_buffer = max_m * tp_size * latent_dim * 2 - routed_bytes = NUM_LAMPORT_BUFFERS * bytes_per_routed_buffer + routed_bytes = LAMPORT_GENERATIONS * bytes_per_routed_buffer self._routed_workspace = symm_mem.empty( routed_bytes // 4, dtype=torch.float32, @@ -1080,7 +1178,7 @@ def __init__( self._routed_symm_mem = symm_mem.rendezvous(self._routed_workspace, group) self._routed_workspace.fill_(-0.0) actual_bytes_per_buffer = ( - self._routed_symm_mem.buffer_size // NUM_LAMPORT_BUFFERS // 16 * 16 + self._routed_symm_mem.buffer_size // LAMPORT_GENERATIONS // 16 * 16 ) if actual_bytes_per_buffer < bytes_per_routed_buffer: raise RuntimeError("routed symmetric workspace is too small") @@ -1105,7 +1203,7 @@ def __init__( self._shared_shard = self._shared_output[:, shard_start:shard_end] self._shared_workspace = symm_mem.empty( - (NUM_LAMPORT_BUFFERS, max_m, tp_size, self.shard_dim), + (LAMPORT_GENERATIONS, max_m, tp_size, self.shard_dim), dtype=torch.bfloat16, device=device, ) diff --git a/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/fused_add_multicast_gemm.py b/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/fused_add_multicast_gemm.py index ea9d86d6fa85..fd91fad1f398 100644 --- a/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/fused_add_multicast_gemm.py +++ b/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/fused_add_multicast_gemm.py @@ -52,10 +52,11 @@ from cutlass.cute.runtime import from_dlpack from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait +from vllm.models.common.ops.moe_tail_fusion.primitives import CUDAGraphCompatibleWrapper + from .fused_add_multicast_skinny_gemm import ( FusedAddMulticastSkinnyGemmKernel, ) -from .primitives import CUDAGraphCompatibleWrapper def _as_cute(tensor: torch.Tensor, *, dynamic_m: bool = False): diff --git a/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/fused_add_multicast_skinny_gemm.py b/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/fused_add_multicast_skinny_gemm.py index 21b27b278f60..635939e7fcee 100644 --- a/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/fused_add_multicast_skinny_gemm.py +++ b/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/fused_add_multicast_skinny_gemm.py @@ -14,15 +14,15 @@ from cutlass import BFloat16, Float32, Int64, const_expr from cutlass.cute.runtime import from_dlpack -from .primitives import ( +from vllm.models.common.ops.moe_tail_fusion.primitives import ( CUDAGraphCompatibleWrapper, bf16x2_to_u32, bf16x4_to_packed_u32x2, bf16x8_to_packed_u32x4, fma_f32_bf16, - sanitize_negative_zero, sanitize_negative_zero_u32, sanitize_negative_zero_u32x2, + sanitize_negative_zero_u32x4, store_global_u32, store_global_u32x2, store_global_u32x4, @@ -283,7 +283,7 @@ def kernel( packed, ) else: - packed = sanitize_negative_zero( + packed = sanitize_negative_zero_u32x4( bf16x8_to_packed_u32x4(fused.load()) ) store_global_u32x4( diff --git a/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/lamport_copy.py b/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/lamport_copy.py index b2a9100b711c..0eccdd9b8740 100644 --- a/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/lamport_copy.py +++ b/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/lamport_copy.py @@ -13,7 +13,7 @@ import torch from cutlass.cute.runtime import make_fake_compact_tensor, make_fake_stream -from .primitives import ( +from vllm.models.common.ops.moe_tail_fusion.primitives import ( VEC_BF16, fragment_is_dirty, load_global_u32x4, diff --git a/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/primitives.py b/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/primitives.py deleted file mode 100644 index 3840caf24a27..000000000000 --- a/vllm/models/kimi_k3/nvidia/ops/cute_dsl/latent_moe_tail/primitives.py +++ /dev/null @@ -1,576 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project - -"""Shared CuTe DSL primitives; this module does not define a CUDA kernel.""" - -from __future__ import annotations - -import cutlass -import cutlass.cute as cute -import torch -from cutlass import BFloat16, Float32, Int32, Int64, Uint16, Uint32 -from cutlass._mlir import ir -from cutlass._mlir.dialects import llvm, vector -from cutlass.cute.runtime import from_dlpack -from cutlass.cutlass_dsl import T, dsl_user_op - -VEC_BF16 = 8 -PACKED_BYTES = 16 -NUM_LAMPORT_BUFFERS = 3 -NEG_ZERO_F32_BITS = 0x80000000 -NEG_ZERO_BF16_BITS = 0x8000 - - -class CUDAGraphCompatibleWrapper: - """DLPack view that does not synchronize with the producer stream.""" - - def __init__(self, tensor: torch.Tensor): - self.tensor = tensor - - def __dlpack__(self, stream=None): - return self.tensor.__dlpack__(stream=-1) - - def __dlpack_device__(self): - return self.tensor.__dlpack_device__() - - -def to_cute(tensor: torch.Tensor, assumed_align: int = 16) -> cute.Tensor: - return from_dlpack( - CUDAGraphCompatibleWrapper(tensor.detach()), assumed_align=assumed_align - ) - - -def to_cute_dynamic_m( - tensor: torch.Tensor, - *, - mode: int, - assumed_align: int = 16, -) -> cute.Tensor: - """Expose exactly one compact tensor mode as a runtime shape. - - Model dimensions remain part of the compiled tensor type. Only the token - mode is symbolic, so changing M within an Op's capacity reuses the same - compiled kernel. - """ - return to_cute(tensor, assumed_align).mark_compact_shape_dynamic( - mode=mode, - stride_order=tensor.dim_order(), - ) - - -@dsl_user_op -def fma_f32_bf16( - a: BFloat16, - b: BFloat16, - acc: Float32, - *, - loc=None, - ip=None, -) -> Float32: - a_bits = llvm.bitcast(T.i16(), a.ir_value(loc=loc, ip=ip), loc=loc, ip=ip) - b_bits = llvm.bitcast(T.i16(), b.ir_value(loc=loc, ip=ip), loc=loc, ip=ip) - result = llvm.inline_asm( - T.f32(), - [a_bits, b_bits, acc.ir_value(loc=loc, ip=ip)], - "fma.rn.f32.bf16 $0, $1, $2, $3;", - "=f,h,h,f", - has_side_effects=False, - is_align_stack=False, - asm_dialect=llvm.AsmDialect.AD_ATT, - loc=loc, - ip=ip, - ) - return Float32(result) - - -@dsl_user_op -def load_global_u32x4( - pointer: cute.Pointer, - *, - volatile: cutlass.Constexpr[bool] = False, - loc=None, - ip=None, -): - """Load one 128-bit fragment as four u32 registers. - - The volatile form is the Lamport polling load. Marking the asm - side-effecting prevents loop-invariant motion and common-subexpression - elimination across polling iterations. - """ - address = pointer.toint(loc=loc, ip=ip) - opcode = "ld.volatile.global.v4.u32" if volatile else "ld.global.v4.u32" - out = llvm.inline_asm( - llvm.StructType.get_literal([T.i32()] * 4), - [address.ir_value(loc=loc, ip=ip)], - f"{opcode} {{$0, $1, $2, $3}}, [$4];", - "=r,=r,=r,=r,l", - has_side_effects=volatile, - is_align_stack=False, - asm_dialect=llvm.AsmDialect.AD_ATT, - loc=loc, - ip=ip, - ) - packed = vector.from_elements( - ir.VectorType.get([4], T.i32(), loc=loc), - [llvm.extractvalue(T.i32(), out, [i], loc=loc, ip=ip) for i in range(4)], - loc=loc, - ip=ip, - ) - return cute.TensorSSA(packed, 4, Uint32) - - -def _make_top16_bf16_finalize_asm() -> str: - lines = [ - "{", - ".reg .pred _valid<16>;", - ".reg .s32 _index<16>;", - ".reg .b32 _weight_words<8>;", - ".reg .b16 _weights<16>;", - ".reg .b32 _data<64>;", - ".reg .b16 _lo, _hi;", - ".reg .f32 _acc<8>;", - ".reg .u64 _address<16>;", - "ld.global.v4.u32 {_index0, _index1, _index2, _index3}, [$5];", - "ld.global.v4.u32 {_index4, _index5, _index6, _index7}, [$5+16];", - "ld.global.v4.u32 {_index8, _index9, _index10, _index11}, [$5+32];", - "ld.global.v4.u32 {_index12, _index13, _index14, _index15}, [$5+48];", - "ld.global.v4.u32 " - "{_weight_words0, _weight_words1, _weight_words2, " - "_weight_words3}, [$6];", - "ld.global.v4.u32 " - "{_weight_words4, _weight_words5, _weight_words6, " - "_weight_words7}, [$6+16];", - ] - for pair in range(8): - lines.append( - f"mov.b32 {{_weights{2 * pair}, _weights{2 * pair + 1}}}, " - f"_weight_words{pair};" - ) - for element in range(8): - lines.append(f"mov.f32 _acc{element}, 0f00000000;") - for route in range(16): - data = 4 * route - lines.extend( - [ - f"setp.ge.s32 _valid{route}, _index{route}, 0;", - f"@_valid{route} mad.wide.s32 _address{route}, " - f"_index{route}, 7168, $4;", - f"@_valid{route} ld.global.v4.u32 " - f"{{_data{data}, _data{data + 1}, _data{data + 2}, " - f"_data{data + 3}}}, [_address{route}];", - ] - ) - for route in range(16): - for pair in range(4): - data = 4 * route + pair - element = 2 * pair - lines.extend( - [ - f"@_valid{route} mov.b32 {{_lo, _hi}}, _data{data};", - f"@_valid{route} fma.rn.f32.bf16 _acc{element}, _lo, " - f"_weights{route}, _acc{element};", - f"@_valid{route} fma.rn.f32.bf16 _acc{element + 1}, _hi, " - f"_weights{route}, _acc{element + 1};", - ] - ) - for pair in range(4): - lines.append(f"cvt.rn.bf16x2.f32 ${pair}, _acc{2 * pair + 1}, _acc{2 * pair};") - lines.append("}") - return "\n".join(lines) - - -_TOP16_BF16_FINALIZE_ASM = _make_top16_bf16_finalize_asm() - - -@dsl_user_op -def finalize_top16_bf16( - gemm2_vector: cute.Pointer, - route_indices: cute.Pointer, - route_weights: cute.Pointer, - *, - loc=None, - ip=None, -): - """Finalize one Kimi K3 top-16 vector with wide metadata loads.""" - addresses = [ - pointer.toint(loc=loc, ip=ip).ir_value(loc=loc, ip=ip) - for pointer in (gemm2_vector, route_indices, route_weights) - ] - out = llvm.inline_asm( - llvm.StructType.get_literal([T.i32()] * 4), - addresses, - _TOP16_BF16_FINALIZE_ASM, - "=r,=r,=r,=r,l,l,l", - has_side_effects=False, - is_align_stack=False, - asm_dialect=llvm.AsmDialect.AD_ATT, - loc=loc, - ip=ip, - ) - packed = vector.from_elements( - ir.VectorType.get([4], T.i32(), loc=loc), - [llvm.extractvalue(T.i32(), out, [i], loc=loc, ip=ip) for i in range(4)], - loc=loc, - ip=ip, - ) - return cute.TensorSSA(packed, 4, Uint32) - - -@dsl_user_op -def store_global_u32x4( - address: Int64, - packed, - *, - volatile: cutlass.Constexpr[bool] = False, - loc=None, - ip=None, -) -> None: - """Store four packed words to an ordinary or NVLS multicast global VA.""" - words = [packed[i].ir_value(loc=loc, ip=ip) for i in range(4)] - opcode = "st.volatile.global.v4.u32" if volatile else "st.global.v4.u32" - llvm.inline_asm( - None, - [address.ir_value(loc=loc, ip=ip), *words], - f"{opcode} [$0], {{$1, $2, $3, $4}};", - "l,r,r,r,r", - has_side_effects=True, - is_align_stack=False, - asm_dialect=llvm.AsmDialect.AD_ATT, - loc=loc, - ip=ip, - ) - - -@dsl_user_op -def store_global_u32x2( - address: Int64, - packed, - *, - loc=None, - ip=None, -) -> None: - words = [packed[i].ir_value(loc=loc, ip=ip) for i in range(2)] - llvm.inline_asm( - None, - [address.ir_value(loc=loc, ip=ip), *words], - "st.global.v2.u32 [$0], {$1, $2};", - "l,r,r", - has_side_effects=True, - is_align_stack=False, - asm_dialect=llvm.AsmDialect.AD_ATT, - loc=loc, - ip=ip, - ) - - -@dsl_user_op -def store_global_u32( - address: Int64, - word: Uint32, - *, - loc=None, - ip=None, -) -> None: - llvm.inline_asm( - None, - [ - address.ir_value(loc=loc, ip=ip), - word.ir_value(loc=loc, ip=ip), - ], - "st.global.u32 [$0], $1;", - "l,r", - has_side_effects=True, - is_align_stack=False, - asm_dialect=llvm.AsmDialect.AD_ATT, - loc=loc, - ip=ip, - ) - - -@dsl_user_op -def stmc_bf16x8(address: Int64, packed, *, loc=None, ip=None) -> None: - """Publish eight BF16 values through an NVLS multicast mapping.""" - words = [packed[i].ir_value(loc=loc, ip=ip) for i in range(4)] - llvm.inline_asm( - None, - [address.ir_value(loc=loc, ip=ip), *words], - "multimem.st.relaxed.sys.global.v4.bf16x2 [$0], {$1, $2, $3, $4};", - "l,r,r,r,r", - has_side_effects=True, - is_align_stack=False, - asm_dialect=llvm.AsmDialect.AD_ATT, - loc=loc, - ip=ip, - ) - - -@dsl_user_op -def store_lamport_sentinel_128(pointer: cute.Pointer, *, loc=None, ip=None) -> None: - """Reset one Lamport fragment to four FP32 negative-zero bit patterns.""" - address = pointer.toint(loc=loc, ip=ip) - value = Uint32(NEG_ZERO_F32_BITS).ir_value(loc=loc, ip=ip) - llvm.inline_asm( - None, - [address.ir_value(loc=loc, ip=ip), value, value, value, value], - "st.global.v4.u32 [$0], {$1, $2, $3, $4};", - "l,r,r,r,r", - has_side_effects=True, - is_align_stack=False, - asm_dialect=llvm.AsmDialect.AD_ATT, - loc=loc, - ip=ip, - ) - - -@dsl_user_op -def red_async_release_gpu_add_u32( - pointer: cute.Pointer, value: Uint32, *, loc=None, ip=None -) -> None: - """The exact SM100 arrival primitive used by upstream LamportFlags.""" - address = pointer.toint(loc=loc, ip=ip) - llvm.inline_asm( - None, - [ - address.ir_value(loc=loc, ip=ip), - value.ir_value(loc=loc, ip=ip), - ], - "red.async.release.global.gpu.add.u32 [$0], $1;", - "l,r", - has_side_effects=True, - is_align_stack=False, - asm_dialect=llvm.AsmDialect.AD_ATT, - loc=loc, - ip=ip, - ) - - -@dsl_user_op -def load_volatile_u32(pointer: cute.Pointer, *, loc=None, ip=None) -> Uint32: - address = pointer.toint(loc=loc, ip=ip) - return Uint32( - llvm.inline_asm( - T.i32(), - [address.ir_value(loc=loc, ip=ip)], - "ld.volatile.global.u32 $0, [$1];", - "=r,l", - has_side_effects=True, - is_align_stack=False, - asm_dialect=llvm.AsmDialect.AD_ATT, - loc=loc, - ip=ip, - ) - ) - - -@dsl_user_op -def map_shared_to_peer( - smem_ptr: cute.Pointer, - peer_rank: Int32, - *, - loc=None, - ip=None, -) -> Int32: - """Map a local shared-memory slot to the same slot in a peer CTA.""" - smem_address = smem_ptr.toint(loc=loc, ip=ip).ir_value() - return Int32( - llvm.inline_asm( - T.i32(), - [smem_address, peer_rank.ir_value(loc=loc, ip=ip)], - "mapa.shared::cluster.u32 $0, $1, $2;", - "=r,r,r", - has_side_effects=False, - is_align_stack=False, - asm_dialect=llvm.AsmDialect.AD_ATT, - loc=loc, - ip=ip, - ) - ) - - -@dsl_user_op -def store_shared_cluster_f32( - remote_address: Int32, - value: Float32, - *, - loc=None, - ip=None, -) -> None: - llvm.inline_asm( - None, - [ - remote_address.ir_value(loc=loc, ip=ip), - value.ir_value(loc=loc, ip=ip), - ], - "st.shared::cluster.f32 [$0], $1;", - "r,f", - has_side_effects=True, - is_align_stack=False, - asm_dialect=llvm.AsmDialect.AD_ATT, - loc=loc, - ip=ip, - ) - - -@dsl_user_op -def load_shared_f32x2(pointer: cute.Pointer, *, loc=None, ip=None): - """Load two aligned FP32 DSM partials from local shared memory.""" - address = Int32(pointer.toint(loc=loc, ip=ip)) - out = llvm.inline_asm( - llvm.StructType.get_literal([T.f32()] * 2), - [address.ir_value(loc=loc, ip=ip)], - "ld.shared.v2.f32 {$0, $1}, [$2];", - "=f,=f,r", - has_side_effects=True, - is_align_stack=False, - asm_dialect=llvm.AsmDialect.AD_ATT, - loc=loc, - ip=ip, - ) - return tuple( - Float32(llvm.extractvalue(T.f32(), out, [i], loc=loc, ip=ip)) for i in range(2) - ) - - -@dsl_user_op -def load_shared_f32x4(pointer: cute.Pointer, *, loc=None, ip=None): - """Load four aligned FP32 DSM partials from local shared memory.""" - address = Int32(pointer.toint(loc=loc, ip=ip)) - out = llvm.inline_asm( - llvm.StructType.get_literal([T.f32()] * 4), - [address.ir_value(loc=loc, ip=ip)], - "ld.shared.v4.f32 {$0, $1, $2, $3}, [$4];", - "=f,=f,=f,=f,r", - has_side_effects=True, - is_align_stack=False, - asm_dialect=llvm.AsmDialect.AD_ATT, - loc=loc, - ip=ip, - ) - return tuple( - Float32(llvm.extractvalue(T.f32(), out, [i], loc=loc, ip=ip)) for i in range(4) - ) - - -@dsl_user_op -def packed_u32x4_to_bf16x8(packed, *, loc=None, ip=None): - target_type = ir.VectorType.get([VEC_BF16], BFloat16.mlir_type, loc=loc) - values = llvm.bitcast( - target_type, - packed.ir_value(loc=loc, ip=ip), - loc=loc, - ip=ip, - ) - return cute.TensorSSA(values, VEC_BF16, BFloat16) - - -@dsl_user_op -def bf16x8_to_packed_u32x4(values, *, loc=None, ip=None): - target_type = ir.VectorType.get([4], T.i32(), loc=loc) - packed = llvm.bitcast( - target_type, - values.ir_value(loc=loc, ip=ip), - loc=loc, - ip=ip, - ) - return cute.TensorSSA(packed, 4, Uint32) - - -@dsl_user_op -def bf16x4_to_packed_u32x2(values, *, loc=None, ip=None): - target_type = ir.VectorType.get([2], T.i32(), loc=loc) - packed = llvm.bitcast( - target_type, - values.ir_value(loc=loc, ip=ip), - loc=loc, - ip=ip, - ) - return cute.TensorSSA(packed, 2, Uint32) - - -@dsl_user_op -def bf16x2_to_u32(values, *, loc=None, ip=None): - packed = llvm.bitcast( - T.i32(), - values.ir_value(loc=loc, ip=ip), - loc=loc, - ip=ip, - ) - return Uint32(packed) - - -@cute.jit -def sanitize_negative_zero_u32(word): - low = Uint16(word & Uint32(0xFFFF)) - high = Uint16(word >> Uint32(16)) - if low == Uint16(NEG_ZERO_BF16_BITS): - word = word & Uint32(0xFFFF0000) - if high == Uint16(NEG_ZERO_BF16_BITS): - word = word & Uint32(0x0000FFFF) - return word - - -@cute.jit -def sanitize_negative_zero_u32x2(packed): - result = cute.make_rmem_tensor(cute.make_layout((2,)), Uint32) - for i in cutlass.range_constexpr(2): - result[i] = sanitize_negative_zero_u32(packed[i]) - return result.load() - - -@cute.jit -def sanitize_negative_zero(packed): - """Turn real BF16 -0 into +0 so it cannot equal the empty sentinel.""" - result = cute.make_rmem_tensor(cute.make_layout((4,)), Uint32) - for i in cutlass.range_constexpr(4): - word = packed[i] - low = Uint16(word & Uint32(0xFFFF)) - high = Uint16(word >> Uint32(16)) - if low == Uint16(NEG_ZERO_BF16_BITS): - word = word & Uint32(0xFFFF0000) - if high == Uint16(NEG_ZERO_BF16_BITS): - word = word & Uint32(0x0000FFFF) - result[i] = word - return result.load() - - -@cute.jit -def fragment_is_dirty(packed): - """Bit-exact upstream sentinel check: one comparison per 32-bit word.""" - dirty = packed[0] == Uint32(NEG_ZERO_F32_BITS) - for i in cutlass.range_constexpr(1, 4): - dirty = dirty | (packed[i] == Uint32(NEG_ZERO_F32_BITS)) - return dirty - - -@cute.jit -def warp_sum_specialized( - value: Float32, - warp_idx: Int32, - lane: Int32, - warps: cutlass.Constexpr[int], - last_warp_lanes: cutlass.Constexpr[int], - last_warp_mask: cutlass.Constexpr[int], -) -> Float32: - """Warp sum supporting a compile-time partial final warp.""" - if warp_idx == Int32(warps - 1) and cutlass.const_expr(last_warp_lanes < 32): - for offset in cutlass.range_constexpr(16, 0, -1): - # range_constexpr does not provide powers-of-two stepping. - if cutlass.const_expr(offset in (16, 8, 4, 2, 1)): - other = cute.arch.shuffle_sync_bfly( - value, - offset=offset, - mask=last_warp_mask, - mask_and_clamp=31, - ) - if (lane ^ Int32(offset)) < Int32(last_warp_lanes): - value = value + other - else: - for offset in cutlass.range_constexpr(16, 0, -1): - if cutlass.const_expr(offset in (16, 8, 4, 2, 1)): - value = value + cute.arch.shuffle_sync_bfly( - value, - offset=offset, - mask=-1, - mask_and_clamp=31, - ) - return value diff --git a/vllm/models/kimi_k3/nvidia/specialized_decode/cutedsl/common/host.py b/vllm/models/kimi_k3/nvidia/specialized_decode/cutedsl/common/host.py index 2833c3a37d13..c6efad7cc3d3 100644 --- a/vllm/models/kimi_k3/nvidia/specialized_decode/cutedsl/common/host.py +++ b/vllm/models/kimi_k3/nvidia/specialized_decode/cutedsl/common/host.py @@ -11,7 +11,7 @@ import torch from cutlass.cute.runtime import make_fake_tensor -from vllm.models.kimi_k3.nvidia.ops.cute_dsl.latent_moe_tail.primitives import to_cute +from vllm.models.common.ops.moe_tail_fusion.primitives import to_cute _NAMES = ("BFloat16", "Float32", "Uint8", "Uint32", "Int32", "Int64") _DTYPES = {getattr(torch, name.lower()): getattr(cutlass, name) for name in _NAMES} diff --git a/vllm/models/kimi_k3/nvidia/specialized_decode/cutedsl/moe/small_batch/front_tp16.py b/vllm/models/kimi_k3/nvidia/specialized_decode/cutedsl/moe/small_batch/front_tp16.py index 7e80d430488e..032261257e25 100644 --- a/vllm/models/kimi_k3/nvidia/specialized_decode/cutedsl/moe/small_batch/front_tp16.py +++ b/vllm/models/kimi_k3/nvidia/specialized_decode/cutedsl/moe/small_batch/front_tp16.py @@ -12,7 +12,7 @@ from cutlass import BFloat16, Float32, Int32, Uint8, Uint32, Uint64 from cutlass.cute.runtime import make_fake_stream, make_fake_tensor -from .....ops.cute_dsl.latent_moe_tail.primitives import to_cute +from vllm.models.common.ops.moe_tail_fusion.primitives import to_cute from ...common.primitives import ( alloc, asm, diff --git a/vllm/models/kimi_k3/nvidia/specialized_decode/runtime/prefetch.py b/vllm/models/kimi_k3/nvidia/specialized_decode/runtime/prefetch.py index 8ca3e1e5277c..8eda4ebe11e0 100644 --- a/vllm/models/kimi_k3/nvidia/specialized_decode/runtime/prefetch.py +++ b/vllm/models/kimi_k3/nvidia/specialized_decode/runtime/prefetch.py @@ -36,7 +36,7 @@ import cuda.bindings.driver as cuda import torch -from ...ops.cute_dsl.latent_moe_tail.primitives import to_cute +from vllm.models.common.ops.moe_tail_fusion.primitives import to_cute from ..cutedsl.common.host import _checked, resolve_kernel from ..cutedsl.common.policy import batch_table from ..cutedsl.common.prefetch import compile_kernel diff --git a/vllm/models/minimax_m3/amd/indexer_nvfp4.py b/vllm/models/minimax_m3/amd/indexer_nvfp4.py new file mode 100644 index 000000000000..47d67244f3ff --- /dev/null +++ b/vllm/models/minimax_m3/amd/indexer_nvfp4.py @@ -0,0 +1,239 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MiniMax M3 lightning indexer over NVFP4 index-K pages on ROCm (gfx950). + +Keys score as ``e4m3_rn_satfinite(e2m1 * scale)`` with AITER's init / local +sentinels; the top-k writes logical block ids for the NVFP4 attend, no page +table. With ``indexer_decode_cp`` at TP4, decode steps of 4 rows per request +and at most 256 requests score context-parallel (``ops/index_cp``). +""" + +import torch + +from vllm.config import get_current_vllm_config +from vllm.forward_context import get_forward_context +from vllm.logger import init_logger +from vllm.models.minimax_m3.amd.indexer_msa import ( + MSA_INDEX_HEAD_DIM, + MSA_SCORE_TYPE, + MSA_SPARSE_BLOCK_SIZE, + MSA_TOPK_BLOCKS, + MiniMaxM3IndexerMSABackend, + MiniMaxM3IndexerMSAMetadata, + _score_width, +) +from vllm.models.minimax_m3.common.indexer import MiniMaxM3IndexerImpl +from vllm.platforms import current_platform +from vllm.v1.worker.ubatching import dbo_enabled + +logger = init_logger(__name__) + +# Index heads per rank (TP4 / TP2 / TP1). +NUM_INDEX_HEADS = (1, 2, 4) +# Decode CP: rows per request (DSpark 3) and the request cap. +CP_QUERY_LEN = 4 +CP_MAX_REQS = 256 + + +def rocm_nvfp4_indexer_unsupported_reason( + *, + topk_blocks: int, + sparse_block_size: int, + num_index_heads: int, + index_head_dim: int, + score_type: str, +) -> str | None: + """Why the ROCm NVFP4 indexer cannot serve this config, None when it can.""" + if not current_platform.is_rocm(): + return "needs ROCm" + from vllm.platforms.rocm import on_gfx950 + + if not on_gfx950(): + return "needs gfx950" + if (topk_blocks, sparse_block_size, index_head_dim, score_type) != ( + MSA_TOPK_BLOCKS, + MSA_SPARSE_BLOCK_SIZE, + MSA_INDEX_HEAD_DIM, + MSA_SCORE_TYPE, + ): + return ( + f"needs topk_blocks={MSA_TOPK_BLOCKS}, block_size=" + f"{MSA_SPARSE_BLOCK_SIZE}, index_head_dim={MSA_INDEX_HEAD_DIM} and " + f"score_type={MSA_SCORE_TYPE!r}" + ) + if num_index_heads not in NUM_INDEX_HEADS: + return f"needs num_index_heads in {NUM_INDEX_HEADS}, got {num_index_heads}" + return None + + +def init_rocm_nvfp4_indexer_decode_cp(max_model_len: int) -> bool: + """Set up decode CP if configured (a TP collective); returns whether it is on.""" + from vllm.distributed import get_tensor_model_parallel_world_size + + from .ops.index_cp import host as index_cp + + if not get_current_vllm_config().attention_config.indexer_decode_cp: + return False + if get_tensor_model_parallel_world_size() != index_cp.WORLD: + logger.warning_once( + "indexer_decode_cp needs TP %d on ROCm; scoring decode locally.", + index_cp.WORLD, + ) + return False + index_cp.init( + torch.device("cuda", torch.accelerator.current_device_index()), + _score_width(max_model_len, MSA_SPARSE_BLOCK_SIZE), + ) + if index_cp.get() is None: + return False + logger.info_once("MiniMax M3 NVFP4 indexer: decode context parallelism on (TP4)") + return True + + +class MiniMaxM3IndexerRocmNvfp4Impl(MiniMaxM3IndexerImpl): + """FlyDSL NVFP4 index scores + top-k block ids for prefill and decode.""" + + # Its builder materializes the prefill rows' block counts. + indexer_backend_cls = MiniMaxM3IndexerMSABackend + + def __init__(self, **kwargs) -> None: + super().__init__(**kwargs) + if self.indexer_kv_dtype != "nvfp4": + raise ValueError( + f"{type(self).__name__} requires indexer_kv_dtype='nvfp4', got " + f"{self.indexer_kv_dtype!r}" + ) + reason = rocm_nvfp4_indexer_unsupported_reason( + topk_blocks=self.topk_blocks, + sparse_block_size=self.block_size, + num_index_heads=self.num_index_heads, + index_head_dim=self.index_head_dim, + score_type=self.score_type, + ) + if reason is not None: + raise ValueError(f"MiniMax M3 NVFP4 indexer on ROCm {reason}") + + def _new_score(self, rows: int, max_seq_len: int) -> torch.Tensor: + """Uninitialized: the scorer writes every block the top-k reads.""" + return torch.empty( + ( + self.num_index_heads, + rows, + _score_width(max_seq_len, self.block_size), + ), + dtype=torch.float32, + device=self.index_cache.kv_cache.device, + ) + + def _decode_cp(self, num_decodes: int, query_len: int): + from .ops.index_cp import host as index_cp + + cp = index_cp.get() + if ( + cp is None + # The push has no back-pressure; under DBO no all-reduce orders it. + or dbo_enabled() + or self.num_index_heads != 1 + or query_len != CP_QUERY_LEN + or num_decodes > CP_MAX_REQS + or num_decodes * query_len > cp.max_rows + ): + return None + return cp + + def forward( + self, + index_query: torch.Tensor, + **_aiter_table_args, + ) -> tuple[torch.Tensor | None, torch.Tensor | None]: + from .ops.index_topk_decode.host import ( + minimax_m3_index_topk_decode_indices, + minimax_m3_index_topk_prefill_indices, + ) + from .ops.nvfp4_index_decode.host import minimax_m3_nvfp4_index_score_decode + from .ops.nvfp4_index_prefill.host import ( + minimax_m3_nvfp4_index_score_prefill, + ) + + attn_metadata = get_forward_context().attn_metadata + if not isinstance(attn_metadata, dict): + return None, None # profiling run; caches unbound + md = attn_metadata[self.index_cache.prefix] + assert isinstance(md, MiniMaxM3IndexerMSAMetadata) + num_tokens = md.num_actual_tokens + nd = md.num_decode_tokens + iq = index_query[:num_tokens].view( + -1, self.num_index_heads, self.index_head_dim + ) + kv = self.index_cache.kv_cache + buf = self.topk_indices_buffer + if buf is None: + buf = torch.empty( + (self.num_index_heads, num_tokens, self.topk_blocks), + dtype=torch.int32, + device=iq.device, + ) + + decode_topk: torch.Tensor | None = None + prefill_topk: torch.Tensor | None = None + if md.num_decodes > 0: + d = md.decode + assert d is not None + cp = self._decode_cp(md.num_decodes, d.decode_query_len) + if cp is not None: + # A view of the receive buffer, valid until the next call. + score = cp.score_push( + iq[:nd, 0], + kv, + d.block_table, + d.seq_lens, + self.init_blocks, + self.local_blocks, + _score_width(d.max_seq_len, self.block_size), + ) + else: + score = self._new_score(nd, d.max_seq_len) + minimax_m3_nvfp4_index_score_decode( + iq[:nd], + kv, + score, + d.block_table, + d.seq_lens, + init_blocks=self.init_blocks, + local_blocks=self.local_blocks, + query_len=d.decode_query_len, + max_seq_len=d.max_seq_len, + ) + decode_topk = buf[:, :nd, :] + minimax_m3_index_topk_decode_indices( + score, + decode_topk, + d.seq_lens, + max_seq_len=d.max_seq_len, + query_len=d.decode_query_len, + ) + + if md.num_prefills > 0: + p = md.prefill + assert p is not None and md.prefill_num_valid_pages is not None + score = self._new_score(num_tokens - nd, p.max_seq_len) + minimax_m3_nvfp4_index_score_prefill( + iq[nd:], + kv, + score, + p.block_table, + p.cu_seqlens_q, + p.seq_lens, + init_blocks=self.init_blocks, + local_blocks=self.local_blocks, + max_query_len=p.max_query_len, + max_seq_len=p.max_seq_len, + ) + prefill_topk = buf[:, nd:num_tokens, :] + minimax_m3_index_topk_prefill_indices( + score, + prefill_topk, + max_seq_len=p.max_seq_len, + num_valid_pages=md.prefill_num_valid_pages, + ) + return decode_topk, prefill_topk diff --git a/vllm/models/minimax_m3/amd/model.py b/vllm/models/minimax_m3/amd/model.py index 3222280b65ab..63c8b42ed2b0 100644 --- a/vllm/models/minimax_m3/amd/model.py +++ b/vllm/models/minimax_m3/amd/model.py @@ -25,7 +25,6 @@ from transformers import PreTrainedConfig from vllm import _custom_ops as ops -from vllm import envs from vllm._aiter_ops import rocm_aiter_ops from vllm.compilation.breakable_cudagraph import eager_break_during_capture from vllm.config import ( @@ -45,10 +44,12 @@ from vllm.model_executor.layers.fused_moe import ( FusedMoEFactory, GateLinear, + RoutedExperts, fused_moe_make_expert_params_mapping, ) from vllm.model_executor.layers.fused_moe.utils import ( is_model_fused_shared_expert_compatible, + resolve_layer_fused_shared_expert, ) from vllm.model_executor.layers.linear import ( MergedColumnParallelLinear, @@ -58,9 +59,7 @@ ) from vllm.model_executor.layers.logits_processor import LogitsProcessor from vllm.model_executor.layers.quantization import QuantizationConfig -from vllm.model_executor.layers.quantization.utils.config_utils import ( - is_shared_expert_quant_fse_compatible, -) +from vllm.model_executor.layers.quantization.modelopt import ModelOptMxFp8Config from vllm.model_executor.layers.rotary_embedding import get_rope from vllm.model_executor.layers.vocab_parallel_embedding import ( ParallelLMHead, @@ -89,12 +88,18 @@ spec_decode_needs_target_embed, ) from vllm.model_executor.models.vision import run_dp_sharded_mrope_vision_model +from vllm.models.minimax_m3.amd import sp_prefill from vllm.models.minimax_m3.amd.indexer_msa import ( MiniMaxM3IndexerMSAImpl, MiniMaxM3MSAIndexer, msa_indexer_cp_enabled, select_msa_indexer_impl_cls, ) +from vllm.models.minimax_m3.amd.indexer_nvfp4 import ( + MiniMaxM3IndexerRocmNvfp4Impl, + init_rocm_nvfp4_indexer_decode_cp, +) +from vllm.models.minimax_m3.amd.mono.envs import envs as mono_envs from vllm.models.minimax_m3.amd.ops import ( gemma_fused_add_rmsnorm, gemma_rmsnorm, @@ -132,8 +137,12 @@ ) from vllm.models.minimax_m3.common.vision_tower import MiniMaxVLVisionModel from vllm.multimodal import MULTIMODAL_REGISTRY +from vllm.platforms.rocm import on_gfx942 from vllm.sequence import IntermediateTensors from vllm.utils.torch_utils import kv_cache_dtype_str_to_dtype +from vllm.v1.attention.ops.triton_reshape_and_cache_flash import ( + triton_reshape_and_cache_flash, +) from vllm.v1.kv_cache_interface import ( FullAttentionSpec, KVCacheSpec, @@ -146,6 +155,9 @@ logger = init_logger(__name__) +# The fused QK-norm/RoPE/KV-insert HIP op segfaults on gfx942. +_USE_GFX942_NATIVE_QKNORM_ROPE = on_gfx942() + def _sparse_attention_layer_ids(config: PreTrainedConfig) -> set[int]: """Layer ids whose attention runs the extra sparse "index" branch.""" @@ -365,6 +377,30 @@ def __init__( f"the number of experts {config.num_local_experts}." ) + # MiniMax-M3.1 like checkpoints (`quant_method: mxfp8`, `moe_quant_algo: + # NVFP4`) have no native NVFP4 MoE backend on ROCm: the routed experts must be + # re-quantized online. + experts_prefix = f"{prefix}.experts" + if ( + isinstance(quant_config, ModelOptMxFp8Config) + and quant_config.moe_quant_algo == "NVFP4" + and not quant_config.is_layer_excluded(experts_prefix) + and ( + quant_config.online_quantization_config is None + or quant_config.online_quantization_config.resolve_quant_method_cls( + RoutedExperts, experts_prefix + ) + is None + ) + ): + raise NotImplementedError( + "This MiniMax model with NVFP4 MoE experts " + "(`moe_quant_algo: NVFP4`, `moe_quant_format: nvfp4-pack-quantized`) " + "is not supported on ROCm. Please use `--quantization-config.moe " + "mxfp8` (or `--quantization-config.moe mxfp4`) to re-quantize the " + "MoE to MXFP8 (or MXFP4) when loading to serve on ROCm." + ) + self.routed_scaling_factor = getattr(config, "routed_scaling_factor", 1.0) self.n_shared_experts = getattr(config, "n_shared_experts", None) @@ -398,30 +434,16 @@ def __init__( # top-k kernel; otherwise it goes through the vLLM top-k bias router. # It is disabled under expert parallelism (the shared slot is appended to # the routed top-k, which the EP expert-mapping path does not handle). - # TODO: Historically, only `VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS=1` - # is checked to enable FSE for MiniMax-M3, despite AITER not being used. - # This should be cleaned up and use `resolve_layer_fused_shared_expert`. - fse_requested = envs.VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS - self.is_fused_shared_expert_enabled = False if ( - fse_requested - and bool(getattr(config, "n_shared_experts", None)) + bool(getattr(config, "n_shared_experts", None)) and not get_current_vllm_config().parallel_config.enable_expert_parallel ): - fse_compatible, fse_reason = is_shared_expert_quant_fse_compatible( + self.is_fused_shared_expert_enabled = resolve_layer_fused_shared_expert( quant_config, - f"{prefix}.experts", - f"{prefix}.shared_experts", + prefix, + shared_expert_name="shared_experts", ) - if not fse_compatible: - logger.warning( - "VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS is enabled but " - "cannot be enabled: %s.", - fse_reason, - ) - else: - self.is_fused_shared_expert_enabled = True # When additionally on gfx950 with an active aiter MoE backend, the shared # expert is appended inside aiter's an active aiter MoE backend, the shared @@ -572,6 +594,22 @@ def forward( hidden_states: torch.Tensor, ) -> torch.Tensor: qkv, _ = self.qkv_proj(hidden_states) + output, _ = self.o_proj(self.attend(positions, qkv)) + return output + + def attend(self, positions: torch.Tensor, qkv: torch.Tensor) -> torch.Tensor: + """The attention of this rank's heads, before o_proj.""" + if _USE_GFX942_NATIVE_QKNORM_ROPE: + num_tokens = qkv.shape[0] + q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1) + q = self.q_norm(q.view(num_tokens, self.num_heads, self.head_dim)) + k = self.k_norm(k.view(num_tokens, self.num_kv_heads, self.head_dim)) + q, k = self.rotary_emb.forward_native(positions, q, k) + assert k is not None + q = q.reshape(num_tokens, self.q_size) + k = k.reshape(num_tokens, self.kv_size) + return self.attn(q, k, v) + # Fused per-head Gemma QK-norm + partial NeoX RoPE on q/k, in place (dense # mode: no index branch, no KV-cache insert). Matches nvidia/model.py and # replaces the unfused split -> q_norm/k_norm -> rotary_emb chain; verified @@ -589,9 +627,7 @@ def forward( kv_cache_dtype="auto", ) q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1) - attn_output = self.attn(q, k, v) - output, _ = self.o_proj(attn_output) - return output + return self.attn(q, k, v) # Widest row pitch aiter's reshape_and_cache can carry in its `int` stride args. @@ -748,6 +784,9 @@ def __init__( # Shared top-k buffer: the indexer writes the selected blocks into it and # the attend impl reads them back (no Python value crosses the break). self.topk_indices_buffer = topk_indices_buffer + # One fused kernel inserts both caches, so NVFP4 K/V needs an NVFP4 + # index cache. + self.use_nvfp4_kv = get_kv_quant_mode(self.kv_cache_dtype).is_nvfp4 # Indexer and main attention are separate impls. This indexer is # ROCm-only, so the model selects it rather than the neutral # MiniMaxM3Indexer, which knows nothing about it and would pick its own. @@ -778,8 +817,10 @@ def __init__( topk_blocks=sparse_cfg["sparse_topk_blocks"], sparse_block_size=sparse_cfg["sparse_block_size"], ) - self.use_aiter_sparse_pa = minimax_m3_use_aiter_sparse_pa( - self.num_kv_heads, emits_sparse_block_table=self.indexer_emits_table + self.use_aiter_sparse_pa = not self.use_nvfp4_kv and ( + minimax_m3_use_aiter_sparse_pa( + self.num_kv_heads, emits_sparse_block_table=self.indexer_emits_table + ) ) self.kv_cache_k = torch.tensor([]) self.kv_cache_v = torch.tensor([]) @@ -806,7 +847,11 @@ def __init__( self.sparse_ctx_buffer = sparse_ctx_buffer # Same condition the forward dispatches on, so the indexer built here # and the branch that calls it cannot disagree about which one this is. - if msa_indexer_impl_cls is None: + if self.use_nvfp4_kv: + self.indexer = MiniMaxM3MSAIndexer( + impl_cls=MiniMaxM3IndexerRocmNvfp4Impl, **indexer_kwargs + ) + elif msa_indexer_impl_cls is None: # Self-contained nn.Module: owns its side cache, selects its impl. self.indexer = MiniMaxM3Indexer(**indexer_kwargs) else: @@ -977,6 +1022,118 @@ def _insert_aiter_sparse_pa_kv( return minimax_m3_insert_index_cache(index_k, index_cache, index_slot_mapping) + def _native_gfx942_qknorm_rope_cache( + self, + qkv: torch.Tensor, + positions: torch.Tensor, + fwd_slot_mapping: dict[str, torch.Tensor], + ) -> tuple[torch.Tensor, torch.Tensor | None]: + """Run QK norm, RoPE, and cache insertion without the fused HIP op.""" + from vllm.models.minimax_m3.amd.ops.sparse_pa import ( + minimax_m3_insert_index_cache, + ) + + num_tokens = qkv.shape[0] + q, k, v, index_q_raw, index_k_raw = qkv.split( + [ + self.q_size, + self.kv_size, + self.kv_size, + self.index_q_size, + self.idx_head_dim, + ], + dim=-1, + ) + + q = self.q_norm(q.view(num_tokens, self.num_heads, self.head_dim)) + k = self.k_norm(k.view(num_tokens, self.num_kv_heads, self.head_dim)) + q, k = self.rotary_emb.forward_native(positions, q, k) + assert k is not None + q = q.reshape(num_tokens, self.q_size) + + main_slot_mapping = fwd_slot_mapping[self.layer_name] + if self.kv_cache.numel() != 0: + # [block, head, token, 2 * dim] -> [block, token, head, dim]. + key_cache, value_cache = self.kv_cache.transpose(1, 2).split( + self.head_dim, dim=-1 + ) + triton_reshape_and_cache_flash( + k, + v.view(num_tokens, self.num_kv_heads, self.head_dim), + key_cache, + value_cache, + main_slot_mapping, + self.kv_cache_dtype, + self._k_scale, + self._v_scale, + ) + + if self.skip_index_topk: + return q, None + + index_q = self.index_q_norm( + index_q_raw.view(num_tokens, self.num_idx_heads, self.idx_head_dim) + ) + index_k = self.index_k_norm(index_k_raw.view(num_tokens, self.idx_head_dim)) + index_q, index_k = self.index_rotary_emb.forward_native( + positions, index_q, index_k + ) + assert index_k is not None + index_q = index_q.reshape(num_tokens, self.index_q_size).to( + self.indexer.index_cache.dtype + ) + + index_cache = self.indexer.index_cache.kv_cache + if index_cache.numel() != 0: + index_slot_mapping = fwd_slot_mapping[self.indexer.index_cache.prefix] + minimax_m3_insert_index_cache( + index_k.reshape(num_tokens, self.idx_head_dim), + index_cache, + index_slot_mapping, + ) + return q, index_q + + def _norm_rope_nvfp4_insert( + self, + qkv: torch.Tensor, + positions: torch.Tensor, + slot_mapping: torch.Tensor, + index_slot_mapping: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Fused norm + RoPE + NVFP4 K/V and index-K insert; returns q, index-q.""" + from vllm.models.minimax_m3.amd.ops.norm_rope_nvfp4_insert.host import ( + minimax_m3_norm_rope_nvfp4_insert, + ) + + num_tokens = qkv.shape[0] + q = qkv.new_empty((num_tokens, self.q_size)) + index_q = qkv.new_empty( + (num_tokens, self.index_q_size), + dtype=self.indexer.index_cache.query_dtype, + ) + minimax_m3_norm_rope_nvfp4_insert( + qkv, + self.q_norm.weight, + self.k_norm.weight, + self.index_q_norm.weight, + self.index_k_norm.weight, + self.rotary_emb.cos_sin_cache, + positions, + slot_mapping, + index_slot_mapping, + self.kv_cache, + self.indexer.index_cache.kv_cache, + self._k_scale, + self._v_scale, + q, + index_q, + num_heads=self.num_heads, + num_kv_heads=self.num_kv_heads, + num_index_heads=self.num_idx_heads, + eps=self.q_norm.variance_epsilon, + ) + return q, index_q + def forward( self, positions: torch.Tensor, @@ -984,7 +1141,11 @@ def forward( ) -> torch.Tensor: # Single fused projection emitting [q | k | v | index_q | index_k]. qkv, _ = self.qkv_proj(hidden_states) + output, _ = self.o_proj(self.attend(positions, qkv)) + return output + def attend(self, positions: torch.Tensor, qkv: torch.Tensor) -> torch.Tensor: + """The attention of this rank's heads, before o_proj.""" # Horizontally-fused per-head Gemma QK-norm + partial NeoX RoPE on the # main (q/k) and index (index_q/index_k) branches, all read straight out # of the single fused ``qkv`` tensor. Once the paged caches are bound the @@ -1004,9 +1165,27 @@ def forward( or self.layer_name not in fwd_slot_mapping ): # Memory-profiling run: caches not yet bound, slot_mapping is empty. - return qkv.new_zeros((num_tokens, self.hidden_size)) + return qkv.new_zeros((num_tokens, self.q_size)) + + if _USE_GFX942_NATIVE_QKNORM_ROPE: + q, index_q = self._native_gfx942_qknorm_rope_cache( + qkv, positions, fwd_slot_mapping + ) + output = torch.empty_like(q) + return self._run_attention(q, index_q, output) main_slot_mapping = fwd_slot_mapping[self.layer_name] + if self.use_nvfp4_kv: + q, index_q = self._norm_rope_nvfp4_insert( + qkv, + positions, + main_slot_mapping, + fwd_slot_mapping[self.indexer.index_cache.prefix], + ) + output = torch.empty_like(q) + return self._run_attention( + q, None if self.skip_index_topk else index_q, output + ) q = qkv.new_empty((num_tokens, self.q_size)) key_cache = value_cache = page16_slot_mapping = None k_scale = v_scale = None @@ -1202,9 +1381,7 @@ def forward( ) output = torch.empty_like(q) - attn_output = self._run_attention(q, index_q, output) - output, _ = self.o_proj(attn_output) - return output + return self._run_attention(q, index_q, output) @eager_break_during_capture def _run_attention( @@ -1356,6 +1533,9 @@ def __init__( self.post_attention_layernorm = MiniMAXGemmaRMSNorm( config.hidden_size, eps=config.rms_norm_eps ) + self.self_attn.o_proj_full = sp_prefill.make_o_proj_full( + self, quant_config, prefix + ) def forward( self, @@ -1384,6 +1564,7 @@ def forward( class MiniMaxM3Model(nn.Module, EagleModelMixin): fall_back_to_pt_during_load = False + supports_aux_hidden_states_over_pp = True def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): super().__init__() @@ -1432,6 +1613,9 @@ def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): indexer_kv_dtype = vllm_config.attention_config.resolve_indexer_kv_dtype( "bf16" ) + use_nvfp4_kv = get_kv_quant_mode( + vllm_config.cache_config.cache_dtype + ).is_nvfp4 # The only MSA indexer probe. It has to live here rather than in # the layer because the buffers it gates are one allocation shared # by all of them, so the answer is needed before any layer exists, @@ -1441,13 +1625,18 @@ def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): # this indexer and there is no such choice until it exists; the # probe owes nothing to CP in return, since what it checks is the # platform and the kernels' shape contract, neither of which a - # head count enters. - impl_cls = select_msa_indexer_impl_cls( - topk_blocks=sparse_cfg["sparse_topk_blocks"], - sparse_block_size=sparse_cfg["sparse_block_size"], - index_head_dim=sparse_cfg["sparse_index_dim"], - indexer_kv_dtype=indexer_kv_dtype, - score_type=sparse_cfg.get("sparse_score_type", "max"), + # head count enters. NVFP4 K/V runs its own indexer, which emits + # no page table. + impl_cls = ( + None + if use_nvfp4_kv + else select_msa_indexer_impl_cls( + topk_blocks=sparse_cfg["sparse_topk_blocks"], + sparse_block_size=sparse_cfg["sparse_block_size"], + index_head_dim=sparse_cfg["sparse_index_dim"], + indexer_kv_dtype=indexer_kv_dtype, + score_type=sparse_cfg.get("sparse_score_type", "max"), + ) ) if impl_cls is not None and minimax_m3_use_aiter_sparse_pa( num_kv_heads, emits_sparse_block_table=True @@ -1479,6 +1668,11 @@ def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): vllm_config, msa_indexer_selected=self.msa_indexer_impl_cls is not None, ) + if use_nvfp4_kv: + # A TP collective (IPC buffers), outside graph capture. + init_rocm_nvfp4_indexer_decode_cp( + vllm_config.model_config.max_model_len + ) else: self.topk_indices_buffer = None @@ -1510,6 +1704,13 @@ def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory( ["hidden_states", "residual"], config.hidden_size ) + # VLLM_ROCM_MINIMAX_M3_MONO=1: supported decode steps run one FlyDSL + # launch per layer (mono kernels) + self._mono = None + if mono_envs.MONO_ENABLE: + from vllm.models.minimax_m3.amd.mono.dispatch import MonoDecode + + self._mono = MonoDecode(self, vllm_config) def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: return self.embed_tokens(input_ids) @@ -1529,6 +1730,10 @@ def forward( intermediate_tensors: IntermediateTensors | None, inputs_embeds: torch.Tensor | None = None, ) -> torch.Tensor | IntermediateTensors | tuple[torch.Tensor, list[torch.Tensor]]: + if self._mono is not None and self._mono.supports( + input_ids, positions, intermediate_tensors, inputs_embeds + ): + return self._mono.forward(input_ids, positions, inputs_embeds) if get_pp_group().is_first_rank: if inputs_embeds is not None: hidden_states = inputs_embeds @@ -1541,10 +1746,20 @@ def forward( residual = intermediate_tensors["residual"] decode = self.specialized_decode - # EAGLE3 is not yet compatible with pipeline parallel - aux_hidden_states = self._maybe_add_hidden_state([], 0, hidden_states, residual) + remote_aux = self.collect_remote_aux_hidden_states(intermediate_tensors) + aux_hidden_states: list[torch.Tensor] = [] + if get_pp_group().is_first_rank: + self._maybe_add_hidden_state( + aux_hidden_states, self.start_layer, hidden_states, residual + ) + sp = sp_prefill.plan_model(self, hidden_states) + if sp is not None: + return sp_prefill.forward( + self, positions, hidden_states, aux_hidden_states, sp + ) + layers = self.layers[self.start_layer : self.end_layer] if decode is None: - for idx, layer in enumerate(self.layers[self.start_layer : self.end_layer]): + for idx, layer in enumerate(layers, start=self.start_layer): hidden_states, residual = layer(positions, hidden_states, residual) self._maybe_add_hidden_state( aux_hidden_states, idx + 1, hidden_states, residual @@ -1553,8 +1768,7 @@ def forward( step = decode.plan(positions, intermediate_tensors) failure: Exception | None = None try: - layers = self.layers[self.start_layer : self.end_layer] - for idx, layer in enumerate(layers): + for idx, layer in enumerate(layers, start=self.start_layer): kernel = step.layer(layer.layer_id) if step else None hidden_states, residual = (kernel or layer)( positions, hidden_states, residual @@ -1568,11 +1782,16 @@ def forward( if not get_pp_group().is_last_rank: return IntermediateTensors( - {"hidden_states": hidden_states, "residual": residual} + { + "hidden_states": hidden_states, + "residual": residual, + **self.pack_local_aux_hidden_states(aux_hidden_states), + } ) hidden_states, _ = self.norm(hidden_states, residual) + aux_hidden_states = remote_aux + aux_hidden_states if len(aux_hidden_states) > 0: return hidden_states, aux_hidden_states return hidden_states @@ -1697,6 +1916,12 @@ def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: param, "weight_loader", default_weight_loader ) weight_loader(param, loaded_weight) + # the sequence-parallel prefill's whole o_proj + full = name.replace(".self_attn.o_proj.", ".self_attn.o_proj_full.") + if full != name and full in params_dict: + param = params_dict[full] + param.weight_loader(param, loaded_weight) + loaded_params.add(full) loaded_params.add(name) return loaded_params diff --git a/vllm/models/minimax_m3/amd/mono/__init__.py b/vllm/models/minimax_m3/amd/mono/__init__.py new file mode 100644 index 000000000000..7a79e4b7c0da --- /dev/null +++ b/vllm/models/minimax_m3/amd/mono/__init__.py @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MiniMax-M3 fused per-layer decode of up to ``config.MAX_TOKENS`` tokens; entered +through ``dispatch.MonoDecode`` (``VLLM_ROCM_MINIMAX_M3_MONO=1``).""" diff --git a/vllm/models/minimax_m3/amd/mono/check.py b/vllm/models/minimax_m3/amd/mono/check.py new file mode 100644 index 000000000000..bef5dbe7d736 --- /dev/null +++ b/vllm/models/minimax_m3/amd/mono/check.py @@ -0,0 +1,68 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Debug tooling for the mono path. + +``forward_checked`` (``VLLM_ROCM_MINIMAX_M3_MONO_CHECK=1``, meant for +``--enforce-eager``) runs every sparse layer twice on the same (ar, res): first +the mono layer kernel, then the original decoder layer. Both insert the same cache +slots (the kernel writes the same bytes up to the re-quantized attention weights), +so running both is side-effect free. Rank 0 logs, per layer and token, the +difference of the residual stream and of the reduced MoE output. +""" + +import torch + +from vllm.logger import init_logger +from vllm.models.minimax_m3.amd.mono.config import HIDDEN + +logger = init_logger(__name__) + + +def _diff(a: torch.Tensor, b: torch.Tensor) -> str: + a, b = a.float().flatten(), b.float().flatten() + d = (a - b).abs() + rel = (d.norm() / b.norm().clamp(min=1e-30)).item() + return f"max {d.max().item():.3e} rel {rel:.3e}" + + +def forward_checked( + runner, + input_ids: torch.Tensor | None, + positions: torch.Tensor, + inputs_embeds: torch.Tensor | None, +) -> torch.Tensor | tuple[torch.Tensor, list[torch.Tensor]]: + """``runner.forward`` with the original decoder layer run beside every mono + layer; the mono chain's output is returned.""" + aux_hidden_states: list[torch.Tensor] | None = ( + [] if runner.model.aux_hidden_state_layers else None + ) + res = runner.start(input_ids, positions, inputs_embeds, aux_hidden_states) + n = res.shape[0] + tables = runner.step_tables(n) + ars = runner.ars + for i, lw in enumerate(runner.sparse): + layer = runner.model.layers[lw.layer_id] + h_in = ars[i % 2][:n].clone() + res_in = res.clone() + res = runner.run_sparse_layer(i, lw, tables, positions, res) + ref_h, ref_res = layer(positions, h_in, res_in) + if aux_hidden_states is not None: + runner.model._maybe_add_hidden_state( + aux_hidden_states, + lw.layer_id + 1, + ars[(i + 1) % 2][:n], + res, + ) + if runner.rank == 0: + for k in range(n): + logger.info( + "mono check layer %d token %d/%d pos %d seq_len %d: residual %s | " + "reduced out %s", + lw.layer_id, k, n, int(positions[k]), int(tables.seq_lens[k]), + _diff(res[k], ref_res.view(n, HIDDEN)[k]), + _diff(ars[(i + 1) % 2][k], ref_h.view(n, HIDDEN)[k]), + ) # fmt: skip + hidden = runner.run_final_norm(res) + if aux_hidden_states is not None: + return hidden, aux_hidden_states + return hidden diff --git a/vllm/models/minimax_m3/amd/mono/config.py b/vllm/models/minimax_m3/amd/mono/config.py new file mode 100644 index 000000000000..9ed7777f3cef --- /dev/null +++ b/vllm/models/minimax_m3/amd/mono/config.py @@ -0,0 +1,108 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +"""Shapes the mono kernels are compiled for: one MiniMax-M3 TP4 rank. + +Every value here is checked against the loaded model in ``weights.py``; a +model that does not match is never routed to the mono path. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +# One CTA per MI355X CU; the kernels rely on every CTA being co-resident. +BLOCKS = 256 +THREADS = 512 +WAVES = THREADS // 64 + +HIDDEN = 6144 +HEAD_DIM = 128 +ROTARY_DIM = 64 +LOCAL_Q_HEADS = 16 + + +def qkv_rows(idx_heads: int) -> int: + """Rows of a rank's fused projection, q | k | v | index_q | index_k: 16 q + heads, one k and v head, ``idx_heads`` index q heads (the rank's one, or every + one under indexer context parallelism) and the index k head.""" + return (LOCAL_Q_HEADS + 3 + idx_heads) * HEAD_DIM + + +O_K = LOCAL_Q_HEADS * HEAD_DIM + +N_ROUTED = 128 +TOP_K = 4 +SHARED_EXPERT = N_ROUTED # the fused shared expert's id +MOE_SLOTS = TOP_K + 1 +INTER = 768 # expert intermediate per rank + +SPARSE_BLOCK = 128 +TOPK_BLOCKS = 16 +MAX_SPARSE_KEYS = SPARSE_BLOCK * TOPK_BLOCKS +# the longest context served: the score region spans it +MAX_CONTEXT = 1 << 20 +MAX_INDEX_BLOCKS = MAX_CONTEXT // SPARSE_BLOCK +PAGE16 = 16 + +MAX_TOKENS = 16 # tokens one mono step serves (the MFMA B operand holds 16) +TP = 4 +# indexer context parallelism: a rank computes every index q head +MAX_QKV_ROWS = qkv_rows(TP) +# indexer context parallelism serves a step's requests past this many index +# blocks: its selection costs a fixed ~7 us (S = 1: ~43.5 us/layer at any length) +# that the one-head path's O(n^2) ranking passes between 258 and 297 blocks +# (S = 1 and S = 16 alike; logs/cp_threshold*.log) +INDEX_CP_FROM_BLOCKS = 288 + + +@dataclass(frozen=True) +class IndexHeads: + """The index q heads in a rank's fused projection, a build parameter: + ``count`` of them (1, or all TP in head order under indexer context + parallelism) and ``own``, the one this rank's selection scores.""" + + count: int = 1 + own: int = 0 + + def __post_init__(self): + assert self.count in (1, TP) and 0 <= self.own < self.count + + @property + def rows(self) -> int: + return qkv_rows(self.count) + + @property + def iq_off(self) -> int: + return (LOCAL_Q_HEADS + 2 + self.own) * HEAD_DIM + + @property + def ik_off(self) -> int: + return (LOCAL_Q_HEADS + 2 + self.count) * HEAD_DIM + + +# without indexer context parallelism: the rank's own index q head only +ONE_INDEX_HEAD = IndexHeads() + +LAYER_SLOTS = 128 # mailbox epochs: step * LAYER_SLOTS + layer + 1 + +# host K/V cache geometry, set by the runner before the kernels are built: the +# page-16 ids one sparse block spans (8: K and V as separate planes; 16: a block +# interleaves K|V and V is reached from the same id at +8 pages, as vLLM lays +# it out) and +# whether fp8 K/V carry the host's fixed unit scale instead of per-token scales +KV_PAGE_STRIDE = SPARSE_BLOCK // PAGE16 +STATIC_KV_SCALE = False + + +def configure(*, kv_page_stride: int, static_kv_scale: bool) -> None: + global KV_PAGE_STRIDE, STATIC_KV_SCALE + assert kv_page_stride in (SPARSE_BLOCK // PAGE16, 2 * SPARSE_BLOCK // PAGE16) + KV_PAGE_STRIDE = kv_page_stride + STATIC_KV_SCALE = static_kv_scale + + +class MonoUnsupported(Exception): + """The loaded model or runtime configuration is outside what mono serves.""" diff --git a/vllm/models/minimax_m3/amd/mono/dispatch.py b/vllm/models/minimax_m3/amd/mono/dispatch.py new file mode 100644 index 000000000000..386f9d023bc9 --- /dev/null +++ b/vllm/models/minimax_m3/amd/mono/dispatch.py @@ -0,0 +1,216 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Which MiniMax-M3 forwards take the mono path (``VLLM_ROCM_MINIMAX_M3_MONO=1``). + +The deployment is checked once (``_config_refusal``); a step is routed to the +kernels only when it is a pure decode of 1..MAX_TOKENS tokens whose tables the +kernels can read (``_step_refusal``). Every per-step condition is decided from +TP-replicated state: the kernels all-reduce in-kernel, so ranks that disagreed +would wait on each other forever. + +The runner is built on the first eligible step, which under cudagraphs is the +warmup run before the first capture (its allocations and IPC handshake cannot be +captured), and rebuilt when vLLM re-binds the KV cache after its memory-profiling +capture round. +""" + +from typing import Any, cast + +import torch + +from vllm.config import VllmConfig +from vllm.forward_context import ForwardContext, get_forward_context +from vllm.logger import init_logger +from vllm.models.minimax_m3.amd.mono.check import forward_checked +from vllm.models.minimax_m3.amd.mono.config import ( + MAX_CONTEXT, + MAX_TOKENS, + SPARSE_BLOCK, + TP, + MonoUnsupported, +) +from vllm.models.minimax_m3.amd.mono.envs import envs +from vllm.models.minimax_m3.amd.mono.runner import MonoDecodeRunner, dense_prefix + +logger = init_logger(__name__) + + +def _dense_prefix_ok(layers) -> bool: + try: + dense_prefix(layers) + except MonoUnsupported: + return False + return True + + +def _separate_shared_ok(layers) -> bool: + """Every MoE layer keeps its shared expert as a separate MLP (the kernels then + run it from that MLP's MXFP8 weights, ``weights.mxfp8_a_tiles``).""" + moes = [lyr.block_sparse_moe for lyr in layers if lyr.is_moe_layer] + return bool(moes) and all( + not m.is_fused_shared_expert_enabled + and getattr(m, "shared_experts", None) is not None + for m in moes + ) + + +def _config_refusal(vllm_config: VllmConfig, model) -> str | None: + """Why this deployment cannot use the kernels at all, or None.""" + pc = vllm_config.parallel_config + cc = vllm_config.cache_config + cg = vllm_config.compilation_config.cudagraph_mode + max_len = vllm_config.model_config.max_model_len + index_dtype = vllm_config.attention_config.resolve_indexer_kv_dtype("bf16") + checks = ( + (pc.tensor_parallel_size == TP, f"TP {pc.tensor_parallel_size} != {TP}"), + (pc.data_parallel_size == 1, "DP > 1"), + (pc.pipeline_parallel_size == 1, "PP > 1"), + (not pc.enable_expert_parallel, "EP"), + (str(cc.cache_dtype).startswith("fp8"), f"kv cache {cc.cache_dtype}"), + (index_dtype == "fp8", f"index cache {index_dtype}"), + (cc.block_size == SPARSE_BLOCK, f"block size {cc.block_size}"), + (max_len <= MAX_CONTEXT, f"max_model_len {max_len} > {MAX_CONTEXT}"), + (cg is None or not cg.requires_piecewise_compilation(), "piecewise cudagraph"), + ( + getattr(model, "is_fused_shared_expert_enabled", False) + or _separate_shared_ok(model.layers), + "shared expert neither fused nor a separate MLP", + ), + (_dense_prefix_ok(model.layers), "layer mix"), + ) + for ok, why in checks: + if not ok: + return why + return None + + +def _step_refusal( + fwd: ForwardContext, layer_name: str, n: int, positions +) -> str | None: + """Why this step cannot run on the kernels, or None when it can.""" + if not 1 <= n <= MAX_TOKENS: + return f"{n} tokens" + if positions.dtype != torch.int64: # read as an int64's low word + return f"positions {positions.dtype}" + if fwd.ubatch_slices is not None: + return "microbatched" + if not isinstance(fwd.attn_metadata, dict) or not isinstance( + fwd.slot_mapping, dict + ): + return "no per-layer metadata" + md = cast(Any, fwd.attn_metadata.get(layer_name)) + if md is None or md.decode is None: + return "no decode metadata" + if md.num_prefills: + return "prefill in the step" + q = md.decode.decode_query_len + if q < 1 or n % q: + return f"{n} tokens for {q} per request" + bt, seq_lens = md.decode.block_table, md.decode.seq_lens + if bt.dtype != torch.int32 or seq_lens.dtype != torch.int32: + return "tables not int32" + if bt.shape[0] < n // q or seq_lens.shape[0] < n // q: + return "tables shorter than the batch" + if bt.stride(0) != bt.shape[1] or bt.stride(1) != 1: # rows bt_width apart + return "block table not row-contiguous" + slots = fwd.slot_mapping.get(layer_name) + if slots is None or slots.dtype != torch.int64 or slots.numel() < n: + return "slot mapping" + return None + + +class MonoDecode: + """Routes supported decode steps of one ``MiniMaxM3Model`` to the kernels.""" + + def __init__(self, model, vllm_config: VllmConfig) -> None: + self._model = model + self._config = vllm_config.model_config.hf_text_config + self._runner: MonoDecodeRunner | None = None + self._enabled = False + self._slots_verified = False + if not envs.MONO_ENABLE: + return + why = _config_refusal(vllm_config, model) + if why is not None: + logger.info("MiniMax-M3 mono decode off: %s", why) + return + attn0 = model.layers[dense_prefix(model.layers)].self_attn + self._layer_name = attn0.layer_name + self._index_prefix = attn0.indexer.index_cache.prefix + self._enabled = True + + def _disable(self, why: str) -> None: + logger.warning("MiniMax-M3 mono decode off: %s", why) + self._enabled = False + + def _ensure_runner(self) -> bool: + """Build (or rebuild after a KV cache re-bind) the runner outside capture.""" + if self._runner is not None and self._runner.stale(): + if torch.cuda.is_current_stream_capturing(): + return False + self._runner.close() + self._runner = None + self._slots_verified = False + logger.info("MiniMax-M3 mono decode: KV cache re-bound, rebuilding") + if self._runner is not None: + return True + if torch.cuda.is_current_stream_capturing(): + return False + try: + self._runner = MonoDecodeRunner(self._model, self._config) + except MonoUnsupported as why: + self._disable(str(why)) + return False + except Exception: + # TP-uniform: every rank fails the same way, so all fall back + logger.exception("MiniMax-M3 mono decode: runner build failed") + self._enabled = False + return False + if self._runner.shared_fp8: + copy = sum(lw.shared_bytes() for lw in self._runner.sparse) + how = f"separate MXFP8 ({copy / 2**30:.2f} GiB tiled copy per rank)" + else: + how = "fused into the MXFP4 expert tables" + logger.info("MiniMax-M3 mono decode on: shared expert %s", how) + return True + + def _slots_shared(self, fwd: ForwardContext, n: int) -> bool: + """The kernels insert K/V and the index key through one page-128 slot + mapping, so the index cache must share the main cache's block ids. + Checked once (a device sync).""" + if self._slots_verified: + return True + slot_mapping = cast(dict[str, Any], fwd.slot_mapping) + slots = slot_mapping[self._layer_name] + index_slots = slot_mapping.get(self._index_prefix) + if index_slots is None or not torch.equal(index_slots[:n], slots[:n]): + self._disable("index cache does not share the KV cache's block ids") + return False + self._slots_verified = True + return True + + def supports( + self, + input_ids: torch.Tensor | None, + positions: torch.Tensor, + intermediate_tensors, + inputs_embeds: torch.Tensor | None, + ) -> bool: + if not self._enabled or intermediate_tensors is not None: + return False + fwd = get_forward_context() + n = positions.numel() + if _step_refusal(fwd, self._layer_name, n, positions) is not None: + return False + return self._ensure_runner() and self._slots_shared(fwd, n) + + def forward( + self, + input_ids: torch.Tensor | None, + positions: torch.Tensor, + inputs_embeds: torch.Tensor | None, + ) -> torch.Tensor: + assert self._runner is not None + if envs.MONO_CHECK: + return forward_checked(self._runner, input_ids, positions, inputs_embeds) + return self._runner.forward(input_ids, positions, inputs_embeds) diff --git a/vllm/models/minimax_m3/amd/mono/envs.py b/vllm/models/minimax_m3/amd/mono/envs.py new file mode 100644 index 000000000000..0ef17463c786 --- /dev/null +++ b/vllm/models/minimax_m3/amd/mono/envs.py @@ -0,0 +1,20 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Environment switches of the mono decode path (read once at import).""" + +import os + + +def _flag(name: str) -> bool: + return os.getenv(name, "0") in ("1", "true", "True") + + +class _Envs: + # route supported decode steps to the mono kernels + MONO_ENABLE = _flag("VLLM_ROCM_MINIMAX_M3_MONO") + # run every sparse layer twice (kernels, then the original modules) and log the + # per-token differences; the layer-parity self-check, meant for --enforce-eager + MONO_CHECK = _flag("VLLM_ROCM_MINIMAX_M3_MONO_CHECK") + + +envs = _Envs() diff --git a/vllm/models/minimax_m3/amd/mono/kernels/__init__.py b/vllm/models/minimax_m3/amd/mono/kernels/__init__.py new file mode 100644 index 000000000000..06c54790d7ae --- /dev/null +++ b/vllm/models/minimax_m3/amd/mono/kernels/__init__.py @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +"""FlyDSL kernels of the mono decode path: K1 ``pre_attn`` and K4 ``post_attn``.""" diff --git a/vllm/models/minimax_m3/amd/mono/kernels/common.py b/vllm/models/minimax_m3/amd/mono/kernels/common.py new file mode 100644 index 000000000000..b42f1e375e3a --- /dev/null +++ b/vllm/models/minimax_m3/amd/mono/kernels/common.py @@ -0,0 +1,418 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +"""Device-side building blocks shared by the mono kernels. + +Ported from the FlyDSL GLM-5 layer kernel (ROCm/FlyDSL branch +``glm5-mla-moe-layer-monokernel`` @ 1e28fd8a, +``kernels/mla_moe_layer/shared_reuse_moe_kernel.py``): wave reductions, tagged +mailboxes and the MFMA GEMV loop. Only published flydsl APIs and aiter's vendored +``buffer_ops`` / ``dpp_utils`` are used, so nothing here needs the FlyDSL repo. + +Every function but ``kernel_symbol`` is traced inside a ``@flyc.kernel`` body. + +Raw boundaries the kernels keep, for want of an equivalent on the pinned FlyDSL: +``buffer_ops`` loads / stores (the kernels take raw Int64 addresses, no tensors +for ``make_buffer_tensor``); raw MFMA intrinsics (hand-laid operands: permlane +transposes, fp8 packing, MXFP4 scales); the LLVM intrinsics here (``expect``, +``s_memrealtime``, the approximate rsq / rcp / exp2) and the struct unpacking of +``permlane*_swap``; ``inttoptr`` for the timeline's global stores. +""" + +from __future__ import annotations + +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import buffer_ops as bo +from aiter.ops.flydsl.kernels.dpp_utils import update_dpp_i32 +from aiter.ops.flydsl.kernels.kernels_common import kernel_signature +from flydsl._mlir import ir +from flydsl._mlir.dialects import llvm +from flydsl.compiler.ast_rewriter import ASTRewriter +from flydsl.expr import const_expr, gpu, range_constexpr, rocdl +from flydsl.expr import math as fmath +from flydsl.expr.typing import T, as_ir_value + +from vllm.models.minimax_m3.amd.mono.config import LAYER_SLOTS, WAVES + +# gfx95x cache policy bits (LLVM CPol): SC0 = 1, SC1 = 16. SC1 alone is device +# scope (past the per-XCD caches); SC0 | SC1 is system scope (peers over XGMI). +CM_DEV = 16 +CM_SYS = 17 +POLL_MAX = 12 # mailbox specs polled per batch (bounds live registers) + + +def kernel_symbol(stem, **params): + """Kernel symbol that profilers demangle to ``vllm::_``. The + amdhsa assembler rejects ``::`` in a symbol, so it is Itanium-mangled, as + aiter's ``_ZN5aiter...E`` kernels are.""" + name = f"{stem}_{kernel_signature(**params)}" + return f"_ZN4vllm{len(name)}{name}E" + + +def rsrc(addr, nbytes=None): + return bo.create_buffer_resource_from_addr(addr, num_records_bytes=nbytes) + + +def permlane_swap(off, x, y): + """v_permlane{32,16}_swap on registers (x, y): off 32 trades x's upper-half + lanes with y's lower-half lanes; off 16 trades x's odd 16-lane rows with y's + even rows (each within its half). -> (x', y').""" + swap = rocdl.permlane32_swap if off == 32 else rocdl.permlane16_swap + pr = swap( + llvm.StructType.get_literal([T.i32, T.i32]), + as_ir_value(fx.Int32(x)), + as_ir_value(fx.Int32(y)), + False, + False, + ) + return tuple(fx.Int32(llvm.extractvalue(T.i32, pr, [j])) for j in range(2)) + + +def lane_gather(v, src_lane): + """Lane ``src_lane``'s value of v, a source lane a lane (ds_bpermute).""" + return fx.Int32( + rocdl.ds_bpermute(T.i32, fx.Int32(src_lane) * 4, fx.Int32(v).ir_value()) + ) + + +def readlane(v, src_lane): + """Lane ``src_lane``'s value of v (wave-uniform).""" + bits = v.bitcast(fx.Int32) if isinstance(v, fx.Float32) else fx.Int32(v) + r = fx.Int32(rocdl.readlane(T.i32, bits, fx.Int32(src_lane))) + return r.bitcast(fx.Float32) if isinstance(v, fx.Float32) else r + + +def memrealtime(): + """s_memrealtime: the 100 MHz device clock (no FlyDSL wrapper).""" + return fx.Int64(llvm.call_intrinsic(T.i64, "llvm.amdgcn.s.memrealtime", [], [], [])) + + +def unlikely(cond): + """``cond`` marked cold (llvm.expect): LLVM lays the branch out of the hot + path. A rare path's code inline among the hot stages costs them even when it + never runs (the long-context selection: S = 16, 3k context +1.4 us).""" + return fx.Boolean( + llvm.call_intrinsic( + ir.IntegerType.get_signless(1), + "llvm.expect.i1", + [as_ir_value(cond), as_ir_value(fx.Boolean(False))], + [], + [], + ) + ) + + +def uniform(v): + return fx.Int32(rocdl.readfirstlane(T.i32, fx.Int32(v).ir_value())) + + +def _hw_f32(name, x): + return fx.Float32( + llvm.call_intrinsic(T.f32, name, [fx.Float32(x).ir_value()], [], []) + ) + + +def hw_rsq(x): + """v_rsq_f32 (~1 ulp, no libm range fixups).""" + return _hw_f32("llvm.amdgcn.rsq.f32", x) + + +def hw_rcp(x): + return _hw_f32("llvm.amdgcn.rcp.f32", x) + + +def hw_exp2(x): + return _hw_f32("llvm.amdgcn.exp2.f32", x) + + +def div_rn(x, d, r): + """``x / d`` rounded to nearest, bit-identical to the IEEE division, given + ``r = 1.0 / d`` from one true division per divisor (Markstein: a quotient + within 1 ulp plus its exact fma residual times RN(1/d) rounds correctly).""" + q = x * r + return fx.Float32(fmath.fma(fx.Float32(fmath.fma(-q, d, x)), r, q)) + + +def xshfl(v, off): + """Value of lane ``lane ^ off``: offsets 32 / 16 via v_permlane*_swap, in-row + offsets via DPP (VALU latency, not LDS).""" + if off >= 16: + return v.shuffle_xor(off, 64) + is_f = isinstance(v, fx.Float32) + x = v.bitcast(fx.Int32) if is_f else fx.Int32(v) + if off == 8: + y = fx.Int32(update_dpp_i32(x, x, 0x118, 0xF, 0xC, False)) + y = fx.Int32(update_dpp_i32(y, x, 0x108, 0xF, 0x3, False)) + elif off == 4: + y = fx.Int32(update_dpp_i32(x, x, 0x114, 0xF, 0xA, False)) + y = fx.Int32(update_dpp_i32(y, x, 0x104, 0xF, 0x5, False)) + elif off == 2: + y = fx.Int32(update_dpp_i32(x, x, 0x4E, 0xF, 0xF, False)) + else: + y = fx.Int32(update_dpp_i32(x, x, 0xB1, 0xF, 0xF, False)) + return y.bitcast(fx.Float32) if is_f else y + + +def xred(v, off, op): + """op(v, lane ^ off) for a symmetric op; 32 / 16 take both halves of one swap.""" + if off < 16: + return op(v, xshfl(v, off)) + is_f = isinstance(v, fx.Float32) + x = v.bitcast(fx.Int32) if is_f else fx.Int32(v) + a, b = permlane_swap(off, x, x) + if is_f: + return op(a.bitcast(fx.Float32), b.bitcast(fx.Float32)) + return op(type(v)(a), type(v)(b)) + + +def _add(a, b): + return a + b + + +def butterfly(v, offsets, op=_add): + """Butterfly reduction over the given xor offsets, in the given order. + + The order is the numerical contract: the aiter per-head norm reduces 32 + lanes with offsets 16, 8, 4, 2, 1, and matching it keeps rstd bit-exact.""" + for off in offsets: + v = xred(v, off, op) + return v + + +def wave_sum(v): + return butterfly(v, (32, 16, 8, 4, 2, 1)) + + +def traced(fn): + """Apply flydsl's AST rewriting to a helper, so its ``while`` / ``if`` over + traced values lower to scf ops. Kernels rewrite only their own body.""" + return ASTRewriter.transform(fn) + + +def wave_max(v): + return butterfly(v, (32, 16, 8, 4, 2, 1), fx.max) + + +@traced +def block_max(v, lane, wave, red): + """Max of v over the CTA's WAVES waves; ``red`` needs WAVES words.""" + wv = wave_max(v) + gpu.barrier() + if lane == 0: + fx.ptr_store(wv, red + wave) + gpu.barrier() + t = fx.ptr_load(red + 0) + for w in range_constexpr(1, WAVES): + t = fx.max(t, fx.ptr_load(red + w)) + gpu.barrier() + return t + + +def mfma_bf16(a, b, c): + return fx.Vector(rocdl.mfma_f32_16x16x32_bf16(T.vec(4, T.f32), [a, b, c])) + + +def fp8x8_bf16_pk(words): + """Eight fp8 of two dwords -> bf16 MFMA operand (exact) by + v_cvt_scalef32_pk_bf16_fp8 (scale 1), two values an instruction.""" + out = [] + for w in words: + for hi in (False, True): + p = rocdl.cvt_scalef32_pk_bf16_fp8( + T.bf16x2, as_ir_value(fx.Int32(w)), as_ir_value(fx.Float32(1.0)), hi + ) + out.append(fx.Vector(p).bitcast(fx.Int32)[0]) + return fx.Vector.from_elements(out, fx.Int32).bitcast(fx.BFloat16) + + +def bf16_round(a): + return fx.Float32(fx.Float32(a).to(fx.BFloat16)) + + +def bf16_pair(a, b): + """Two f32 -> one f32-typed word holding (bf16(a), bf16(b)).""" + return ( + fx.Vector.from_elements([a, b], fx.Float32) + .to(fx.BFloat16) + .bitcast(fx.Float32)[0] + ) + + +def bf2_f32(w): + """Packed bf16 pair word -> (f32 low, f32 high).""" + return (w << 16).bitcast(fx.Float32), (w & fx.Int32(-65536)).bitcast(fx.Float32) + + +def fp8_pack4(a, b, c, d): + """Four f32 (already in range) -> one dword of four E4M3 bytes, RNE.""" + lo = fx.Int32(rocdl.cvt_pk_fp8_f32(T.i32, a, b, fx.Int32(0), False)) + return fx.Int32(rocdl.cvt_pk_fp8_f32(T.i32, c, d, lo, True)) + + +@traced +def _spin(load_all, pending): + """Re-issue ``load_all`` until ``pending`` clears; a side-effecting op in the + loop keeps the loads from being hoisted.""" + v = load_all() + while pending(v): + rocdl.s_sleep(0) + v = load_all() + return v + + +class Mailbox: + """Tagged-pair hand-off between CTAs (device scope) and GPUs (system scope). + + Every 32-bit value is stored next to this launch's epoch tag; a consumer + polls the payload until all tags match, so a hand-off costs one round trip + (no store drain, no separate flag). The epoch is ``step * LAYER_SLOTS + + layer + 1`` with ``step`` a device counter, so the sequence is graph-safe. + """ + + def __init__(self, scratch, step_ptr, layer): + self.scratch = scratch + self.tag = ( + uniform(bo.buffer_load(rsrc(step_ptr), 0, vec_width=1, dtype=T.i32)) + * LAYER_SLOTS + + layer + + 1 + ) + + def addr(self, offset): + return self.scratch + fx.Int64(offset) + + def put(self, base_addr, i, v, cm=CM_DEV): + bits = v.bitcast(fx.Int32) if isinstance(v, fx.Float32) else fx.Int32(v) + bo.buffer_store( + fx.Vector.from_elements([bits, self.tag], fx.Int32), + rsrc(base_addr), + i * 2, + cache_modifier=cm, + ) + + def put_bf(self, base_addr, i, vs, cm=CM_DEV): + """Store 2 or 4 elements as aligned packed bf16 pairs.""" + words = [] + for j in range_constexpr(len(vs) // 2): + words += [bf16_pair(vs[2 * j], vs[2 * j + 1]).bitcast(fx.Int32), self.tag] + bo.buffer_store( + fx.Vector.from_elements(words, fx.Int32), + rsrc(base_addr), + i, + cache_modifier=cm, + ) + + def put_words(self, base_addr, i, words, cm=CM_DEV): + """Raw 32-bit words (1 or 2) at pairs i.. as (word, tag). Integer payloads + (fp8 words) must come this way: through an f32 value a NaN bit pattern is + not kept.""" + vals = [] + for w in words: + vals += [fx.Int32(w), self.tag] + bo.buffer_store( + fx.Vector.from_elements(vals, fx.Int32), + rsrc(base_addr), + i * 2, + cache_modifier=cm, + ) + + def poll(self, specs, scope="agent", batch=POLL_MAX): + """Poll ``(base_addr, pair index, npairs)`` specs in one batch. + + All pairs are re-loaded together while any tag is stale, so a batch costs + one round trip after its last producer lands. ``scope``: "agent" for pairs + another CTA of this GPU wrote, "system" for pairs a peer GPU wrote. Returns + the value words.""" + if const_expr(len(specs) == 0): + return [] + if const_expr(len(specs) > batch): + return self.poll(specs[:batch], scope, batch) + self.poll( + specs[batch:], scope, batch + ) + assert scope in ("agent", "system"), scope + cm = CM_DEV if const_expr(scope == "agent") else CM_SYS + tag = self.tag + + def load_all(): + words = [] + for b, i, n in specs: + w = fx.Vector( + bo.buffer_load( + rsrc(b), + fx.Int32(i) * 2, + vec_width=2 * n, + dtype=T.i32, + cache_modifier=cm, + ) + ) + words += [w[e] for e in range(2 * n)] + return fx.Vector.from_elements(words, fx.Int32) + + nw = sum(2 * n for _, _, n in specs) + + def pending(v): + bad = v[1] != tag + for e in range_constexpr(3, nw, 2): + bad = bad | (v[e] != tag) + return bad + + v = _spin(load_all, pending) + outs, e = [], 0 + for _, _, n in specs: + outs.append([v[e + 2 * q] for q in range(n)]) + e += 2 * n + return outs + + +def ar_pack_sumsq(vals): + """One logical thread of the custom all-reduce epilogue: its 8 elements' + squares accumulated in order (hipcc contracts ``acc += v * v`` into fma).""" + acc = fx.Float32(0.0) + for v in vals: + acc = fmath.fma(v, v, acc) + return acc + + +@traced +def ar_block_sum(p0, p1, lane, wave, red): + """Sum of the 768 per-pack partials of a 6144-wide bf16 row in the order the + 1-stage fused all-reduce + RMSNorm reduces them: 24 warps of 32, a 16..1 + butterfly per warp, then the 24 warp sums butterflied again in one warp. + + Logical warp ``3 * wave + lane // 32`` holds ``p0``; logical warp + ``3 * wave + 2`` holds ``p1`` in lanes < 32 (``WAVES`` = 8). ``red`` needs + 24 words. Matching this order keeps rstd bit-exact with the original path. + """ + return ar_block_sums([(p0, p1)], lane, wave, red)[0] + + +@traced +def ar_block_sums(parts, lane, wave, red): + """``ar_block_sum`` of several rows ``parts = [(p0, p1), ...]`` behind one set + of barriers; ``red`` needs 24 words per row.""" + bs = [ + (butterfly(p0, (16, 8, 4, 2, 1)), butterfly(p1, (16, 8, 4, 2, 1))) + for p0, p1 in parts + ] + gpu.barrier() + for k in range_constexpr(len(bs)): + b0, b1 = bs[k] + if lane % 32 == 0: + fx.ptr_store(b0, red + (24 * k + wave * 3 + lane // 32)) + if lane == 0: + fx.ptr_store(b1, red + (24 * k + wave * 3 + 2)) + gpu.barrier() + li = lane % 32 + tots = [ + butterfly( + (li < 24).select( + fx.ptr_load(red + (24 * k + fx.min(li, 23))), fx.Float32(0.0) + ), + (16, 8, 4, 2, 1), + ) + for k in range(len(parts)) + ] + gpu.barrier() + return tots diff --git a/vllm/models/minimax_m3/amd/mono/kernels/index_score.py b/vllm/models/minimax_m3/amd/mono/kernels/index_score.py new file mode 100644 index 000000000000..8080b01334ed --- /dev/null +++ b/vllm/models/minimax_m3/amd/mono/kernels/index_score.py @@ -0,0 +1,471 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +"""Indexer block scores for K4's sparse selection (``select_blocks`` polls them). + +The Triton decode scorer's math, one 128-key block of index-K per task: bf16(fp8 +K) x bf16 index q on the MFMA, max over the causal keys, times fp32(sm_scale * +log2 e). A context of <= TOPK_BLOCKS blocks keeps every block and is not scored; +nor are the blocks the selector pins (the first ``init_blocks``, the last +``local_blocks``): their keys are forced. A scored block waits for the index keys +K1 inserts this step only when it may hold one (``wait_new_keys``). + +A task is one block of one request and runs on one wave: the request's q tokens +(a speculative verify's rows) are the MFMA's B columns, so the block's index-K is +read once for all of them, and no task needs the CTA (no barrier). + +Emitted at the end of K1 (``emit_index_scores``), which makes index q: K4's +selector then finds the scores in place instead of scoring after its launch. +``build_index_score_kernel`` runs the same tasks alone, for K4's harnesses. +""" + +import struct +from typing import NamedTuple + +import flydsl.compiler as flyc +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import buffer_ops as bo +from aiter.ops.flydsl.kernels.kernels_common import LOG2E +from flydsl.expr import const_expr, gpu, range_constexpr +from flydsl.expr.typing import Int32, Int64, T + +from vllm.models.minimax_m3.amd.mono.config import ( + BLOCKS, + HEAD_DIM, + INDEX_CP_FROM_BLOCKS, + MAX_INDEX_BLOCKS, + MAX_TOKENS, + ONE_INDEX_HEAD, + SPARSE_BLOCK, + THREADS, + TOPK_BLOCKS, + TP, + WAVES, + IndexHeads, +) +from vllm.models.minimax_m3.amd.mono.kernels.common import ( + Mailbox, + butterfly, + fp8x8_bf16_pk, + kernel_symbol, + lane_gather, + mfma_bf16, + permlane_swap, + readlane, + rsrc, + traced, + uniform, + unlikely, +) + +INDEX_BLOCK_BYTES = SPARSE_BLOCK * HEAD_DIM # one fp8 index-K block +KEY_TILES = SPARSE_BLOCK // 16 # MFMA row tiles of a block +_CURRENT_STREAM = fx.Stream(None) + + +def _f32(x: float) -> float: + return struct.unpack("f", struct.pack("f", x))[0] + + +def index_scale_log2e(sm_scale: float) -> float: + """fp32(sm_scale * log2 e), the scorer's scale.""" + return _f32(_f32(sm_scale) * _f32(LOG2E)) + + +def scored_count(n_blk, init_blocks: int, local_blocks: int): + """How many blocks (from block init_blocks on) a context of n_blk blocks scores.""" + return (n_blk > TOPK_BLOCKS).select(n_blk - (init_blocks + local_blocks), 0) + + +class StepRows(NamedTuple): + """A decode step's rows as the indexer sees them (``step_rows``).""" + + seq: list # each row's context, >= 1 (a graph's pad rows carry 0) + n_blks: list # each row's index blocks + long: list # each row's request is long + + def any_long(self): + v = self.long[0] + for lg in self.long[1:]: + v = v | lg + return v + + +def step_rows(seq_lens, tokens: int, q_len, heads: IndexHeads) -> StepRows: + """The one place a request is decided long: past INDEX_CP_FROM_BLOCKS index + blocks with every index head (its scores take the context-parallel layout, + ``emit_index_scores``), past THREADS with one (more blocks than + ``rank_blocks`` ranks); either way K4 selects it past the split stage. + + Decided by the request's last row (a request is ``q_len`` consecutive rows): + a speculative verify's rows can sit either side of the threshold, and a + request's rows must all read the layout its scores were written in.""" + seq = [ + fx.max(uniform(bo.buffer_load(rsrc(seq_lens), k, vec_width=1, dtype=T.i32)), 1) + for k in range(tokens) + ] + n_blks = [(s + SPARSE_BLOCK - 1) // SPARSE_BLOCK for s in seq] + req_blks = list(n_blks) + for k in range(tokens - 2, -1, -1): + req_blks[k] = (fx.Int32(k) % q_len == q_len - 1).select( + n_blks[k], req_blks[k + 1] + ) + past = INDEX_CP_FROM_BLOCKS if heads.count > 1 else THREADS + return StepRows(seq, n_blks, [nb > past for nb in req_blks]) + + +def _pick(vals, k): + """vals[k] for a traced index k.""" + v = vals[0] + for j in range_constexpr(1, len(vals)): + v = (k == j).select(vals[j], v) + return v + + +@traced +def emit_index_scores( + slot, lane, wave, red, mb_put, iscore, q_frag, tokens, q_len, init_blocks, + local_blocks, scale, index_cache, block_table, seq_lens, bt_width, + wait_new_keys=None, prepare=None, heads=ONE_INDEX_HEAD, q_frag_head=None, + prepare_heads=None, +): # fmt: skip + """This CTA's (``slot``) share of the step's score tasks: up to BLOCKS tasks, + task u runs on CTA u, else on wave (u // BLOCKS) % WAVES of CTA u % BLOCKS + (``red``: WAVES * 16 floats of LDS). The tokens form requests of ``q_len`` + consecutive rows sharing a block table; the last one has the longest context + and lists the request's scored blocks. ``q_frag(k, s)``: this lane's B operand + for token k, k-chunk s (bf16x8 of index q). Pair k * MAX_INDEX_BLOCKS + b of + mailbox ``iscore`` <- the score of token k's block b. + + ``wait_new_keys()`` (K1 fused into the layer kernel; wave-local) waits for the + index keys this launch inserts: a block within MAX_TOKENS keys of a token's + end may hold an earlier token of its request (speculative decode rows). + Without it, every key this launch inserts must sit in a pinned block + (one-token requests). ``prepare(first, last)`` (with CTA barriers) runs on a + CTA with tasks before any index q is read: K1 makes rows first..last's + there. + + Indexer context parallelism (``heads.count`` > 1): a long request + (``step_rows``) scores only this rank's blocks, b = heads.own + (mod TP) -- every index q head of them, a task's key block read once for all: + pair k * MAX_INDEX_BLOCKS + h * (MAX_INDEX_BLOCKS / TP) + b / TP <- the score + of token k's block b for head h. ``q_frag_head(k, s, h)``: head h's B operand + (every lane its own h); ``prepare_heads()`` (with CTA barriers, on every CTA) + makes those requests' rows' heads first. The other requests score as above.""" + assert local_blocks >= 1, "the block of the current token must be pinned" + l16 = lane % 16 + g4 = lane // 16 + r_ic = rsrc(index_cache) + rows = step_rows(seq_lens, tokens, q_len, heads) + seq = rows.seq + # every request's scored blocks in one list, a task per wave across the grid; + # context-parallel requests' (this rank's blocks) in a second + cp = heads.count > 1 + first_own = init_blocks + (heads.own - init_blocks) % TP + pre = [fx.Int32(0)] + pre_cp = [fx.Int32(0)] + for k in range_constexpr(tokens): + last = fx.Int32(k) % q_len == q_len - 1 + n_scored = scored_count(rows.n_blks[k], init_blocks, local_blocks) + if const_expr(cp): + long = rows.long[k] + n_own = fx.max(init_blocks + n_scored - first_own + TP - 1, 0) // TP + pre.append(pre[-1] + (last & ~long).select(n_scored, fx.Int32(0))) + pre_cp.append(pre_cp[-1] + (last & long).select(n_own, fx.Int32(0))) + else: + pre.append(pre[-1] + last.select(n_scored, fx.Int32(0))) + total = pre[tokens] + total_cp = pre_cp[-1] # 0 without context parallelism + + r_bt = rsrc(block_table) + + def task_block(u, pre=pre, first=init_blocks, stride=1): + """Task u of list ``pre`` -> (the request's last token, block b); per lane + if u is.""" + tk = fx.Int32(0) + for j in range_constexpr(1, tokens): + tk = tk + (u >= pre[j]).select(fx.Int32(1), fx.Int32(0)) + return tk, first + stride * (u - _pick(pre[:tokens], tk)) + + def page_of(tk, b): + return fx.Int32( + bo.buffer_load(r_bt, tk * bt_width + b, vec_width=1, dtype=T.i32) + ) + + def new_keys_in(tk, b): + """Block b of the request ending at token tk may hold keys this launch + inserts (a speculative verify's earlier rows).""" + return (b + 1) * SPARSE_BLOCK > _pick(seq, tk) - MAX_TOKENS + + def cols_of(tk): + """B column l16's token (the request's token l16, the last one repeated) + and its context.""" + col = tk - (q_len - 1) + fx.min(l16, q_len - 1) + return col, _pick(seq, col) + + def load_raw(page, tiles): + """Key tiles ``tiles`` (16 keys each) of a block, in flight: lane g4 = + lane / 16 reads its key's bytes 32 g4 .. 32 g4 + 32 with two 16 B loads + (half the load instructions of eight-byte operand reads, scattered over + the rows: 1M context, S = 16, scores 125 -> 100 us); ``split_tiles`` + makes them MFMA operands.""" + words = [] + for i in tiles: + row = (page * INDEX_BLOCK_BYTES + (16 * i + l16) * HEAD_DIM + 32 * g4) // 4 + for h in range_constexpr(2): + w = fx.Vector( + bo.buffer_load(r_ic, row + 4 * h, vec_width=4, dtype=T.i32) + ) + words += [w[e] for e in range(4)] + return fx.Vector.from_elements(words, fx.Int32) + + def split_tiles(raw, tiles): + """``load_raw``'s words -> per tile the MFMA A operands: tile i holds keys + 16 i + lane % 16, k = 32 s + 8 (lane / 16). A 4 x 4 transpose of the 8 B + parts across the key's four lanes (permlane swaps) gives each lane part + g4 of every chunk s.""" + out = [] + for n in range_constexpr(len(tiles)): + d = [raw[8 * n + e] for e in range(8)] + # part j = dwords 2 j, 2 j + 1; lanes g4 and g4 ^ 2, then g4 ^ 1, trade + for off, pairs in ((32, ((0, 2), (1, 3))), (16, ((0, 1), (2, 3)))): + for a, b in pairs: + for w in range_constexpr(2): + d[2 * a + w], d[2 * b + w] = permlane_swap( + off, d[2 * a + w], d[2 * b + w] + ) + out.append( + [ + fx.Vector.from_elements([d[2 * s], d[2 * s + 1]], fx.Int32) + for s in range(HEAD_DIM // 32) + ] + ) + return out + + def tiles_max(b, qb, col_seq, tiles, kw): + """Max over key tiles ``tiles`` of block b (``kw``: ``split_tiles``) of this + lane's column's causal scores (its B operand ``qb``, per k-chunk; the + column's context ``col_seq``), the same in every lane of the column.""" + v = fx.Float32(float("-inf")) + for n, i in enumerate(tiles): + c = fx.Vector.filled(4, 0.0, fx.Float32) + for s in range_constexpr(HEAD_DIM // 32): + c = mfma_bf16(fp8x8_bf16_pk(kw[n][s]), qb[s], c) + # lane holds keys 16 i + 4 (lane / 16) + e of column lane % 16 + key0 = b * SPARSE_BLOCK + 16 * i + 4 * g4 + for e in range_constexpr(4): + v = fx.max(v, (key0 + e < col_seq).select(c[e], float("-inf"))) + return butterfly(v, (32, 16), fx.max) + + def put(b, col, v): + if (lane < 16) & (l16 < q_len): + mb_put(iscore, col * MAX_INDEX_BLOCKS + b, v * scale) + + def emit_cp_tasks(): + """The context-parallel requests' tasks, a task a wave: B column f of pass + p (f = 16 p + lane % 16) is head f / q_len's row f % q_len of the request, + the key block's operands kept for every pass.""" + if const_expr(prepare_heads is not None): + prepare_heads() + tiles = range(KEY_TILES) + seq_lane = _pick(seq, fx.min(lane, tokens - 1)) # lane k: token k's context + n_cols = TP * q_len + + def score_cp(tk, b, page): + """Block b of the request ending at token tk, at ``page``: every head.""" + if const_expr(wait_new_keys is not None): # noqa: SIM102 + if (b + 1) * SPARSE_BLOCK > readlane(seq_lane, tk) - MAX_TOKENS: + wait_new_keys() + kw = split_tiles(load_raw(page, tiles), tiles) + # every pass unrolled, the unused ones skipped: a runtime pass loop + # slowed the whole kernel's short contexts (S = 1, 3k: +0.6 us) + for p in range_constexpr(TP * MAX_TOKENS // 16): + if p * 16 < n_cols: + f = p * 16 + l16 + head = fx.min(f // q_len, TP - 1) + col = tk - (q_len - 1) + f % q_len + qb = [q_frag_head(col, s, head) for s in range(HEAD_DIM // 32)] + v = tiles_max(b, qb, lane_gather(seq_lane, col), tiles, kw) + if (lane < 16) & (f < n_cols): + mb_put( + iscore, + col * MAX_INDEX_BLOCKS + + head * (MAX_INDEX_BLOCKS // TP) + + b // TP, + v * scale, + ) + + # as the wave mode below: task u on wave (u // BLOCKS) % WAVES of CTA + # u % BLOCKS, lane j decoding task c0 + step j + step = BLOCKS * WAVES + for c0 in range(slot + BLOCKS * wave, total_cp, step * 64): + c0 = fx.Int32(c0) + tk_j, b_j = task_block( + fx.min(c0 + step * lane, total_cp - 1), pre_cp, first_own, TP + ) + pages = page_of(tk_j, b_j) + for i in range(fx.min((total_cp - c0 + step - 1) // step, 64)): + i = fx.Int32(i) + score_cp(readlane(tk_j, i), readlane(b_j, i), readlane(pages, i)) + + # Up to BLOCKS tasks: one a CTA, a key tile a wave, the columns' maxima met in + # LDS; the keys go out before prepare() (only the task's request's rows), so + # their latency hides under the index q's: the scores are on the step's + # critical path (keys after: S = 1, 3k context +1 us). More: a task a wave, + # every row's index q first (a wave's task count differs: no barrier inside), + # the pages of a wave's next 64 tasks fetched at once, a lane each. + if total <= BLOCKS: + for u in range(slot, total, BLOCKS): + tk, b = task_block(fx.Int32(u)) + page = uniform(page_of(tk, b)) + if const_expr(wait_new_keys is not None): # noqa: SIM102 + if new_keys_in(tk, b): + wait_new_keys() + raw = load_raw(page, [wave]) + if const_expr(prepare is not None): + prepare(tk - (q_len - 1), tk) + col, col_seq = cols_of(tk) + qb = [q_frag(col, s) for s in range(HEAD_DIM // 32)] + v = tiles_max(b, qb, col_seq, [wave], split_tiles(raw, [wave])) + if lane < 16: + fx.ptr_store(v, red + (wave * 16 + l16)) + gpu.barrier() + if wave == 0: + for w in range_constexpr(1, WAVES): + v = fx.max(v, fx.ptr_load(red + (w * 16 + l16))) + put(b, col, v) + gpu.barrier() + if total > BLOCKS: + if const_expr(prepare is not None): + prepare(fx.Int32(0), fx.Int32(tokens - 1)) + tiles = range(KEY_TILES) + seq_lane = _pick(seq, fx.min(lane, tokens - 1)) # lane k: token k's context + + def score_task(tk, b, page): + """Block b of the request ending at token tk, at ``page``.""" + if const_expr(wait_new_keys is not None): # noqa: SIM102 + if (b + 1) * SPARSE_BLOCK > readlane(seq_lane, tk) - MAX_TOKENS: + wait_new_keys() + raw = load_raw(page, tiles) + col = tk - (q_len - 1) + fx.min(l16, q_len - 1) + col_seq = lane_gather(seq_lane, col) + qb = [q_frag(col, s) for s in range(HEAD_DIM // 32)] + put(b, col, tiles_max(b, qb, col_seq, tiles, split_tiles(raw, tiles))) + + # Every wave the same task count: task u on wave + # (u // BLOCKS) % WAVES of CTA u % BLOCKS; lane j decodes task c0 + step j + # once -- token, block, page -- read back per task (a task's select chains + # sat between one task's keys and the next: S = 16, +8 us). + step = BLOCKS * WAVES + for c0 in range(slot + BLOCKS * wave, total, step * 64): + c0 = fx.Int32(c0) + tk_j, b_j = task_block(fx.min(c0 + step * lane, total - 1)) + pages = page_of(tk_j, b_j) + for i in range(fx.min((total - c0 + step - 1) // step, 64)): + i = fx.Int32(i) + score_task(readlane(tk_j, i), readlane(b_j, i), readlane(pages, i)) + if const_expr(cp): # noqa: SIM102 + # cold: a step without context-parallel requests runs none of it + if unlikely(total_cp > 0): + emit_cp_tasks() + + +def q_frag_from(iq, heads=ONE_INDEX_HEAD): + """(``q_frag``, ``q_frag_head``) reading index q from memory: [token][head] + [HEAD_DIM] bf16, ``heads.count`` heads a token.""" + + def q_frag_head(tk, s, head): + lane = fx.thread_idx.x % 64 + return fx.Vector( + bo.buffer_load( + rsrc(iq), + ((tk * heads.count + head) * HEAD_DIM + 32 * s + 8 * (lane // 16)) // 2, + vec_width=4, + dtype=T.i32, + ) + ).bitcast(fx.BFloat16) + + def q_frag(tk, s): + return q_frag_head(tk, s, heads.own) + + return q_frag, q_frag_head + + +def build_index_score_kernel( + sm_scale: float, + init_blocks: int, + local_blocks: int, + tokens: int = 1, + heads: IndexHeads = ONE_INDEX_HEAD, +): + """``@flyc.jit`` launcher of the score tasks alone (index q from memory, + ``heads.count`` heads a token), for K4's harnesses: scores into mailbox + ``iscore`` with K4's (step, layer) tag.""" + assert 1 <= tokens <= MAX_TOKENS + scale = index_scale_log2e(sm_scale) + # the JIT cache key holds scalar closure values only: the heads go in as ints + ih_count, ih_own = heads.count, heads.own + + @fx.struct + class Smem: + red: fx.Array[fx.Float32, WAVES * 16, 16] + + kernel_name = kernel_symbol( + "minimax_m3_index_score", + s=tokens, + ib=init_blocks, + lb=local_blocks, + ih=heads.count, + io=heads.own, + ) + + @flyc.kernel(name=kernel_name, known_block_size=[THREADS, 1, 1]) + def index_score_kernel( + iq: Int64, + index_cache: Int64, + block_table: Int64, + seq_lens: Int64, + bt_width: Int32, + q_len: Int32, + iscore: Int64, + step: Int64, + layer: Int32, + ): + tid = fx.thread_idx.x + lds = fx.SharedAllocator().allocate(Smem).peek() + red = lds.red.ptr + mbox = Mailbox(iscore, step, layer) + mb_put = mbox.put + k_heads = IndexHeads(ih_count, ih_own) + q_frag, q_frag_head = q_frag_from(iq, k_heads) + emit_index_scores( + fx.block_idx.x, tid % 64, uniform(tid // 64), red, mb_put, iscore, + q_frag, tokens, q_len, init_blocks, local_blocks, scale, index_cache, + block_table, seq_lens, bt_width, heads=k_heads, q_frag_head=q_frag_head, + ) # fmt: skip + + @flyc.jit + def launch_index_score( + iq: Int64, + index_cache: Int64, + block_table: Int64, + seq_lens: Int64, + bt_width: Int32, + q_len: Int32, + iscore: Int64, + step: Int64, + layer: Int32, + stream: fx.Stream = _CURRENT_STREAM, + ): + index_score_kernel( + iq, + index_cache, + block_table, + seq_lens, + bt_width, + q_len, + iscore, + step, + layer, + ).launch(grid=(BLOCKS,), block=(THREADS,), stream=stream) + + return launch_index_score diff --git a/vllm/models/minimax_m3/amd/mono/kernels/post_attn.py b/vllm/models/minimax_m3/amd/mono/kernels/post_attn.py new file mode 100644 index 000000000000..7824d15b8030 --- /dev/null +++ b/vllm/models/minimax_m3/amd/mono/kernels/post_attn.py @@ -0,0 +1,2963 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +"""K4 ``mono_post``: one MiniMax-M3 sparse MoE layer, attention through FFN reduce. + +One launch per layer and rank, ``BLOCKS`` CTAs x ``THREADS`` threads, for a step of +S = 1..MAX_TOKENS tokens (each token's stage tasks side by side); for one token:: + + index : K1, fused in, scored every index-K block (the Triton decode scorer's + block score; with indexer context parallelism a long context's + blocks of this rank, for every index head); every split CTA then + runs the Triton selector's top-k and page-16 table emission itself + (ranking, no sort; for a long request the split tasks' shares' + best TOPK_BLOCKS are ranked, gathered from the peers under CP) + split : one 256-key context partition x 16 heads per task (the gluon decode's + partitioning) over that page-16 table, FP8 QK / PV with its scale + placement + o : combine the partitions (the gluon reduce), per-token FP8 (standalone + quant formula) -> o_proj GEMV + -> push bf16 partial rows to every peer -> rank-ordered sum + -> acc = bf16(sum) + h (h_mid = bf16(acc), mailbox ``a`` = acc) + router: gemma RMSNorm(acc) in the fused all-reduce's reduction order -> bf16 + gate GEMV -> logits; publishes its slice of the normalized input + moe : sigmoid + bias top-4 (+ the fused shared expert) -> MXFP4 a16w4 + up/gate on aiter's shuffled layout -> swiglu -> mid (bf16); + the CTA's down task reuses that routing, its weights prefetched + under the up/gate GEMV: route-weighted down GEMV -> push bf16 + partial rows -> rank-ordered sum -> ar_out = bf16(sum) + +From ``WIDE_FROM`` tokens the MoE groups its work by expert (``wide_moe``): the +router tasks publish xn as MXFP8, each up / gate task pair runs one distinct +expert's 32 rows for every token routed to it (a8w4 MFMA, a B column per token) +and publishes MXFP8 mid rows, and a down task sums over the step's (expert, +token) mids. From ``AG_RS_FROM`` tokens both all-reduces are a reduce-scatter to +the row group's owner rank, which sums in rank order and all-gathers the result. + +The next layer's K1 takes (ar_out, h_mid) exactly as the original path's fused +all-reduce + RMSNorm takes (partials, residual). + +Every stage is a task list; task t runs on CTA (base + t) % BLOCKS and every CTA +walks the stages in order. Dependencies only point to earlier stages and all +CTAs are co-resident, so every spin wait makes progress. +""" + +import struct + +import flydsl.compiler as flyc +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import buffer_ops as bo +from aiter.ops.flydsl.kernels.act import swiglu_mul_batch +from aiter.ops.flydsl.kernels.kernels_common import LOG2E +from flydsl.expr import const_expr, gpu, range_constexpr, rocdl +from flydsl.expr import math as fmath +from flydsl.expr.typing import Int32, Int64, T, as_ir_value + +from vllm.models.minimax_m3.amd.mono import config as mono_config +from vllm.models.minimax_m3.amd.mono.config import ( + BLOCKS, + HEAD_DIM, + HIDDEN, + INDEX_CP_FROM_BLOCKS, + INTER, + MAX_INDEX_BLOCKS, + MAX_TOKENS, + MOE_SLOTS, + N_ROUTED, + ONE_INDEX_HEAD, + PAGE16, + SHARED_EXPERT, + SPARSE_BLOCK, + THREADS, + TOP_K, + TOPK_BLOCKS, + TP, + WAVES, + IndexHeads, +) +from vllm.models.minimax_m3.amd.mono.kernels.common import ( + CM_DEV, + CM_SYS, + Mailbox, + bf2_f32, + bf16_pair, + bf16_round, + butterfly, + fp8_pack4, + hw_exp2, + hw_rcp, + hw_rsq, + kernel_symbol, + memrealtime, + rsrc, + uniform, + unlikely, + wave_max, + wave_sum, + xshfl, +) +from vllm.models.minimax_m3.amd.mono.kernels.common import ( + block_max as block_max_of, +) +from vllm.models.minimax_m3.amd.mono.kernels.index_score import ( + index_scale_log2e, + step_rows, +) +from vllm.models.minimax_m3.amd.mono.kernels.pre_attn import ( + K1_ARGS, + emit_k1, +) +from vllm.models.minimax_m3.amd.mono.kernels.pre_attn import ( + N_HEAD_TASKS as K1_HEAD_TASKS, +) +from vllm.models.minimax_m3.amd.mono.kernels.pre_attn import ( + SCRATCH_HDONE as K1_SCRATCH_HDONE, +) +from vllm.models.minimax_m3.amd.mono.kernels.pre_attn import ( + SCRATCH_RDONE as K1_SCRATCH_RDONE, +) +from vllm.models.minimax_m3.amd.mono.layout import ( + AG_RS_FROM, + DN_ROWS, + MID_ROW, + MIDSC_ROW, + N_DN, + N_O, + N_ROUTER, + N_SPLIT, + O_K, + O_ROW, + O_ROWS, + PAGES_PER_BLOCK, + SCORE_COPIES, + SCRATCH, + SH_ROWS, + SH_TASKS, + SPARSE_TABLE_WORDS, + SPLIT_KEYS, + UG_PER_SLOT, + UG_ROWS, + XN8_ROW, + XSC_ROW, + H, + pool_words, + shared_after_routing, + stage_bases, + sym_layout, + ug_ctas_per_token, + ug_tasks_of, + wide_moe, +) + +FP8_MAX = 448.0 +NEG = -3.4e38 # the gluon decode's masked-score value +PAGE_BYTES = PAGE16 * HEAD_DIM +XN_SLICE = HIDDEN // N_ROUTER # normalized-input elements each router task publishes +W13_ROWS = 2 * INTER # gate rows then up rows (GGUU) +W13_BYTES = W13_ROWS * HIDDEN // 2 # one expert, fp4 +W2_BYTES = HIDDEN * INTER // 2 +W13_SCALE_COLS = HIDDEN // 32 +W2_SCALE_COLS = INTER // 32 +# the separate MXFP8 shared expert (weights.mxfp8_a_tiles): 16-row x 128-k tiles, +# its four tables reached through the ``sh_args`` pointer table (SH_ARGS order) +F8_TILE = 16 * 128 +SH8_W13_BYTES = W13_ROWS * HIDDEN +SH8_W2_BYTES = HIDDEN * INTER +SH8_S13_BYTES = W13_ROWS * W13_SCALE_COLS +SH8_S2_BYTES = HIDDEN * W2_SCALE_COLS +SH_ARGS = ("sh_w13", "sh_s13", "sh_w2", "sh_s2") +SH_W13, SH_S13, SH_W2, SH_S2 = range(len(SH_ARGS)) + +# The launch goes on the caller's current stream (graph capture included). +_CURRENT_STREAM = fx.Stream(None) + + +def _f32(x: float) -> float: + return struct.unpack("f", struct.pack("f", x))[0] + + +TL_POINTS = 32 # timeline stamps per CTA +K1_STAMPS = {1: 27, 2: 28, 3: 29, 4: 30, 6: 31} # fuse_k1: K1's points -> K4's +RANK_SPLIT = 8 # threads ranking one indexer block +RANK_LANES = (4, 2, 1) # butterfly over those RANK_SPLIT lanes +KEY_NONE = -(2**31) # the sort key below every block's +# blocks a thread keys in its split task's eighth of a context (<= MAX_INDEX_BLOCKS) +CAND_BATCH = 2 +assert N_SPLIT * THREADS * CAND_BATCH >= MAX_INDEX_BLOCKS +# Indexer context parallelism: a long context's split task p scans index head +# p // 2's scores of half p % 2 of this rank's blocks -- as many as a TP split task +# scans -- for the head's rank; a request is long past INDEX_CP_FROM_BLOCKS blocks +# (``step_rows``; every long request context-parallel: no TP long selection in that +# build), its rows ending less than a block apart are >= INDEX_CP_FROM_BLOCKS blocks +# each, and a split task then scans >= TOPK_BLOCKS blocks +assert N_SPLIT == 2 * TP +assert N_SPLIT * TOPK_BLOCKS <= INDEX_CP_FROM_BLOCKS <= THREADS +assert MAX_TOKENS <= SPARSE_BLOCK + + +def scale_index(row, col, cols): + """Byte of e8m0 scale (row, col) in aiter's ``shuffle_scale`` layout: + ``view(rows/32, 2, 16, cols/8, 2, 4).permute(0, 3, 5, 2, 4, 1)``.""" + r32, a, b = row // 32, (row // 16) % 2, row % 16 + c8, d, e = col // 8, (col // 4) % 2, col % 4 + return ((((r32 * (cols // 8) + c8) * 4 + e) * 16 + b) * 2 + d) * 2 + a + + +def build_post_attn_kernel( + npes: int, + sm_scale: float, + eps: float, + route_scale: float, + shared_weight: float, + swiglu_limit: float, + init_blocks: int, + local_blocks: int, + tokens: int = 1, + timeline: bool = False, + fuse_k1: bool = False, + heads: IndexHeads = ONE_INDEX_HEAD, + shared_fp8: bool = False, +): + """``@flyc.jit`` launcher of K4 for one rank of an ``npes``-way TP group and a + decode step of ``tokens`` (<= MAX_TOKENS) rows, ``q_len`` consecutive rows a + request (a speculative verify's), with contexts up to MAX_CONTEXT. + ``fuse_k1``: the layer's K1 runs first in the same launch (``K1_ARGS``, + ``positions``, ``slot_mapping``, ``res``; 0 otherwise), for a fused projection + of index q ``heads`` (``IndexHeads``). ``shared_fp8``: the expert tables hold + the routed experts only and the shared expert is MXFP8, its tables behind + the ``sh_args`` pointer table (``SH_ARGS``; 0 otherwise), its GEMVs fp8 x fp8 + MFMAs.""" + assert 1 <= tokens <= MAX_TOKENS + N_E = N_ROUTED if shared_fp8 else N_ROUTED + 1 # experts in w13 .. s2 + E_TOP = N_E - 1 # the bound a routed expert id is clamped to + S13_BYTES = N_E * W13_ROWS * W13_SCALE_COLS # e8m0, every expert + S2_BYTES = N_E * HIDDEN * W2_SCALE_COLS + W = npes + G = BLOCKS + BASE = stage_bases(tokens) + SY = sym_layout(W) + # fuse_k1: K1's outputs are read device-coherent (K1 stores them so) + CM_K1 = CM_DEV if fuse_k1 else 0 + WIDE = wide_moe(tokens) + POOL = pool_words(tokens) + U_MAX = TOP_K * tokens + 1 # distinct routed experts at most, then the shared + + @fx.struct + class Smem: + # activations, bf16 pairs / fp8 quads: every token's xn, o_proj input or + # mid; wide: also the split's PV partials (the stages take turns) + x: fx.Array[fx.Int32, POOL, 16] + red: fx.Array[fx.Float32, WAVES * 64 * 4, 16] + p8: fx.Array[fx.Int32, H * SPLIT_KEYS // 4, 16] + q8: fx.Array[fx.Int32, O_K // 4, 16] + opart: fx.Array[fx.Float32, 1 if WIDE else WAVES * O_K, 16] # PV partials + # wide MoE: the step's distinct experts (the shared one last), token masks + uexp: fx.Array[fx.Int32, U_MAX + 2, 16] + umask: fx.Array[fx.Int32, U_MAX + 2, 16] + # and per (expert, B column) the down stage's mid row and route weight + urow: fx.Array[fx.Int32, U_MAX * 16 if WIDE else 1, 16] + uwt: fx.Array[fx.Float32, U_MAX * 16 if WIDE else 1, 16] + hst: fx.Array[ + fx.Float32, 3 * WAVES * H + WAVES, 16 + ] # head max / sum, max, v_scale max + misc: fx.Array[fx.Float32, O_ROWS * MAX_TOKENS, 16] # a task's output rows + route: fx.Array[fx.Int32, 8 * MAX_TOKENS, 16] # token k's slots at 8 k + rwt: fx.Array[fx.Float32, 8 * MAX_TOKENS, 16] # and their routing weights + # indexer sort keys, a block a thread (a long request: the waves' + # candidate (key, block) pairs) and their ranks + keys: fx.Array[fx.Int32, THREADS, 16] + ranks: fx.Array[fx.Int32, THREADS, 16] + blk: fx.Array[fx.Int32, 32, 16] # this split's 16 pages, n_ctx, tail flag + tls: fx.Array[fx.Int64, TL_POINTS if timeline else 1, 16] # timeline stamps + # fuse_k1: index q (every head's: in the pool) + qs: fx.Array[fx.Float32, HEAD_DIM // 2 * tokens if heads.count == 1 else 1, 16] + + kernel_name = kernel_symbol( + "minimax_m3_mono_layer" if fuse_k1 else "minimax_m3_post_attn", + tp=npes, + s=tokens, + ib=init_blocks, + lb=local_blocks, + ih=heads.count, + io=heads.own, + tl=timeline, + kps=mono_config.KV_PAGE_STRIDE, + sks=mono_config.STATIC_KV_SCALE, + sf8=shared_fp8, + ) + + # the JIT cache key holds the kernel's scalar closure values, not objects: the + # index heads go in as ints (a shared cache otherwise serves one rank's build + # to every rank) + ih_count, ih_own = heads.count, heads.own + # fuse_k1 with every index head: K1's index q of every head (qs) after its x8 + # rows in the pool (K1 is done with the pool before K4's stages use it) + QS_CP = tokens * HIDDEN // 4 + assert not (fuse_k1 and heads.count > 1) or ( + QS_CP + HEAD_DIM // 2 * tokens * heads.count <= POOL + ) + + @flyc.kernel(name=kernel_name, known_block_size=[THREADS, 1, 1]) + def post_attn_kernel( + h_in: Int64, + q: Int64, + block_table: Int64, + seq_lens: Int64, + k_cache: Int64, + v_cache: Int64, + k_scale: Int64, + v_scale: Int64, + w_o: Int64, + s_o: Int64, + g_post: Int64, + w_gate: Int64, + bias: Int64, + w13: Int64, + s13: Int64, + w2: Int64, + s2: Int64, + sh_args: Int64, + h_mid: Int64, + ar_out: Int64, + scratch: Int64, + sym: Int64, + peers: Int64, + step: Int64, + rank: Int32, + layer: Int32, + bt_width: Int32, + q_len: Int32, + tl: Int64, + k1_args: Int64, + positions: Int64, + slot_mapping: Int64, + res: Int64, + ): + tid = fx.thread_idx.x + bid = fx.block_idx.x + lane = tid % 64 + wave = tid // 64 + g4 = lane // 16 + l16 = lane % 16 + lds = fx.SharedAllocator().allocate(Smem).peek() + xs = lds.x.ptr + red = lds.red.ptr + p8 = lds.p8.ptr + q8 = lds.q8.ptr + # the pool read and written as f32 (wide: the split's PV partials live there) + fpool = fx.recast_iter(fx.Float32, xs) + opart = fpool if WIDE else lds.opart.ptr + uexp = lds.uexp.ptr + umask = lds.umask.ptr + urow = lds.urow.ptr + uwt = lds.uwt.ptr + hst = lds.hst.ptr + misc = lds.misc.ptr + route = lds.route.ptr + rwt = lds.rwt.ptr + keys = lds.keys.ptr + ranks = lds.ranks.ptr + blk = lds.blk.ptr + tls = lds.tls.ptr + v4f = fx.Vector.make_type(4, fx.Float32) + v2i = fx.Vector.make_type(2, fx.Int32) + + mbox = Mailbox(scratch, step, layer) + # Plain names, not method calls: flydsl's AST rewriter carries every local + # whose method is called inside a dynamic if/for as loop state. + mb_put = mbox.put + mb_put_bf = mbox.put_bf + mb_put_words = mbox.put_words + mb_poll = mbox.poll + + def mb(name): + return scratch + fx.Int64(SCRATCH[name]) + + def acquire(): + fx.memory_fence( + syncscope=rocdl.SyncScope.Workgroup, ordering=fx.AtomicOrdering.Acquire + ) + + def scores_copy(c, k=0): + """Copy c of token k's router outputs: expert e's (routing key, sigmoid) + at pairs 2 e, 2 e + 1.""" + return mb("scores") + (fx.Int64(c) * MAX_TOKENS + fx.Int64(k)) * ( + N_ROUTED * 16 + ) + + def route_key(v, e): + """Signed-orderable i32 of score ``v`` with its low 7 bits replaced by + 127 - expert ``e``: a pick is one integer max, a tie goes to the lower + expert.""" + b = v.bitcast(fx.Int32) + b = (b < 0).select(b ^ fx.Int32(0x7FFFFFFF), b) + return (b & fx.Int32(-128)) | (127 - e) + + # each wave pushes to one peer + pv = fx.Vector( + bo.buffer_load( + rsrc(peers), fx.min(wave, W - 1) * 2, vec_width=2, dtype=T.i32 + ) + ) + peer_dst = (fx.Int64(uniform(pv[1])) << 32) | fx.Int64( + fx.Uint32(uniform(pv[0])) + ) + AG_RS = tokens >= AG_RS_FROM + + def peer_addr(w): + pw = fx.Vector(bo.buffer_load(rsrc(peers), w * 2, vec_width=2, dtype=T.i32)) + return (fx.Int64(uniform(pw[1])) << 32) | fx.Int64( + fx.Uint32(uniform(pw[0])) + ) + + def start(name): + return (bid + (G - BASE[name])) % G + + def stamp(k): + """``timeline``: s_memrealtime (100 MHz) of this CTA passing point k, kept + in LDS until the kernel ends -- a global store per stamp would put its + write latency on every later ``s_waitcnt vmcnt(0)``.""" + # The compile-time and traced conditions cannot share one ``and``. + if const_expr(timeline): # noqa: SIM102 + if tid == 0: + fx.ptr_store(memrealtime(), tls + k) + + def flush_stamps(): + if const_expr(timeline): # noqa: SIM102 + if tid < TL_POINTS: + fx.generic_store( + fx.inttoptr( + fx.PointerType.get( + fx.Int64.ir_type, fx.AddressSpace.Global, 8 + ), + tl + fx.Int64((bid * TL_POINTS + tid) * 8), + ), + fx.ptr_load(tls + tid), + ) + + def ld_bf16x4(r, k, cm=0): + w = fx.Vector( + bo.buffer_load(r, k // 2, vec_width=2, dtype=T.i32, cache_modifier=cm) + ) + v = w.bitcast(fx.BFloat16).to(fx.Float32) + return [v[j] for j in range(4)] + + def mfma_fp8(a64, b64, c): + return fx.Vector( + rocdl.mfma_f32_16x16x32_fp8_fp8(T.vec(4, T.f32), [a64, b64, c, 0, 0, 0]) + ) + + def block_max(v): + return block_max_of(v, lane, wave, red) + + def push_rows(region, row0, n_rows, only=None): + """This task's bf16 partial rows (misc: token k's n_rows from k n_rows) to + the peers' ``region``, a pair a lane, wave w -> peer w (itself too); + ``only``: to that peer alone.""" + half = n_rows // 2 + to = (wave < W) if only is None else (wave == only) + for c in range_constexpr((half * tokens + 63) // 64): + i = lane + 64 * c + if to & (i < half * tokens): + mb_put_bf( + peer_dst + fx.Int64(SY[region]), + (rank * MAX_TOKENS + i // half) * HIDDEN + + row0 + + (i % half) * 2, + [fx.ptr_load(misc + i * 2), fx.ptr_load(misc + (i * 2 + 1))], + CM_SYS, + ) + + if const_expr(timeline): # noqa: SIM102 + if tid < TL_POINTS: # same wave as the stamping thread: ordered + fx.ptr_store(fx.Int64(0), tls + tid) + stamp(0) + + if const_expr(fuse_k1): + # this layer's K1 first: its GEMV / head / norm tasks and the scores + def k1_ptr(i): + v = fx.Vector( + bo.buffer_load(rsrc(k1_args), 2 * i, vec_width=2, dtype=T.i32) + ) + return (fx.Int64(uniform(v[1])) << 32) | fx.Int64( + fx.Uint32(uniform(v[0])) + ) + + def k1_stamp(k): + """K1's timeline points 1-4 and 6 on K4's free stamps 27-31.""" + if const_expr(k in K1_STAMPS): + stamp(K1_STAMPS[k]) + + ( + ar_in, g_in, w_qkv, s_qkv, g_q, g_k, g_iq, g_ik, cos_sin, index_cache, + iq_out, scratch1, + ) = [k1_ptr(i) for i in range(len(K1_ARGS))] # fmt: skip + qs_k1 = lds.qs.ptr + if const_expr(ih_count > 1): + qs_k1 = fpool + QS_CP + emit_k1( + tid, bid, lane, wave, xs, red, qs_k1, k1_stamp, step, layer, + eps, index_scale_log2e(sm_scale), tokens, q_len, init_blocks, + local_blocks, IndexHeads(ih_count, ih_own), + ( + ar_in, res, h_in, g_in, w_qkv, s_qkv, g_q, g_k, g_iq, g_ik, + cos_sin, positions, slot_mapping, k_cache, v_cache, k_scale, + v_scale, index_cache, q, iq_out, block_table, seq_lens, + mb("iscore"), scratch1, + ), + bt_width, + True, + ) # fmt: skip + gpu.barrier() + k1_mbox = Mailbox(scratch1, step, layer) + k1_poll = k1_mbox.poll + hdone_mb = k1_mbox.addr(K1_SCRATCH_HDONE) + rdone_mb = k1_mbox.addr(K1_SCRATCH_RDONE) + + # ============================================================ 0. index + # Indexer: K1 scored every block the selection does not pin (index_score); + # here only the selection runs. + # a graph's pad rows carry seq_len 0 and an all-zero block-table row: as one + # key of page 0 they stay finite and select a real page + seq_lens_k, n_blks, long_rows = step_rows( + seq_lens, tokens, q_len, IndexHeads(ih_count, ih_own) + ) + # Up to TOPK_BLOCKS blocks the top-k keeps every block and the scores would + # only order them. The original selector's own contract calls either order + # equally correct (index_topk._pack_score_key), so a short context is not + # scored and takes the blocks in id order -- the tail block is last either + # way -- instead of putting the scoring chain in front of the attention. + scored = [nb > TOPK_BLOCKS for nb in n_blks] + + def bt_row(k): + """Token k's block-table row (rows are ``bt_width`` apart).""" + return block_table + fx.Int64(k) * fx.Int64(bt_width) * 4 + + def pick(vals, k): + """vals[k] for a traced token index k.""" + v = vals[0] + for i in range_constexpr(1, tokens): + v = (k == i).select(vals[i], v) + return v + + def index_key(b, word, n_blk): + """Sort key of block b's raw score word: forced blocks pinned, then a + signed int ordered like the float (-0 == 0, NaN below -inf).""" + sc = word.bitcast(fx.Float32) + sc = (b < init_blocks).select(fx.Float32(1e30), sc) + sc = (b >= n_blk - local_blocks).select(fx.Float32(1e29), sc) + bits = sc.bitcast(fx.Int32) + bits = (bits == fx.Int32(-(2**31))).select(fx.Int32(0), bits) + key = (bits < 0).select(bits ^ 0x7FFFFFFF, bits) + return ((bits & 0x7FFFFFFF) > 0x7F800000).select(fx.Int32(-(2**31)), key) + + def rank_blocks(k, iscore, n_blk, r_bt, scored_k): + """Up to THREADS blocks: thread b keys block b, and a block's rank + counts the blocks that beat it. -> this thread's (key, block, rank, + live, the tail block's key, page). ``scored_k``: the scores are read + (else the blocks rank by id).""" + b = tid + live = b < n_blk + bb = fx.min(b, n_blk - 1) + page = fx.Int32(bo.buffer_load(r_bt, bb, vec_width=1, dtype=T.i32)) + # K1 (or the harnesses' scorer) wrote every score before this launch, so + # a plain load reads them: it goes out before the context length is in. + # A pinned block's slot holds no score (index_key forces its key); past + # n_blk the keys are never read + if const_expr(fuse_k1): + # the scorers are CTAs of this launch: poll (a pinned block's slot + # polls a scored block's) + word = fx.Int32(0) + if scored_k: + word = mb_poll( + [ + ( + iscore, + fx.min( + fx.max(tid, init_blocks), + n_blk - 1 - local_blocks, + ), + 1, + ) + ] + )[0][0] + else: + word = fx.Int32( + bo.buffer_load(rsrc(iscore), 2 * tid, vec_width=1, dtype=T.i32) + ) + fx.ptr_store(scored_k.select(index_key(tid, word, n_blk), -tid), keys + tid) + stamp(18) + gpu.barrier() + stamp(20) + # rank = the keys that beat it. RANK_SPLIT threads share a block, each + # comparing every RANK_SPLIT-th key: one lane walking all 61 keys of a + # 7.8k context took 1.9 us (a serial compare -> SGPR mask chain) + part = tid % RANK_SPLIT + for b0 in range(0, n_blk, THREADS // RANK_SPLIT): + rb = fx.Int32(b0) + tid // RANK_SPLIT + rbc = fx.min(rb, n_blk - 1) + kb = fx.ptr_load(keys + rbc) + cnt = fx.Int32(0) + for j0 in range(0, n_blk, RANK_SPLIT): + j = fx.Int32(j0) + part + kj = fx.ptr_load(keys + fx.min(j, n_blk - 1)) + beats = (kj > kb) | ((kj == kb) & (j > rbc)) + cnt = cnt + (beats & (j < n_blk)).select(fx.Int32(1), fx.Int32(0)) + cnt = butterfly(cnt, RANK_LANES) + if (part == 0) & (rb < n_blk): + fx.ptr_store(cnt, ranks + rb) + gpu.barrier() + key = fx.ptr_load(keys + bb) + rank = fx.ptr_load(ranks + bb) + stamp(19) + kt = fx.ptr_load(keys + (n_blk - 1)) + return key, bb, rank, live, kt, page + + def ballot(pred): + return fx.Int64(rocdl.ballot(T.i64, pred)) + + def beats(ah, al, bh, bl): + """(key, block) pair a orders before b.""" + return (ah > bh) | ((ah == bh) & (al > bl)) + + def choose_pair(key, block, peer_key, peer_block, take_high): + partner_high = beats(peer_key, peer_block, key, block) + high_h = partner_high.select(peer_key, key) + high_l = partner_high.select(peer_block, block) + low_h = partner_high.select(key, peer_key) + low_l = partner_high.select(block, peer_block) + return take_high.select(high_h, low_h), take_high.select(high_l, low_l) + + def merge16_best(ah, al, bh, bl): + """Return the top half of two descending 16-item lists.""" + b_hi = beats(bh, bl, ah, al) + key, block = b_hi.select(bh, ah), b_hi.select(bl, al) + for off in (8, 4, 2, 1): + ph, pl = xshfl(key, off), xshfl(block, off) + p_hi = beats(ph, pl, key, block) + hi_h, hi_l = p_hi.select(ph, key), p_hi.select(pl, block) + lo_h, lo_l = p_hi.select(key, ph), p_hi.select(block, pl) + take_hi = (l16 & off) == 0 + key = take_hi.select(hi_h, lo_h) + block = take_hi.select(hi_l, lo_l) + return key, block + + def sort16_desc(key, block): + for size, strides in ( + (2, (1,)), + (4, (2, 1)), + (8, (4, 2, 1)), + (16, (8, 4, 2, 1)), + ): + for stride in strides: + ph, pl = xshfl(key, stride), xshfl(block, stride) + asc = (l16 & size) != 0 + low = (l16 & stride) == 0 + key, block = choose_pair(key, block, ph, pl, low ^ asc) + return key, block + + def wave_best(h0, l0, h1, l1): + """Return the exact top 16 of 128 pairs in lanes 0..15.""" + h0, l0 = sort16_desc(h0, l0) + h1, l1 = sort16_desc(h1, l1) + h0, l0 = merge16_best(h0, l0, xshfl(h0, 31), xshfl(l0, 31)) + h1, l1 = merge16_best(h1, l1, xshfl(h1, 31), xshfl(l1, 31)) + h0, l0 = merge16_best(h0, l0, xshfl(h0, 47), xshfl(l0, 47)) + h1, l1 = merge16_best(h1, l1, xshfl(h1, 47), xshfl(l1, 47)) + h0, l0 = merge16_best( + h0, + l0, + h1.shuffle_xor(15, 64), + l1.shuffle_xor(15, 64), + ) + return h0, l0 + + def rank_cands(): + """Merge eight sorted candidate rows to the exact top 16.""" + key, block = fx.Int32(KEY_NONE), fx.Int32(-1) + if wave == 0: + group = lane // TOPK_BLOCKS + index = l16 + ai = (2 * group) * TOPK_BLOCKS + index + bi = (2 * group + 1) * TOPK_BLOCKS + (TOPK_BLOCKS - 1 - index) + key, block = merge16_best( + fx.ptr_load(keys + 2 * ai), + fx.ptr_load(keys + (2 * ai + 1)), + fx.ptr_load(keys + 2 * bi), + fx.ptr_load(keys + (2 * bi + 1)), + ) + key, block = merge16_best(key, block, xshfl(key, 31), xshfl(block, 31)) + key, block = merge16_best(key, block, xshfl(key, 47), xshfl(block, 47)) + return key, block, tid, (tid < TOPK_BLOCKS) & (block >= 0) + + def place(key, bb, rank, live, kt, n_blk, seq_len, active): + """The ranked blocks' slots, as the Triton selector emits them: full + blocks by rank, the tail block (the one holding the current token) + last. -> (selected, slot, sparse context length); ``active``: this + CTA places (a uniform flag).""" + n_sel = fx.min(n_blk, TOPK_BLOCKS) + tail = n_blk - 1 + tail_first = (kt > key) | ((kt == key) & (tail > bb)) + sel = live & (rank < n_sel) & active + is_tail = sel & (bb == tail) + if is_tail: + fx.ptr_store(fx.Int32(1), blk + 17) + gpu.barrier() + tail_sel = fx.ptr_load(blk + 17) != 0 + n_full = n_sel - tail_sel.select(fx.Int32(1), fx.Int32(0)) + slot = is_tail.select( + n_full, rank - tail_first.select(fx.Int32(1), fx.Int32(0)) + ) + n_ctx = tail_sel.select( + n_full * SPARSE_BLOCK + seq_len - tail * SPARSE_BLOCK, + fx.min(n_sel * SPARSE_BLOCK, seq_len), + ) + return sel, slot, n_ctx + + def table_of(k): + return rsrc(mb("sparse_table") + fx.Int64(k) * (SPARSE_TABLE_WORDS * 4)) + + def select_blocks(k, t): + """blk[0:16] := the pages of selection slots 2t, 2t+1 and blk[16] := the + sparse context length, exactly as the Triton selector emits them: top + TOPK_BLOCKS by (score, block id) descending with the init blocks pinned + to 1e30 and the local ones to 1e29, full blocks in that order and the + tail block (the one holding the current token) last. A block's slot + follows from its rank, the count of blocks that beat it. k: token. + For a long request ``stage_select_long`` left blk: a one-block + stand-in is ranked, placing nothing.""" + iscore = mb("iscore") + fx.Int64(k) * (MAX_INDEX_BLOCKS * 8) + short = ~pick(long_rows, k) + n_blk = short.select(pick(n_blks, k), fx.Int32(1)) + seq_len = pick(seq_lens_k, k) + r_bt = rsrc(bt_row(k)) + table = table_of(k) + if (tid < 2 * PAGES_PER_BLOCK + 2) & short: + fx.ptr_store(fx.Int32(0), blk + tid) + key, bb, rank, live, kt, page = rank_blocks( + k, iscore, n_blk, r_bt, pick(scored, k) & short + ) + sel, slot, n_ctx = place(key, bb, rank, live, kt, n_blk, seq_len, short) + if sel & (slot // 2 == t): + for j in range_constexpr(PAGES_PER_BLOCK): + fx.ptr_store( + page * mono_config.KV_PAGE_STRIDE + j, + blk + ((slot % 2) * PAGES_PER_BLOCK + j), + ) + if sel & (t == 0): + for j in range_constexpr(PAGES_PER_BLOCK): + bo.buffer_store( + page * mono_config.KV_PAGE_STRIDE + j, + table, + slot * PAGES_PER_BLOCK + j, + ) + if (tid == 0) & short: + fx.ptr_store(n_ctx, blk + 16) + if t == 0: + bo.buffer_store(n_ctx, table, TOPK_BLOCKS * PAGES_PER_BLOCK) + gpu.barrier() + + def select_long(k, part): + """Split task (k, part) of a long request's token, before the + split stage. Its share of the blocks (a thread keys CAND_BATCH) -> each + wave's TOPK_BLOCKS best -> the CTA's, to a candidate mailbox; then the + N_SPLIT shares' candidates (the context's TOPK_BLOCKS best are among + them) are ranked and placed -> blk as ``select_blocks`` leaves it, and + (part 0) the sparse table. The share: an eighth of the blocks, to this + rank's sel_long; with every index head (indexer context parallelism) + head part // 2's scores of half part % 2 of this rank's blocks, to the + head's rank's sel_cp -- the shares its own head's candidates come in.""" + n_blk = pick(n_blks, k) + iscore = mb("iscore") + fx.Int64(k) * (MAX_INDEX_BLOCKS * 8) + first = k * (N_SPLIT * TOPK_BLOCKS) # token k's candidates (pair pairs) + table = table_of(k) + if tid == 0: # the tail flag ``place`` reads: LDS, not zeroed on this path + fx.ptr_store(fx.Int32(0), blk + 17) + if const_expr(ih_count > 1): + own0 = init_blocks + (ih_own - init_blocks) % TP # this rank's first + n_own = (n_blk - own0 + TP - 1) // TP + # the last scored one: the local blocks' slots hold no score + last = own0 + TP * ((n_blk - local_blocks - own0 + TP - 1) // TP - 1) + span = (n_own + 1) // 2 + lo = (part % 2) * span + hi = fx.min(lo + span, n_own) + js = [lo + tid + THREADS * i for i in range(CAND_BATCH)] + blocks = [own0 + TP * j for j in js] + live = [j < hi for j in js] + src = iscore + fx.Int64(part // 2) * (MAX_INDEX_BLOCKS // TP * 8) + slots = [fx.min(b, last) // TP for b in blocks] + out, out_slot = peer_addr(part // 2) + fx.Int64(SY["sel_cp"]), 2 * rank + out_slot = out_slot + part % 2 + got_from, got_scope = sym + fx.Int64(SY["sel_cp"]), "system" + else: + span = (n_blk + N_SPLIT - 1) // N_SPLIT + lo = part * span + hi = fx.min(lo + span, n_blk) + blocks = [lo + tid + THREADS * i for i in range(CAND_BATCH)] + live = [b < hi for b in blocks] + src = iscore + slots = [ + fx.min(fx.max(b, init_blocks), n_blk - 1 - local_blocks) + for b in blocks + ] + out, out_slot = mb("sel_long"), part + got_from, got_scope = out, "agent" + if const_expr(fuse_k1): + words = [w[0] for w in mb_poll([(src, sl, 1) for sl in slots])] + else: + words = [ + fx.Int32( + bo.buffer_load(rsrc(src), 2 * sl, vec_width=1, dtype=T.i32) + ) + for sl in slots + ] + hs = [ + lv.select(index_key(b, w, n_blk), fx.Int32(KEY_NONE)) + for b, w, lv in zip(blocks, words, live) + ] + ls = [lv.select(b, fx.Int32(-1)) for b, lv in zip(blocks, live)] + stamp(18) + rh, rl = wave_best(hs[0], ls[0], hs[1], ls[1]) + if lane < TOPK_BLOCKS: + fx.ptr_store(rh, keys + 2 * (wave * TOPK_BLOCKS + lane)) + fx.ptr_store(rl, keys + (2 * (wave * TOPK_BLOCKS + lane) + 1)) + gpu.barrier() + ch, cl, cnt, held = rank_cands() + # a share holds >= TOPK_BLOCKS blocks: its 16 best are blocks of + # distinct ranks + if held & (cnt < TOPK_BLOCKS): + mb_put_words( + out, + 2 * (first + out_slot * TOPK_BLOCKS + cnt), + [ch, cl], + CM_SYS if ih_count > 1 else CM_DEV, + ) + gpu.barrier() + stamp(20) + if tid < N_SPLIT * TOPK_BLOCKS: + got = mb_poll([(got_from, 2 * (first + tid), 2)], got_scope)[0] + fx.ptr_store(got[0], keys + 2 * tid) + fx.ptr_store(got[1], keys + (2 * tid + 1)) + gpu.barrier() + ch, cl, cnt, held = rank_cands() + page = fx.Int32( + bo.buffer_load( + rsrc(bt_row(k), MAX_INDEX_BLOCKS * 4), + cl, + vec_width=1, + dtype=T.i32, + mask=held, + ) + ) + stamp(19) + # the tail block is a local one: its key is forced + kt = index_key(n_blk - 1, fx.Int32(0), n_blk) + sel, slot, n_ctx = place( + ch, cl, cnt, held, kt, n_blk, pick(seq_lens_k, k), pick(long_rows, k) + ) + if sel & (slot // 2 == part): + for j in range_constexpr(PAGES_PER_BLOCK): + fx.ptr_store( + page * mono_config.KV_PAGE_STRIDE + j, + blk + ((slot % 2) * PAGES_PER_BLOCK + j), + ) + if sel & (part == 0): + for j in range_constexpr(PAGES_PER_BLOCK): + bo.buffer_store( + page * mono_config.KV_PAGE_STRIDE + j, + table, + slot * PAGES_PER_BLOCK + j, + ) + if tid == 0: + fx.ptr_store(n_ctx, blk + 16) + if part == 0: + bo.buffer_store(n_ctx, table, TOPK_BLOCKS * PAGES_PER_BLOCK) + gpu.barrier() + + def stage_select_long(): + """The split tasks of a long request's token select before the + split stage (``select_long``), each leaving its blk for its split task + (a CTA runs at most one). Out of the split stage and cold: inline + there, this code slowed the split for every context (64k: +1 us).""" + ts = start("split") + k = ts // N_SPLIT + if unlikely((ts < N_SPLIT * tokens) & pick(long_rows, k)): + select_long(k, ts % N_SPLIT) + + # Each stage is its own function: flydsl carries a local reassigned inside a + # dynamic if / for as region state, so names must not be shared across stages. + # ============================================================ 1. split + def stage_split(): + r_k, r_v = rsrc(k_cache), rsrc(v_cache) + r_ks, r_vs = rsrc(k_scale), rsrc(v_scale) + PPW = SPLIT_KEYS // WAVES // PAGE16 # pages per wave + for ts in range(start("split"), N_SPLIT * tokens, G): + ts = fx.Int32(ts) # token tok's partition t: ts = tok N_SPLIT + t + tok = ts // N_SPLIT + t = ts % N_SPLIT + select_blocks(tok, t) + stamp(17) + if const_expr(fuse_k1): + # this token's q heads and every token's new K / V: a request's + # tokens of one step (speculative decode) attend to each other's + if wave == 0: + kv = lane - H + k1_poll( + [ + ( + hdone_mb, + (lane < H).select( + tok * K1_HEAD_TASKS + lane, + fx.min(kv // 2, tokens - 1) * K1_HEAD_TASKS + + H + + kv % 2, + ), + 1, + ) + ] + ) + gpu.barrier() + acquire() + # Every independent load goes out first: this wave's pages and q. + # Pages past the context read junk masked below. + n_ctx = uniform(fx.ptr_load(blk + 16)) + pages = [ + uniform(fx.ptr_load(blk + (wave * PPW + j))) for j in range(PPW) + ] + qv = ld_bf16x4(rsrc(q), tok * O_K + tid * 4, CM_K1) + # K (QK B operand, key = lane % 16 of page j), V (PV B operand: dims + # 16 jd + lane % 16, keys 8 (lane / 16) .. + 8), per-token scales + kw = [] + for j in range_constexpr(PPW): + for s in range_constexpr(HEAD_DIM // 32): + kw.append( + fx.Vector( + bo.buffer_load( + r_k, + ( + pages[j] * PAGE_BYTES + + (2 * s + g4 // 2) * 256 + + l16 * 16 + + (g4 % 2) * 8 + ) + // 4, + vec_width=2, + dtype=T.i32, + cache_modifier=CM_K1, + ) + ).bitcast(fx.Int64)[0] + ) + vpg = (g4 // 2 == 0).select(pages[0], pages[1]) + vw = [ + fx.Vector( + bo.buffer_load( + r_v, + (vpg * PAGE_BYTES + (16 * jd + l16) * PAGE16 + (g4 % 2) * 8) + // 4, + vec_width=2, + dtype=T.i32, + cache_modifier=CM_K1, + ) + ).bitcast(fx.Int64)[0] + for jd in range(HEAD_DIM // 16) + ] + kss = [ + fx.Float32( + bo.buffer_load( + r_ks, + pages[j] * PAGE16 + l16, + vec_width=1, + dtype=T.f32, + cache_modifier=CM_K1, + ) + ) + for j in range(PPW) + ] + vss = [ + fx.Float32( + bo.buffer_load( + r_vs, + pages[j] * PAGE16 + l16, + vec_width=1, + dtype=T.f32, + cache_modifier=CM_K1, + ) + ) + for j in range(PPW) + ] + fx.ptr_store(fp8_pack4(qv[0], qv[1], qv[2], qv[3]), q8 + tid) + gpu.barrier() + stamp(12) + # QK per page: A=q (heads), B=K (keys); a lane holds heads + # 4*g4+e and key l16. + key0 = t * SPLIT_KEYS + wave * (PPW * PAGE16) + valid = [key0 + j * PAGE16 + l16 < n_ctx for j in range(PPW)] + sc = [] + for j in range_constexpr(PPW): + c = fx.Vector.filled(4, 0.0, fx.Float32) + for s in range_constexpr(HEAD_DIM // 32): + qw = fx.Vector( + fx.ptr_load( + q8 + (l16 * 32 + 8 * s + 2 * g4), result_type=v2i + ) + ) + c = mfma_fp8( + qw.bitcast(fx.Int64)[0], kw[j * (HEAD_DIM // 32) + s], c + ) + qk = sm_scale * kss[j] + sc.append( + [valid[j].select(qk * c[e], fx.Float32(NEG)) for e in range(4)] + ) + # partition max per head and max v_scale: in-wave butterfly, then LDS + vloc = fx.max( + valid[0].select(vss[0], fx.Float32(0.0)), + valid[1].select(vss[1], fx.Float32(0.0)), + ) + vmax_w = wave_max(vloc) + for e in range_constexpr(4): + mh = butterfly(fx.max(sc[0][e], sc[1][e]), (8, 4, 2, 1), fx.max) + if l16 == 0: + fx.ptr_store(mh, hst + (wave * H + g4 * 4 + e)) + if lane == 0: + fx.ptr_store(vmax_w, hst + (3 * WAVES * H + wave)) + gpu.barrier() + stamp(13) + # every wave partial is read before the first p8 store below: LDS + # stores in between serialize each read behind its own wait + vmax = fx.ptr_load(hst + 3 * WAVES * H) + for w in range_constexpr(1, WAVES): + vmax = fx.max(vmax, fx.ptr_load(hst + (3 * WAVES * H + w))) + mxs = [] + for e in range_constexpr(4): + mx = fx.ptr_load(hst + (g4 * 4 + e)) + for w in range_constexpr(1, WAVES): + mx = fx.max(mx, fx.ptr_load(hst + (w * H + g4 * 4 + e))) + mxs.append(mx) + fscale = FP8_MAX * hw_rcp(vmax + 1e-8) + pscale = vmax * (1.0 / FP8_MAX) + for e in range_constexpr(4): + head = g4 * 4 + e + mx = mxs[e] + ls = fx.Float32(0.0) + for j in range_constexpr(PPW): + pj = hw_exp2((sc[j][e] - mx) * LOG2E) + ls = ls + pj + b8 = ( + fp8_pack4( + (valid[j].select(vss[j], fx.Float32(0.0)) * fscale) + * pj, + 0.0, + 0.0, + 0.0, + ) + & 0xFF + ) + w8 = b8 | (xshfl(b8, 1) << 8) + w8 = w8 | (xshfl(w8, 2) << 16) + if l16 % 4 == 0: + kloc = wave * (PPW * PAGE16) + j * PAGE16 + l16 + fx.ptr_store( + w8, p8 + (head * (SPLIT_KEYS // 4) + kloc // 4) + ) + ls = butterfly(ls, (8, 4, 2, 1)) + if l16 == 0: + fx.ptr_store(ls, hst + (WAVES * H + wave * H + head)) + fx.ptr_store(mx, hst + (2 * WAVES * H + head)) + gpu.barrier() + stamp(14) + # PV over this wave's 32 keys: A = P (heads), B = V (dims) + pw = fx.Vector( + fx.ptr_load( + p8 + + ( + l16 * (SPLIT_KEYS // 4) + + (wave * (PPW * PAGE16) + 8 * g4) // 4 + ), + result_type=v2i, + ) + ).bitcast(fx.Int64)[0] + # keys past the context carry P = 0, but a NaN V byte would still poison + nv = n_ctx - (key0 + 8 * g4) + vmask = (nv >= 8).select( + fx.Int64(-1), + (nv <= 0).select( + fx.Int64(0), (fx.Int64(1) << (fx.Int64(nv) * 8)) - 1 + ), + ) + for jd in range_constexpr(HEAD_DIM // 16): + cv = mfma_fp8( + pw, vw[jd] & vmask, fx.Vector.filled(4, 0.0, fx.Float32) + ) + for e in range_constexpr(4): + fx.ptr_store( + cv[e], + opart + + (wave * O_K + (g4 * 4 + e) * HEAD_DIM + 16 * jd + l16), + ) + gpu.barrier() + stamp(15) + # Sum wave partials: acc=prob_scale*PV, then /exp_sum, bf16. + e0 = tid * 4 + head = e0 // HEAD_DIM + lsum = fx.ptr_load(hst + (WAVES * H + head)) + for w in range_constexpr(1, WAVES): + lsum = lsum + fx.ptr_load(hst + (WAVES * H + w * H + head)) + inv_l = 1.0 / (lsum > 0.0).select(lsum, fx.Float32(1.0)) + ov = [] + for k in range_constexpr(4): + acc = fx.ptr_load(opart + (e0 + k)) + for w in range_constexpr(1, WAVES): + acc = acc + fx.ptr_load(opart + (w * O_K + e0 + k)) + ov.append((pscale * acc) * inv_l) + mb_put_bf(mb("sp_o"), ts * O_K + e0, ov) + if tid < H: + mb_put( + mb("sp_m"), + ts * H + tid, + fx.ptr_load(hst + (2 * WAVES * H + tid)), + ) + lt = fx.ptr_load(hst + (WAVES * H + tid)) + for w in range_constexpr(1, WAVES): + lt = lt + fx.ptr_load(hst + (WAVES * H + w * H + tid)) + mb_put(mb("sp_l"), ts * H + tid, lt) + gpu.barrier() + + stage_select_long() + stage_split() + stamp(1) + + def merge_token(k): + """Token k's partitions merged (the gluon decode's reduce; thread = 4 dims + of one head) and quantized per token (standalone quant: scale = amax * + (1 / FP8_MAX), x * rcp(scale)) -> (this thread's fp8 word, scale).""" + hm = tid // (HEAD_DIM // 4) + e0 = tid * 4 + sp0 = k * N_SPLIT # token k's partitions + # wave 0 waits on every partition's l, then the CTA polls once: 512 + # threads x 24 loads spinning through the whole split load the memory + # system the split itself reads (-0.4 us) + if wave == 0: + mb_poll( + [ + (mb("sp_l"), sp0 * H + lane + 64 * i, 1) + for i in range(N_SPLIT * H // 64) + ] + ) + gpu.barrier() + # one batch: every partition's (m, l) and this thread's 4 outputs + got = mb_poll( + [(mb("sp_m"), (sp0 + i) * H + hm, 1) for i in range(N_SPLIT)] + + [(mb("sp_l"), (sp0 + i) * H + hm, 1) for i in range(N_SPLIT)] + + [ + (mb("sp_o"), ((sp0 + i) * O_K + e0) // 2, 2) for i in range(N_SPLIT) + ], + batch=3 * N_SPLIT, + ) + mls = got[: 2 * N_SPLIT] + ovs = got[2 * N_SPLIT :] + stamp(3) + m_i = [mls[i][0].bitcast(fx.Float32) for i in range(N_SPLIT)] + l_i = [mls[N_SPLIT + i][0].bitcast(fx.Float32) for i in range(N_SPLIT)] + gm = m_i[0] + for i in range_constexpr(1, N_SPLIT): + gm = fx.max(gm, m_i[i]) + sl = [l_i[i] * hw_exp2((m_i[i] - gm) * LOG2E) for i in range(N_SPLIT)] + gs = sl[0] + for i in range_constexpr(1, N_SPLIT): + gs = gs + sl[i] + gs = (gs > 0.0).select(gs, fx.Float32(1.0)) + av = [fx.Float32(0.0) for _ in range(4)] + for i in range_constexpr(N_SPLIT): + wi = sl[i] / gs + o01 = bf2_f32(ovs[i][0]) + o23 = bf2_f32(ovs[i][1]) + av = [ + av[0] + wi * o01[0], + av[1] + wi * o01[1], + av[2] + wi * o23[0], + av[3] + wi * o23[1], + ] + a0, a1, a2, a3 = (bf16_round(x) for x in av) + amax = block_max( + fx.max( + fx.max(fmath.absf(a0), fmath.absf(a1)), + fx.max(fmath.absf(a2), fmath.absf(a3)), + ) + ) + x_scale = amax * (1.0 / FP8_MAX) + # an all-zero row (a pad row) quantizes to zeros, not 0 * inf + inv = (amax == 0.0).select(fx.Float32(0.0), hw_rcp(x_scale)) + return fp8_pack4(a0 * inv, a1 * inv, a2 * inv, a3 * inv), x_scale + + # ======================================= 2b. attention merge (S > 1) + # One task per token, in parallel on its own CTA: merged in the o tasks, the + # tokens' merges ran one after another in every one of them (+14 us at S = 4) + def stage_merge(): + if const_expr(tokens > 1): + for k in range(start("merge"), tokens, G): + k = fx.Int32(k) + word, x_scale = merge_token(k) + # plain words, then the scale: its pair is the flag + bo.buffer_store( + word, + rsrc(mb("attnq")), + k * (O_K // 4) + tid, + cache_modifier=CM_DEV, + ) + fx.memory_fence( + syncscope=rocdl.SyncScope.Workgroup, + ordering=fx.AtomicOrdering.Release, + ) + gpu.barrier() + if tid == 0: + mb_put(mb("attnq_s"), k, x_scale) + + stage_merge() + + # ================================================ 3. o_proj + attn reduce + def stage_o(): + r_wo = rsrc(w_o) + O_CPW = O_K // 64 // 4 # 64-k chunks per wave: 4 waves per 16-row group + for t in range(start("o"), N_O, G): + t = fx.Int32(t) + rg = t * 2 + wave // 4 + wts = [] + for cc in range_constexpr(O_CPW): + kc = (wave % 4) * O_CPW + cc + wts.append( + fx.Vector( + bo.buffer_load( + r_wo, + ((rg * (O_K // 32) + kc * 2) * 512 + lane * 16) // 4, + vec_width=4, + dtype=T.i32, + ) + ) + ) + # this task's row scales, before the wait + ws = fx.Float32( + bo.buffer_load( + rsrc(s_o), t * O_ROWS + tid % O_ROWS, vec_width=1, dtype=T.f32 + ) + ) + + if const_expr(tokens == 1): + # the merge folded in: the partitions -> this CTA's fp8 input + word, x_scale = merge_token(0) + x_scales = [x_scale] + fx.ptr_store(word, xs + tid) + else: + # the merge tasks' fp8 inputs: every token's scale (published + # after its plain words), then the words, 16 B a load + got = mb_poll([(mb("attnq_s"), k, 1) for k in range(tokens)]) + stamp(3) + x_scales = [got[k][0].bitcast(fx.Float32) for k in range(tokens)] + acquire() + n_v = tokens * O_K // 16 + for i in range_constexpr((n_v + THREADS - 1) // THREADS): + v = tid + THREADS * i + if v < n_v: + fx.ptr_store( + fx.Vector( + bo.buffer_load( + rsrc(mb("attnq")), + v * 4, + vec_width=4, + dtype=T.i32, + cache_modifier=CM_DEV, + ) + ), + xs + (v * 4 // (O_K // 4) * O_ROW + v * 4 % (O_K // 4)), + ) + gpu.barrier() + # B column l % 16 is token l % 16 (token 0 past the last): C column k + # is token k's rows, the weight stream is the same for any token count + col_tok = fx.min(l16, tokens - 1) + c = fx.Vector.filled(4, 0.0, fx.Float32) + # chunks kc, kc + 1 in one 16x16x128 FP8 MFMA (unit scales): its lane + # holds k 16 (l / 16) .. + 16 of each 64-k half -- the chunks' packing + for p in range_constexpr(O_CPW // 2): + xb = [ + fx.Vector( + fx.ptr_load( + xs + + ( + col_tok * O_ROW + + ((wave % 4) * O_CPW + 2 * p + h) * 16 + + g4 * 4 + ), + result_type=v4f, + ) + ).bitcast(fx.Int32) + for h in range(2) + ] + c = fx.Vector( + rocdl.mfma_scale_f32_16x16x128_f8f6f4( + T.vec(4, T.f32), + [ + fx.Vector.from_elements( + [ + wts[2 * p + h][e] + for h in range(2) + for e in range(4) + ], + fx.Int32, + ), + fx.Vector.from_elements( + [xb[h][e] for h in range(2) for e in range(4)], + fx.Int32, + ), + c, + 0, + 0, + 0, + fx.Int32(127), + 0, + fx.Int32(127), + ], + ) + ) + fx.ptr_store(c, red + (wave * 64 + lane) * 4) + gpu.barrier() + if tid < O_ROWS * tokens: + tk = tid // O_ROWS + grp = (tid % O_ROWS) // 16 + rr = tid % 16 + tot = fx.Float32(0.0) + for w in range_constexpr(4): + tot = tot + fx.ptr_load( + red + + (((grp * 4 + w) * 64 + 16 * (rr // 4) + tk) * 4 + rr % 4) + ) + fx.ptr_store(bf16_round(tot * pick(x_scales, tk) * ws), misc + tid) + gpu.barrier() + # push bf16 partial rows, wave w -> peer w (to itself too); with AG_RS + # to the row group's owner rank only + push_rows("attn", t * O_ROWS, O_ROWS, t % W if AG_RS else None) + gpu.barrier() + if const_expr(AG_RS): # noqa: SIM102 + # the owner sums every peer's partials in rank order and gathers + # the sums to every rank's a_ag (h_mid: the router tasks) + if (t % W == rank) & (tid < O_ROWS // 2 * tokens): + ptk = tid // (O_ROWS // 2) + row = t * O_ROWS + (tid % (O_ROWS // 2)) * 2 + own = sym + fx.Int64(SY["attn"]) + prt = mb_poll( + [ + (own, ((src * MAX_TOKENS + ptk) * HIDDEN + row) // 2, 1) + for src in range(W) + ], + "system", + ) + t0 = fx.Float32(0.0) + t1 = fx.Float32(0.0) + for src in range_constexpr(W): + f0, f1 = bf2_f32(prt[src][0]) + t0 = t0 + f0 + t1 = t1 + f1 + for w in range_constexpr(W): + mb_put_bf( + peer_addr(w) + fx.Int64(SY["a_ag"]), + ptk * HIDDEN + row, + [t0, t1], + CM_SYS, + ) + if const_expr(not AG_RS): # noqa: SIM102 + # this task's rows of the all-reduce, finished here (GLM's + # peer_reduce): sum peer partials in rank order, bf16, then + # add the residual into h_mid and the 'a' mailbox. A router + # reads 24 KB device-scope, not 4 peers' 48 KB system-scope. + if tid < O_ROWS // 2 * tokens: + ptk = tid // (O_ROWS // 2) + row = t * O_ROWS + (tid % (O_ROWS // 2)) * 2 + if const_expr(tokens != 1): + if const_expr(fuse_k1): + k1_poll([(rdone_mb, ptk, 1)]) + acquire() + hr = fx.Int32( + bo.buffer_load( + rsrc(h_in), + (ptk * HIDDEN + row) // 2, + vec_width=1, + dtype=T.i32, + cache_modifier=CM_K1, + ) + ) + own = sym + fx.Int64(SY["attn"]) + prt = mb_poll( + [ + (own, ((src * MAX_TOKENS + ptk) * HIDDEN + row) // 2, 1) + for src in range(W) + ], + "system", + ) + t0 = fx.Float32(0.0) + t1 = fx.Float32(0.0) + for src in range_constexpr(W): + f0, f1 = bf2_f32(prt[src][0]) + t0 = t0 + f0 + t1 = t1 + f1 + # the rank sum only: the router adds the residual in f32, so the + # norm reads bf16(sum) plus the unrounded residual. + mb_put_bf(mb("a"), ptk * HIDDEN + row, [t0, t1]) + if const_expr(tokens != 1): + r0, r1 = bf2_f32(hr) + a0 = bf16_round(t0) + r0 + a1 = bf16_round(t1) + r1 + bo.buffer_store( + fx.Vector.from_elements([a0, a1], fx.Float32).to( + fx.BFloat16 + ), + rsrc(h_mid), + ptk * HIDDEN + row, + ) + + stage_o() + stamp(4) + + # ======================================================= MoE helpers + def e8m0_load(r_s, byte_idx): + """An e8m0 scale byte, still in flight (the MFMA takes it as is).""" + return fx.Int32(bo.buffer_load(r_s, byte_idx, vec_width=1, dtype=T.i8)) + + def group_scale_byte(expert, rows, rg, kc, cols): + """scale_index(expert rows + 16 rg + l16, 4 kc + g4, cols): this lane's + byte for row group rg, 128-k chunk kc, folded to wave-uniform terms plus + the lane (the general form's per-lane arithmetic cost the S = 16 up / + gate loop ~8 us).""" + base = (expert * (rows // 32) + rg // 2) * (cols // 8) + kc // 2 + return (base * 64 + lane) * 4 + (kc % 2) * 2 + rg % 2 + + def route_top4(k, k0, sc0, k1, sc1, sig, wave_mask=None): + """route[8k : 8k+4] / rwt[..] := token k's sigmoid top-k gating from the + router tasks' routing keys ``k0`` / ``k1`` (experts ``lane`` / ``lane + + 64``, sigmoid + bias, see route_key) and unbiased sigmoids (wave k % WAVES + computes it, looking the sigmoids up in LDS at ``sig``): a pick is one + wave max; the weights are the picks' sigmoids renormalized and scaled by + route_scale. Slot 4 is the fused shared expert. ``wave_mask``: this + wave's expert -> token mask, the picks' bit k set (the picks are + distinct, and the wave's tokens run in program order). The caller + syncs.""" + if wave == k % WAVES: + # the unbiased weights, looked up by expert once the picks are known + fx.ptr_store(sc0, sig + (k * N_ROUTED + lane)) + fx.ptr_store(sc1, sig + (k * N_ROUTED + 64 + lane)) + pid = fx.Int32(0) + for p in range_constexpr(TOP_K): + m = butterfly(fx.max(k0, k1), (32, 16, 8, 4, 2, 1), fx.max) + hit0 = k0 == m + k0 = hit0.select(fx.Int32(-(2**31)), k0) + k1 = ((k1 == m) & (k0 != m)).select(fx.Int32(-(2**31)), k1) + pid = (lane == p).select(127 - (m & 127), pid) + if lane < TOP_K: + w = fx.ptr_load(sig + (k * N_ROUTED + pid)) + tot = butterfly(w, (1, 2)) + fx.ptr_store(pid, route + (8 * k + lane)) + fx.ptr_store( + w * (route_scale / fx.max(tot, 1e-20)), rwt + (8 * k + lane) + ) + if const_expr(wave_mask is not None): + was = fx.Int32(fx.ptr_load(wave_mask + pid)) + fx.ptr_store(was | (fx.Int32(1) << k), wave_mask + pid) + if lane == 0: + fx.ptr_store(fx.Int32(SHARED_EXPERT), route + (8 * k + TOP_K)) + fx.ptr_store(fx.Float32(shared_weight), rwt + (8 * k + TOP_K)) + + # a8w4 operands in xs (Int32 words, never through f32 arithmetic): the up / + # gate stage holds every token's MXFP8 xn then its E8M0 scales; the down + # stage every token's MXFP8 mid then its scales + XN8_WORDS = HIDDEN // 4 + XSC_WORDS = HIDDEN // 32 + XSC_LDS = tokens * XN8_ROW + MID16_WORDS = MOE_SLOTS * INTER // 2 # bf16 pairs, as the mids land + MID8_WORDS = MOE_SLOTS * INTER // 4 + MID8_LDS = tokens * MID16_WORDS + MIDSC_WORDS = MOE_SLOTS * INTER // 32 + MIDSC_LDS = MID8_LDS + tokens * MID8_WORDS + + def mx8_scale(vals, offsets): + """E8M0 byte (>= 1) of the 32-block the lanes xor-``offsets`` apart share, + aiter's MXFP8 RoundUp rule ceil_pow2(amax / 448), and its reciprocal.""" + amax = fx.max(vals[0], -vals[0]) + for v in vals[1:]: + amax = fx.max(amax, fx.max(v, -v)) + amax = butterfly(amax, offsets, fx.max) + bits = (amax * fx.Float32(1.0 / FP8_MAX)).bitcast(fx.Int32) + e = (bits >> 23) & 0xFF + e = e + ((bits & 0x7FFFFF) != 0).select(fx.Int32(1), fx.Int32(0)) + e = fx.max(fx.min(e, fx.Int32(254)), fx.Int32(1)) + return e, hw_rcp((e << 23).bitcast(fx.Float32)) + + def mx8_q(v, inv): + return fx.max(fx.min(v * inv, fx.Float32(FP8_MAX)), fx.Float32(-FP8_MAX)) + + def lds_b8(chunk_word): + """This lane's B operand of the 128-k chunk at LDS word ``chunk_word``: + fp8 k 16 g .. + 16 then 64 + 16 g .. + 16 (g = lane // 16), the + f8f6f4 MFMA's B layout (harness/mfma_f4f8_probe.py).""" + h = [ + fx.Vector( + fx.ptr_load(xs + (chunk_word + 16 * j + 4 * g4), result_type=v4f) + ).bitcast(fx.Int32) + for j in range(2) + ] + return fx.Vector.from_elements( + [h[j][e] for j in range(2) for e in range(4)], fx.Int32 + ) + + def bf16x2(word): + return fx.Vector.from_elements([word], fx.Int32).bitcast(fx.BFloat16) + + def lds_i32(word): + return fx.ptr_load(xs + word).bitcast(fx.Int32) + + def mfma_f4f8(w4, sa, b8, sb, c, sa_byte=None): + """16x16x128 scaled MFMA: A = this lane's 32 fp4 (row l % 16, k block + l / 16) with E8M0 ``sa``, B = its 32 fp8 with E8M0 ``sb``. ``sa_byte``: + ``sa`` is a scale dword, the MFMA takes that byte of it.""" + if const_expr(sa_byte is None): + sa, sa_byte = sa & 0xFF, 0 + return fx.Vector( + rocdl.mfma_scale_f32_16x16x128_f8f6f4( + T.vec(4, T.f32), [w4, b8, c, 4, 0, sa_byte, sa, 0, sb] + ) + ) + + def mfma_f8f8(w8, sa, b8, sb, c, sa_byte=None): + """``mfma_f4f8`` with an fp8 A: this lane's 32 fp8 of row l % 16 in the B + operand's k order (``f8_tile_load``); the scales are placed alike.""" + if const_expr(sa_byte is None): + sa, sa_byte = sa & 0xFF, 0 + return fx.Vector( + rocdl.mfma_scale_f32_16x16x128_f8f6f4( + T.vec(4, T.f32), [w8, b8, c, 0, 0, sa_byte, sa, 0, sb] + ) + ) + + def f8_tile_load(r_w, tile, slot): + """Lane ``slot``'s 32 fp8 of 16 x 128 tile ``tile`` (weights.mxfp8_a_tiles) + as the f8f6f4 MFMA's 8-dword A operand.""" + word = (tile * F8_TILE + slot * 32) // 4 + h = [ + fx.Vector(bo.buffer_load(r_w, word + 4 * j, vec_width=4, dtype=T.i32)) + for j in range(2) + ] + return fx.Vector.from_elements( + [h[j][e] for j in range(2) for e in range(4)], fx.Int32 + ) + + def sh_ptr(i): + """The MXFP8 shared expert's table ``SH_ARGS[i]``, read at use from the + ``sh_args`` pointer table (as K1's are): as four more kernel arguments + they widened the kernarg pointer tuple, which ROCm LLVM's partial- + register rewrite spilled incompletely (a fault at S = 2).""" + v = fx.Vector( + bo.buffer_load(rsrc(sh_args), 2 * i, vec_width=2, dtype=T.i32) + ) + return (fx.Int64(uniform(v[1])) << 32) | fx.Int64(fx.Uint32(uniform(v[0]))) + + def w_tile(r_w, rg, kc, slot, k, fp8): + """Lane ``slot``'s A operand of row group rg, 128-k chunk kc of a table + of k columns: fp4 (two 16 x 64 tiles of 512 B, shuffle_weight(16, 16)) + or MXFP8 (``f8_tile_load``).""" + if const_expr(fp8): + return f8_tile_load(r_w, rg * (k // 128) + kc, slot) + return fx.Vector( + bo.buffer_load( + r_w, + ((rg * (k // 64) + kc * 2) * 512 + slot * 16) // 4, + vec_width=4, + dtype=T.i32, + ) + ) + + mfma_sh = mfma_f8f8 if shared_fp8 else mfma_f4f8 # the shared expert's + + # ============================================================ 4. router + def stage_router(): + r_g = rsrc(g_post) + r_gate = rsrc(w_gate) + # this thread's 12 consecutive elements of the row (512 x 12 = HIDDEN): + # the poll is 3 specs per rank, 12 in one batch, every thread busy + RE = HIDDEN // THREADS + rw0 = tid * (RE // 2) + + def ld_bf16x12(r, word, cm=0): + """12 bf16 from ``word`` (a 16 B then an 8 B load).""" + a8 = fx.Vector( + bo.buffer_load(r, word, vec_width=4, dtype=T.i32, cache_modifier=cm) + ).bitcast(fx.BFloat16) + a4 = fx.Vector( + bo.buffer_load( + r, word + 4, vec_width=2, dtype=T.i32, cache_modifier=cm + ) + ).bitcast(fx.BFloat16) + return [a8[e] for e in range(8)] + [a4[e] for e in range(4)] + + # one task per (token, 8 experts): the tokens' norms and dot products run + # on different CTAs, not one after another in each (S = 4: 74.7 -> 64.1 us) + for tt in range(start("router"), N_ROUTER * tokens, G): + tt = fx.Int32(tt) + k = tt // N_ROUTER + t = tt % N_ROUTER + e_r = t * WAVES + wave + bias_r = fx.Float32( + bo.buffer_load(rsrc(bias), e_r, vec_width=1, dtype=T.f32) + ) + gw = [ # bf16 pairs + fx.Vector( + bo.buffer_load( + r_gate, + (e_r * HIDDEN + (i * 64 + lane) * 8) // 2, + vec_width=4, + dtype=T.i32, + ) + ) + for i in range(HIDDEN // 512) + ] + gp = ld_bf16x12(r_g, rw0) + if const_expr(fuse_k1): + # the residual (K1's norm / GEMV task) + if wave == 0: + k1_poll([(rdone_mb, k, 1)]) + gpu.barrier() + acquire() + hres = ld_bf16x12(rsrc(h_in), k * (HIDDEN // 2) + rw0, CM_K1) + # the all-reduced post-attention row (the o tasks finished it; with + # AG_RS the owner ranks gathered it into this rank's a_ag) + a_src, a_scope = ( + (sym + fx.Int64(SY["a_ag"]), "system") + if AG_RS + else (mb("a"), "agent") + ) + arow = mb_poll( + [ + (a_src, (k * HIDDEN + tid * RE) // 2 + 2 * h, 2) + for h in range(RE // 4) + ], + a_scope, + ) + stamp(22) + v = [ + f + fx.Float32(hres[4 * h + 2 * qq + i]) + for h in range(RE // 4) + for qq in range(2) + for i, f in enumerate(bf2_f32(arow[h][qq])) + ] + if const_expr(AG_RS or tokens == 1): # noqa: SIM102 + # h_mid = bf16(bf16(sum) + residual): task t writes slice t + if tid // (XN_SLICE // RE) == t: + hw = (k * HIDDEN + tid * RE) // 2 + hb = fx.Vector.from_elements(v, fx.Float32).to(fx.BFloat16) + hi = hb.bitcast(fx.Int32) + bo.buffer_store( + fx.Vector.from_elements( + [hi[e] for e in range(4)], fx.Int32 + ), + rsrc(h_mid), + hw, + ) + bo.buffer_store( + fx.Vector.from_elements([hi[4], hi[5]], fx.Int32), + rsrc(h_mid), + hw + 4, + ) + # the row's sum of squares: a wave sum each, one barrier, every lane + # adds the 8 + ssw = fx.Float32(0.0) + for e in range_constexpr(RE): + ssw = fmath.fma(v[e], v[e], ssw) + ssw = wave_sum(ssw) + if lane == 0: + fx.ptr_store(ssw, red + wave) + gpu.barrier() + ss = fx.ptr_load(red) + for w in range_constexpr(1, WAVES): + ss = ss + fx.ptr_load(red + w) + stamp(24) + rstd = hw_rsq(ss / float(HIDDEN) + eps) + for j in range_constexpr(RE // 2): + fx.ptr_store( + bf16_pair( + v[2 * j] * rstd * (fx.Float32(gp[2 * j]) + 1.0), + v[2 * j + 1] * rstd * (fx.Float32(gp[2 * j + 1]) + 1.0), + ), + xs + (rw0 + j), + ) + gpu.barrier() + stamp(25) + if tid < XN_SLICE // 4: # 4 elements a lane, 8 lanes a 32-block + w0 = t * (XN_SLICE // 2) + tid * 2 + f = [ + v + for j in range(2) + for v in bf2_f32(fx.ptr_load(xs + (w0 + j)).bitcast(fx.Int32)) + ] + e, inv = mx8_scale(f, (1, 2, 4)) + word = fp8_pack4(*[mx8_q(v, inv) for v in f]) + xw = k * XN8_WORDS + t * (XN_SLICE // 4) + tid + xsw = k * XSC_WORDS + t * (XN_SLICE // 32) + tid // 8 + if const_expr(WIDE): + # plain words, flagged once the task is done (below) + bo.buffer_store( + word, rsrc(mb("xn8p")), xw, cache_modifier=CM_DEV + ) + if tid % 8 == 0: + bo.buffer_store( + e, rsrc(mb("xscp")), xsw, cache_modifier=CM_DEV + ) + else: + mb_put_words(mb("xn8"), xw, [word]) + if tid % 8 == 0: + mb_put_words(mb("xsc"), xsw, [e]) + stamp(26) + # bf16 pair dot products, one accumulator per pair position: four + # 12-long chains instead of one 96-long FMA chain behind 192 widenings + accs = [fx.Float32(0.0) for _ in range(4)] + for i in range_constexpr(HIDDEN // 512): + xv = fx.Vector( + fx.ptr_load(xs + (i * 64 + lane) * 4, result_type=v4f) + ).bitcast(fx.Int32) + for j in range_constexpr(4): + accs[j] = fx.Float32( + rocdl.fdot2_f32_bf16( + T.f32, + as_ir_value(bf16x2(gw[i][j])), + as_ir_value(bf16x2(xv[j])), + as_ir_value(accs[j]), + clamp=False, + ).result + ) + logit = wave_sum((accs[0] + accs[1]) + (accs[2] + accs[3])) + stamp(23) + # the routing key and sigmoid go out, not the logit: the consumers' + # routing starts at the max rounds + sc = hw_rcp(1.0 + hw_exp2(-bf16_round(logit) * LOG2E)) + rk = route_key(sc + bias_r, e_r) + if lane < SCORE_COPIES: + mb_put_words( + scores_copy(lane, k), e_r * 2, [rk, sc.bitcast(fx.Int32)] + ) + if const_expr(WIDE): + # this task's xn slice is out: its flag (after the logits, not + # in front of them) + fx.memory_fence( + syncscope=rocdl.SyncScope.Workgroup, + ordering=fx.AtomicOrdering.Release, + ) + gpu.barrier() + if tid == 0: + mb_put(mb("xndone"), tt, fx.Int32(1)) + + stage_router() + stamp(5) + + # ================================ 5. experts: up / gate -> down -> FFN reduce + UG_KC = HIDDEN // 128 # 128-k chunks + UG_CPW = UG_KC // WAVES # 128-k chunks per wave: each wave a k eighth + DN_KC = INTER // 128 # 128-k chunks of one slot + DN_UNITS = TOP_K * DN_KC # routed (slot, 128-k chunk) units per row group + DN_UPW = (DN_UNITS + 3) // 4 # 4 waves per row group + SH_UPW = (DN_KC + 3) // 4 # the shared expert's chunks, once for all tokens + # routed (token, slot, row group) tasks t < ROUTED_TASKS; the shared expert's + # row groups (one GEMV with a column per token) are tasks ROUTED_TASKS + j, + # run as task j of stage "shared" while the routing is still on its way, so + # the routed tasks alone set the rounds (S = 4: 768 = 3 x 256) + ROUTED_TASKS = TOP_K * UG_PER_SLOT * tokens + TPT = TOP_K * UG_PER_SLOT # routed tasks per token + CPT = ug_ctas_per_token(tokens) + UG_ITERS = max(ug_tasks_of(c, tokens) for c in range(G)) # per CTA, at most + + def ug_task_id(it): + """(this CTA's it-th routed task, clamped; whether it exists).""" + if const_expr(CPT is not None): + u = bid % CPT + it * CPT + return (bid // CPT) * TPT + fx.min(u, TPT - 1), u < TPT + t = start("ug") + it * G + return fx.min(t, ROUTED_TASKS - 1), t < ROUTED_TASKS + + def ug_task(t): + """(shared expert?, token, slot, row group) of up / gate task t.""" + shared = t >= ROUTED_TASKS + r = fx.min(t, ROUTED_TASKS - 1) + tk = r // (TOP_K * UG_PER_SLOT) + slot = shared.select( + fx.Int32(TOP_K), (r % (TOP_K * UG_PER_SLOT)) // UG_PER_SLOT + ) + return shared, tk, slot, t % UG_PER_SLOT + + def ug_load(t): + """Up / gate weights and scales of task t.""" + shared, tk, slot, cg = ug_task(t) + # the bound keeps a corrupt route from addressing past the expert table + # (a shared task never gets here: ug_task_id clamps to the routed tasks + # and sh_load runs the shared expert) + e_u = shared.select( + fx.Int32(min(SHARED_EXPERT, E_TOP)), + fx.min(uniform(fx.ptr_load(route + (8 * tk + slot))), E_TOP), + ) + r_w = rsrc(w13 + fx.Int64(e_u) * W13_BYTES) + r_s = rsrc(s13) + wts: list[list] = [] # [gate, up][chunk] + scs: list[list] = [] + for gu in range_constexpr(2): + rg = gu * UG_PER_SLOT + cg + wts.append([]) + scs.append([]) + for i in range_constexpr(UG_CPW): + kc = wave * UG_CPW + i + wts[gu].append( + fx.Vector( + bo.buffer_load( + r_w, + ((rg * (HIDDEN // 64) + kc * 2) * 512 + lane * 16) // 4, + vec_width=4, + dtype=T.i32, + ) + ) + ) + scs[gu].append( + e8m0_load( + r_s, + group_scale_byte(e_u, W13_ROWS, rg, kc, W13_SCALE_COLS), + ) + ) + return wts, scs + + def ug_compute(t, wts, scs): + """Up / gate GEMV of task t -> swiglu -> its 16 mid values (of every token + for the shared expert: B column l % 16 is token l % 16).""" + shared, tk, slot, cg = ug_task(t) + col = shared.select(fx.min(l16, tokens - 1), tk) + cg_ = fx.Vector.filled(4, 0.0, fx.Float32) + cu_ = fx.Vector.filled(4, 0.0, fx.Float32) + # every chunk's B scale up front: read at use, each MFMA waited out an LDS + # latency (S = 4 up / gate 3.5 us over the unscaled floor) + sbs = [ + lds_i32(XSC_LDS + col * XSC_ROW + (wave * UG_CPW + i) * 4 + g4) + for i in range(UG_CPW) + ] + for i in range_constexpr(UG_CPW): + kc = wave * UG_CPW + i + xb = lds_b8(col * XN8_ROW + kc * 32) + cg_ = mfma_f4f8(wts[0][i], scs[0][i], xb, sbs[i], cg_) + cu_ = mfma_f4f8(wts[1][i], scs[1][i], xb, sbs[i], cu_) + stamp(9) + # gate partials in red, up partials in opart (free once the split is done) + fx.ptr_store(cg_, red + (wave * 64 + lane) * 4) + fx.ptr_store(cu_, opart + (wave * 64 + lane) * 4) + gpu.barrier() + # row tid % 16; a shared task's thread tid reads token tid / 16's column + if tid < shared.select(fx.Int32(UG_ROWS * tokens), fx.Int32(UG_ROWS)): + r = tid % UG_ROWS + col = tid // UG_ROWS + kk = shared.select(col, tk) + gsum = fx.Float32(0.0) + usum = fx.Float32(0.0) + for w in range_constexpr(WAVES): + gsum = gsum + fx.ptr_load( + red + ((w * 64 + 16 * (r // 4) + col) * 4 + r % 4) + ) + usum = usum + fx.ptr_load( + opart + ((w * 64 + 16 * (r // 4) + col) * 4 + r % 4) + ) + y = swiglu_mul_batch([gsum], [usum], fx.Float32(-swiglu_limit))[0] + mb_put( + mb("mid"), + (kk * MOE_SLOTS + slot) * INTER + cg * UG_ROWS + r, + bf16_round(y), + ) + gpu.barrier() + + def sh_load(j, has=None): + """The shared expert's half task j: gate rows 8 j .. + 8 on lanes l16 < 8, + the up rows alike on the rest -- one MFMA tile; the waves split k.""" + row = (l16 < 8).select(SH_ROWS * j + l16, INTER + SH_ROWS * j + l16 - 8) + rg = row // 16 + if const_expr(shared_fp8): + w_base, s_base = sh_ptr(SH_W13), sh_ptr(SH_S13) + w_bytes, s_bytes, e_rows = SH8_W13_BYTES, SH8_S13_BYTES, 0 + else: + w_base, s_base = w13 + fx.Int64(SHARED_EXPERT) * W13_BYTES, s13 + w_bytes, s_bytes = W13_BYTES, S13_BYTES + e_rows = SHARED_EXPERT * W13_ROWS + if const_expr(has is None): + r_w = rsrc(w_base) + r_s = rsrc(s_base) + else: # a CTA without the task reads through zero-sized buffers + r_w = rsrc(w_base, has.select(fx.Int32(w_bytes), fx.Int32(0))) + r_s = rsrc(s_base, has.select(fx.Int32(s_bytes), fx.Int32(0))) + wts = [] + scs = [] + # Row offset; each chunk adds 256 * (kc // 2) + 2 * (kc % 2). + sc_row = scale_index(e_rows + row, g4, W13_SCALE_COLS) + for i in range_constexpr(UG_CPW): + kc = wave * UG_CPW + i + wts.append(w_tile(r_w, rg, kc, g4 * 16 + row % 16, HIDDEN, shared_fp8)) + scs.append(e8m0_load(r_s, sc_row + kc // 2 * 256 + kc % 2 * 2)) + return wts, scs + + def sh_compute(j, wts, scs): + """Half task j's GEMV (B column l % 16 = token l % 16) -> swiglu -> the + shared slot's mid rows 8 j .. + 8 of every token.""" + col = fx.min(l16, tokens - 1) + c = fx.Vector.filled(4, 0.0, fx.Float32) + sbs = [ + lds_i32(XSC_LDS + col * XSC_ROW + (wave * UG_CPW + i) * 4 + g4) + for i in range(UG_CPW) + ] + for i in range_constexpr(UG_CPW): + kc = wave * UG_CPW + i + c = mfma_sh(wts[i], scs[i], lds_b8(col * XN8_ROW + kc * 32), sbs[i], c) + fx.ptr_store(c, red + (wave * 64 + lane) * 4) + gpu.barrier() + # mid row r = tid % 8 of token tid / 8: gate in tile row r, up in r + 8 + if tid < SH_ROWS * tokens: + r = tid % SH_ROWS + col = tid // SH_ROWS + gsum = fx.Float32(0.0) + usum = fx.Float32(0.0) + for w in range_constexpr(WAVES): + gsum = gsum + fx.ptr_load( + red + ((w * 64 + 16 * (r // 4) + col) * 4 + r % 4) + ) + usum = usum + fx.ptr_load( + red + ((w * 64 + 16 * (r // 4 + 2) + col) * 4 + r % 4) + ) + y = swiglu_mul_batch([gsum], [usum], fx.Float32(-swiglu_limit))[0] + mb_put( + mb("mid"), + (col * MOE_SLOTS + TOP_K) * INTER + j * SH_ROWS + r, + bf16_round(y), + ) + gpu.barrier() + + def down_load(k, td, has_dn): + """Token k's route-weighted down units of row group td; a CTA without a + down task reads through zero-sized buffers.""" + dn_bytes = has_dn.select(fx.Int32(W2_BYTES), fx.Int32(0)) + dn_scale_bytes = has_dn.select(fx.Int32(S2_BYTES), fx.Int32(0)) + rg_d = td * 2 + wave // 4 + units = [] + for i in range_constexpr(DN_UPW): + j = (wave % 4) + 4 * i + jj = fx.min(j, DN_UNITS - 1) + sl = jj // DN_KC + kc = jj % DN_KC + e_d = fx.min(uniform(fx.ptr_load(route + (8 * k + sl))), E_TOP) + wv = fx.Vector( + bo.buffer_load( + rsrc(w2 + fx.Int64(e_d) * W2_BYTES, dn_bytes), + ((rg_d * (INTER // 64) + kc * 2) * 512 + lane * 16) // 4, + vec_width=4, + dtype=T.i32, + ) + ) + sc = e8m0_load( + rsrc(s2, dn_scale_bytes), + group_scale_byte(e_d, HIDDEN, rg_d, kc, W2_SCALE_COLS), + ) + wgt = (j < DN_UNITS).select( + fx.ptr_load(rwt + (8 * k + sl)), fx.Float32(0.0) + ) + units.append((wv, sc, sl, kc, wgt)) + return units + + def down_load_shared(td, has_dn): + """The shared expert's down units of row group td (every token's).""" + rg_d = td * 2 + wave // 4 + if const_expr(shared_fp8): + w_base, s_base, w_bytes, s_bytes = ( + sh_ptr(SH_W2), sh_ptr(SH_S2), SH8_W2_BYTES, SH8_S2_BYTES, + ) # fmt: skip + e = 0 + else: + w_base, s_base, w_bytes, s_bytes = ( + w2 + fx.Int64(SHARED_EXPERT) * W2_BYTES, s2, W2_BYTES, S2_BYTES, + ) # fmt: skip + e = SHARED_EXPERT + r_w = rsrc(w_base, has_dn.select(fx.Int32(w_bytes), fx.Int32(0))) + r_s = rsrc(s_base, has_dn.select(fx.Int32(s_bytes), fx.Int32(0))) + units = [] + for i in range_constexpr(SH_UPW): + j = (wave % 4) + 4 * i + kc = fx.min(j, DN_KC - 1) + wv = w_tile(r_w, rg_d, kc, lane, INTER, shared_fp8) + sc = e8m0_load( + r_s, group_scale_byte(e, HIDDEN, rg_d, kc, W2_SCALE_COLS) + ) + wgt = (j < DN_KC).select(fx.Float32(shared_weight), fx.Float32(0.0)) + units.append((wv, sc, kc, wgt)) + return units + + def ffn_finish(t): + """Misc (row group t's bf16 partial rows, token k's DN_ROWS from k DN_ROWS) + -> every peer -> rank-ordered sum -> ar_out.""" + # every token's rows: reduce threads take token tid // 16, pair tid % 16 + row_tok = tid // (DN_ROWS // 2) + row_pair = tid % (DN_ROWS // 2) + if const_expr(W > 1): # push bf16 partial rows: wave w -> peer w + # (with AG_RS to the row group's owner rank only) + push_rows("ffn", t * DN_ROWS, DN_ROWS, t % W if AG_RS else None) + gpu.barrier() + if tid < DN_ROWS // 2 * tokens: + row = t * DN_ROWS + row_pair * 2 + if const_expr(W == 1): + t0 = fx.ptr_load(misc + tid * 2) + t1 = fx.ptr_load(misc + (tid * 2 + 1)) + else: + own = sym + fx.Int64(SY["ffn"]) + + def rank_sum(): + parts = mb_poll( + [ + ( + own, + ((src * MAX_TOKENS + row_tok) * HIDDEN + row) // 2, + 1, + ) + for src in range(W) + ], + "system", + ) + s0 = fx.Float32(0.0) + s1 = fx.Float32(0.0) + for src in range_constexpr(W): + f0, f1 = bf2_f32(parts[src][0]) + s0 = s0 + f0 + s1 = s1 + f1 + return s0, s1 + + if const_expr(AG_RS): + t0 = fx.Float32(0.0) + t1 = fx.Float32(0.0) + if t % W == rank: # the owner: sum, gather to every rank + t0, t1 = rank_sum() + for w in range_constexpr(W): + mb_put_bf( + peer_addr(w) + fx.Int64(SY["ffn_ag"]), + row_tok * HIDDEN + row, + [t0, t1], + CM_SYS, + ) + else: # the owner's sums (bf16, as ar_out stores them) + got = mb_poll( + [ + ( + sym + fx.Int64(SY["ffn_ag"]), + (row_tok * HIDDEN + row) // 2, + 1, + ) + ], + "system", + ) + t0, t1 = bf2_f32(got[0][0]) + else: + t0, t1 = rank_sum() + bo.buffer_store( + fx.Vector.from_elements([t0, t1], fx.Float32).to(fx.BFloat16), + rsrc(ar_out), + row_tok * HIDDEN + row, + ) + + # ======================================== 5w. experts, wide (S > 4) + # LDS pool words: MXFP8 xn, its scales, the up partials, router sigmoids; the + # down stage reuses the pool for MXFP8 mid rows (token k's slot s at row + # k MOE_SLOTS + s, a zero row last) and their scales + W_UPP = tokens * (XN8_ROW + XSC_ROW) + W_SIG = W_UPP + WAVES * 64 * 4 + MID_ROWS = MOE_SLOTS * tokens # the zero row's index + MID_ROW_WORDS = INTER // 4 + MIDSC_ROW_WORDS = INTER // 32 + W_MIDSC = (MID_ROWS + 1) * MID_ROW + # up / gate tasks go in pairs, a CTA runs both: an MXFP8 block is 32 rows + UG_PAIRS = UG_PER_SLOT // 2 + UGW_ITERS = 2 * ((U_MAX * UG_PAIRS + G - 1) // G) # up / gate tasks a CTA runs + # distinct experts the expert-table loops run (shared_fp8: the shared + # expert's MXFP8 tasks / units follow them, compiled apart) + U_TBL = U_MAX - 1 if shared_fp8 else U_MAX + # an MXFP8 shared task runs as SH_PARTS k parts, a part's weights in flight + # as many as a table task's: the whole task's and the next's were 192 VGPRs + # (256 with spills, and the table's tasks ran slower too) + SH_PARTS = 2 + assert UG_CPW % SH_PARTS == 0 + + def sh_ks(part): + n = UG_CPW // SH_PARTS + return tuple(range(part * n, (part + 1) * n)) + + DN_WITERS = (U_TBL * DN_KC + 3) // 4 # (expert, chunk) units a wave runs + DN_DEPTH = 12 # units whose weights are in flight + ROUTE_ITERS = (tokens + WAVES - 1) // WAVES # tokens a wave routes + + def popc64(x): + return fx.Int32(fx.ctpop(x)) + + def slot_of(k, e): + """Token k's slot routed to expert e (TOP_K: the shared expert).""" + s = fx.Int32(TOP_K) + for j in range_constexpr(TOP_K): + s = (fx.Int32(fx.ptr_load(route + (8 * k + j))) == e).select( + fx.Int32(j), s + ) + return s + + def build_experts(): + """Uexp / umask[0 .. n_u) := the tokens' distinct routed experts in + expert order and their token masks, [n_u] := the shared expert (every + token), uexp[U_MAX + 1] := n_u. The waves' masks must be in (synced).""" + m = fx.Int32(0) + if tid < N_ROUTED: + for w in range_constexpr(WAVES): + m = m | fx.Int32(fx.ptr_load(xs + (W_UPP + w * N_ROUTED + tid))) + bal = ballot(m != 0) + below = popc64(bal & ((fx.Int64(1) << fx.Int64(lane)) - 1)) + if tid == 0: + fx.ptr_store(popc64(bal), umask + (U_MAX + 1)) + gpu.barrier() + if tid < N_ROUTED: + off = (wave == 0).select( + fx.Int32(0), fx.Int32(fx.ptr_load(umask + (U_MAX + 1))) + ) + rank_ = off + below + if m != 0: + fx.ptr_store(fx.Int32(tid), uexp + rank_) + fx.ptr_store(m, umask + rank_) + if tid == N_ROUTED - 1: + nu_ = off + popc64(bal) + fx.ptr_store(nu_, uexp + (U_MAX + 1)) + fx.ptr_store(fx.Int32(SHARED_EXPERT), uexp + nu_) + fx.ptr_store(fx.Int32((1 << tokens) - 1), umask + nu_) + gpu.barrier() + + UG_KS = tuple(range(UG_CPW)) + + def wug_load(t, has, scales=True, fp8=False, ks=UG_KS): + """Up / gate weights (this wave's 128-k chunks ``ks``; and ``scales``: + the scale dwords, which hold the pair's both halves) of task t = + (distinct expert t / UG_PER_SLOT, row group t % UG_PER_SLOT); without + the task, reads go through zero-sized buffers. ``fp8``: the MXFP8 + shared expert's task (weights.mxfp8_a_tiles; the scales -- every + chunk's -- in the routed tables' order).""" + u = t // UG_PER_SLOT + cg = t % UG_PER_SLOT + if const_expr(fp8): + e_u = 0 + r_w = rsrc( + sh_ptr(SH_W13), has.select(fx.Int32(SH8_W13_BYTES), fx.Int32(0)) + ) + r_s = rsrc( + sh_ptr(SH_S13), has.select(fx.Int32(SH8_S13_BYTES), fx.Int32(0)) + ) + else: + e_u = fx.min(uniform(fx.ptr_load(uexp + u)), E_TOP) + r_w = rsrc( + w13 + fx.Int64(e_u) * W13_BYTES, + has.select(fx.Int32(W13_BYTES), fx.Int32(0)), + ) + r_s = rsrc(s13, has.select(fx.Int32(S13_BYTES), fx.Int32(0))) + wts: list[list] = [] + scs: list[list] = [] + for gu in range_constexpr(2): + rg = gu * UG_PER_SLOT + cg + wts.append([]) + scs.append([]) + for i in range_constexpr(UG_CPW): + kc = wave * UG_CPW + i + if const_expr(i in ks): + wts[gu].append(w_tile(r_w, rg, kc, lane, HIDDEN, fp8)) + if const_expr(scales and i % 2 == 0): + # the dword holding this lane's scales of chunks kc, kc + 1 + # of both 16-row halves of the 32-row block (bytes 2 d + a) + scs[gu].append( + fx.Int32( + bo.buffer_load( + r_s, + group_scale_byte( + e_u, W13_ROWS, rg, kc, W13_SCALE_COLS + ) + // 4, + vec_width=1, + dtype=T.i32, + ) + ) + ) + return wts, scs + + def wug_acc(wts, scs, half, cg_, cu_, ks=UG_KS, fp8=False): + """A task's up / gate MFMAs over its 128-k chunks ``ks`` of this wave + (wts[gu][j]: chunk ks[j]) for every token (B column l % 16 = token + l % 16), into (cg_, cu_). ``half``: the task's 16-row half of its + 32-row scale block (compile time); ``fp8``: an MXFP8 task + (``wug_load(fp8=True)``).""" + mfma_ = mfma_f8f8 if fp8 else mfma_f4f8 + col = fx.min(l16, tokens - 1) + sbs = [ + lds_i32(XSC_LDS + col * XSC_ROW + (wave * UG_CPW + i) * 4 + g4) + for i in ks + ] + for j in range_constexpr(len(ks)): + i = ks[j] + kc = wave * UG_CPW + i + xb = lds_b8(col * XN8_ROW + kc * 32) + sel = (i % 2) * 2 + half + cg_ = mfma_(wts[0][j], scs[0][i // 2], xb, sbs[j], cg_, sel) + cu_ = mfma_(wts[1][j], scs[1][i // 2], xb, sbs[j], cu_, sel) + return cg_, cu_ + + def wug_y(wts, scs, half): + """A task's up / gate GEMV (``wug_acc``) -> swiglu: thread (row r, + token k)'s mid value.""" + zero = fx.Vector.filled(4, 0.0, fx.Float32) + return wug_swiglu(*wug_acc(wts, scs, half, zero, zero)) + + def wug_swiglu(cg_, cu_): + """The waves' up / gate partials -> swiglu (``wug_y``).""" + fx.ptr_store(cg_, red + (wave * 64 + lane) * 4) + fx.ptr_store(cu_, fpool + (W_UPP + (wave * 64 + lane) * 4)) + gpu.barrier() + r = tid % UG_ROWS + k = fx.min(tid // UG_ROWS, tokens - 1) + gsum = fx.Float32(0.0) + usum = fx.Float32(0.0) + for w in range_constexpr(WAVES): + gsum = gsum + fx.ptr_load( + red + ((w * 64 + 16 * (r // 4) + k) * 4 + r % 4) + ) + usum = usum + fx.ptr_load( + fpool + (W_UPP + (w * 64 + 16 * (r // 4) + k) * 4 + r % 4) + ) + gpu.barrier() # red and the up partials are free for the next task + return swiglu_mul_batch([gsum], [usum], fx.Float32(-swiglu_limit))[0] + + def fp8_lanes4(q): + """Lane r (r % 4 == 0): the E4M3 dword of lanes r .. r + 3's values.""" + lo = fx.Int32( + rocdl.cvt_pk_fp8_f32(T.i32, q, xshfl(q, 1), fx.Int32(0), False) + ) + return lo | (xshfl(lo, 2) << 16) + + def wug_publish(pr, y_lo, y_hi): + """Task pair pr = (distinct expert pr / UG_PAIRS, 32-row block + pr % UG_PAIRS): its mid rows (thread (r, k) holds rows r and 16 + r of + the block) as the down stage's MXFP8 -- the rounding its bf16 staging + did, one 32-block a 16-lane group -- then the pair's flag.""" + u = pr // UG_PAIRS + blk_ = pr % UG_PAIRS + r = tid % UG_ROWS + k = fx.min(tid // UG_ROWS, tokens - 1) + lo = bf16_round(y_lo) + hi = bf16_round(y_hi) + sc, inv = mx8_scale([lo, hi], (1, 2, 4, 8)) + words = [fp8_lanes4(mx8_q(v, inv)) for v in (lo, hi)] + e_u = fx.Int32(fx.ptr_load(uexp + u)) + m_u = fx.Int32(fx.ptr_load(umask + u)) + row = k * MOE_SLOTS + slot_of(k, e_u) + if (tid < UG_ROWS * tokens) & (((m_u >> k) & 1) != 0): + if r % 4 == 0: + for h in range_constexpr(2): + bo.buffer_store( + words[h], + rsrc(mb("mid8p")), + row * MID_ROW_WORDS + blk_ * 8 + h * 4 + r // 4, + cache_modifier=CM_DEV, + ) + if r == 0: + bo.buffer_store( + sc, + rsrc(mb("midsp")), + row * MIDSC_ROW_WORDS + blk_, + cache_modifier=CM_DEV, + ) + fx.memory_fence( + syncscope=rocdl.SyncScope.Workgroup, ordering=fx.AtomicOrdering.Release + ) + gpu.barrier() + if tid == 0: + mb_put(mb("ugdone"), pr, fx.Int32(1)) + + def down_tables(): + """Urow / uwt := per (distinct expert, B column) the down stage's mid row + (the zero row where the column's token is not routed there) and route + weight. Routing only: built while the first up / gate weights land.""" + nu = uniform(fx.ptr_load(uexp + (U_MAX + 1))) + for i in range_constexpr((U_MAX * 16 + THREADS - 1) // THREADS): + ix = tid + THREADS * i + if ix < U_MAX * 16: + xu = ix // 16 + xk = ix % 16 + xe = fx.Int32(fx.ptr_load(uexp + fx.min(xu, nu))) + xm = fx.Int32(fx.ptr_load(umask + fx.min(xu, nu))) + xt = fx.min(xk, tokens - 1) + xs_ = slot_of(xt, xe) + xh = (((xm >> xk) & 1) != 0) & (xu <= nu) + fx.ptr_store( + xh.select(xt * MOE_SLOTS + xs_, fx.Int32(MID_ROWS)), urow + ix + ) + fx.ptr_store( + xh.select(fx.ptr_load(rwt + (8 * xt + xs_)), fx.Float32(0.0)), + uwt + ix, + ) + + def stage_moe_wide(): + td = start("down") # this CTA's down task (the split tasks come first) + has_dn = td < N_DN + td = fx.min(td, N_DN - 1) + # every token's routing: wave w routes tokens w, w + WAVES, .., their + # scores polled in one batch + mine = bid % SCORE_COPIES + # wave w's expert -> mask of the tokens it routed there, in the up + # partials' words (free until the first up / gate task) + wave_mask = xs + (W_UPP + wave * N_ROUTED) + fx.ptr_store(fx.Int32(0), wave_mask + lane) + fx.ptr_store(fx.Int32(0), wave_mask + (lane + 64)) + wave_toks = [ + fx.min(wave + WAVES * j, tokens - 1) for j in range(ROUTE_ITERS) + ] + sg = mb_poll( + [ + (scores_copy(mine, k), (lane + 64 * h) * 2, 2) + for k in wave_toks + for h in range(2) + ] + ) + for j in range_constexpr(ROUTE_ITERS): + if wave + WAVES * j < tokens: + route_top4( + wave_toks[j], + sg[2 * j][0], + sg[2 * j][1].bitcast(fx.Float32), + sg[2 * j + 1][0], + sg[2 * j + 1][1].bitcast(fx.Float32), + fpool + W_SIG, + wave_mask, + ) + stamp(2) + gpu.barrier() + build_experts() + stamp(6) + if (bid == BASE["down"]) & (tid < MOE_SLOTS * tokens): + sk = tid // MOE_SLOTS + sj = tid % MOE_SLOTS + mb_put( + mb("sel"), + sk * 2 * MOE_SLOTS + sj, + fx.ptr_load(route + (8 * sk + sj)), + ) + mb_put( + mb("sel"), + sk * 2 * MOE_SLOTS + MOE_SLOTS + sj, + fx.ptr_load(rwt + (8 * sk + sj)), + ) + nu_ug = uniform(fx.ptr_load(uexp + (U_MAX + 1))) + n_pairs = (nu_ug if shared_fp8 else nu_ug + 1) * UG_PAIRS + # shared_fp8: shared pair j runs after the table's pairs on CTA + # (sh0 + j) % G. It costs two of theirs: from a full round of pairs on, + # the table's skip slots hole0 .. hole0 + UG_PAIRS - 1 (slot s: CTA s % + # G's (s / G)-th pair), the shared CTAs' last full round, so that those + # carry one pair fewer (otherwise the up / gate stage ran a pair longer + # than the fused build's at every S; S = 8: 25.8 -> 31.6 us slowest CTA) + sh0 = n_pairs + if const_expr(shared_fp8): + hole0 = n_pairs + (UG_PAIRS - G) + holes = hole0 >= 0 + sh0 = n_pairs + holes.select(fx.Int32(UG_PAIRS), fx.Int32(0)) + sh_j = (bid + (G - sh0 % G)) % G + has_shp = sh_j < UG_PAIRS + sh_pr = n_pairs + fx.min(sh_j, UG_PAIRS - 1) + UG_ALL = UGW_ITERS + (2 * SH_PARTS if shared_fp8 else 0) + + def task(it): + """Iteration it's task: slot bid + (it / 2) G's pair, half it % 2 + (past UGW_ITERS: the shared pair's, half (it - UGW_ITERS) / SH_PARTS + a k part an iteration).""" + if const_expr(it >= UGW_ITERS): + return sh_pr * 2 + (it - UGW_ITERS) // SH_PARTS, has_shp + pr = fx.Int32(bid + it // 2 * G) + if const_expr(shared_fp8): + # a hole runs nothing (pair n_pairs); past them, UG_PAIRS lower + pr = (holes & (pr >= hole0)).select( + (pr < hole0 + UG_PAIRS).select(n_pairs, pr - UG_PAIRS), pr + ) + return fx.min(pr, n_pairs - 1) * 2 + it % 2, pr < n_pairs + + def task_load(it, t, has, scales=True): + if const_expr(it >= UGW_ITERS): + # the shared pair's scales come with its first part + q = it - UGW_ITERS + return wug_load( + t, has, scales=q == 0, fp8=True, ks=sh_ks(q % SH_PARTS) + ) + return wug_load(t, has, scales) + + t0, h0 = task(0) + cur = task_load(0, t0, h0) # task 0: a lo half, with the pair's scales + down_tables() + stamp(7) + # the first task's weights are in flight: now the xn + # every token's MXFP8 xn and scales -> the pool, once every router task + # flagged its slice (plain words, 16 B a load) + n_rt = N_ROUTER * tokens + if wave == 0: + mb_poll( + [ + (mb("xndone"), fx.min(lane + 64 * c, n_rt - 1), 1) + for c in range((n_rt + 63) // 64) + ] + ) + gpu.barrier() + acquire() + for base_w, n_row, lds_w, lds_row in ( + (mb("xn8p"), XN8_WORDS, 0, XN8_ROW), + (mb("xscp"), XSC_WORDS, XSC_LDS, XSC_ROW), + ): + n_v = tokens * n_row // 4 + for i in range_constexpr((n_v + THREADS - 1) // THREADS): + v = tid + THREADS * i + if v < n_v: + fx.ptr_store( + fx.Vector( + bo.buffer_load( + rsrc(base_w), + v * 4, + vec_width=4, + dtype=T.i32, + cache_modifier=CM_DEV, + ) + ), + xs + (lds_w + v * 4 // n_row * lds_row + v * 4 % n_row), + ) + gpu.barrier() + y_lo = fx.Float32(0.0) # the pair's first half, until the second's + if const_expr(shared_fp8): + # a shared half's up / gate accumulators, part to part + sh_cg = fx.Vector.filled(4, 0.0, fx.Float32) + sh_cu = fx.Vector.filled(4, 0.0, fx.Float32) + for it in range_constexpr(UG_ALL): + t, has_t = task(it) + if const_expr(it + 1 < UG_ALL): + tn, hn = task(it + 1) + # a hi half reads no scales: its lo half's dwords hold them + nxt = task_load(it + 1, tn, hn, scales=(it + 1) % 2 == 0) + if const_expr(it < UGW_ITERS): + if const_expr(it % 2 == 0): + pair_scs = cur[1] + if has_t: + # a pair: row groups cg, cg + 1 + y = wug_y(cur[0], pair_scs, it % 2) + if const_expr(it % 2 == 0): + y_lo = y + else: + wug_publish(t // 2, y_lo, y) + else: + half, part = divmod(it - UGW_ITERS, SH_PARTS) + if const_expr(half == 0 and part == 0): + pair_scs = cur[1] + if has_t: + if const_expr(part == 0): + sh_cg = fx.Vector.filled(4, 0.0, fx.Float32) + sh_cu = fx.Vector.filled(4, 0.0, fx.Float32) + sh_cg, sh_cu = wug_acc( + cur[0], pair_scs, half, sh_cg, sh_cu, sh_ks(part), fp8=True + ) + if const_expr(part == SH_PARTS - 1): + y = wug_swiglu(sh_cg, sh_cu) + if const_expr(half == 0): + y_lo = y + else: + wug_publish(t // 2, y_lo, y) + if const_expr(it + 1 < UG_ALL): + cur = nxt + stamp(8) + if has_dn: + wide_down(td) + stamp(11) + + def wide_down(td): + """Row group td's down GEMV over every distinct expert (B column l % 16 = + token l % 16's mid for it, the zero row where the token is not routed + there), route-weighted per column -> ffn_finish.""" + nu = uniform(fx.ptr_load(uexp + (U_MAX + 1))) + rg_d = td * 2 + wave // 4 + n_units = (nu if shared_fp8 else nu + 1) * DN_KC + + def unit_load(i): + """(weights, scale, unit) of this wave's i-th (expert, 128-k chunk) + unit, zero-sized reads past the last.""" + j = wave % 4 + 4 * i + ok = j < n_units + # clamped into the table: a unit past the last reads a real or zero + # row, never past urow (a garbage row is garbage B, and 0 * NaN) + du = fx.min(j // DN_KC, U_MAX - 1) + dkc = j % DN_KC + de = fx.min(uniform(fx.ptr_load(uexp + du)), E_TOP) + dwv = fx.Vector( + bo.buffer_load( + rsrc( + w2 + fx.Int64(de) * W2_BYTES, + ok.select(fx.Int32(W2_BYTES), fx.Int32(0)), + ), + ((rg_d * (INTER // 64) + dkc * 2) * 512 + lane * 16) // 4, + vec_width=4, + dtype=T.i32, + ) + ) + dsc = e8m0_load( + rsrc(s2, ok.select(fx.Int32(S2_BYTES), fx.Int32(0))), + group_scale_byte(de, HIDDEN, rg_d, dkc, W2_SCALE_COLS), + ) + return dwv, dsc, du, dkc, ok + + def with_rows(u): + """A loaded unit plus its B row and route weight (the tables are in), + read ahead so the unit's B loads wait on one LDS trip.""" + dwv, dsc, du, dkc, ok = u + drow = fx.Int32(fx.ptr_load(urow + (du * 16 + l16))) + dw = ok.select(fx.ptr_load(uwt + (du * 16 + l16)), fx.Float32(0.0)) + return dwv, dsc, drow, dkc, dw, ok + + # software pipeline: the first units' weights go out before the mids are + # in; unit i + DN_DEPTH's before unit i's MFMA + acc = [fx.Float32(0.0) for _ in range(4)] + if const_expr(shared_fp8): + # the MXFP8 shared expert's units (wave % 4 + 4 i): no routing needed, + # their weights go out first + r_shared_w = rsrc(sh_ptr(SH_W2)) + r_shared_s = rsrc(sh_ptr(SH_S2)) + sh_dn = [] + for i in range_constexpr(SH_UPW): + skc = fx.min(wave % 4 + 4 * i, DN_KC - 1) + sh_dn.append( + ( + f8_tile_load(r_shared_w, rg_d * (INTER // 128) + skc, lane), + e8m0_load( + r_shared_s, + group_scale_byte(0, HIDDEN, rg_d, skc, W2_SCALE_COLS), + ), + skc, + wave % 4 + 4 * i < DN_KC, + ) + ) + inflight = [unit_load(i) for i in range(min(DN_DEPTH, DN_WITERS))] + # every up / gate task pair's flag, then the MXFP8 mid rows and their + # scales, the pool's layout (plain words, 16 B a load) + n_ug = (nu + 1) * UG_PAIRS + mb_poll( + [ + (mb("ugdone"), fx.min(tid + THREADS * i, n_ug - 1), 1) + for i in range((U_MAX * UG_PAIRS + THREADS - 1) // THREADS) + ] + ) + gpu.barrier() + acquire() + for base_w, n_row, lds_w, lds_row in ( + (mb("mid8p"), MID_ROW_WORDS, 0, MID_ROW), + (mb("midsp"), MIDSC_ROW_WORDS, W_MIDSC, MIDSC_ROW), + ): + n_v = MID_ROWS * n_row // 4 + for i in range_constexpr((n_v + THREADS - 1) // THREADS): + v = tid + THREADS * i + if v < n_v: + fx.ptr_store( + fx.Vector( + bo.buffer_load( + rsrc(base_w), + v * 4, + vec_width=4, + dtype=T.i32, + cache_modifier=CM_DEV, + ) + ), + xs + (lds_w + v * 4 // n_row * lds_row + v * 4 % n_row), + ) + if tid < MID_ROW_WORDS: + fx.ptr_store(fx.Int32(0), xs + (MID_ROWS * MID_ROW + tid)) + if tid < MIDSC_ROW_WORDS: + fx.ptr_store(fx.Int32(0), xs + (W_MIDSC + MID_ROWS * MIDSC_ROW + tid)) + gpu.barrier() + stamp(10) + for i in range_constexpr(DN_WITERS): + if const_expr(i == 0): # the tables are in: the early units' rows + inflight = [with_rows(u) for u in inflight] + dwv, dsc, drow, dkc, dw, ok = inflight.pop(0) + if const_expr(i + DN_DEPTH < DN_WITERS): + inflight.append(with_rows(unit_load(i + DN_DEPTH))) + dcu = mfma_f4f8( + dwv, + dsc, + lds_b8(drow * MID_ROW + dkc * 32), + lds_i32(W_MIDSC + drow * MIDSC_ROW + dkc * 4 + g4), + fx.Vector.filled(4, 0.0, fx.Float32), + ) + # a unit past the last adds nothing, whatever its MFMA gave + acc = [ + acc[e] + ok.select(dcu[e] * dw, fx.Float32(0.0)) for e in range(4) + ] + if const_expr(shared_fp8): + # the shared expert's B column l16: its mid row (slot TOP_K) and weight + srow = fx.Int32(fx.ptr_load(urow + (nu * 16 + l16))) + sw = fx.ptr_load(uwt + (nu * 16 + l16)) + for swv, ssc, skc, sok in sh_dn: + dcu = mfma_f8f8( + swv, + ssc, + lds_b8(srow * MID_ROW + skc * 32), + lds_i32(W_MIDSC + srow * MIDSC_ROW + skc * 4 + g4), + fx.Vector.filled(4, 0.0, fx.Float32), + ) + acc = [ + acc[e] + sok.select(dcu[e] * sw, fx.Float32(0.0)) + for e in range(4) + ] + a0, a1, a2, a3 = acc + fx.ptr_store( + fx.Vector.from_elements([a0, a1, a2, a3], fx.Float32), + red + (wave * 64 + lane) * 4, + ) + gpu.barrier() + if tid < DN_ROWS * tokens: + k = tid // DN_ROWS + grp = (tid % DN_ROWS) // 16 + rr = tid % 16 + tot = fx.Float32(0.0) + for w in range_constexpr(4): + tot = tot + fx.ptr_load( + red + (((grp * 4 + w) * 64 + 16 * (rr // 4) + k) * 4 + rr % 4) + ) + fx.ptr_store(bf16_round(tot), misc + tid) + gpu.barrier() + ffn_finish(td) + + def stage_moe(): + td = bid - BASE["down"] # this CTA's down task + has_dn = (td >= 0) & (td < N_DN) + td = fx.min(fx.max(td, 0), N_DN - 1) + has_sh = start("shared") < SH_TASKS + n_xw = XN8_WORDS // THREADS + + def xn_specs(k): + return [ + (mb("xn8"), k * XN8_WORDS + tid + i * THREADS, 1) + for i in range(n_xw) + ] + [(mb("xsc"), k * XSC_WORDS + fx.min(tid, XSC_WORDS - 1), 1)] + + def stage_xn(k, got): + for i in range_constexpr(n_xw): + fx.ptr_store(got[i][0], xs + (k * XN8_ROW + tid + i * THREADS)) + if tid < XSC_WORDS: + fx.ptr_store(got[n_xw][0], xs + (XSC_LDS + k * XSC_ROW + tid)) + + def fetch_xn(tok=None): + """Token tok's (default: every token's) MXFP8 xn and scales -> xs. Wave + 0 first polls the last word of each router task's slice: all 512 + threads of 256 CTAs spinning on the whole of it (S = 4) held the + shared-expert CTAs' xn back 3 us.""" + gate_tok = fx.min(lane // N_ROUTER, tokens - 1) if tok is None else tok + if wave == 0: + mb_poll( + [ + ( + mb("xn8"), + gate_tok * XN8_WORDS + + (lane % N_ROUTER + 1) * (XN_SLICE // 4) + - 1, + 1, + ) + ] + ) + gpu.barrier() + if tok is None: + got = mb_poll([sp for k in range(tokens) for sp in xn_specs(k)]) + for k in range_constexpr(tokens): + stage_xn(k, got[k * (n_xw + 1) : (k + 1) * (n_xw + 1)]) + else: + stage_xn(tok, mb_poll(xn_specs(tok))) + + sh_late = shared_after_routing(tokens) + if const_expr(sh_late): + sh_j = fx.min(start("shared"), SH_TASKS - 1) + sh_w = sh_load(sh_j, has_sh) + if has_sh: + fetch_xn() + elif has_sh: # the shared expert needs xn, not the routing + sh_j0 = start("shared") + sh_w0 = sh_load(sh_j0) + fetch_xn() + gpu.barrier() + sh_compute(sh_j0, sh_w0[0], sh_w0[1]) + if ug_task_id(0)[1] | has_dn: + # xn lands before the logits: stage it while waiting (a shared-expert + # CTA has it already); a CTA's routed tasks are one token's + if start("shared") >= SH_TASKS: + fetch_xn(bid // CPT if CPT is not None else None) + # wave k polls token k's router logits and routes it right away + mine = bid % SCORE_COPIES + for k in range_constexpr(tokens): + if wave == k: + got = mb_poll( + [ + (scores_copy(mine, k), (lane + 64 * h) * 2, 2) + for h in range(2) + ] + ) + stamp(21) + route_top4( + k, + got[0][0], + got[0][1].bitcast(fx.Float32), + got[1][0], + got[1][1].bitcast(fx.Float32), + opart, + ) + stamp(2) + gpu.barrier() + stamp(6) + if (bid == BASE["down"]) & (tid < MOE_SLOTS * tokens): + sk = tid // MOE_SLOTS + sj = tid % MOE_SLOTS + mb_put( + mb("sel"), + sk * 2 * MOE_SLOTS + sj, + fx.ptr_load(route + (8 * sk + sj)), + ) + mb_put( + mb("sel"), + sk * 2 * MOE_SLOTS + MOE_SLOTS + sj, + fx.ptr_load(rwt + (8 * sk + sj)), + ) + cur = ug_load(ug_task_id(0)[0]) + stamp(7) + if const_expr(sh_late): # noqa: SIM102 + if has_sh: # while the first routed task's weights are in flight + sh_compute(sh_j, sh_w[0], sh_w[1]) + # task i + 1's weights go out before task i's GEMV (software pipeline); + # past the last task the load index is clamped and the result dropped + for it in range_constexpr(UG_ITERS): + t, has_t = ug_task_id(it) + if const_expr(it + 1 < UG_ITERS): + nxt = ug_load(ug_task_id(it + 1)[0]) + if has_t: + ug_compute(t, cur[0], cur[1]) + if const_expr(it == 0): + # token 0's down weights stream under the mid exchange; issued + # with the first task's up / gate weights they share the CU's + # bandwidth and delay them (K4 on 4 GPUs 34.3 -> 32.8 us) + dn_units = {0: down_load(0, td, has_dn)} + sh_units = down_load_shared(td, has_dn) + if const_expr(tokens > 1 and it == UG_ITERS - 1): + # two tokens in flight when the down GEMVs start + dn_units[1] = down_load(1, td, has_dn) + if const_expr(it + 1 < UG_ITERS): + cur = nxt + stamp(8) + if has_dn: + moe_down(td, has_dn, dn_units, sh_units) + stamp(11) + + def moe_down(t, has_dn, dn_units, sh_units): + """Every token's route-weighted down GEMV of row group ``t`` -> push bf16 + partial rows -> rank-ordered sum -> ar_out.""" + + def stage_mids(k): + """Token k's mid rows (every slot) -> xs, as bf16 pairs.""" + mids = mb_poll( + [ + ( + mb("mid"), + k * MOE_SLOTS * INTER + + fx.min(tid * 2 + i * 2 * THREADS, MOE_SLOTS * INTER - 2), + 2, + ) + for i in range(4) + ] + ) + for i in range_constexpr(4): + e = tid * 2 + i * 2 * THREADS + if e < MOE_SLOTS * INTER: + fx.ptr_store( + bf16_pair( + mids[i][0].bitcast(fx.Float32), + mids[i][1].bitcast(fx.Float32), + ), + xs + (k * (MOE_SLOTS * INTER // 2) + e // 2), + ) + + # every token's mid in one go: they land together (S = 4: -1.1 us) + for k in range_constexpr(tokens): + stage_mids(k) + stamp(10) + gpu.barrier() + # then MXFP8 in a pass of its own: quantizing inside stage_mids (after + # each poll) cost S = 1 / 4 1.75 / 6 us, though the arithmetic is tiny + for k in range_constexpr(tokens): + if tid < MID8_WORDS // 2: # 8 elements a lane, 4 lanes a 32-block + w = fx.Vector( + fx.ptr_load(xs + (k * MID16_WORDS + tid * 4), result_type=v4f) + ).bitcast(fx.Int32) + f = [v for j in range(4) for v in bf2_f32(w[j])] + sc, inv = mx8_scale(f, (1, 2)) + qv = [mx8_q(v, inv) for v in f] + fx.ptr_store( + fp8_pack4(*qv[:4]), xs + (MID8_LDS + k * MID8_WORDS + tid * 2) + ) + fx.ptr_store( + fp8_pack4(*qv[4:]), + xs + (MID8_LDS + k * MID8_WORDS + tid * 2 + 1), + ) + if tid % 4 == 0: + fx.ptr_store(sc, xs + (MIDSC_LDS + k * MIDSC_WORDS + tid // 4)) + gpu.barrier() + # the shared expert once, B column l % 16 = token l % 16's mid -> opart + # (free once the split is done); each token's reduce adds its column + col_tok = fx.min(l16, tokens - 1) + sh = [fx.Float32(0.0) for _ in range(4)] + for wv, sc, kc, wgt in sh_units: + cu = mfma_sh( + wv, + sc, + lds_b8( + MID8_LDS + + col_tok * MID8_WORDS + + (TOP_K * INTER + kc * 128) // 4 + ), + lds_i32( + MIDSC_LDS + + col_tok * MIDSC_WORDS + + (TOP_K * INTER + kc * 128) // 32 + + g4 + ), + fx.Vector.filled(4, 0.0, fx.Float32), + ) + sh = [sh[j4] + cu[j4] * wgt for j4 in range(4)] + fx.ptr_store( + fx.Vector.from_elements(sh, fx.Float32), opart + (wave * 64 + lane) * 4 + ) + # every token's GEMV first, partials in opart past the shared ones: one + # barrier and one reduce for all tokens, not two barriers per token + for k in range_constexpr(tokens): + # token k + 2's weights go out before token k's GEMV + if const_expr(k + 2 < tokens): + dn_units[k + 2] = down_load(k + 2, t, has_dn) + acc = [fx.Float32(0.0) for _ in range(4)] + for wv, sc, sl, kc, wgt in dn_units.pop(k): + cu = mfma_f4f8( + wv, + sc, + lds_b8( + MID8_LDS + k * MID8_WORDS + (sl * INTER + kc * 128) // 4 + ), + lds_i32( + MIDSC_LDS + + k * MIDSC_WORDS + + (sl * INTER + kc * 128) // 32 + + g4 + ), + fx.Vector.filled(4, 0.0, fx.Float32), + ) + acc = [acc[j4] + cu[j4] * wgt for j4 in range(4)] + fx.ptr_store( + fx.Vector.from_elements(acc, fx.Float32), + opart + ((k + 1) * WAVES * 64 + wave * 64 + lane) * 4, + ) + gpu.barrier() + if tid < DN_ROWS * tokens: + k = tid // DN_ROWS + grp = (tid % DN_ROWS) // 16 + rr = tid % 16 + tot = fx.Float32(0.0) + for w in range_constexpr(4): + tot = tot + fx.ptr_load( + opart + + ( + ((k + 1) * WAVES * 64 + (grp * 4 + w) * 64 + 16 * (rr // 4)) + * 4 + + rr % 4 + ) + ) + for w in range_constexpr(4): + tot = tot + fx.ptr_load( + opart + (((grp * 4 + w) * 64 + 16 * (rr // 4) + k) * 4 + rr % 4) + ) + fx.ptr_store(bf16_round(tot), misc + tid) + gpu.barrier() + ffn_finish(t) + + (stage_moe_wide if WIDE else stage_moe)() + flush_stamps() + + @flyc.jit + def launch_post_attn( + h_in: Int64, + q: Int64, + block_table: Int64, + seq_lens: Int64, + k_cache: Int64, + v_cache: Int64, + k_scale: Int64, + v_scale: Int64, + w_o: Int64, + s_o: Int64, + g_post: Int64, + w_gate: Int64, + bias: Int64, + w13: Int64, + s13: Int64, + w2: Int64, + s2: Int64, + sh_args: Int64, + h_mid: Int64, + ar_out: Int64, + scratch: Int64, + sym: Int64, + peers: Int64, + step: Int64, + rank: Int32, + layer: Int32, + bt_width: Int32, + q_len: Int32, + tl: Int64, + k1_args: Int64, + positions: Int64, + slot_mapping: Int64, + res: Int64, + stream: fx.Stream = _CURRENT_STREAM, + ): + post_attn_kernel( + h_in, + q, + block_table, + seq_lens, + k_cache, + v_cache, + k_scale, + v_scale, + w_o, + s_o, + g_post, + w_gate, + bias, + w13, + s13, + w2, + s2, + sh_args, + h_mid, + ar_out, + scratch, + sym, + peers, + step, + rank, + layer, + bt_width, + q_len, + tl, + k1_args, + positions, + slot_mapping, + res, + ).launch(grid=(G,), block=(THREADS,), stream=stream) + + return launch_post_attn diff --git a/vllm/models/minimax_m3/amd/mono/kernels/pre_attn.py b/vllm/models/minimax_m3/amd/mono/kernels/pre_attn.py new file mode 100644 index 000000000000..b8b9b2133e39 --- /dev/null +++ b/vllm/models/minimax_m3/amd/mono/kernels/pre_attn.py @@ -0,0 +1,902 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +"""K1 ``mono_pre``: one MiniMax-M3 sparse layer, input norm through cache insert. + +One launch per layer and rank, ``BLOCKS`` CTAs x ``THREADS`` threads, for S = +``tokens`` decode rows, ``q_len`` consecutive rows a request (each row below is +per token):: + + acc = ar + res (f32) -> residual out bf16(acc) + -> gemma RMSNorm -> per-token FP8 (amax / FP8_MAX, true divide) + -> qkv | index_q | index_k GEMV on the preshuffled ptpc-FP8 weight + -> per-head gemma norm + partial NeoX RoPE + -> q, index_q out (bf16); K / V -> page-16 SHUFFLE cache with per-token + scales; index_k -> index cache (E4M3, unit scale) + +It reads exactly what the original path leaves in memory (the ``ar`` / ``res`` +pair of the custom all-reduce, the loaded weights, the bound caches) and writes +what the original ``fused_qknorm_idxrqknorm`` writes, so either path can run any +layer. The numerical contracts (reduction orders, where values round to bf16) +follow the aiter kernels the original path uses; see each stage. +""" + +import flydsl.compiler as flyc +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import buffer_ops as bo +from flydsl.expr import const_expr, gpu, range_constexpr, rocdl +from flydsl.expr import math as fmath +from flydsl.expr.typing import Int32, Int64, T + +from vllm.models.minimax_m3.amd.mono import config as mono_config +from vllm.models.minimax_m3.amd.mono.config import ( + BLOCKS, + HEAD_DIM, + HIDDEN, + LOCAL_Q_HEADS, + MAX_QKV_ROWS, + MAX_TOKENS, + ONE_INDEX_HEAD, + PAGE16, + ROTARY_DIM, + THREADS, + TP, + WAVES, + IndexHeads, + qkv_rows, +) +from vllm.models.minimax_m3.amd.mono.kernels.common import ( + CM_DEV, + Mailbox, + ar_block_sums, + ar_pack_sumsq, + bf16_pair, + bf16_round, + butterfly, + div_rn, + fp8_pack4, + hw_rsq, + kernel_symbol, + memrealtime, + rsrc, + traced, + uniform, + wave_max, +) +from vllm.models.minimax_m3.amd.mono.kernels.index_score import ( + emit_index_scores, + index_scale_log2e, + step_rows, +) + +FP8_MAX = 448.0 +ROWS_PER_TASK = 16 +K_CHUNKS = HIDDEN // 64 # 64-k chunks: one dwordx4 of weight per lane +CHUNKS_PER_WAVE = K_CHUNKS // WAVES +Q_OFF, K_OFF, V_OFF = 0, LOCAL_Q_HEADS * HEAD_DIM, (LOCAL_Q_HEADS + 1) * HEAD_DIM +N_HEAD_TASKS = LOCAL_Q_HEADS + 4 # q heads, k, v, the rank's index_q, index_k +IK_TASK = LOCAL_Q_HEADS + 3 +HEAD_ROW_GROUPS = HEAD_DIM // ROWS_PER_TASK # GEMV tasks a head +ELEMS = 4 # per lane in a head task: 32 lanes x 4 = 128, the aiter kernel's split +PAGE_BYTES = PAGE16 * HEAD_DIM # one page-16 of one kv head (fp8) + + +def page16_of(slot): + """Page-16 id of a page-128 slot under the host's K/V block page stride.""" + kps = mono_config.KV_PAGE_STRIDE + if kps == mono_config.SPARSE_BLOCK // PAGE16: + return slot // PAGE16 + blk, t = slot // mono_config.SPARSE_BLOCK, slot % mono_config.SPARSE_BLOCK + return blk * kps + t // PAGE16 + + +# GEMV tasks, head tasks (every token of a head on one CTA) and the tokens' norm +# tasks each own a CTA, in this order; a head CTA's half waves hold the tokens. +# The rank's own rows (q | k | v | its index q | index k) are the first ONE_GEMV +# tasks under indexer context parallelism too, and its other index q heads' the +# OTHER_GEMV after the norm tasks, run only in a step that needs them: the CTA +# layout of a step without long requests is the one-head build's. +ONE_GEMV = qkv_rows(1) // ROWS_PER_TASK +OTHER_GEMV = (TP - 1) * HEAD_ROW_GROUPS +HT0 = ONE_GEMV +NT0 = HT0 + N_HEAD_TASKS +XT0 = NT0 + MAX_TOKENS +assert XT0 + OTHER_GEMV <= BLOCKS +assert MAX_TOKENS * 32 <= THREADS +assert HIDDEN // 4 % THREADS == 0 + +# The launch goes on the caller's current stream (graph capture included). +_CURRENT_STREAM = fx.Stream(None) + +SCRATCH_QKV = 0 # (value, tag) pairs, one per qkv row +SCRATCH_X8 = MAX_TOKENS * MAX_QKV_ROWS * 8 # S > 2: the norm tasks' x8 rows, words +SCRATCH_X8S = SCRATCH_X8 + MAX_TOKENS * HIDDEN // 4 * 8 # and their scales +# fused layer kernel only: a head task's / the residual's done flags +SCRATCH_HDONE = SCRATCH_X8S + MAX_TOKENS * 8 +SCRATCH_RDONE = SCRATCH_HDONE + MAX_TOKENS * N_HEAD_TASKS * 8 +SCRATCH_BYTES = SCRATCH_RDONE + MAX_TOKENS * 8 + + +def _ld_bf16x4(r, k): + w = fx.Vector(bo.buffer_load(r, k // 2, vec_width=2, dtype=T.i32)) + v = w.bitcast(fx.BFloat16).to(fx.Float32) + return [v[j] for j in range(4)] + + +def ld_raw8(r, lt): + """Logical thread lt's 8 bf16 of a row, as loaded (for ``bf16x8_f32``).""" + return fx.Vector(bo.buffer_load(r, lt * 4, vec_width=4, dtype=T.i32)) + + +def bf16x8_f32(raw): + v = raw.bitcast(fx.BFloat16) + return [fx.Float32(v[j]) for j in range(8)] + + +def head_rope_inputs(tk, gamma, d0, cos_sin, positions): + """Token tk's head gamma and cos / sin at dims d0 .. d0 + ELEMS (as f32).""" + # positions are int64: this token's low word + pos = fx.Int32(bo.buffer_load(rsrc(positions), 2 * tk, vec_width=1, dtype=T.i32)) + half = ROTARY_DIM // 2 + ib = (d0 < half).select(d0, d0 - half) + r_cs = rsrc(cos_sin) + return ( + _ld_bf16x4(rsrc(gamma), d0), + _ld_bf16x4(r_cs, pos * ROTARY_DIM + fx.min(ib, half - ELEMS)), + _ld_bf16x4(r_cs, pos * ROTARY_DIM + half + fx.min(ib, half - ELEMS)), + ) + + +def head_norm_rope(e, lane, gw4, cs, sn, eps): + """One head's gemma RMSNorm + partial NeoX RoPE on a half wave, lane l of it + holding dims 4 (l % 32) .. + 4 (the aiter kernel's split and reduction order).""" + d0 = (lane % 32) * ELEMS + half = ROTARY_DIM // 2 + first = d0 < half + ss = fx.Float32(0.0) + for j in range_constexpr(ELEMS): + ss = ss + e[j] * e[j] + ss = butterfly(ss, (16, 8, 4, 2, 1)) + rr = hw_rsq(ss / float(HEAD_DIM) + eps) + n = [e[j] * rr * (gw4[j] + 1.0) for j in range(ELEMS)] + # partial NeoX RoPE over the first ROTARY_DIM dims: the partner is in this half + in_rope = d0 < ROTARY_DIM + partner_lane = first.select(lane + half // ELEMS, lane - half // ELEMS) + out = [] + for j in range_constexpr(ELEMS): + p = fx.Int32( + rocdl.ds_bpermute( + T.i32, + (fx.min(fx.max(partner_lane, 0), 63) * 4).ir_value(), + n[j].bitcast(fx.Int32).ir_value(), + ) + ).bitcast(fx.Float32) + # hipcc contracts ``x*c - p*s`` into fma(x, c, -(p*s)); match it + ps = p * sn[j] + rot = fmath.fma(n[j], cs[j], first.select(-ps, ps)) + out.append(in_rope.select(rot, n[j])) + return out + + +@traced +def emit_pre_attn( + tid, bid, lane, wave, x8, red, mb_put, mb_put_words, mb_poll, qkv_mb, x8_mb, + x8s_mb, stamp, eps, tokens, heads, ptrs, signal=None, long_step=None, +): # fmt: skip + """K1's body: the GEMV tasks (ROWS_PER_TASK of the ``heads`` projection's rows + each: the rank's own on CTAs 0 .. ONE_GEMV, its other index q heads' on CTAs + XT0 .., in a step where ``long_step()``), the head tasks (CTAs HT0 .., a token + per half wave) and, with S > 2, one norm task per token (CTAs NT0 ..) feeding + the GEMV tasks.""" + rows = heads.rows + ( + ar, + res, + h_out, g_in, w_qkv, s_qkv, g_q, g_k, g_iq, g_ik, cos_sin, positions, + slot_mapping, k_cache, v_cache, k_scale, v_scale, index_cache, q_out, iq_out, + ) = ptrs # fmt: skip + + # stores K4 reads in the same launch (signal): device-coherent like the + # mailboxes, so the done flags need no L2 writeback + cm_out = CM_DEV if signal is not None else 0 + + def publish_done(mb_addr, idx, who=None): + """The CTA's stores done, then flag idx of ``mb_addr`` (from thread 0, or + from every thread where ``who``).""" + if const_expr(signal is not None): + fx.memory_fence( + syncscope=rocdl.SyncScope.Workgroup, ordering=fx.AtomicOrdering.Release + ) + gpu.barrier() + if (tid == 0) if who is None else who: + mb_put(mb_addr, idx, fx.Int32(1)) + + # acc = bf16(sum of partials) + residual, f32; the norm reads acc unrounded. + # Elements are laid out as the fused all-reduce's logical threads (8 each): this + # lane holds lt0 and, in lanes < 32, lt1, so rstd reduces in its order. + lts = [wave * 96 + lane, wave * 96 + 64 + fx.min(lane, 31)] + + def load_norm_inputs(toks): + """(gamma, [token][lt] -> (all-reduce, residual)) as loaded.""" + raw_g = [ld_raw8(rsrc(g_in), lt) for lt in lts] + raw_ar = [ + [ + ( + ld_raw8(rsrc(ar), tk * (HIDDEN // 8) + lt), + ld_raw8(rsrc(res), tk * (HIDDEN // 8) + lt), + ) + for lt in lts + ] + for tk in toks + ] + return raw_g, raw_ar + + def norm_quant(toks, raw_g, raw_ar, store_residual): + """Tokens toks: the residual out (where ``store_residual(j)``), gemma RMSNorm + and per-token FP8 into x8 row j (the j-th of toks) -> the x scales.""" + gs = [bf16x8_f32(raw) for raw in raw_g] + accs = [ # [j][lt][8] + [ + [a + r for a, r in zip(bf16x8_f32(ra), bf16x8_f32(rr))] + for ra, rr in raw_ar[j] + ] + for j in range(len(toks)) + ] + for j in range_constexpr(len(toks)): + if store_residual(j): + r_h = rsrc(h_out) + bo.buffer_store( + fx.Vector.from_elements(accs[j][0], fx.Float32).to(fx.BFloat16), + r_h, + toks[j] * HIDDEN + lts[0] * 8, + cache_modifier=cm_out, + ) + if lane < 32: + bo.buffer_store( + fx.Vector.from_elements(accs[j][1], fx.Float32).to(fx.BFloat16), + r_h, + toks[j] * HIDDEN + lts[1] * 8, + cache_modifier=cm_out, + ) + # every token's sum of squares behind one set of barriers + tots = ar_block_sums( + [ + ( + ar_pack_sumsq(accs[j][0]), + (lane < 32).select(ar_pack_sumsq(accs[j][1]), fx.Float32(0.0)), + ) + for j in range(len(toks)) + ], + lane, + wave, + red, + ) + stamp(1) + normed = [] + for j in range_constexpr(len(toks)): + rstd = hw_rsq(tots[j] / float(HIDDEN) + eps) + normed.append( + [ + [accs[j][i][e] * rstd * (gs[i][e] + 1.0) for e in range(8)] + for i in range(2) + ] + ) + for j in range_constexpr(len(toks)): + amax = fx.Float32(0.0) + for e in range_constexpr(8): + amax = fx.max(amax, fmath.absf(normed[j][0][e])) + amax = fx.max( + amax, + (lane < 32).select(fmath.absf(normed[j][1][e]), fx.Float32(0.0)), + ) + w_max = wave_max(amax) + if lane == 0: + fx.ptr_store(w_max, red + (j * WAVES + wave)) + gpu.barrier() + x_scales = [] + for j in range_constexpr(len(toks)): + amax = fx.ptr_load(red + j * WAVES) + for w in range_constexpr(1, WAVES): + amax = fx.max(amax, fx.ptr_load(red + (j * WAVES + w))) + x_scale = (amax == 0.0).select(fx.Float32(1.0), amax / FP8_MAX) + x_scales.append(x_scale) + x_rcp = 1.0 / x_scale + for i in range_constexpr(2): + q = [div_rn(normed[j][i][e], x_scale, x_rcp) for e in range(8)] + w01 = [ + fp8_pack4(q[0], q[1], q[2], q[3]), + fp8_pack4(q[4], q[5], q[6], q[7]), + ] + xo = x8 + (j * (HIDDEN // 4) + lts[i] * 2) + if (i == 0) | (lane < 32): + fx.ptr_store(w01[0].bitcast(fx.Float32), xo) + fx.ptr_store(w01[1].bitcast(fx.Float32), xo + 1) + gpu.barrier() + stamp(2) + return x_scales + + # ============================================ norm tasks (S > 2) + # (S <= 2 the GEMV tasks normalize every token themselves: S = 2 fused layer + # 43.8 -> 43.6 us; S = 4 57.5 -> 59.4 us the other way round) + if const_expr(tokens > 2): # noqa: SIM102 + if (bid >= NT0) & (bid < NT0 + tokens): + tk = bid - NT0 + raw_g, raw_ar = load_norm_inputs([tk]) + x_scale = norm_quant([tk], raw_g, raw_ar, lambda j: True)[0] + if const_expr(signal is not None): + publish_done(signal[1], tk) # the residual + # the x8 row as plain words, then its scale: the scale's pair is the flag + for i in range_constexpr(2): + if (i == 0) | (lane < 32): + bo.buffer_store( + fx.Vector( + fx.ptr_load( + x8 + lts[i] * 2, + result_type=fx.Vector.make_type(2, fx.Int32), + ) + ), + rsrc(x8_mb), + tk * (HIDDEN // 4) + lts[i] * 2, + cache_modifier=CM_DEV, + ) + fx.memory_fence( + syncscope=rocdl.SyncScope.Workgroup, ordering=fx.AtomicOrdering.Release + ) + gpu.barrier() + if tid == 0: + mb_put(x8s_mb, tk, x_scale) + + # ============================================ GEMV tasks (one per CTA) + # CTA bid < ONE_GEMV: row group bid of q | k | v, then the own index q head's + # and index k's (the identity in the one-head build) + own_q = (LOCAL_Q_HEADS + 2) * HEAD_ROW_GROUPS + rg = (bid < own_q).select( + bid, + (bid < own_q + HEAD_ROW_GROUPS).select( + heads.iq_off // ROWS_PER_TASK + bid - own_q, + heads.ik_off // ROWS_PER_TASK + bid - own_q - HEAD_ROW_GROUPS, + ), + ) + gemv = bid < ONE_GEMV + if const_expr(heads.count > 1): + xt = bid - XT0 + if (xt >= 0) & (xt < OTHER_GEMV): + other = xt // HEAD_ROW_GROUPS # the other heads in head order, own skipped + head = other + (other >= heads.own).select(1, 0) + rg = (LOCAL_Q_HEADS + 2 + head) * HEAD_ROW_GROUPS + xt % HEAD_ROW_GROUPS + gemv = long_step() + if gemv: + if const_expr(tokens <= 2): + raw_g, raw_ar = load_norm_inputs(list(range(tokens))) + # weight stream after the norm's inputs: the norm waits on its loads in issue + # order (vmcnt), so it would otherwise wait for the 96 KB of weights too; the + # scheduling barrier keeps the compiler from interleaving them again (nothing + # before it uses a loaded value, so it does not wait either) + rocdl.sched_barrier(0) + r_w = rsrc(w_qkv) + # 64-k chunk kc of row group rg is 1 KB at ((rg*K/32 + 2kc)*512); lane l + # holds row l%16, k = 64kc + 16(l/16) + [0, 16). + wts = [] + for c in range_constexpr(CHUNKS_PER_WAVE): + kc = wave * CHUNKS_PER_WAVE + c + wts.append( + fx.Vector( + bo.buffer_load( + r_w, + ((rg * (HIDDEN // 32) + kc * 2) * 512 + lane * 16) // 4, + vec_width=4, + dtype=T.i32, + ) + ) + ) + ws = fx.Float32( # row tid % 16's scale, sampled below by tid < 16 tokens + bo.buffer_load( + rsrc(s_qkv), + rg * ROWS_PER_TASK + tid % ROWS_PER_TASK, + vec_width=1, + dtype=T.f32, + ) + ) + if const_expr(tokens <= 2): + x_scales = norm_quant( + list(range(tokens)), raw_g, raw_ar, lambda j: bid == j + ) + if const_expr(signal is not None): # noqa: SIM102 + if bid < tokens: + publish_done(signal[1], bid) # the residual + else: + # the norm tasks' scales (each published after its row's plain x8 words), + # then every row, 16 B a load + got = mb_poll([(x8s_mb, tk, 1) for tk in range(tokens)]) + x_scales = [got[tk][0].bitcast(fx.Float32) for tk in range(tokens)] + fx.memory_fence( + syncscope=rocdl.SyncScope.Workgroup, ordering=fx.AtomicOrdering.Acquire + ) + n_v = tokens * HIDDEN // 16 # 16 B loads + for i in range_constexpr((n_v + THREADS - 1) // THREADS): + v = tid + THREADS * i + if v < n_v: + fx.ptr_store( + fx.Vector( + bo.buffer_load( + rsrc(x8_mb), + v * 4, + vec_width=4, + dtype=T.i32, + cache_modifier=CM_DEV, + ) + ), + x8 + v * 4, + ) + gpu.barrier() + stamp(2) + # 12 chunks per wave: two 16x16x32 FP8 MFMAs each (k halves of 8 bytes). + # B column l % 16 is token l % 16 (token 0 past the last): C column t is + # token t's rows, the weight stream is the same for any token count. + col_tok = fx.min(lane % 16, tokens - 1) + c = fx.Vector.filled(4, 0.0, fx.Float32) + for cc in range_constexpr(CHUNKS_PER_WAVE): + kc = wave * CHUNKS_PER_WAVE + cc + xb = fx.Vector( + fx.ptr_load( + x8 + (col_tok * (HIDDEN // 4) + kc * 16 + (lane // 16) * 4), + result_type=fx.Vector.make_type(4, fx.Float32), + ) + ).bitcast(fx.Int64) + wa = wts[cc].bitcast(fx.Int64) + for h in range_constexpr(2): + c = fx.Vector( + rocdl.mfma_f32_16x16x32_fp8_fp8( + T.vec(4, T.f32), [wa[h], xb[h], c, 0, 0, 0] + ) + ) + fx.ptr_store(c, red + (wave * 64 + lane) * 4) + gpu.barrier() + # sample column t of C: lanes t, 16 + t, 32 + t, 48 + t hold rows 4 (l/16) + e + if tid < ROWS_PER_TASK * tokens: + r = tid % ROWS_PER_TASK + tk = tid // ROWS_PER_TASK + tot_r = fx.Float32(0.0) + for w in range_constexpr(WAVES): + tot_r = tot_r + fx.ptr_load( + red + ((w * 64 + 16 * (r // 4) + tk) * 4 + r % 4) + ) + x_scale = x_scales[0] + for k in range_constexpr(1, tokens): + x_scale = (tk == k).select(x_scales[k], x_scale) + mb_put( + qkv_mb, + tk * rows + rg * ROWS_PER_TASK + r, + bf16_round(tot_r * x_scale * ws), + ) + + stamp(3) + + # ======================================= head tasks: norm / rope / cache + # one CTA per head, token k on the half wave of threads 32 k .. 32 k + 31 + if (bid >= HT0) & (bid < HT0 + N_HEAD_TASKS): + ht = bid - HT0 + tk = tid // 32 + l32 = tid % 32 + is_q = ht < LOCAL_Q_HEADS + is_k = ht == LOCAL_Q_HEADS + is_v = ht == LOCAL_Q_HEADS + 1 + is_iq = ht == LOCAL_Q_HEADS + 2 + base = tk * rows + is_q.select( + ht * HEAD_DIM, + is_k.select( + K_OFF, is_v.select(V_OFF, is_iq.select(heads.iq_off, heads.ik_off)) + ), + ) + if tk < tokens: + d0 = l32 * ELEMS + # slot_mapping is int64: this token's low word + slot = fx.Int32( + bo.buffer_load(rsrc(slot_mapping), 2 * tk, vec_width=1, dtype=T.i32) + ) + # gamma and this position's cos / sin go out before the wait + gw = is_q.select(g_q, is_k.select(g_k, is_iq.select(g_iq, g_ik))) + gw4, cs, sn = head_rope_inputs(tk, gw, d0, cos_sin, positions) + got = mb_poll([(qkv_mb, base + d0, 2), (qkv_mb, base + d0 + 2, 2)]) + stamp(4) + e = [ + got[0][0].bitcast(fx.Float32), + got[0][1].bitcast(fx.Float32), + got[1][0].bitcast(fx.Float32), + got[1][1].bitcast(fx.Float32), + ] + if is_v: + # raw V: per-token amax over the head, scale = amax / FP8_MAX + if const_expr(mono_config.STATIC_KV_SCALE): + vs = fx.Float32(1.0) + else: + am = fx.Float32(0.0) + for j in range_constexpr(ELEMS): + am = fx.max(am, fmath.absf(e[j])) + am = butterfly(am, (16, 8, 4, 2, 1), fx.max) + vs = (am > 0.0).select(am / FP8_MAX, fx.Float32(1.0)) + if slot >= 0: + b = page16_of(slot) + t = slot % PAGE16 + if l32 == 0: + bo.buffer_store( + vs, rsrc(v_scale), b * PAGE16 + t, cache_modifier=cm_out + ) + r_v = rsrc(v_cache) + for j in range_constexpr(ELEMS): + q8 = fp8_pack4(e[j] / vs, 0.0, 0.0, 0.0) & 0xFF + bo.buffer_store( + fx.Int8(q8), + r_v, + b * PAGE_BYTES + (d0 + j) * PAGE16 + t, + cache_modifier=cm_out, + ) + else: + out = head_norm_rope(e, lane, gw4, cs, sn, eps) + if is_q: + bo.buffer_store( + fx.Vector.from_elements(out, fx.Float32).to(fx.BFloat16), + rsrc(q_out), + (tk * LOCAL_Q_HEADS + ht) * HEAD_DIM + d0, + cache_modifier=cm_out, + ) + if is_iq: + bo.buffer_store( + fx.Vector.from_elements(out, fx.Float32).to(fx.BFloat16), + rsrc(iq_out), + tk * HEAD_DIM + d0, + ) + if is_k: + if const_expr(mono_config.STATIC_KV_SCALE): + ksc = fx.Float32(1.0) + else: + am = fx.Float32(0.0) + for j in range_constexpr(ELEMS): + am = fx.max(am, fmath.absf(out[j])) + am = butterfly(am, (16, 8, 4, 2, 1), fx.max) + ksc = (am > 0.0).select(am / FP8_MAX, fx.Float32(1.0)) + if slot >= 0: + b = page16_of(slot) + t = slot % PAGE16 + if l32 == 0: + bo.buffer_store( + ksc, + rsrc(k_scale), + b * PAGE16 + t, + cache_modifier=cm_out, + ) + qk = [bf16_round(out[j]) / ksc for j in range(ELEMS)] + bo.buffer_store( + fp8_pack4(qk[0], qk[1], qk[2], qk[3]), + rsrc(k_cache), + ( + b * PAGE_BYTES + + (d0 // 16) * (PAGE16 * 16) + + t * 16 + + d0 % 16 + ) + // 4, + cache_modifier=cm_out, + ) + if (ht == IK_TASK) & (slot >= 0): + qi = [bf16_round(out[j]) for j in range(ELEMS)] + bo.buffer_store( + fp8_pack4(qi[0], qi[1], qi[2], qi[3]), + rsrc(index_cache), + (slot * HEAD_DIM + d0) // 4, + cache_modifier=cm_out, + ) + + if const_expr(signal is not None): + # every token's flag once the whole CTA's stores are out + publish_done(signal[0], tid * N_HEAD_TASKS + ht, tid < tokens) + + +# the fused layer kernel's K1 pointers that do not change per step, in its device +# array (the rest are K4's own, or kernel arguments) +K1_ARGS = ( + "ar", "g_in", "w_qkv", "s_qkv", "g_q", "g_k", "g_iq", "g_ik", "cos_sin", + "index_cache", "iq_out", "scratch", +) # fmt: skip + + +@traced +def emit_k1( + tid, bid, lane, wave, x8, red, qs, stamp, step, layer, eps, index_scale, tokens, + q_len, init_blocks, local_blocks, heads, ptrs, bt_width, signal=False, +): # fmt: skip + """K1 whole: the GEMV / head / norm tasks, then every CTA's indexer scores. + ``x8``: tokens * HIDDEN / 4 words of LDS, ``red``: WAVES * 256 floats, ``qs``: + tokens * heads.count * HEAD_DIM / 2 floats. ``q_len``: tokens per request + (speculative verify rows). ``heads``: the index q heads of the fused projection + (``IndexHeads``). ``signal`` (the fused layer kernel): the head tasks and + residual writers publish done flags (SCRATCH_HDONE / SCRATCH_RDONE).""" + ( + ar, res, h_out, g_in, w_qkv, s_qkv, g_q, g_k, g_iq, g_ik, cos_sin, positions, + slot_mapping, k_cache, v_cache, k_scale, v_scale, index_cache, q_out, iq_out, + block_table, seq_lens, iscore, scratch, + ) = ptrs # fmt: skip + mbox = Mailbox(scratch, step, layer) + qkv_mb = mbox.addr(SCRATCH_QKV) + x8_mb = mbox.addr(SCRATCH_X8) + x8s_mb = mbox.addr(SCRATCH_X8S) + # Plain names, not method calls: flydsl's AST rewriter carries every local whose + # method is called inside a dynamic if/for as loop state. + mb_put = mbox.put + mb_put_words = mbox.put_words + mb_poll = mbox.poll + + def index_q_row(tk, head): + """Token tk's index q of the projection's index head ``head`` into qs (row + tk * heads.count + head, HEAD_DIM / 2 words), made from the GEMV's raw rows + with the index-q head's math, by this wave's lanes < 32.""" + d0 = lane * ELEMS + gw4, cs, sn = head_rope_inputs(tk, g_iq, d0, cos_sin, positions) + base = tk * heads.rows + IndexHeads(heads.count, 0).iq_off + head * HEAD_DIM + got = mb_poll([(qkv_mb, base + d0, 2), (qkv_mb, base + d0 + 2, 2)]) + e = [got[h][j].bitcast(fx.Float32) for h in range(2) for j in range(2)] + out = head_norm_rope(e, lane, gw4, cs, sn, eps) + row = qs + (tk * heads.count + head) * (HEAD_DIM // 2) + fx.ptr_store(bf16_pair(out[0], out[1]), row + lane * 2) + fx.ptr_store(bf16_pair(out[2], out[3]), row + (lane * 2 + 1)) + + def make_index_q(first, last): + """Tokens first..last's index q of this rank's head into qs: wave w makes + tokens w, w + WAVES, ..; run by a CTA with score tasks only.""" + for k0 in range_constexpr(0, tokens, WAVES): + tk = wave + k0 + if (tk < tokens) & (tk >= first) & (tk <= last) & (lane < 32): + index_q_row(tk, heads.own) + gpu.barrier() + + def make_index_q_heads(): + """Every token's index q of every head into qs (indexer context + parallelism): (token, head) job j on wave j % WAVES.""" + for j0 in range_constexpr(0, tokens * heads.count, WAVES): + j = wave + j0 + if (j < tokens * heads.count) & (lane < 32): + index_q_row(j // heads.count, j % heads.count) + gpu.barrier() + + def q_frag_head(tk, s, head): + """This lane's MFMA B operand of token tk's index q of head ``head``, + k-chunk s.""" + row = (tk * heads.count + head) * (HEAD_DIM // 2) + return fx.Vector( + fx.ptr_load( + qs + (row + (32 * s + 8 * (lane // 16)) // 2), + result_type=fx.Vector.make_type(4, fx.Float32), + ) + ).bitcast(fx.BFloat16) + + def q_frag(tk, s): + """This lane's MFMA B operand of token tk's index q (this rank's head), + k-chunk s.""" + return q_frag_head(tk, s, heads.own) + + def long_step(): + """A request of the step is long (``step_rows``): it scores every index q + head (indexer context parallelism).""" + return step_rows(seq_lens, tokens, q_len, heads).any_long() + + emit_pre_attn( + tid, bid, lane, wave, x8, red, mb_put, mb_put_words, mb_poll, qkv_mb, x8_mb, + x8s_mb, stamp, eps, tokens, heads, + ( + ar, res, h_out, g_in, w_qkv, s_qkv, g_q, g_k, g_iq, g_ik, + cos_sin, positions, slot_mapping, k_cache, v_cache, k_scale, + v_scale, index_cache, q_out, iq_out, + ), + (mbox.addr(SCRATCH_HDONE), mbox.addr(SCRATCH_RDONE)) if signal else None, + long_step, + ) # fmt: skip + stamp(5) + # the scorers: the idle CTAs first (the norm tasks' come first but finish + # early), then the GEMV CTAs, the head CTAs last + score_base = ONE_GEMV + N_HEAD_TASKS + hdone_mb = mbox.addr(SCRATCH_HDONE) + + def wait_new_keys(): + """Every token's index_k head task done, its key visible to this wave.""" + mb_poll([(hdone_mb, fx.min(lane, tokens - 1) * N_HEAD_TASKS + IK_TASK, 1)]) + fx.memory_fence( + syncscope=rocdl.SyncScope.Agent, ordering=fx.AtomicOrdering.Acquire + ) + + emit_index_scores( + (bid + (BLOCKS - score_base)) % BLOCKS, lane, uniform(wave), red, + mb_put, iscore, q_frag, tokens, q_len, init_blocks, local_blocks, + index_scale, index_cache, block_table, seq_lens, bt_width, + wait_new_keys if signal else None, + make_index_q, heads, q_frag_head, make_index_q_heads, + ) # fmt: skip + stamp(6) + + +TL_POINTS = 8 # timeline stamps per CTA + + +def build_pre_attn_kernel( + eps: float, + sm_scale: float, + init_blocks: int, + local_blocks: int, + tokens: int = 1, + timeline: bool = False, + heads: IndexHeads = ONE_INDEX_HEAD, +): + """``@flyc.jit`` launcher of K1 for this model's RMSNorm epsilon, attention + scale and sparse pinned blocks, a decode batch of ``tokens`` (<= MAX_TOKENS) + rows and the fused projection's index q ``heads``.""" + assert 1 <= tokens <= MAX_TOKENS + index_scale = index_scale_log2e(sm_scale) + + @fx.struct + class Smem: + # FP8 activations, natural k order, one row per token + x8: fx.Array[fx.Int32, tokens * HIDDEN // 4, 16] + red: fx.Array[fx.Float32, WAVES * 64 * 4, 16] + tls: fx.Array[fx.Int64, TL_POINTS if timeline else 1, 16] # timeline stamps + # every token's index q for the scorers, bf16 pairs + qs: fx.Array[fx.Float32, HEAD_DIM // 2 * tokens * heads.count, 16] + + kernel_name = kernel_symbol( + "minimax_m3_pre_attn", + s=tokens, + ib=init_blocks, + lb=local_blocks, + ih=heads.count, + io=heads.own, + tl=timeline, + kps=mono_config.KV_PAGE_STRIDE, + sks=mono_config.STATIC_KV_SCALE, + ) + + # the JIT cache key holds the kernel's scalar closure values, not objects: the + # index heads go in as ints (a shared cache otherwise serves one rank's build + # to every rank) + ih_count, ih_own = heads.count, heads.own + + @flyc.kernel(name=kernel_name, known_block_size=[THREADS, 1, 1]) + def pre_attn_kernel( + ar: Int64, + res: Int64, + h_out: Int64, + g_in: Int64, + w_qkv: Int64, + s_qkv: Int64, + g_q: Int64, + g_k: Int64, + g_iq: Int64, + g_ik: Int64, + cos_sin: Int64, + positions: Int64, + slot_mapping: Int64, + k_cache: Int64, + v_cache: Int64, + k_scale: Int64, + v_scale: Int64, + index_cache: Int64, + q_out: Int64, + iq_out: Int64, + block_table: Int64, + seq_lens: Int64, + bt_width: Int32, + q_len: Int32, + iscore: Int64, + scratch: Int64, + step: Int64, + layer: Int32, + tl: Int64, + ): + tid = fx.thread_idx.x + bid = fx.block_idx.x + lane = tid % 64 + wave = tid // 64 + lds = fx.SharedAllocator().allocate(Smem).peek() + x8 = lds.x8.ptr + red = lds.red.ptr + tls = lds.tls.ptr + qs = lds.qs.ptr + + def stamp(k): + """``timeline``: s_memrealtime (100 MHz) of this CTA passing point k, kept + in LDS until the kernel ends.""" + # The compile-time and traced conditions cannot share one ``and``. + if const_expr(timeline): # noqa: SIM102 + if tid == 0: + fx.ptr_store(memrealtime(), tls + k) + + if const_expr(timeline): # noqa: SIM102 + if tid < TL_POINTS: # same wave as the stamping thread: ordered + fx.ptr_store(fx.Int64(0), tls + tid) + stamp(0) + emit_k1( + tid, bid, lane, wave, x8, red, qs, stamp, step, layer, eps, index_scale, + tokens, q_len, init_blocks, local_blocks, IndexHeads(ih_count, ih_own), + ( + ar, res, h_out, g_in, w_qkv, s_qkv, g_q, g_k, g_iq, g_ik, + cos_sin, positions, slot_mapping, k_cache, v_cache, k_scale, + v_scale, index_cache, q_out, + iq_out, block_table, seq_lens, iscore, scratch, + ), + bt_width, + ) # fmt: skip + if const_expr(timeline): # noqa: SIM102 + if tid < TL_POINTS: + fx.generic_store( + fx.inttoptr( + fx.PointerType.get(fx.Int64.ir_type, fx.AddressSpace.Global, 8), + tl + fx.Int64((bid * TL_POINTS + tid) * 8), + ), + fx.ptr_load(tls + tid), + ) + + @flyc.jit + def launch_pre_attn( + ar: Int64, + res: Int64, + h_out: Int64, + g_in: Int64, + w_qkv: Int64, + s_qkv: Int64, + g_q: Int64, + g_k: Int64, + g_iq: Int64, + g_ik: Int64, + cos_sin: Int64, + positions: Int64, + slot_mapping: Int64, + k_cache: Int64, + v_cache: Int64, + k_scale: Int64, + v_scale: Int64, + index_cache: Int64, + q_out: Int64, + iq_out: Int64, + block_table: Int64, + seq_lens: Int64, + bt_width: Int32, + q_len: Int32, + iscore: Int64, + scratch: Int64, + step: Int64, + layer: Int32, + tl: Int64, + stream: fx.Stream = _CURRENT_STREAM, + ): + pre_attn_kernel( + ar, + res, + h_out, + g_in, + w_qkv, + s_qkv, + g_q, + g_k, + g_iq, + g_ik, + cos_sin, + positions, + slot_mapping, + k_cache, + v_cache, + k_scale, + v_scale, + index_cache, + q_out, + iq_out, + block_table, + seq_lens, + bt_width, + q_len, + iscore, + scratch, + step, + layer, + tl, + ).launch(grid=(BLOCKS,), block=(THREADS,), stream=stream) + + return launch_pre_attn diff --git a/vllm/models/minimax_m3/amd/mono/layout.py b/vllm/models/minimax_m3/amd/mono/layout.py new file mode 100644 index 000000000000..d8eb34168f01 --- /dev/null +++ b/vllm/models/minimax_m3/amd/mono/layout.py @@ -0,0 +1,230 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +"""Where the mono layer kernel (K4) puts its tasks and data, per decode token count. + +Plain Python, evaluated at build time: which CTA runs each stage's tasks, the +scratch and peer-symmetric regions, and the LDS row pitches. Kept free of FlyDSL +so it is testable without a GPU. +""" + +from vllm.models.minimax_m3.amd.mono.config import ( + BLOCKS, + HEAD_DIM, + HIDDEN, + INTER, + LOCAL_Q_HEADS, + MAX_INDEX_BLOCKS, + MAX_SPARSE_KEYS, + MAX_TOKENS, + MOE_SLOTS, + N_ROUTED, + PAGE16, + SPARSE_BLOCK, + TOP_K, + TOPK_BLOCKS, + WAVES, +) + +H = LOCAL_Q_HEADS +SPLIT_KEYS = 256 # one gluon context partition per split task +N_SPLIT = MAX_SPARSE_KEYS // SPLIT_KEYS +O_K = H * HEAD_DIM +O_ROWS = 32 # hidden rows per o_proj / attention-reduce task +# from this many tokens the attention all-reduce is a reduce-scatter to the row +# group's owner rank (t % npes) plus an all-gather of the sums: half the bytes over +# each link for one more hop (smaller batches are latency-bound: one hop wins) +AG_RS_FROM = 12 +N_O = HIDDEN // O_ROWS +PAGES_PER_BLOCK = SPARSE_BLOCK // PAGE16 +N_ROUTER = N_ROUTED // WAVES # one expert per wave +UG_ROWS = 16 +UG_PER_SLOT = INTER // UG_ROWS +SH_ROWS = 8 # mid rows per shared-expert up / gate task (a half task) +SH_TASKS = INTER // SH_ROWS +DN_ROWS = 32 +N_DN = HIDDEN // DN_ROWS +# The router logits are written SCORE_COPIES times and CTA b polls copy +# b % SCORE_COPIES: 240 expert CTAs spinning on one 1 KB region serialize on its +# lines. K4 on 4 GPUs 37.3 -> 35.9 us; copies of xn / mid measured neutral and of +# the split outputs +0.3 us (the split CTAs pay the extra stores). +SCORE_COPIES = 8 + + +def _layout(items, align=256): + """Byte offsets of (value, tag) pair regions, 8 bytes per pair.""" + off, out = 0, {} + for name, pairs in items: + out[name] = off + off += (pairs * 8 + align - 1) // align * align + out["_bytes"] = off + return out + + +# plain words, not pairs: the selected pages then the context length, as the +# original selector emits them (read by the tests); one row per token +SPARSE_TABLE_WORDS = TOPK_BLOCKS * PAGES_PER_BLOCK + 2 +# a context past THREADS blocks, one-head build: each split task's TOPK_BLOCKS +# best (key, block) (indexer context parallelism: the peers' sel_cp) +SEL_LONG_PAIRS = N_SPLIT * TOPK_BLOCKS * 2 + +# every region holds MAX_TOKENS rows (token k at k * the one-token size) +SCRATCH = _layout( + [ + # indexer block scores, token k's block b at pair k * MAX_INDEX_BLOCKS + b + ("iscore", MAX_INDEX_BLOCKS * MAX_TOKENS), + ("sparse_table", SPARSE_TABLE_WORDS // 2 * MAX_TOKENS), + ("sp_o", N_SPLIT * H * HEAD_DIM // 2 * MAX_TOKENS), # packed bf16 pairs + ("sp_m", N_SPLIT * H * MAX_TOKENS), + ("sp_l", N_SPLIT * H * MAX_TOKENS), + ("attnq", O_K // 4 * MAX_TOKENS // 2), # merged attention, plain FP8 words + ("attnq_s", MAX_TOKENS), # and its per-token scale + # the finished attention all-reduce + residual, bf16 pairs (o tasks -> router) + ("a", HIDDEN // 2 * MAX_TOKENS), + ("xn8", HIDDEN // 4 * MAX_TOKENS), # MXFP8 xn, 4 fp8 per word + ("xsc", HIDDEN // 32 * MAX_TOKENS), # and its per-1x32 E8M0 scales + # copy c, token k at pairs [(c * MAX_TOKENS + k) * N_ROUTED, ..) + # per expert (routing key, sigmoid) pairs, see route_key + ("scores", 2 * N_ROUTED * MAX_TOKENS * SCORE_COPIES), + ("mid", MOE_SLOTS * INTER * MAX_TOKENS), + # routing record read by the tests: token k's expert ids, then weights + ("sel", 2 * MOE_SLOTS * MAX_TOKENS), + # token k's split task p's candidates: rank r at pairs 2 ((k N_SPLIT + p) + # TOPK_BLOCKS + r) + (0 key, 1 block) + ("sel_long", SEL_LONG_PAIRS * MAX_TOKENS), + # wide: the MXFP8 xn and scales as plain words (every token's row), and a + # done flag per router task + ("xn8p", HIDDEN // 4 * MAX_TOKENS // 2), + ("xscp", HIDDEN // 32 * MAX_TOKENS // 2), + ("xndone", N_ROUTER * MAX_TOKENS), + # and the mid rows as MXFP8 words, their E8M0 scales a word each (the down + # stage's LDS layout), a done flag per up / gate task pair + ("mid8p", MOE_SLOTS * INTER * MAX_TOKENS // 8), + ("midsp", MOE_SLOTS * INTER // 32 * MAX_TOKENS // 2), + ("ugdone", (TOP_K * MAX_TOKENS + 1) * UG_PER_SLOT // 2), + ] +) +SCRATCH_BYTES = SCRATCH["_bytes"] + + +def sym_layout(npes: int): + """Per-rank symmetric buffer: attn / ffn partial regions, [src rank][token][HIDDEN], + and the peers' index-selection candidates (``sel_cp``).""" + rows = npes * MAX_TOKENS * HIDDEN // 2 + # a_ag / ffn_ag: the finished attention / FFN all-reduce rows, each written by + # its owner rank (the reduce-scatter + all-gather form, S >= AG_RS_FROM) + ag = MAX_TOKENS * HIDDEN // 2 + return _layout( + [ + ("attn", rows), + ("ffn", rows), + ("a_ag", ag), + ("ffn_ag", ag), + # indexer context parallelism: token k's candidates for this rank's + # index head, source rank s's half h's r-th best at pairs + # 2 ((k N_SPLIT + 2 s + h) TOPK_BLOCKS + r) + (0 key, 1 block) + ("sel_cp", SEL_LONG_PAIRS * MAX_TOKENS), + ] + ) + + +def stage_bases(tokens: int): + """Task t of a stage runs on CTA (base + t) % BLOCKS; the merge (S > 1), o and + down tasks start past the tokens' split CTAs.""" + n_split = N_SPLIT * tokens + n_merge = tokens if tokens > 1 else 0 + router = (n_split + n_merge + N_O) % BLOCKS + return { + "split": 0, + "merge": n_split, + "o": n_split + n_merge, + "router": router, + "shared": _shared_base(tokens, router), + "ug": 0, + "down": n_split, + } + + +def ug_ctas_per_token(tokens: int): + """CTAs per token of the routed up / gate tasks, token k on CTAs k C .. (k + 1) + C - 1: a CTA stages one token's xn, not all (fused layer, S = 4: 57.9 -> 57.6 + us). None: round-robin -- S < 4 (S = 2: +0.4 us) or S not dividing the grid.""" + return BLOCKS // tokens if tokens >= 4 and BLOCKS % tokens == 0 else None + + +def ug_tasks_of(cta: int, tokens: int) -> int: + """Routed up / gate tasks CTA ``cta`` runs.""" + per_token = TOP_K * UG_PER_SLOT + cpt = ug_ctas_per_token(tokens) + if cpt is None: + return (per_token * tokens - cta + BLOCKS - 1) // BLOCKS + return (per_token - cta % cpt + cpt - 1) // cpt + + +def _shared_base(tokens: int, router: int) -> int: + """First of the SH_TASKS consecutive CTAs that run the shared expert's up / + gate before the routing lands. Ranked by the most routed up / gate tasks a + window CTA carries (they queue behind it); then, only if that is the most any + CTA carries, by its router CTAs (they start it late and would delay the last + routed tasks: S = 4, 4 us); then by its down CTAs (S = 2: 43.1 vs 43.7 us); + then by its router CTAs anyway.""" + n_router = N_ROUTER * tokens + n_split = N_SPLIT * tokens + most = max(ug_tasks_of(c, tokens) for c in range(BLOCKS)) + + def cost(base): + ctas = [(base + j) % BLOCKS for j in range(SH_TASKS)] + busiest = max(ug_tasks_of(c, tokens) for c in ctas) + in_router = sum((c - router) % BLOCKS < n_router for c in ctas) + in_down = sum(n_split <= c < n_split + N_DN for c in ctas) + return busiest, in_router if busiest == most else 0, in_down, in_router + + return min(range(BLOCKS), key=cost) + + +def shared_after_routing(tokens: int) -> bool: + """Every CTA carries the same number of routed up / gate tasks (S = 4): a + shared-expert CTA routes first and runs its shared half task while its first + routed task's weights are in flight, instead of holding its routing back + (S = 4 54.51 -> 54.09 us; S = 2, where the shared window sits on CTAs with one + task fewer, +0.1).""" + loads = [ug_tasks_of(c, tokens) for c in range(BLOCKS)] + return min(loads) == max(loads) + + +WIDE_FROM = 5 # token counts from here run the expert-grouped MoE + + +def wide_moe(tokens: int) -> bool: + """The MoE stage groups its work by expert (every distinct expert's weights + read once, a B column per token) instead of by (token, slot): past four tokens + the per-token tasks re-read the experts the tokens share, and their operands + no longer fit in LDS.""" + return tokens >= WIDE_FROM + + +# LDS rows of a token's MXFP8 xn and of its E8M0 scales, padded by 16 B: at the +# natural 1536 / 192-word rows the 16 tokens a MFMA B operand gathers sit in one +# bank group (16-way conflicts; ug spent ~3 us a task in them at S = 16) +XN8_ROW = HIDDEN // 4 + 4 +XSC_ROW = HIDDEN // 32 + 4 +# and the down stage's MXFP8 mid rows / their scales (16 lanes, 16 rows): 196 and +# 28 words put the rows' 16 B reads, and 4 B scale reads, in distinct banks +MID_ROW = INTER // 4 + 4 +MIDSC_ROW = INTER // 32 + 4 +# and the o stage's FP8 attention rows (512 words: the same 16-way conflict) +O_ROW = O_K // 4 + 4 + + +def pool_words(tokens: int) -> int: + """LDS words of the activation pool ``x``. Narrow: every token's bf16 xn (the + largest stage operand). Wide: the largest of the split's PV partials, the up / + gate stage's MXFP8 xn + scales + up partials + router sigmoids, and the down + stage's MXFP8 mids + scales + a zero row.""" + if not wide_moe(tokens): + return HIDDEN // 2 * tokens + rows = MOE_SLOTS * tokens + 1 + return max( + WAVES * O_K, + tokens * (XN8_ROW + XSC_ROW + N_ROUTED) + WAVES * 64 * 4, + rows * (MID_ROW + MIDSC_ROW), + ) diff --git a/vllm/models/minimax_m3/amd/mono/peer_buffer.py b/vllm/models/minimax_m3/amd/mono/peer_buffer.py new file mode 100644 index 000000000000..8ea5e873e88f --- /dev/null +++ b/vllm/models/minimax_m3/amd/mono/peer_buffer.py @@ -0,0 +1,49 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +"""Symmetric peer memory for the mono kernels' in-kernel all-reduces.""" + +import torch +import torch.distributed as dist +from aiter.ops.flydsl.quick_allreduce_int4_ipc import UncachedIpcHeap + + +class PeerBuffer: + """One uncached buffer per rank, every rank holding every peer's address. + + K4 pushes a layer's attention partials into every peer's ``attn`` region and + its FFN partials into the ``ffn`` region, then polls its own. Regions are + reused by every layer and step (the mailbox epoch tells a stale pair from a + fresh one) and no rank can overwrite a peer's unread pairs: to push layer L's + FFN partials a rank must have passed layer L's attention reduce, which needs + every peer's layer-L attention push, and a peer only pushes that after it + finished reading layer L-1's FFN region. So ranks are at most half a layer + apart and the two regions double-buffer each other. + """ + + def __init__(self, nbytes: int, group, rank: int, npes: int, device: torch.device): + self.local = UncachedIpcHeap.alloc_uncached(nbytes) + self._opened: list[int] = [] + addresses = [self.local] + if npes > 1: + handles = UncachedIpcHeap.gather_object_list_via_broadcast( + group, UncachedIpcHeap.get_mem_handle_bytes(self.local) + ) + addresses = [] + for peer, handle in enumerate(handles): + if peer == rank: + addresses.append(self.local) + else: + base = UncachedIpcHeap.open_mem_handle(handle) + self._opened.append(base) + addresses.append(base) + dist.barrier(group=group) + self.addresses = torch.tensor(addresses, dtype=torch.int64, device=device) + + def close(self) -> None: + """Close the peer mappings and free the local buffer; idempotent.""" + opened, self._opened = self._opened, [] + for base in opened: + UncachedIpcHeap.close_mem_handle(base) + if self.local: + UncachedIpcHeap.free_device_mem(self.local) + self.local = 0 diff --git a/vllm/models/minimax_m3/amd/mono/runner.py b/vllm/models/minimax_m3/amd/mono/runner.py new file mode 100644 index 000000000000..048a4aaba6a8 --- /dev/null +++ b/vllm/models/minimax_m3/amd/mono/runner.py @@ -0,0 +1,334 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""One decode step of 1..MAX_TOKENS tokens on the mono kernels. + +Every sparse MoE layer is one launch of the fused layer kernel; it takes +``(ar, res)`` -- the pair vLLM's input norm would receive (reduced MoE output, +residual) -- and leaves ``(ar, h_mid)`` for the next layer, alternating between +two buffers by layer parity. The embedding, the leading dense-FFN layers and the +final norm run the original modules. The K/V cache is read in vLLM's interleaved +page-16 layout under the fixed unit fp8 scale; the step's tables come from the +forward context. +""" + +from typing import Any, NamedTuple, cast + +import torch + +from vllm.distributed import ( + get_tensor_model_parallel_rank, + get_tensor_model_parallel_world_size, + get_tp_group, +) +from vllm.forward_context import get_forward_context +from vllm.model_executor.layers.fused_moe.experts import rocm_aiter_moe +from vllm.models.minimax_m3.amd.mono import config as mono_config +from vllm.models.minimax_m3.amd.mono.config import ( + BLOCKS, + HEAD_DIM, + HIDDEN, + LOCAL_Q_HEADS, + MAX_TOKENS, + N_ROUTED, + PAGE16, + TOP_K, + TOPK_BLOCKS, + TP, + IndexHeads, + MonoUnsupported, +) +from vllm.models.minimax_m3.amd.mono.kernels.post_attn import build_post_attn_kernel +from vllm.models.minimax_m3.amd.mono.kernels.pre_attn import K1_ARGS +from vllm.models.minimax_m3.amd.mono.kernels.pre_attn import ( + SCRATCH_BYTES as K1_SCRATCH_BYTES, +) +from vllm.models.minimax_m3.amd.mono.layout import SCRATCH_BYTES as K4_SCRATCH_BYTES +from vllm.models.minimax_m3.amd.mono.layout import sym_layout +from vllm.models.minimax_m3.amd.mono.peer_buffer import PeerBuffer +from vllm.models.minimax_m3.amd.mono.weights import SparseMoeLayer, build_sparse_layer +from vllm.platforms import current_platform + + +def _ptr(t: torch.Tensor) -> int: + return t.data_ptr() + + +class StepTables(NamedTuple): + """The per-step inputs every layer launch of a decode step shares.""" + + block_table: torch.Tensor # int32 [rows, width], one row per token + seq_lens: torch.Tensor # int32 [rows] + slot_mapping: torch.Tensor # int64, page-128 slots (K/V and index cache) + q_len: int # query tokens per request (speculative verify rows) + + +def token_rows( + block_table: torch.Tensor, seq_lens: torch.Tensor, q: int, n: int +) -> tuple[torch.Tensor, torch.Tensor]: + """One (block table row, seq_len) per token of the step: a request of q query + tokens becomes q rows, token j seeing ``seq_len - (q - 1 - j)`` keys.""" + if q == 1: + return block_table, seq_lens + reqs = n // q + back = torch.arange(q - 1, -1, -1, dtype=seq_lens.dtype, device=seq_lens.device) + return ( + block_table[:reqs].repeat_interleave(q, dim=0), + (seq_lens[:reqs, None] - back).reshape(-1), + ) + + +def dense_prefix(layers) -> int: + """Leading layers without an MoE FFN; every later layer must be sparse MoE.""" + n = 0 + while n < len(layers) and not layers[n].is_moe_layer: + n += 1 + if n == len(layers) or not all( + lyr.is_moe_layer and hasattr(lyr.self_attn, "indexer") for lyr in layers[n:] + ): + raise MonoUnsupported("layer mix: dense layers must precede the MoE layers") + return n + + +def _fused_shared_weight() -> float: + """The fused shared expert's slot weight, from aiter's routing metadata.""" + meta = rocm_aiter_moe.aiter_topK_meta_data + if meta is None: + raise MonoUnsupported("fused shared expert routing metadata") + total_w, total_ids = meta + if int(total_ids[0, TOP_K].item()) != N_ROUTED: + raise MonoUnsupported("fused shared expert id") + return float(total_w[0, TOP_K].item()) + + +class MonoDecodeRunner: + """Owns the per-layer weight views, scratch, peer buffers and compiled kernels.""" + + def __init__(self, model, config) -> None: + npes = get_tensor_model_parallel_world_size() + if npes != TP: + raise MonoUnsupported(f"TP {npes}") + self.model = model + self.rank = get_tensor_model_parallel_rank() + layers = list(model.layers) + # Enable indexer context parallelism: each rank computes all TP index + # heads, allowing local block scoring without cross-rank exchange. + heads = IndexHeads(count=TP, own=self.rank) + tp_group = get_tp_group().device_group + self.n_dense = n_dense = dense_prefix(layers) + self.sparse = [ + build_sparse_layer(layers[i], i, heads, rank=self.rank, tp_group=tp_group) + for i in range(n_dense, len(layers)) + ] + attn0 = layers[n_dense].self_attn + moe0 = layers[n_dense].block_sparse_moe + self.shared_fp8 = self.sparse[0].shared_fp8 + if any(lw.shared_fp8 != self.shared_fp8 for lw in self.sparse): + raise MonoUnsupported("shared expert fused in some layers only") + # a separate MXFP8 shared expert adds unscaled: routed_scaling_factor goes + # on the routed weights alone (route_scale), as the model's runner does + shared_weight = 1.0 if self.shared_fp8 else _fused_shared_weight() + self.sm_scale = attn0.scaling + if abs(self.sm_scale - HEAD_DIM**-0.5) > 1e-12: + raise MonoUnsupported(f"softmax scale {self.sm_scale}") + sel = attn0.indexer.impl + if sel.topk_blocks != TOPK_BLOCKS: + raise MonoUnsupported(f"indexer top-{sel.topk_blocks} blocks") + self.layer_name = attn0.layer_name + self.index_prefix = attn0.indexer.index_cache.prefix + # the caches this build viewed: vLLM re-binds them after its cudagraph + # memory-profiling capture, which must rebuild the runner + self._cache_ptrs = self.cache_ptrs(model, n_dense) + # the K/V page views (V offset to its side of the block) and how many page + # ids a block spans; the kernels are compiled for that geometry + self.kv_views = [lyr.self_attn.get_aiter_sparse_pa_kv_cache() for lyr in layers] + stride = attn0._aiter_sparse_pa_block_page_stride + mono_config.configure(kv_page_stride=stride, static_kv_scale=True) + self._build( + npes, heads, float(config.rms_norm_eps), float(moe0.routed_scaling_factor), + shared_weight, + float(getattr(moe0.experts, "routed_experts", moe0.experts).swiglu_limit), + sel.init_blocks, sel.local_blocks, + ) # fmt: skip + dev = self.h.device + n16 = self.kv_views[0][0].shape[0] + # the host's unit fp8 scale for every page-16 slot (K1 writes 1.0 back) + self.kv_scale = torch.ones(n16, 1, PAGE16, dtype=torch.float32, device=dev) + self.res0 = torch.zeros(MAX_TOKENS, HIDDEN, dtype=torch.bfloat16, device=dev) + + @staticmethod + def cache_ptrs(model, n_dense: int) -> tuple[int, int]: + """Addresses of the first MoE layer's KV cache and index cache.""" + attn = model.layers[n_dense].self_attn + return attn.kv_cache.data_ptr(), attn.indexer.index_cache.kv_cache.data_ptr() + + def stale(self) -> bool: + """Whether vLLM re-bound the caches this runner viewed (profiling capture).""" + return self.cache_ptrs(self.model, self.n_dense) != self._cache_ptrs + + def step_tables(self, n: int) -> StepTables: + """The current step's tables for ``n`` tokens, from the forward context.""" + fwd = get_forward_context() + decode = cast(Any, fwd.attn_metadata[self.layer_name]).decode + q = decode.decode_query_len + block_table, seq_lens = token_rows(decode.block_table, decode.seq_lens, q, n) + return StepTables(block_table, seq_lens, fwd.slot_mapping[self.layer_name], q) + + def start( + self, + input_ids: torch.Tensor | None, + positions: torch.Tensor, + inputs_embeds: torch.Tensor | None, + aux_hidden_states: list[torch.Tensor] | None = None, + ) -> torch.Tensor: + """Embedding and the dense layers on the original modules; leaves the first + MoE layer's (ar, res) in ``ars[0][:n]`` and the returned residual (zeros + when layer 0 is already an MoE layer: (embeddings, 0)).""" + n = positions.numel() + hidden = ( + inputs_embeds + if inputs_embeds is not None + else self.model.embed_input_ids(input_ids) + ) + residual = None + if aux_hidden_states is not None: + self.model._maybe_add_hidden_state(aux_hidden_states, 0, hidden, residual) + for i in range(self.n_dense): + hidden, residual = self.model.layers[i](positions, hidden, residual) + if aux_hidden_states is not None: + self.model._maybe_add_hidden_state( + aux_hidden_states, i + 1, hidden, residual + ) + self.ars[0][:n].copy_(hidden.view(n, HIDDEN)) + return self.res0[:n] if residual is None else residual.view(n, HIDDEN) + + def forward( + self, + input_ids: torch.Tensor | None, + positions: torch.Tensor, + inputs_embeds: torch.Tensor | None = None, + ) -> torch.Tensor | tuple[torch.Tensor, list[torch.Tensor]]: + """The final hidden states of one decode step (what the model returns).""" + aux_hidden_states: list[torch.Tensor] | None = ( + [] if self.model.aux_hidden_state_layers else None + ) + res = self.start(input_ids, positions, inputs_embeds, aux_hidden_states) + tables = self.step_tables(res.shape[0]) + for i, lw in enumerate(self.sparse): + res = self.run_sparse_layer(i, lw, tables, positions, res) + if aux_hidden_states is not None: + self.model._maybe_add_hidden_state( + aux_hidden_states, + lw.layer_id + 1, + self.ars[(i + 1) % 2][: res.shape[0]], + res, + ) + hidden = self.run_final_norm(res) + if aux_hidden_states is not None: + return hidden, aux_hidden_states + return hidden + + def run_sparse_layer( + self, + i: int, + lw: SparseMoeLayer, + tables: StepTables, + positions: torch.Tensor, + res: torch.Tensor, + ) -> torch.Tensor: + """Sparse layer ``i``: (ars[i % 2][:n], res) -> (ars[(i + 1) % 2][:n], the + returned residual).""" + n = res.shape[0] + block_table, seq_lens, slots, q_len = tables + k16, v16 = self.kv_views[lw.layer_id] + self.k4[n]( + _ptr(self.h), _ptr(self.q), _ptr(block_table), _ptr(seq_lens), + _ptr(k16), _ptr(v16), _ptr(self.kv_scale), _ptr(self.kv_scale), + _ptr(lw.w_o), _ptr(lw.s_o), _ptr(lw.g_post), + _ptr(lw.gate), _ptr(lw.bias), _ptr(lw.w13), _ptr(lw.s13), + _ptr(lw.w2), _ptr(lw.s2), + _ptr(lw.sh_args) if lw.shared_fp8 else 0, + _ptr(self.h_mids[(i + 1) % 2]), _ptr(self.ars[(i + 1) % 2]), + _ptr(self.scratch4), self.peers.local, _ptr(self.peers.addresses), + _ptr(self.step), self.rank, lw.layer_id, + block_table.shape[1], q_len, + 0, # timeline stamps (kernel debug build only) + _ptr(self.k1_args[i]), _ptr(positions), _ptr(slots), _ptr(res), + stream=torch.cuda.current_stream(), # flydsl rejects torch.Stream + ) # fmt: skip + return self.h_mids[(i + 1) % 2][:n] + + def _build( + self, npes, heads, eps, route_scale, shared_weight, swiglu_limit, + init_blocks, local_blocks, + ) -> None: # fmt: skip + """Compile the layer kernels and allocate scratch, peer buffers and the + per-step activation buffers; ``self.sparse`` and ``self.sm_scale`` are set.""" + device_index = torch.accelerator.current_device_index() + dev = torch.device("cuda", device_index) + cus = current_platform.get_device_properties(device_index).multi_processor_count + if cus != BLOCKS: + raise MonoUnsupported( + f"{cus} CUs: the kernels need all {BLOCKS} CTAs co-resident" + ) + # one layer kernel per decode batch size (every graph captures its own) + self.k4 = { + s: build_post_attn_kernel( + npes, + self.sm_scale, + eps, + route_scale, + shared_weight, + swiglu_limit, + init_blocks, + local_blocks, + s, + fuse_k1=True, + heads=heads, + shared_fp8=self.shared_fp8, + ) + for s in range(1, MAX_TOKENS + 1) + } + self.scratch1 = torch.zeros(K1_SCRATCH_BYTES, dtype=torch.uint8, device=dev) + self.scratch4 = torch.zeros(K4_SCRATCH_BYTES, dtype=torch.uint8, device=dev) + self.peers = PeerBuffer( + sym_layout(npes)["_bytes"], get_tp_group().cpu_group, self.rank, npes, dev + ) + self.step = torch.zeros(1, dtype=torch.int32, device=dev) + bf16 = torch.bfloat16 + # row k = token k of the step; sparse layer i reads ars[i % 2] (the + # previous layer's output) and writes ars[(i + 1) % 2], likewise h_mids + self.ars = [ + torch.empty(MAX_TOKENS, HIDDEN, dtype=bf16, device=dev) for _ in range(2) + ] + self.h_mids = [ + torch.empty(MAX_TOKENS, HIDDEN, dtype=bf16, device=dev) for _ in range(2) + ] + self.h = torch.empty(MAX_TOKENS, HIDDEN, dtype=bf16, device=dev) + self.q = torch.empty( + MAX_TOKENS, LOCAL_Q_HEADS * HEAD_DIM, dtype=bf16, device=dev + ) + self.iq = torch.empty(MAX_TOKENS, 1, HEAD_DIM, dtype=bf16, device=dev) + # each layer's K1 pointers that do not change per step (K1_ARGS order) + self.k1_args = [] + for i, lw in enumerate(self.sparse): + ptrs = { + "ar": _ptr(self.ars[i % 2]), "g_in": _ptr(lw.g_in), + "w_qkv": _ptr(lw.w_qkv), + "s_qkv": _ptr(lw.s_qkv), "g_q": _ptr(lw.g_q), "g_k": _ptr(lw.g_k), + "g_iq": _ptr(lw.g_iq), "g_ik": _ptr(lw.g_ik), + "cos_sin": _ptr(lw.cos_sin), + "index_cache": _ptr(lw.index_cache), "iq_out": _ptr(self.iq), + "scratch": _ptr(self.scratch1), + } # fmt: skip + self.k1_args.append( + torch.tensor([ptrs[a] for a in K1_ARGS], dtype=torch.int64, device=dev) + ) + + def close(self) -> None: + self.peers.close() + + def run_final_norm(self, res: torch.Tensor) -> torch.Tensor: + ar = self.ars[len(self.sparse) % 2] + hidden, _ = self.model.norm(ar[: res.shape[0]], res) + self.step.add_(1) + return hidden diff --git a/vllm/models/minimax_m3/amd/mono/weights.py b/vllm/models/minimax_m3/amd/mono/weights.py new file mode 100644 index 000000000000..ad7446e601cf --- /dev/null +++ b/vllm/models/minimax_m3/amd/mono/weights.py @@ -0,0 +1,377 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Zero-copy views (and two converted copies) of one vLLM ``MiniMaxM3DecoderLayer`` +for the mono kernels. + +The kernels read tensors through raw pointers in fixed layouts: a differently +laid-out weight would not fault, it would produce plausible garbage. So every +layout assumption is asserted once and a model that does not match is refused +(``MonoUnsupported``). The experts already have the kernels' layout (MXFP4, aiter +``shuffle_weight(16, 16)`` + ``e8m0_shuffle`` scales, fused shared expert in slot +128). The attention linears are MXFP8 in vLLM and the router gate is fp32, so +those are converted once when the runner is built: MXFP8 -> bf16 -> per-channel +fp8, preshuffled (16, 16); gate -> bf16. + +Without shared-expert fusion the routed table holds the 128 routed experts and +the shared expert stays the separate MXFP8 MLP; its weights are copied once into +the f8f6f4 MFMA's fp8 A-operand order (``mxfp8_a_tiles``, the same bytes) with +``e8m0_shuffle``-ordered scales, so the kernels run it in MXFP8. +""" + +from dataclasses import dataclass + +import torch +import torch.distributed as dist +from aiter import dtypes +from aiter.ops.quant import pertoken_quant +from aiter.ops.shuffle import shuffle_weight + +from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( + dequant_mxfp8_to_bf16, +) +from vllm.models.minimax_m3.amd.mono.config import ( + HEAD_DIM, + HIDDEN, + INTER, + LOCAL_Q_HEADS, + N_ROUTED, + O_K, + ONE_INDEX_HEAD, + ROTARY_DIM, + TOP_K, + TOPK_BLOCKS, + TP, + IndexHeads, + MonoUnsupported, +) +from vllm.models.minimax_m3.amd.mono.kernels.post_attn import SH_ARGS + + +def _need(ok: bool, what: str) -> None: + if not ok: + raise MonoUnsupported(what) + + +def _bf16_vec(t: torch.Tensor, n: int, name: str) -> torch.Tensor: + _need( + t.dtype == torch.bfloat16 and t.numel() == n and t.is_contiguous(), + f"{name}: {t.dtype} {tuple(t.shape)}", + ) + return t.data + + +@dataclass(frozen=True) +class SparseMoeLayer: + """Everything the layer kernel reads for one sparse-attention MoE layer.""" + + layer_id: int + attn: object # MiniMaxM3SparseAttention: layer name, KV cache views, scales + index_cache: torch.Tensor # [blocks, block, head_dim] fp8, shared block ids + g_in: torch.Tensor + w_qkv: torch.Tensor + s_qkv: torch.Tensor + g_q: torch.Tensor + g_k: torch.Tensor + g_iq: torch.Tensor + g_ik: torch.Tensor + cos_sin: torch.Tensor + w_o: torch.Tensor + s_o: torch.Tensor + g_post: torch.Tensor + gate: torch.Tensor + bias: torch.Tensor + w13: torch.Tensor + s13: torch.Tensor + w2: torch.Tensor + s2: torch.Tensor + # the separate MXFP8 shared expert (``mxfp8_a_tiles``) and the int64 table of + # their addresses the kernels take (``SH_ARGS`` order); None when it is fused + sh_w13: torch.Tensor | None = None + sh_s13: torch.Tensor | None = None + sh_w2: torch.Tensor | None = None + sh_s2: torch.Tensor | None = None + sh_args: torch.Tensor | None = None + + @property + def shared_fp8(self) -> bool: + return self.sh_args is not None + + def shared_bytes(self) -> int: + """Bytes of the kernels' copy of the separate shared expert.""" + if not self.shared_fp8: + return 0 + nbytes = 0 + for t in (self.sh_w13, self.sh_s13, self.sh_w2, self.sh_s2): + assert t is not None + nbytes += t.numel() + return nbytes + + +def _ptpc_fp8_from_mxfp8( + linear, rows: int, cols: int, name: str +) -> tuple[torch.Tensor, torch.Tensor]: + """MXFP8 linear (fp8 [rows, cols], e8m0 [rows, cols/32]) -> per-channel fp8 + preshuffled (16, 16) + fp32 scale [rows], as the kernels' PTPC GEMV reads.""" + w = getattr(linear, "weight", None) + s = getattr(linear, "weight_scale", None) + _need( + w is not None and w.dtype == dtypes.fp8 and tuple(w.shape) == (rows, cols), + f"{name}: weight {None if w is None else (w.dtype, tuple(w.shape))}", + ) + _need( + s is not None and tuple(s.shape) == (rows, cols // 32), + f"{name}: scale {None if s is None else tuple(s.shape)}", + ) + assert w is not None and s is not None + bf = dequant_mxfp8_to_bf16(w.data, s.data.view(torch.uint8)) + q, scale = pertoken_quant(bf, quant_dtype=dtypes.fp8) + return ( + shuffle_weight(q, layout=(16, 16)).contiguous(), + scale.view(rows).to(torch.float32).contiguous(), + ) + + +def mxfp8_a_tiles( + linear, rows: int, cols: int, name: str +) -> tuple[torch.Tensor, torch.Tensor]: + """MXFP8 linear (fp8 [rows, cols], e8m0 [rows, cols/32]) -> its bytes in the + f8f6f4 MFMA's fp8 A order and its scales in ``e8m0_shuffle`` order. + + A 16-row x 128-k tile is 2 KiB; lane g * 16 + r of a tile holds row r's k + 16 g .. + 16 then 64 + 16 g .. + 16 (the B operand's order), 32 bytes.""" + w = getattr(linear, "weight", None) + s = getattr(linear, "weight_scale", None) + _need( + w is not None and w.dtype == dtypes.fp8 and tuple(w.shape) == (rows, cols), + f"{name}: weight {None if w is None else (w.dtype, tuple(w.shape))}", + ) + _need( + s is not None and tuple(s.shape) == (rows, cols // 32), + f"{name}: scale {None if s is None else tuple(s.shape)}", + ) + assert w is not None and s is not None + # the row-major layout the native MXFP8 linear kernel keeps; a kernel that + # preshuffles or pads would make the tiles silently wrong + _need( + not getattr(w, "is_shuffled", False) and not getattr(s, "is_shuffled", False), + f"{name}: weight preshuffled", + ) + _need(rows % 32 == 0 and cols % 256 == 0, f"{name}: shape {rows} x {cols}") + tiles = ( + w.data.contiguous() + .view(torch.uint8) + .view(rows // 16, 16, cols // 128, 2, 4, 16) + .permute(0, 2, 4, 1, 3, 5) + .contiguous() + .view(-1) + ) + scales = ( + s.data.contiguous() + .view(torch.uint8) + .view(rows // 32, 2, 16, cols // 256, 2, 4) + .permute(0, 3, 5, 2, 4, 1) + .contiguous() + .view(-1) + ) + return tiles, scales + + +def _ptpc_fp8_from_bf16( + bf: torch.Tensor, rows: int +) -> tuple[torch.Tensor, torch.Tensor]: + """bf16 [rows, cols] -> per-channel fp8 preshuffled (16, 16) + fp32 scale [rows].""" + q, scale = pertoken_quant(bf, quant_dtype=dtypes.fp8) + return ( + shuffle_weight(q, layout=(16, 16)).contiguous(), + scale.view(rows).to(torch.float32).contiguous(), + ) + + +def _build_cp_qkv( + linear, rank: int, tp_group, layer_id: int +) -> tuple[torch.Tensor, torch.Tensor]: + """The wider fused projection of indexer context parallelism: every rank's + index q head, all-gathered once at build time (``IndexHeads(TP, rank)``). + + One rank's rows (2560): q(2048) | k(128) | v(128) | index_q(128) | index_k(128) + CP rows (2944): q(2048) | k(128) | v(128) | iq_rank0..3 | index_k(128) + + The gather's list order is the TP group's rank order, which ``IndexHeads.own`` + indexes; the rank's own slot is checked against its local rows.""" + one_rows = (LOCAL_Q_HEADS + 3 + 1) * HEAD_DIM # 2560 + w = getattr(linear, "weight", None) + s = getattr(linear, "weight_scale", None) + _need( + w is not None + and w.dtype == dtypes.fp8 + and tuple(w.shape) == (one_rows, HIDDEN), + f"layer {layer_id} qkv_proj CP: weight " + f"{None if w is None else (w.dtype, tuple(w.shape))}", + ) + _need( + s is not None and tuple(s.shape) == (one_rows, HIDDEN // 32), + f"layer {layer_id} qkv_proj CP: scale {None if s is None else tuple(s.shape)}", + ) + assert w is not None and s is not None + _need( + dist.get_rank(tp_group) == rank and dist.get_world_size(tp_group) == TP, + f"layer {layer_id} qkv_proj CP: TP group rank {dist.get_rank(tp_group)}" + f" of {dist.get_world_size(tp_group)}, not {rank} of {TP}", + ) + bf = dequant_mxfp8_to_bf16(w.data, s.data.view(torch.uint8)) + + iq_start = (LOCAL_Q_HEADS + 2) * HEAD_DIM # 2304 + iq_end = iq_start + HEAD_DIM # 2432 + my_iq = bf[iq_start:iq_end].contiguous() + + all_iq = [torch.empty_like(my_iq) for _ in range(TP)] + dist.all_gather(all_iq, my_iq, group=tp_group) + _need( + torch.equal(all_iq[rank], my_iq), + f"layer {layer_id} qkv_proj CP: gathered index q heads not in rank order", + ) + + cp_bf = torch.cat([bf[:iq_start], *all_iq, bf[iq_end:]], dim=0) + cp_rows = (LOCAL_Q_HEADS + 3 + TP) * HEAD_DIM # 2944 + assert cp_bf.shape[0] == cp_rows, f"CP QKV rows {cp_bf.shape[0]} != {cp_rows}" + return _ptpc_fp8_from_bf16(cp_bf, cp_rows) + + +def _cos_sin(attn, layer_id: int) -> torch.Tensor: + t = attn.rotary_emb.cos_sin_cache + _need( + t.dim() == 2 and t.shape[1] == ROTARY_DIM, + f"layer {layer_id}: cos/sin cache {tuple(t.shape)}", + ) + if t.dtype != torch.bfloat16: + t = t.to(torch.bfloat16) + return t.contiguous() + + +def build_sparse_layer( + layer, + layer_id: int, + heads: IndexHeads = ONE_INDEX_HEAD, + rank: int = 0, + tp_group=None, +) -> SparseMoeLayer: + attn = layer.self_attn + _need( + hasattr(attn, "indexer") and layer.is_moe_layer, + f"layer {layer_id}: not sparse MoE", + ) + # the model has one index head per rank; under indexer context parallelism + # the fused projection is built wider (every rank's), see _build_cp_qkv + _need( + (attn.num_heads, attn.num_kv_heads, attn.num_idx_heads, attn.head_dim) + == (LOCAL_Q_HEADS, 1, 1, HEAD_DIM), + f"layer {layer_id}: heads " + f"{attn.num_heads}/{attn.num_kv_heads}/{attn.num_idx_heads}", + ) + _need(attn.rotary_emb.rotary_dim == ROTARY_DIM, f"layer {layer_id}: rotary_dim") + sel = attn.indexer.impl # the selection config lives on the indexer impl + _need( + (sel.topk_blocks, sel.init_blocks, sel.local_blocks, attn.skip_index_topk) + == (TOPK_BLOCKS, 0, 1, False), + f"layer {layer_id}: sparse selection config", + ) + _need( + attn.use_aiter_sparse_pa and str(attn.kv_cache_dtype).startswith("fp8"), + f"layer {layer_id}: needs the AITER sparse PA path with an fp8 KV cache", + ) + index_cache = attn.indexer.index_cache.kv_cache + _need( + index_cache.numel() > 0 + and index_cache.dtype == dtypes.fp8 + and index_cache.dim() == 3 + and index_cache.shape[2] == HEAD_DIM + and index_cache.is_contiguous(), + f"layer {layer_id}: index cache {index_cache.dtype} {tuple(index_cache.shape)}", + ) + + if heads.count > 1: + _need(tp_group is not None, f"layer {layer_id}: CP requires tp_group") + w_qkv, s_qkv = _build_cp_qkv(attn.qkv_proj, rank, tp_group, layer_id) + else: + w_qkv, s_qkv = _ptpc_fp8_from_mxfp8( + attn.qkv_proj, heads.rows, HIDDEN, f"layer {layer_id} qkv_proj" + ) + + w_o, s_o = _ptpc_fp8_from_mxfp8( + attn.o_proj, HIDDEN, O_K, f"layer {layer_id} o_proj" + ) + + moe = layer.block_sparse_moe + # FusedMoEFactory returns a MoERunner wrapping the RoutedExperts module + experts = getattr(moe.experts, "routed_experts", moe.experts) + fused = moe.is_fused_shared_expert_enabled + E = N_ROUTED + 1 if fused else N_ROUTED + w13, w2 = experts.w13_weight, experts.w2_weight + _need( + w13.shape[0] == E, + f"layer {layer_id}: {'fused' if fused else 'separate'} shared expert " + f"(experts {w13.shape[0]})", + ) + shared = {} + if not fused: + mlp = moe.shared_experts + _need(mlp is not None, f"layer {layer_id}: no shared expert") + shared["sh_w13"], shared["sh_s13"] = mxfp8_a_tiles( + mlp.gate_up_proj, 2 * INTER, HIDDEN, f"layer {layer_id} shared gate_up" + ) + shared["sh_w2"], shared["sh_s2"] = mxfp8_a_tiles( + mlp.down_proj, HIDDEN, INTER, f"layer {layer_id} shared down" + ) + shared["sh_args"] = torch.tensor( + [shared[a].data_ptr() for a in SH_ARGS], + dtype=torch.int64, + device=shared["sh_w13"].device, + ) + _need(experts.top_k == TOP_K, f"layer {layer_id}: top_k {experts.top_k}") + _need( + getattr(w13, "is_shuffled", False) and getattr(w2, "is_shuffled", False), + f"layer {layer_id}: experts not in aiter shuffled layout", + ) + _need( + w13.numel() * w13.element_size() == E * 2 * INTER * HIDDEN // 2 + and w2.numel() * w2.element_size() == E * HIDDEN * INTER // 2, + f"layer {layer_id}: expert weight bytes", + ) + s13, s2 = experts.w13_weight_scale, experts.w2_weight_scale + _need( + s13.numel() == E * 2 * INTER * HIDDEN // 32 + and s2.numel() == E * HIDDEN * INTER // 32, + f"layer {layer_id}: expert scale bytes", + ) + gate = moe.gate.weight.data + _need(tuple(gate.shape) == (N_ROUTED, HIDDEN), f"layer {layer_id}: gate") + bias = moe.e_score_correction_bias + _need( + bias is not None and bias.dtype == torch.float32 and bias.numel() == N_ROUTED, + f"layer {layer_id}: bias", + ) + return SparseMoeLayer( + layer_id=layer_id, + attn=attn, + index_cache=index_cache, + g_in=_bf16_vec(layer.input_layernorm.weight, HIDDEN, "input_layernorm"), + w_qkv=w_qkv, + s_qkv=s_qkv, + g_q=_bf16_vec(attn.q_norm.weight, HEAD_DIM, "q_norm"), + g_k=_bf16_vec(attn.k_norm.weight, HEAD_DIM, "k_norm"), + g_iq=_bf16_vec(attn.index_q_norm.weight, HEAD_DIM, "index_q_norm"), + g_ik=_bf16_vec(attn.index_k_norm.weight, HEAD_DIM, "index_k_norm"), + cos_sin=_cos_sin(attn, layer_id), + w_o=w_o, + s_o=s_o, + g_post=_bf16_vec( + layer.post_attention_layernorm.weight, HIDDEN, "post_attention_layernorm" + ), + gate=gate.to(torch.bfloat16).contiguous(), + bias=bias.data, + w13=w13.data, + s13=s13.data, + w2=w2.data, + s2=s2.data, + **shared, + ) diff --git a/vllm/models/minimax_m3/amd/ops/flydsl_utils.py b/vllm/models/minimax_m3/amd/ops/flydsl_utils.py new file mode 100644 index 000000000000..890ab3714e74 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/flydsl_utils.py @@ -0,0 +1,196 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Helpers shared by the MiniMax-M3 FlyDSL kernels (gfx950).""" + +import functools + +import flydsl.expr as fx +import torch +from flydsl._mlir import ir +from flydsl._mlir.dialects import arith, llvm +from flydsl.expr import rocdl +from flydsl.expr.typing import T +from flydsl.expr.typing import Vector as Vec + +# Cache-policy bits of buffer loads and stores: sc1 is coherent across the XCDs' +# L2s, sc0 | sc1 across the system, nt streams. +SC0, NT, SC1 = 0x1, 0x2, 0x10 +LOG2E = 1.4426950409 # softmax runs in exp2 +# The first 16 dwords of kernel arguments arrive in SGPRs, so a kernel's first +# loads do not wait for s_load. +PRELOAD_HINTS = { + "llvm_options": { + "amdgpu-kernarg-preload": True, + "amdgpu-kernarg-preload-count": 16, + } +} + + +def run_compiled(exe, *args, waves_per_eu: int | None = None): + """Compiles and runs ``exe`` on the first call, then dispatches the cache.""" + import flydsl.compiler as flyc + from flydsl.compiler.kernel_function import CompilationContext + + cf = getattr(exe, "_cf", None) + if cf is None: + hints = {"waves_per_eu": waves_per_eu} if waves_per_eu else {} + with CompilationContext.compile_hints(hints): + exe._cf = flyc.compile(exe, *args) + else: + cf(*args) + + +@functools.cache +def cu_count(device: torch.device) -> int: + return torch.cuda.get_device_properties(device).multi_processor_count + + +@functools.cache +def unit_scale(device: torch.device) -> torch.Tensor: + return torch.ones(1, dtype=torch.float32, device=device) + + +def global_i32_ptr(addr_i64): + ptr_ty = fx.PointerType.get( + T.i32, address_space=fx.AddressSpace.Global, alignment=4 + ) + return fx.inttoptr(ptr_ty, fx.Int64(addr_i64)) + + +def bits(x): + return fx.Float32(x).bitcast(fx.Int32) + + +def as_f32(x): + return fx.Int32(x).bitcast(fx.Float32) + + +def permlane_swap(op, d_a, d_b): + """v_permlane{16,32}_swap; fx has no wrapper.""" + pair_ty = ir.Type.parse("!llvm.struct<(i32, i32)>") + res = op(pair_ty, fx.as_ir_value(d_a), fx.as_ir_value(d_b), False, False) + return ( + fx.Int32(llvm.extractvalue(T.i32, res, [0])), + fx.Int32(llvm.extractvalue(T.i32, res, [1])), + ) + + +def maxf_nn(a, b): + """v_max_f32 with nnan; without it LLVM canonicalizes both inputs first.""" + fm = ir.Attribute.parse("#arith.fastmath") + return fx.Float32( + arith.MaxNumFOp(fx.as_ir_value(a), fx.as_ir_value(b), fastmath=fm).result + ) + + +def xlane4(x, op): + """``op`` over lanes L, L^16, L^32, L^48, broadcast to all four.""" + a, b = permlane_swap(rocdl.permlane32_swap, bits(x), bits(x)) + m = op(as_f32(a), as_f32(b)) + a, b = permlane_swap(rocdl.permlane16_swap, bits(m), bits(m)) + return op(as_f32(a), as_f32(b)) + + +def perm(hi, lo, sel): + """v_perm_b32: byte i of the result is byte sel_i of (hi:lo).""" + return fx.Int32(rocdl.perm_b32(fx.Int32(hi), fx.Int32(lo), fx.Int32(sel))) + + +def exp2(x): + """v_exp_f32 without denormal range reduction.""" + return fx.Float32(fx.rocdl.exp2(fx.Float32.ir_type, fx.Float32(x).ir_value())) + + +def pk_bf16(a, b): + """Two fp32 -> one dword of two bf16 (RNE), ``a`` low.""" + return fx.Int32( + fx.rocdl.cvt_pk_bf16_f32( + fx.as_ir_value(fx.Float32(a)), fx.as_ir_value(fx.Float32(b)) + ) + ) + + +def pk_f16(a, b): + """Two fp32 -> one dword of two fp16 (RNE), ``a`` low.""" + return ( + Vec.from_elements([fx.Float32(a), fx.Float32(b)], fx.Float32) + .to(fx.Float16) + .bitcast(fx.Int32)[0] + ) + + +def cvt_fp4x2_f16(word, sel): + """The two e2m1 codes of byte ``sel`` of ``word`` as two fp16 (exact).""" + return Vec( + fx.rocdl.cvt_scalef32_pk_f16_fp4( + Vec.make_type(2, fx.Float16), + fx.as_ir_value(fx.Int32(word)), + fx.as_ir_value(fx.Float32(1.0)), + sel, + ) + ) + + +def cvt_fp8x2_f16(word, hi): + """E4M3 bytes 0, 1 (``hi``: 2, 3) of ``word`` as two fp16 (exact).""" + return Vec( + fx.rocdl.cvt_scalef32_pk_f16_fp8( + Vec.make_type(2, fx.Float16), + fx.as_ir_value(fx.Int32(word)), + fx.as_ir_value(fx.Float32(1.0)), + hi, + ) + ) + + +def mfma_16x16x32(a4, b4, acc, fp16: bool): + """v_mfma_f32_16x16x32_{bf16,f16} on 4-dword operands.""" + dtype = fx.Float16 if fp16 else fx.BFloat16 + op = fx.rocdl.mfma_f32_16x16x32_f16 if fp16 else fx.rocdl.mfma_f32_16x16x32_bf16 + a = Vec(a4).bitcast(dtype) + b = Vec(b4).bitcast(dtype) + return Vec(op(Vec.make_type(4, fx.Float32), [a, b, acc, 0, 0, 0])) + + +def mfma_fp8_16x16x128(a8, b8, acc4): + """v_mfma_f32_16x16x128_f8f6f4 on e4m3 operands; zero scales select the + unscaled instruction.""" + return Vec( + fx.rocdl.mfma_scale_f32_16x16x128_f8f6f4( + Vec.make_type(4, fx.Float32), [a8, b8, acc4, 0, 0, 0, 0, 0, 0] + ) + ) + + +def pack8(h0, h1): + """Two 4 x i32 halves -> the 8 x i32 operand of the fp8 16x16x128 MFMA.""" + a, b = Vec(h0), Vec(h1) + return Vec.from_elements( + [a[k] for k in range(4)] + [b[k] for k in range(4)], fx.Int32 + ) + + +# Byte selectors of the even and odd dims in key order. +PERM_EVEN, PERM_ODD = 0x06040200, 0x07050301 + + +def key_order4(d): + """4 dwords of e4m3 (16 dims) -> even dims, then odd dims per 8 (key order).""" + return Vec.from_elements( + [ + perm(d[1], d[0], PERM_EVEN), + perm(d[1], d[0], PERM_ODD), + perm(d[3], d[2], PERM_EVEN), + perm(d[3], d[2], PERM_ODD), + ], + fx.Int32, + ) + + +def dequant8(c, t_lo, t_hi): + """8 e2m1 codes (low nibble the even dim) and the group's e4m3 table -> + the e4m3 keys of the even dims, then of the odd dims.""" + ml = perm(t_hi, t_lo, c & fx.Int32(0x07070707)) + mh = perm(t_hi, t_lo, (c >> 4) & fx.Int32(0x07070707)) + sign = fx.Int32(0x80808080 - (1 << 32)) + return ml ^ ((c << 4) & sign), mh ^ (c & sign) diff --git a/vllm/models/minimax_m3/amd/ops/index_cp/__init__.py b/vllm/models/minimax_m3/amd/ops/index_cp/__init__.py new file mode 100644 index 000000000000..208f01a7cb5e --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/index_cp/__init__.py @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project diff --git a/vllm/models/minimax_m3/amd/ops/index_cp/host.py b/vllm/models/minimax_m3/amd/ops/index_cp/host.py new file mode 100644 index 000000000000..91ecd0646f80 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/index_cp/host.py @@ -0,0 +1,126 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Buffers of the context-parallel decode indexer (TP4, gfx950). + +Rank ``me`` holds index head ``me``; ``kernel_cp_push`` scores a quarter of every +request's blocks for all four heads and stores head h's scores into rank h's +receive buffer. Buffers and flags are uncached memory mapped by the peers; the +call counts stay on the device, so the handshake replays in CUDA graphs. +""" + +import torch +import torch.distributed as dist + +from vllm.distributed.device_communicators.custom_all_reduce import CustomAllreduce +from vllm.models.minimax_m3.amd.ops.nvfp4_index_decode import ( + kernel_cp_push as _kernel, +) + +WORLD = _kernel.WORLD + + +class _DevicePointer: + """A raw device allocation as a tensor (``__cuda_array_interface__``).""" + + def __init__(self, ptr: int, nbytes: int): + self.__cuda_array_interface__ = { + "shape": (nbytes,), + "typestr": "|u1", + "data": (ptr, False), + "version": 3, + } + + +class IndexCP: + def __init__( + self, rank: int, group, device: torch.device, max_rows: int, max_width: int + ): + self.rank, self.device = rank, device + self.max_rows, self.max_width = max_rows, max_width + score_bytes = max_rows * max_width * 4 + iq_bytes = WORLD * max_rows * _kernel.D + # Each rank's buffer, mapped by every peer (uncached on ROCm). + self.score_ptrs, self.iq_ptrs, self.flag_ptrs = ( + CustomAllreduce.create_shared_buffer(n, group=group) + for n in (score_bytes, iq_bytes, _kernel.FLAG_BYTES) + ) + self.score_rcv = torch.as_tensor( + _DevicePointer(self.score_ptrs[rank], score_bytes), device=device + ).view(torch.float32) + flags = torch.as_tensor( + _DevicePointer(self.flag_ptrs[rank], _kernel.FLAG_BYTES), device=device + ) + flags.zero_() + # Call counts (the flag values), equal on every rank. + self.counts = torch.zeros(_kernel.CNT_WORDS, dtype=torch.int32, device=device) + torch.accelerator.synchronize(device) + dist.barrier(group=group) + + def score_push( + self, + iq: torch.Tensor, + index_cache: torch.Tensor, + block_table: torch.Tensor, + seq_lens: torch.Tensor, + init_blocks: int, + local_blocks: int, + width: int, + grid: int = 0, + ) -> torch.Tensor: + """Score this rank's blocks of every head from its index-q rows ``iq``. + + Returns this rank's head over every block, [1, rows, width]: a view of + the receive buffer, valid until the next call. + """ + from vllm.models.minimax_m3.amd.ops.nvfp4_index_decode.host import ( + minimax_m3_nvfp4_index_score_push_cp, + ) + + rows = iq.shape[0] + assert rows <= self.max_rows and width <= self.max_width + minimax_m3_nvfp4_index_score_push_cp( + iq, + index_cache, + self.score_ptrs, + width, + rows * width * 4, + block_table, + seq_lens, + init_blocks, + local_blocks, + self.rank, + self.counts, + self.flag_ptrs, + self.iq_ptrs, + self.max_rows, + grid=grid, + ) + return self.score_rcv[: rows * width].view(1, rows, width) + + +# None means the single-head decode path. +_CP: IndexCP | None = None + + +def init(device: torch.device, max_width: int) -> None: + """Create this rank's ``IndexCP``; a collective, called once outside capture.""" + global _CP + if _CP is not None: + return + from vllm.config import get_current_vllm_config + from vllm.distributed import get_tp_group + from vllm.platforms.rocm import on_gfx950 + + tp = get_tp_group() + # One set of buffers and flags: microbatches would share them. + if ( + tp.world_size != WORLD + or not on_gfx950() + or get_current_vllm_config().parallel_config.use_ubatching + ): + return + _CP = IndexCP(tp.rank_in_group, tp.cpu_group, device, _kernel.MAX_ROWS, max_width) + + +def get() -> IndexCP | None: + return _CP diff --git a/vllm/models/minimax_m3/amd/ops/index_topk_decode/__init__.py b/vllm/models/minimax_m3/amd/ops/index_topk_decode/__init__.py new file mode 100644 index 000000000000..208f01a7cb5e --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/index_topk_decode/__init__.py @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project diff --git a/vllm/models/minimax_m3/amd/ops/index_topk_decode/host.py b/vllm/models/minimax_m3/amd/ops/index_topk_decode/host.py new file mode 100644 index 000000000000..f3669b733c96 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/index_topk_decode/host.py @@ -0,0 +1,113 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Launch wrappers of the FlyDSL index top-k: the block ids AITER's +``pa_sparse_block_topk`` selects, in its order.""" + +import functools + +import torch + +from vllm.models.minimax_m3.amd.ops.flydsl_utils import ( + run_compiled, +) + +from . import prefill_kernel as _kernel + +MAX_SLOTS = 128 # AITER's TOPK_MAX_SLOTS: 8192 blocks + + +def _pow2_ceil(n: int) -> int: + return 1 << (n - 1).bit_length() if n >= 1 else 1 + + +@functools.lru_cache(maxsize=len(_kernel.PREFILL_STRIPS)) +def _get_prefill_kernel(strips: int): + return _kernel.compile_topk_prefill(strips) + + +@functools.lru_cache(maxsize=1) +def _get_decode_kernel(): + return _kernel.compile_topk_prefill(26, decode=True) + + +def supports_index_topk(topk_blocks: int, block_size: int) -> bool: + from vllm.platforms.rocm import on_gfx950 + + return on_gfx950() and topk_blocks == _kernel.TOPK and block_size == _kernel.BLK + + +def _check(score: torch.Tensor, topk_idx: torch.Tensor, max_seq_len: int) -> int: + """Validate the layouts; returns the score columns the kernel walks.""" + heads, rows, width = score.shape + assert score.dtype == torch.float32 and score.stride(2) == 1 + assert topk_idx.dtype == torch.int32 and topk_idx.stride(2) == 1 + assert topk_idx.shape == (heads, rows, _kernel.TOPK) + slots = _pow2_ceil((max_seq_len + _kernel.BLK * 64 - 1) // (_kernel.BLK * 64)) + assert slots <= MAX_SLOTS and width >= slots * 64 + return slots * 64 + + +def minimax_m3_index_topk_prefill_indices( + score: torch.Tensor, # [H, rows, S] fp32 + topk_idx: torch.Tensor, # [H, rows, 16] int32 + *, + max_seq_len: int, + num_valid_pages: torch.Tensor, # [>= rows] int32: row n's visible blocks +) -> None: + """Top-16 blocks of ragged prefill rows.""" + heads, rows, _ = score.shape + cols = _check(score, topk_idx, max_seq_len) + assert num_valid_pages.dtype == torch.int32 + assert num_valid_pages.is_contiguous() and num_valid_pages.numel() >= rows + if rows == 0: + return + tiles = _kernel.PREFILL_STRIPS + strips = next((s for s in tiles if max_seq_len <= s * _kernel.BLK * 64), tiles[-1]) + run_compiled( + _get_prefill_kernel(strips), + score.data_ptr(), + score.stride(0), + score.stride(1), + cols, + num_valid_pages.data_ptr(), + 1, + topk_idx.data_ptr(), + topk_idx.stride(0), + topk_idx.stride(1), + rows, + heads, + torch.cuda.current_stream(), + ) + + +def minimax_m3_index_topk_decode_indices( + score: torch.Tensor, # [H, num_reqs * query_len, S] fp32 + topk_idx: torch.Tensor, # [H, num_reqs * query_len, 16] int32 + seq_lens: torch.Tensor, # [>= num_reqs] int32 + *, + max_seq_len: int, + query_len: int, +) -> None: + """Top-16 blocks of decode rows, ``query_len`` rows per request.""" + heads, rows, _ = score.shape + cols = _check(score, topk_idx, max_seq_len) + assert query_len > 0 and rows % query_len == 0 + assert seq_lens.dtype == torch.int32 and seq_lens.is_contiguous() + assert seq_lens.numel() >= rows // query_len + if rows == 0: + return + run_compiled( + _get_decode_kernel(), + score.data_ptr(), + score.stride(0), + score.stride(1), + cols, + seq_lens.data_ptr(), + query_len, + topk_idx.data_ptr(), + topk_idx.stride(0), + topk_idx.stride(1), + rows, + heads, + torch.cuda.current_stream(), + ) diff --git a/vllm/models/minimax_m3/amd/ops/index_topk_decode/prefill_kernel.py b/vllm/models/minimax_m3/amd/ops/index_topk_decode/prefill_kernel.py new file mode 100644 index 000000000000..b18db79e055a --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/index_topk_decode/prefill_kernel.py @@ -0,0 +1,387 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Index top-k for MiniMax-M3 (FlyDSL, gfx950). + +One 64-lane workgroup per (row, head) returns the 16 highest-scoring block ids +in AITER's order, walking the row in windows of STRIPS x 64 blocks. +""" + +import flydsl.compiler as flyc +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import buffer_ops +from flydsl.expr import const_expr, range_constexpr +from flydsl.expr.typing import T +from flydsl.expr.typing import Vector as Vec + +from vllm.models.minimax_m3.amd.ops.flydsl_utils import PRELOAD_HINTS + +BLK = 128 # tokens per block +TOPK = 16 +PREFILL_STRIPS = (4, 8, 16, 20, 26) +CAP = 64 # candidates one rank pass holds (one per lane) +IDX_BITS = 13 # block index bits (slots * 64 <= 8192) +INT_MIN = -(1 << 31) +KEY_NEG_INF = (0xFF800000 ^ 0x7FFFFFFF) - (1 << 32) # signed key of -inf (NaN's) +KEY_POS_INF = 0x7F800000 + + +def _s32(v): + v &= 0xFFFFFFFF + return v - (1 << 32) if v >= 1 << 31 else v + + +def _key(bits): + """Signed key in AITER's order; NaNs land above +inf or below -inf.""" + return bits ^ ((bits >> 31) & 0x7FFFFFFF) + + +def _fold_nan(k): + return ((k > KEY_POS_INF) | (k < KEY_NEG_INF)).select(fx.Int32(KEY_NEG_INF), k) + + +def _ballot(c): + return fx.Int64(fx.rocdl.ballot(T.i64, c)) + + +def _popc(m): + """Set bits of a wave mask; two 32-bit counts keep the compare scalar.""" + lo = fx.math.ctpop(m.to(fx.Int32)).to(fx.Int32) + hi = fx.math.ctpop((m >> 32).to(fx.Int32)).to(fx.Int32) + return fx.Int32(lo) + fx.Int32(hi) + + +def _below(mask, base): + """The set bits of ``mask`` below this lane, plus ``base`` (v_mbcnt).""" + lo = mask.to(fx.Int32) + hi = (mask >> 32).to(fx.Int32) + r = fx.rocdl.mbcnt_lo(T.i32, lo.ir_value(), fx.Int32(base).ir_value()) + return fx.Int32(fx.rocdl.mbcnt_hi(T.i32, hi.ir_value(), r)) + + +def _imax(a, b): + return (a > b).select(a, b) + + +def _one(c): + return c.select(fx.Int32(1), fx.Int32(0)) + + +def _comp(k, i): + """(key, index) as one i64 whose signed order is AITER's.""" + return (k.to(fx.Int64) << 32) | (i.to(fx.Int64) & 0xFFFFFFFF) + + +def compile_topk_prefill(strips: int, *, decode: bool = False): + assert strips == 26 if decode else strips in PREFILL_STRIPS + STRIPS = strips + WIN = STRIPS * 64 + RANK_BLOCK = 8 + # Candidates, rank-loop padding, then one discard slot per lane. + TRASH = CAP + RANK_BLOCK + CAND = TRASH + 64 + name = f"m3_index_topk_{'decode' if decode else 'prefill'}_indices_w{STRIPS}" + + @fx.struct + class Shared: + cand: fx.Array[fx.Int32, 2 * CAND, 16] + sel: fx.Array[fx.Int32, 4 * TOPK, 16] + + @flyc.kernel(name=name, known_block_size=[64, 1, 1]) + def kernel( + arg_score: fx.Int64, + i64_s_head: fx.Int64, + i64_s_row: fx.Int64, + i32_width: fx.Int32, + arg_nvp: fx.Int64, + i32_query_len: fx.Int32, + arg_topk: fx.Int64, + i64_t_head: fx.Int64, + i64_t_row: fx.Int64, + ): + smem = fx.SharedAllocator().allocate(Shared).peek() + n, h = fx.block_idx.x, fx.block_idx.y + lane = fx.thread_idx.x + n64 = fx.Int32(n).to(fx.Int64) + h64 = fx.Int32(h).to(fx.Int64) + + def rsrc(base, nbytes): + """Buffer at an i64 base; per-row rebasing keeps offsets small.""" + return buffer_ops.create_buffer_resource_from_addr( + base, num_records_bytes=fx.Int64(nbytes) + ) + + # Reads past the row's width return 0. + score_row = arg_score + (h64 * i64_s_head + n64 * i64_s_row) * 4 + srs = rsrc(score_row, i32_width.to(fx.Int64) * 4) + + def load_window(srs, wbase): + return Vec.from_elements( + [ + fx.Int32( + buffer_ops.buffer_load( + srs, + wbase + (j * 64) + lane, + vec_width=1, + dtype=fx.Int32, + ) + ) + for j in range_constexpr(STRIPS) + ], + fx.Int32, + ) + + # The first window is loaded before the row's length is known. + bits = load_window(srs, 0) + + def scalar_at(base, idx64, nbytes): + return fx.Int32( + buffer_ops.buffer_load( + rsrc(base + idx64 * 4, nbytes), + fx.Int32(0), + vec_width=1, + is_scalar=True, + ) + ) + + if const_expr(decode): + req = (fx.Int32(n) // i32_query_len).to(fx.Int64) + seq = scalar_at(arg_nvp, req, fx.Int64(4)) + kv0 = seq - i32_query_len + fx.Int32(n) % i32_query_len + 1 + kv = (kv0 < 0).select(fx.Int32(0), kv0) + nblk = (kv + BLK - 1) // BLK + else: + nblk = scalar_at(arg_nvp, n64, fx.Int64(4)) + nlive = (nblk < i32_width).select(nblk, i32_width) + # Later windows read only the row's live blocks. + srs_live = rsrc(score_row, nlive.to(fx.Int64) * 4) + + def view(ptr, n_dw, width): + return fx.logical_divide( + fx.make_view(fx.recast_iter(fx.Int32, ptr), fx.make_layout(n_dw, 1)), + fx.make_layout(width, 1), + ) + + pairs = view(smem.cand.ptr, 2 * CAND, 2) + quads = view(smem.cand.ptr, 2 * CAND, 4) + sels = view(smem.sel.ptr, 4 * TOPK, 4) + atom64 = fx.make_copy_atom(fx.UniversalCopy64b(), fx.Int32) + atom128 = fx.make_copy_atom(fx.UniversalCopy128b(), fx.Int32) + + def lds_put(atom, v, w, vals): + r = fx.make_rmem_tensor(fx.make_layout(w, 1), fx.Int32) + r.store(Vec.from_elements(vals, fx.Int32)) + fx.copy(atom, r, v) + + def lds_get(atom, v, w): + r = fx.make_rmem_tensor(fx.make_layout(w, 1), fx.Int32) + fx.copy(atom, v, r) + x = Vec(r.load()) + return [fx.Int32(x[e]) for e in range_constexpr(w)] + + def put_pair(pos, i, k): + lds_put(atom64, fx.slice(pairs, (None, pos)), 2, [i, k]) + + def wave_sum(c): + """Sum over the wave of a per-lane count in [0, 63].""" + t = fx.Int32(0) + for b in range_constexpr(6): + t = t + (_popc(_ballot((c & (1 << b)) != 0)) << b) + return t + + def compact(keys, wbase, base, pred): + """Append the keys ``pred`` keeps at ``base`` if they fit below CAP.""" + oks = [ + _one(pred(keys[j], wbase + (j * 64) + lane)) + for j in range_constexpr(STRIPS) + ] + cnt = oks[0] + for j in range_constexpr(1, STRIPS): + cnt = cnt + oks[j] + pos = fx.Int32(base) + end = fx.Int32(base) + for b in range_constexpr(6): # cnt <= 32 + bm = _ballot((cnt & (1 << b)) != 0) + pos = pos + (_below(bm, 0) << b) + end = end + (_popc(bm) << b) + # On overflow nothing is written; the caller rebuilds the candidates. + if end <= CAP: + for j in range_constexpr(STRIPS): + put_pair( + (oks[j] != 0).select(pos, TRASH + lane), + wbase + (j * 64) + lane, + keys[j], + ) + pos = pos + oks[j] + return end + + def exact_cut(keys, wbase): + """The window's 16th key v and the index cut ie among the keys tied + with it: (k > v) | (k == v & i >= ie) keeps exactly its top 16.""" + pe = fx.Int32(0) + b = fx.Int32(31) + while b >= 0: + t = (pe | (fx.Int32(1) << b)) ^ INT_MIN + c = fx.Int32(0) + for j in range_constexpr(STRIPS): + c = c + _one(keys[j] >= t) + pe = (wave_sum(c) >= TOPK).select(t ^ INT_MIN, pe) + b = b - 1 + v = pe ^ INT_MIN + c = fx.Int32(0) + for j in range_constexpr(STRIPS): + c = c + _one(keys[j] > v) + need = TOPK - wave_sum(c) + ie = fx.Int32(0) + b = fx.Int32(IDX_BITS - 1) + while b >= 0: + t = ie | (fx.Int32(1) << b) + c = fx.Int32(0) + for j in range_constexpr(STRIPS): + c = c + _one((keys[j] == v) & ((wbase + (j * 64) + lane) >= t)) + ie = (wave_sum(c) >= need).select(t, ie) + b = b - 1 + return v, ie + + def lane_max_bound(m): + p = fx.Int32(0) + for d in range_constexpr(12): + t = p | _s32(1 << (31 - d)) + count = _popc(_ballot(m >= (t ^ INT_MIN))) + p = (count >= TOPK).select(t, p) + return p ^ INT_MIN + + def window(bits, wbase, nrun, tprev): + """One window of keys merged into the running top 16 (sel).""" + keys = [] + for j in range_constexpr(STRIPS): + live = (wbase + (j * 64) + lane) < nlive + keys.append(live.select(_key(bits[j]), fx.Int32(INT_MIN))) + m = keys[0] + for j in range_constexpr(1, STRIPS): + m = _imax(m, keys[j]) + # Bound: the lane maxima in the first window, the running 16th later. + tw = fx.Int32(INT_MIN) + if nrun < TOPK: + tw = lane_max_bound(m) + ta = _imax(tw, tprev) + total = compact(keys, wbase, nrun, lambda k, i: k >= ta) + # Exact only if 16 keys above -inf bound it and no NaN is above +inf. + nan_hi = _ballot(m > KEY_POS_INF) != fx.Int64(0) + if (total > CAP) | (ta <= KEY_NEG_INF) | nan_hi: + wl = nlive - wbase + if wl <= CAP - nrun: + # Every live block of the window is a candidate. + put_pair( + (lane < wl).select(nrun + lane, TRASH + lane), + wbase + lane, + _fold_nan(keys[0]), + ) + total = nrun + wl + else: + # NaNs to -inf and re-bound; exact search if still too many. + fixed = [] + for j in range_constexpr(STRIPS): + live = (wbase + (j * 64) + lane) < nlive + fixed.append(live.select(_fold_nan(keys[j]), fx.Int32(INT_MIN))) + mf = fixed[0] + for j in range_constexpr(1, STRIPS): + mf = _imax(mf, fixed[j]) + tf = _imax(lane_max_bound(mf), tprev) + total = compact(fixed, wbase, nrun, lambda k, i: k >= tf) + if total > CAP: + v, ie = exact_cut(fixed, wbase) + total = compact( + fixed, + wbase, + nrun, + lambda k, i: (k > v) | ((k == v) & (i >= ie)), + ) + if lane < RANK_BLOCK: + put_pair(total + lane, fx.Int32(0), fx.Int32(INT_MIN)) + fx.gpu.barrier() + mi, mk = lds_get(atom64, fx.slice(pairs, (None, lane)), 2) + mw = _comp(mk, mi) + rank = fx.Int32(0) + for g in range_constexpr(CAP // RANK_BLOCK): + if total > RANK_BLOCK * g: + es = [ + lds_get( + atom128, fx.slice(quads, (None, RANK_BLOCK // 2 * g + u)), 4 + ) + for u in range_constexpr(RANK_BLOCK // 2) + ] + # All of a block's reads in flight before the compares. + fx.rocdl.sched_barrier(0) + for e in es: + rank = rank + _one(_comp(e[1], e[0]) > mw) + rank = rank + _one(_comp(e[3], e[2]) > mw) + if (lane < total) & (rank < TOPK): + lds_put(atom128, fx.slice(sels, (None, rank)), 4, [mi, mk, 0, mi]) + return (total < TOPK).select(total, fx.Int32(TOPK)) + + wbase = fx.Int32(0) + nrun = fx.Int32(0) + tprev = fx.Int32(INT_MIN + 1) # dead keys are INT_MIN + while (wbase == 0) | (wbase < nlive): + if wbase > 0: + bits = load_window(srs_live, wbase) + # The running top 16 back into cand; its 16th key bounds the window. + fx.gpu.barrier() + r = lds_get(atom128, fx.slice(sels, (None, lane & (TOPK - 1))), 4) + if lane < nrun: + put_pair(lane, r[0], r[1]) + k15 = fx.Int32(fx.rocdl.readlane(T.i32, r[1], fx.Int32(TOPK - 1))) + tprev = (nrun >= TOPK).select(k15, fx.Int32(INT_MIN + 1)) + fx.gpu.barrier() + nrun = window( + [fx.Int32(bits[j]) for j in range_constexpr(STRIPS)], + wbase, + nrun, + tprev, + ) + wbase = wbase + WIN + + fx.gpu.barrier() + r = lds_get(atom128, fx.slice(sels, (None, lane & (TOPK - 1))), 4) + blk = (lane < nrun).select(r[0], fx.Int32(-1)) + buffer_ops.buffer_store( + blk, + rsrc(arg_topk + (h64 * i64_t_head + n64 * i64_t_row) * 4, TOPK * 4), + lane, + mask=lane < TOPK, + ) + + @flyc.jit + def launch( + arg_score: fx.Int64, + i64_s_head: fx.Int64, + i64_s_row: fx.Int64, + i32_width: fx.Int32, + arg_nvp: fx.Int64, + i32_query_len: fx.Int32, + arg_topk: fx.Int64, + i64_t_head: fx.Int64, + i64_t_row: fx.Int64, + i32_rows: fx.Int32, + i32_heads: fx.Int32, + stream: fx.Stream, + ): + kernel( + arg_score, + i64_s_head, + i64_s_row, + i32_width, + arg_nvp, + i32_query_len, + arg_topk, + i64_t_head, + i64_t_row, + ).launch( + grid=(fx.Int64(i32_rows), fx.Int64(i32_heads), 1), + block=(64, 1, 1), + stream=stream, + ) + + launch.kernel_name = name + launch.compile_hints = PRELOAD_HINTS + return launch diff --git a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/__init__.py b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/__init__.py new file mode 100644 index 000000000000..eebdf8490751 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/__init__.py @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Routing, launch and memory helpers for MiniMax-M3 FlyDSL MoE kernels.""" diff --git a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/epilogue.py b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/epilogue.py new file mode 100644 index 000000000000..c10b2f0dbbb6 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/epilogue.py @@ -0,0 +1,72 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MiniMax-M3 FlyDSL MoE epilogue helpers.""" + +import flydsl.expr as fx +from flydsl._mlir import ir as _ir +from flydsl._mlir.dialects import arith as _arith +from flydsl._mlir.dialects import llvm as _llvm +from flydsl.expr.typing import T as _T +from flydsl.expr.typing import Vector as Vec + +from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.loaders import _lds_ptr_t + +_NUM_XCDS = 8 + + +def _lds_ptr(addr_i32): + return _llvm.inttoptr(_lds_ptr_t(), fx.as_ir_value(addr_i32)) + + +def _lds_load_vec(addr_i32, n): + ty = _ir.VectorType.get([n], _T.i32) + return _llvm.LoadOp(ty, _lds_ptr(addr_i32), alignment=4 * n).result + + +def _lds_store_vec(vec, addr_i32, n): + _llvm.StoreOp(vec, _lds_ptr(addr_i32), alignment=4 * n) + + +def _bf16x2(a, b): + """Two f32 -> one i32 of 2 bf16 (RNE, v_cvt_pk_bf16_f32).""" + return Vec.from_elements([a, b], fx.Float32).to(fx.BFloat16).bitcast(fx.Int32)[0] + + +def _cvt_pk_fp8(old, a, b, scale_f32, hi: bool): + """(a, b) / scale -> 2 x e4m3 into the low or high (``hi``) 16 bits of ``old``.""" + v2i16 = _ir.VectorType.get([2], _ir.IntegerType.get_signless(16)) + old_v = _llvm.bitcast(v2i16, fx.as_ir_value(old)) + res = _llvm.call_intrinsic( + v2i16, + "llvm.amdgcn.cvt.scalef32.pk.fp8.f32", + [ + old_v, + fx.as_ir_value(a), + fx.as_ir_value(b), + fx.as_ir_value(scale_f32), + fx.Boolean(hi).ir_value(), + ], + [], + [], + ) + return fx.Int32(_llvm.bitcast(_T.i32, res)) + + +def _maxf_nn(a, b): + """Max with nnan: else LLVM canonicalizes both inputs first (2 extra VALU).""" + fm = _ir.Attribute.parse("#arith.fastmath") + return fx.Float32( + _arith.MaxNumFOp(fx.as_ir_value(a), fx.as_ir_value(b), fastmath=fm).result + ) + + +def _undef_i32(): + """Cvt destination whose other half is overwritten: saves a v_mov 0.""" + return _llvm.mlir_undef(_T.i32) + + +def _v2i32(a, b): + return Vec.from_elements([a, b], fx.Int32).ir_value() + + +_STORE_CPOL = 0x2 diff --git a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/launch.py b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/launch.py new file mode 100644 index 000000000000..6ec18cefe02f --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/launch.py @@ -0,0 +1,32 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MiniMax-M3 FlyDSL MoE launch helpers.""" + +import functools + +import torch + +from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.reduce_bf16 import ( + compile_moe_reduce_bf16, +) +from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.sort import compile_moe_sort +from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.tile_map import compile_tile_map + + +def _u8_flat(t: torch.Tensor) -> torch.Tensor: + return t.view(torch.uint8).view(-1) + + +@functools.cache +def _get_sort(num_experts: int, topk: int, block_m: int): + return compile_moe_sort(E=num_experts, topk=topk, block_m=block_m) + + +@functools.cache +def _get_tile_map(intermediate_size: int, block_m: int): + return compile_tile_map(I=intermediate_size, BM=block_m) + + +@functools.cache +def _get_reduce_bf16(hidden_size: int, topk: int): + return compile_moe_reduce_bf16(H=hidden_size, topk=topk) diff --git a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/loaders.py b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/loaders.py new file mode 100644 index 000000000000..12f683495455 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/loaders.py @@ -0,0 +1,397 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MiniMax-M3 FlyDSL MoE loaders helpers.""" + +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import buffer_ops +from flydsl._mlir import ir as _ir +from flydsl._mlir.dialects import llvm as _llvm +from flydsl.expr import const_expr, range_constexpr +from flydsl.expr import rocdl as _rocdl +from flydsl.expr.typing import T as _T +from flydsl.expr.typing import Vector as Vec + +_N_WAVES = 4 + + +def divmod(a, b): + """Divmod for DSL values (the builtin rejects them).""" + return (a // b, a % b) + + +def swizzle_128(row, col): + """The dense kernel's 128-B-row XOR swizzle: (row, col) -> (row', col').""" + offset = row * 128 + col + swizzle = ((offset % (16 * 128)) >> 8) << 4 + swizzled_offset = offset ^ swizzle + return swizzled_offset // 128, swizzled_offset % 128 + + +SWIGLU_ALPHA = 1.702 + + +SWIGLU_LIMIT = 7.0 + + +class _Buf: + def __init__(self, base_ptr, byte_off): + self.base_ptr = base_ptr + self.byte_off = byte_off + + @property + def ptr(self): + return fx.add_offset(self.base_ptr, self.byte_off) + + +_gep = buffer_ops.get_element_ptr + + +def _lds_ptr_t(): + return _ir.Type.parse("!llvm.ptr<3>") + + +def _asm_void(operands, asm_string, constraints, clobbers=""): + """Side-effecting void inline asm (LLVM sees no memory op -> no waitcnt added).""" + if clobbers: + constraints = f"{constraints},{clobbers}" + _llvm.inline_asm(None, operands, asm_string, constraints, has_side_effects=True) + + +def wait_barrier(count): + """``s_waitcnt vmcnt(count) lgkmcnt(0)`` + ``s_barrier``""" + _rocdl.s_waitcnt(vmcnt=count, lgkmcnt=0) + _rocdl.s_barrier() + + +def _uniform_i32(value): + """i32 in a wave-uniform SGPR, for scalar inline-asm operands.""" + raw = fx.as_ir_value(value) if not isinstance(value, _ir.Value) else value + if raw.type != _T.i32: + raw = fx.as_ir_value(fx.Int32(raw)) + return _rocdl.readfirstlane(_T.i32, raw) + + +def _swizzled_col(row, col): + """The swizzled 128-B-row byte column ``swizzle_128`` lands (row, col) on.""" + r, c = swizzle_128(row, col) + return c + + +class G2SLoaderAsm: + """global -> LDS, 16 B per lane per step: per-lane offsets in VGPRs, the K-step + in soffset. With ``step_bytes`` all steps share ``gl_offsets[0]`` (one VGPR) and + advance soffset by that stride; ``soff_bytes`` is added to every soffset.""" + + def __init__( + self, rsrc, gl_offsets, n_load_steps, wave_id, step_bytes=None, soff_bytes=0 + ): + self.rsrc = fx.as_ir_value(rsrc) + self.gl_offsets = gl_offsets + self.n_load_steps = n_load_steps + self.wave_id = wave_id + self.step_bytes = step_bytes + self.soff_bytes = soff_bytes + + @property + def _step_stride(self): + # m0 (LDS byte) advance per step: 4 waves x 64 lanes x 16 B. + return _N_WAVES * 1024 + + def set_wave_base(self, base_ptr): + # the wave-uniform LDS base, in an SGPR once + wb = fx.Int32(fx.ptrtoint(base_ptr)) + fx.Int32(self.wave_id * 1024) + self._wave_base_s = _rocdl.readfirstlane(_T.i32, fx.as_ir_value(wb)) + + def _lds_base_sgpr(self, lds_dst): + m0 = fx.Int32(self._wave_base_s) + fx.Int32(lds_dst.byte_off) + return fx.as_ir_value(m0) + + def _voffset(self, step): + if self.step_bytes is not None: + return fx.as_ir_value(fx.Int32(self.gl_offsets[0])) + return fx.as_ir_value(fx.Int32(self.gl_offsets[step])) + + def _emit(self, lds_dst, k_offset, step): + # set m0 at step 0, then s_add it for the rest + voff = self._voffset(step) + extra = self.soff_bytes + (step * self.step_bytes if self.step_bytes else 0) + if extra: + k_offset = fx.Int32(k_offset) + fx.Int32(extra) + soff = _uniform_i32(k_offset) + stride = self._step_stride + # s_add_u32 writes SCC: without ~{scc} a live SCC (loop exit) gets clobbered + if step == 0: + m0 = self._lds_base_sgpr(lds_dst) + asm = "s_mov_b32 m0, $0\nbuffer_load_dwordx4 $1, $2, $3 offen lds" + _asm_void([m0, voff, self.rsrc, soff], asm, "s,v,s,s", "~{scc}") + else: + asm = ( + f"s_add_u32 m0, {stride}, m0\nbuffer_load_dwordx4 $0, $1, $2 offen lds" + ) + _asm_void([voff, self.rsrc, soff], asm, "v,s,s", "~{scc}") + + def load(self, lds_dst, k_offset): + for step in range_constexpr(self.n_load_steps): + self._emit(lds_dst, k_offset, step) + + def load_one(self, lds_dst, k_offset, step): + self._emit(lds_dst, k_offset, step) + + +class S2RLoader128B: + """LDS -> registers: two 16-byte halves of a swizzled 128-byte row.""" + + def __init__(self, wave_idx, n_tiles): + self.lane_id = fx.thread_idx.x % 64 + self.wave_idx = wave_idx + self.n_tiles = n_tiles + + def _vec_load_16xf8(self, lds_src, dyn_offset, const_offset): + total_off = lds_src.byte_off + const_offset + window_base = (total_off // 0x10000) * 0x10000 + imm = total_off - window_base + assert 0 <= imm <= 0xFFFF + vaddr = fx.Int32(fx.ptrtoint(lds_src.base_ptr)) + fx.Int32( + window_base + dyn_offset + ) + lds_ptr = _llvm.inttoptr(_lds_ptr_t(), fx.as_ir_value(vaddr)) + if imm != 0: + lds_ptr = _gep(lds_ptr, static_byte_offset=imm) + vec_i32 = _ir.VectorType.get([4], fx.Int32.ir_type) + return Vec(_llvm.LoadOp(vec_i32, lds_ptr, alignment=16).result) + + def _offset(self, unit, preshuffled): + row = self.wave_idx * (self.n_tiles * 16) + self.lane_id % 16 + if const_expr(preshuffled): + return (row // 8) * 1024 + (row % 8) * 16 + unit * 128 + row_swz, col_swz = swizzle_128(row, unit * 16) + return row_swz * 128 + col_swz + + def _dyn_offset(self, step, preshuffled): + return self._offset(self.lane_id // 16 + step * 4, preshuffled) + + def load(self, lds_src, preshuffled=False): + frag = [] + for i in range_constexpr(self.n_tiles): + halves = [] + for step in range_constexpr(2): + dyn = self._dyn_offset(step, preshuffled) + v = self._vec_load_16xf8(lds_src, dyn, i * 2048) + halves.append(v.bitcast(fx.Int32)) + frag.append(halves) + return frag + + def load_one(self, lds_src, i, ksub, preshuffled=False): + dyn = self._dyn_offset(ksub, preshuffled) + return self._vec_load_16xf8(lds_src, dyn, i * 2048).bitcast(fx.Int32) + + +def _flat_frag(frag): + return [fx.as_ir_value(x) for t in frag for x in t] + + +def _unflat_frag(flat, n_tiles, arity=2): + return [list(flat[arity * i : arity * i + arity]) for i in range(n_tiles)] + + +def _g2s_thunks(g2s, dst, gl_off, n_steps): + return [lambda s=s: g2s.load_one(dst, gl_off, s) for s in range(n_steps)] + + +def _riffle(glb, lds): + """Interleave global and LDS thunks proportionally.""" + if not glb or not lds: + return list(glb) + list(lds) + out = [] + step = len(lds) / len(glb) + li = 0 + for gi, t in enumerate(glb): + out.append(t) + upto = int(round((gi + 1) * step)) + out += lds[li:upto] + li = upto + return out + lds[li:] + + +def _s2r_thunks(s2r, src, holder, n, pre): + ts = [] + for i in range(n): + for ks in range(_FP4_PACK): + + def f(i=i, ks=ks): + if holder[i] is None: + holder[i] = [None, None] + holder[i][ks] = s2r.load_one(src, i, ks, preshuffled=pre) + + ts.append(f) + return ts + + +def _min(a, b): + return (a < b).select(a, b) + + +def _divmod_nonneg(a, b): + if const_expr(isinstance(b, int) and b > 0 and (b & (b - 1)) == 0): + sh = b.bit_length() - 1 + return (a >> sh, a & (b - 1)) if const_expr(sh > 0) else (a, 0) + return divmod(a, b) + + +_FP4_PACK = 2 # pack_M = pack_N = pack_K = 2 +_SCALE_QUARTER_BYTES = 1024 # one gather = 4 blocks = one wave's share of one operand +_SCALE_REGION_BYTES = 2 * _SCALE_QUARTER_BYTES # all of A (or all of B) for one K-step +_SCALE_SLOT_BYTES = _N_WAVES * _SCALE_QUARTER_BYTES +_SCALE_SLOTS = 4 +_SCALE_LDS_BYTES = _SCALE_SLOTS * _SCALE_SLOT_BYTES +_SCALE_A_REGION = 0 +_SCALE_B_REGION = _SCALE_REGION_BYTES + + +class ScaleGatherMoE: + """One ``buffer_load_dwordx4 ... lds`` per wave per K-step: waves 0/1 fetch A + scales, waves 2/3 B scales (the expert's gate + up slabs). A 256 B block = 32 + rows x 8 K-blocks; lane blocks ``lane // 16`` 0/1 go to LDS half 0 (R0 / gate), + 2/3 to half 1 (R1 / up).""" + + def __init__( + self, + a_scale, + b_scale, + K, + lane_id, + wave_id, + lds_base_ptr, + a_scale_bytes, + b_scale_bytes, + a_wave_groups, + a_half_groups, + b_wave_groups, + b_half_groups, + ): + self.row_i32 = (K // 256) * 64 # i32 per 32-row group (32 rows x K/32 bytes) + self.wave_id = wave_id + self.a_rsrc = fx.as_ir_value( + buffer_ops.create_buffer_resource( + a_scale, max_size=False, num_records_bytes=a_scale_bytes + ) + ) + self.b_rsrc = fx.as_ir_value( + buffer_ops.create_buffer_resource( + b_scale, max_size=False, num_records_bytes=b_scale_bytes + ) + ) + self._blk = lane_id // 16 + self._in16 = lane_id % 16 + self._lds_base = fx.Int32(fx.ptrtoint(lds_base_ptr)) + self._a_wave_groups = a_wave_groups + self._a_half_groups = a_half_groups + self._b_wave_groups = b_wave_groups + self._b_half_groups = b_half_groups + + def set_wave_base(self, a_base_row, b_base_row): + """``a_base_row``: first sorted row of the m-tile; ``b_base_row``: first + W13 row (gate) of the n-tile, both multiples of 32.""" + wid = fx.Int32(_rocdl.readfirstlane(_T.i32, fx.as_ir_value(self.wave_id))) + self._wave_base_s = fx.as_ir_value( + self._lds_base + wid * fx.Int32(_SCALE_QUARTER_BYTES) + ) + is_a = wid < fx.Int32(2) + q = wid % fx.Int32(2) + g_a = a_base_row // fx.Int32(32) + q * fx.Int32(self._a_wave_groups) + g_b = b_base_row // fx.Int32(32) + q * fx.Int32(self._b_wave_groups) + self._G = _uniform_i32(is_a.select(g_a, g_b)) + self._HS = _uniform_i32( + is_a.select(fx.Int32(self._a_half_groups), fx.Int32(self._b_half_groups)) + ) + self._rsrc = fx.arith.select(is_a, self.a_rsrc, self.b_rsrc) + self._soff0 = _uniform_i32(fx.Int32(0)) + + def gather(self, kstep, slot): + grp = ( + fx.Int32(self._G) + (self._blk // 2) * fx.Int32(self._HS) + (self._blk % 2) + ) + i32_off = ( + grp * fx.Int32(self.row_i32) + + fx.Int32(kstep) * fx.Int32(64) + + self._in16 * fx.Int32(4) + ) + voff = fx.as_ir_value(i32_off * fx.Int32(4)) # bytes + addr = fx.Int32(self._wave_base_s) + fx.Int32(slot) * fx.Int32( + _SCALE_SLOT_BYTES + ) + asm = "s_mov_b32 m0, $0\nbuffer_load_dwordx4 $1, $2, $3 offen lds" + _asm_void( + [fx.as_ir_value(addr), voff, self._rsrc, self._soff0], + asm, + "s,v,s,s", + "~{m0}", + ) + + +class ScaleLoaderLDS: + def __init__(self, n_tiles, lane_id, quarter, lds_base_ptr, region_off): + assert n_tiles % _FP4_PACK == 0 + self.n_groups = n_tiles // _FP4_PACK + self.lane_id = lane_id + self._region_base = ( + fx.Int32(fx.ptrtoint(lds_base_ptr)) + + fx.Int32(region_off) + + quarter * fx.Int32(_SCALE_QUARTER_BYTES) + ) + + def _slot_wave_byte(self, slot): + return self._region_base + fx.Int32(slot) * fx.Int32(_SCALE_SLOT_BYTES) + + def read_half(self, slot, half): + L = self.lane_id + base = self._slot_wave_byte(slot) + fx.Int32((L // 4) * 16 + (L % 4) * 4) + grp_list = [] + for gi in range_constexpr(self.n_groups): + blk = half * 2 + gi + vaddr = base + fx.Int32(blk * 256) + lds_ptr = _llvm.inttoptr(_lds_ptr_t(), fx.as_ir_value(vaddr)) + load = _llvm.LoadOp(fx.Int32.ir_type, lds_ptr, alignment=4) + grp_list.append(fx.Int32(load.result)) + return grp_list + + def read(self, slot): + return self.read_half(slot, 0), self.read_half(slot, 1) + + +def _fmax(a, b): + return (a > b).select(a, b) + + +def _fmin(a, b): + return (a < b).select(a, b) + + +def _swiglu_oai(g, u): + """SwiGLU-OAI, op for op aiter's stage-1 ``swiglu_mul_vec4``; the two separate + multiplies of ``t`` matter (folding them changes the last bit).""" + lim = fx.Float32(SWIGLU_LIMIT) + g = _fmin(g, lim) + u = _fmax(_fmin(u, lim), fx.Float32(-SWIGLU_LIMIT)) + t = (g * fx.Float32(SWIGLU_ALPHA)) * fx.Float32(-1.4426950408889634) + e = fx.Float32(_rocdl.exp2(_T.f32, t.ir_value())) + sig = fx.Float32(_rocdl.rcp(_T.f32, (fx.Float32(1.0) + e).ir_value())) + return g * sig * (u + fx.Float32(1.0)) + + +def _bits(f): + return fx.Float32(f).bitcast(fx.Int32) + + +def _as_f32(i): + return fx.Int32(i).bitcast(fx.Float32) + + +def _permlane16_swap(d_a, d_b): + pair_ty = _ir.Type.parse("!llvm.struct<(i32, i32)>") + res = _rocdl.permlane16_swap( + pair_ty, fx.as_ir_value(d_a), fx.as_ir_value(d_b), False, False + ) + return fx.Int32(_llvm.extractvalue(_T.i32, res, [0])), fx.Int32( + _llvm.extractvalue(_T.i32, res, [1]) + ) diff --git a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/reduce_bf16.py b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/reduce_bf16.py new file mode 100644 index 000000000000..c0bd2c5be45a --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/reduce_bf16.py @@ -0,0 +1,98 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Top-k sum of gemm2's routing-weighted bf16 partials ``[n_tokens * topk, H]`` -> +``[n_tokens, H]`` bf16, fp32 accumulate (aiter ``moe_reduction_kernel``'s math). +One wave per (token, 512-column chunk), non-temporal loads.""" + +import flydsl.compiler as flyc +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import buffer_ops +from flydsl.expr import range_constexpr +from flydsl.expr.typing import Vector as Vec + +from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.epilogue import _bf16x2 +from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.loaders import _as_f32 +from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.utils import ( + PRELOAD_HINTS, + _tensor_addr, +) + +WAVES_PER_CTA = 1 +CHUNKS_PER_WAVE = 1 # dwordx4 per lane per row +_CHUNK = 512 # bf16 columns per (wave, dwordx4) +_NT = 2 # non-temporal cache policy + + +def compile_moe_reduce_bf16(*, H: int, topk: int): + CPW = CHUNKS_PER_WAVE + WPC = WAVES_PER_CTA + assert H % (_CHUNK * CPW) == 0 + SEGS = H // (_CHUNK * CPW) # waves per token + ROW_DW = H // 2 + CHUNK_DW = _CHUNK // 2 + LD = _NT + ST = 0 # default-policy stores + name = f"m3_reduce_bf16_h{H}_k{topk}" + + # addresses, not tensors: every argument arrives preloaded in SGPRs + @flyc.kernel(name=name, known_block_size=[64 * WPC, 1, 1]) + def kernel_reduce_bf16(n_tokens: fx.Int32, arg_out: fx.Int64, arg_y: fx.Int64): + lane = fx.thread_idx.x % 64 + gw = fx.block_idx.x * WPC + fx.thread_idx.x // 64 + tok = gw // SEGS + seg = gw % SEGS + out_rsrc = buffer_ops.create_buffer_resource_from_addr( + arg_out, num_records_bytes=n_tokens * (topk * H * 2) + ) + y_rsrc = buffer_ops.create_buffer_resource_from_addr( + arg_y, num_records_bytes=n_tokens * (H * 2) + ) + if tok < n_tokens: + col_dw = seg * (CHUNK_DW * CPW) + lane * 4 + row_dw = tok * (topk * ROW_DW) + col_dw + data = [ + [ + Vec( + buffer_ops.buffer_load( + out_rsrc, + row_dw + k * ROW_DW + j * CHUNK_DW, + vec_width=4, + dtype=fx.Int32, + cache_modifier=LD, + ) + ) + for j in range(CPW) + ] + for k in range(topk) + ] + acc = [[fx.Float32(0.0) for _ in range(8)] for _ in range(CPW)] + for k in range_constexpr(topk): + for j in range_constexpr(CPW): + for d in range_constexpr(4): + dw = fx.Int32(data[k][j][d]) + acc[j][2 * d] = acc[j][2 * d] + _as_f32(dw << 16) + acc[j][2 * d + 1] = acc[j][2 * d + 1] + _as_f32( + dw & fx.Int32(-65536) + ) + y_dw = tok * ROW_DW + col_dw + for j in range_constexpr(CPW): + packed = Vec.from_elements( + [_bf16x2(acc[j][2 * i], acc[j][2 * i + 1]) for i in range(4)], + fx.Int32, + ).ir_value() + buffer_ops.buffer_store( + packed, y_rsrc, y_dw + j * CHUNK_DW, cache_modifier=ST + ) + + @flyc.jit + def launch_reduce_bf16( + OUT: fx.Tensor, Y: fx.Tensor, n_tokens: fx.Int32, stream: fx.Stream + ): + grid = (n_tokens * SEGS + (WPC - 1)) // WPC + kernel_reduce_bf16(n_tokens, _tensor_addr(OUT), _tensor_addr(Y)).launch( + grid=(grid, 1, 1), block=(64 * WPC, 1, 1), stream=stream + ) + + launch_reduce_bf16.kernel_name = name + launch_reduce_bf16.compile_hints = PRELOAD_HINTS + return launch_reduce_bf16 diff --git a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/sort.py b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/sort.py new file mode 100644 index 000000000000..a16a338d8862 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/sort.py @@ -0,0 +1,223 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Prefill routing sort (aiter's ``moe_3stage_sort`` contract) in two launches: +``sort_count`` histograms each CTA's (token, slot) pairs, ``sort_place_pad`` scans +the padded totals, places the pairs and pads. ``sorted_ids[row] = token | slot << 24`` +(padding rows: ``n_tokens``, weight 0); the order inside an expert is not fixed.""" + +import functools +from dataclasses import dataclass + +import flydsl.compiler as flyc +import flydsl.expr as fx +import torch +from flydsl.expr import range_constexpr + +from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.utils import _lds_atomic_add_i32 + +SORT_CTAS = 128 # histogram / placement blocks +THREADS = 1024 # >= E and >= block_m + + +def max_sorted_rows(n_tokens: int, E: int, topk: int, block_m: int) -> int: + """Aiter's bound: every active expert pads by < block_m rows.""" + active = min(E, n_tokens * topk) + cumsum_max = n_tokens * topk + active * (block_m - 1) + return ((cumsum_max + block_m - 1) // block_m) * block_m + + +@dataclass +class SortBuffers: + sorted_ids: torch.Tensor + sorted_expert_ids: torch.Tensor + num_valid_ids: torch.Tensor # [2] i32: padded rows, last expert's first row + sorted_weights: torch.Tensor + block_offsets: torch.Tensor # workspace [E * SORT_CTAS]: per-CTA counts + max_sorted: int + block_m: int + + @staticmethod + def allocate(n_tokens, E, topk, block_m, device): + ms = max_sorted_rows(n_tokens, E, topk, block_m) + i32 = torch.int32 + return SortBuffers( + sorted_ids=torch.empty(ms, dtype=i32, device=device), + sorted_expert_ids=torch.empty(ms // block_m, dtype=i32, device=device), + num_valid_ids=torch.empty(2, dtype=i32, device=device), + sorted_weights=torch.empty(ms, dtype=torch.float32, device=device), + block_offsets=torch.empty(E * SORT_CTAS, dtype=i32, device=device), + max_sorted=ms, + block_m=block_m, + ) + + def launch_args(self, topk_ids, topk_weights, n_tokens): + return ( + topk_ids.contiguous().int().view(-1), + topk_weights.contiguous().float().view(-1), + self.sorted_ids, + self.sorted_expert_ids, + self.num_valid_ids, + self.sorted_weights, + self.block_offsets, + int(n_tokens), + torch.cuda.current_stream(), + ) + + +@functools.cache +def compile_moe_sort(*, E: int, topk: int, block_m: int): + assert (block_m & (block_m - 1)) == 0 and max(E, block_m) <= THREADS + experts_per_cta = (E + SORT_CTAS - 1) // SORT_CTAS + bm_shift = block_m.bit_length() - 1 + tag = f"E{E}_K{topk}_BM{block_m}" + + SCAN_W = THREADS # the padded-count scan runs on the whole block (no branch) + assert E <= SCAN_W and (SCAN_W & (SCAN_W - 1)) == 0 + PART = 4 # threads per expert summing the per-CTA counts in place_pad + assert PART * E <= THREADS and SORT_CTAS % PART == 0 and PART * E <= 2 * SCAN_W + scan_rounds = SCAN_W.bit_length() - 1 + + @fx.struct + class Shared: + count: fx.Array[fx.Int32, E] # per-CTA count / cursor + total: fx.Array[fx.Int32, E] + padded: fx.Array[fx.Int32, E] + prefix: fx.Array[fx.Int32, E] # rows placed by the earlier CTAs + starts: fx.Array[fx.Int32, E + 1] # expert start rows, [E] = padded total + scan: fx.Array[fx.Int32, 2 * SCAN_W] # ping-pong scan buffers + + def pair_range(n_tok, bx): + """This CTA's [start, end) of the n_tok * topk routing pairs""" + total = n_tok * topk + per_cta = (total + (SORT_CTAS - 1)) // SORT_CTAS + start = bx * per_cta + end = start + per_cta + return start, (end < total).select(end, total) + + @flyc.kernel(name=f"m3_sort_count_{tag}", known_block_size=[THREADS, 1, 1]) + def sort_count(topk_ids: fx.Tensor, block_offsets: fx.Tensor, n_tok: fx.Int32): + count = fx.SharedAllocator().allocate(Shared).peek().count.ptr + tx, bx = fx.thread_idx.x, fx.block_idx.x + start, end = pair_range(n_tok, bx) + if tx < E: + count[tx] = 0 + fx.gpu.barrier() + for i in range(start + tx, end, THREADS): + _lds_atomic_add_i32(count + fx.Int32(topk_ids[fx.Int32(i)]), 1) + fx.gpu.barrier() + if tx < E: + block_offsets[tx * SORT_CTAS + bx] = fx.Int32(count[tx]) + + @flyc.kernel(name=f"m3_sort_place_pad_{tag}", known_block_size=[THREADS, 1, 1]) + def sort_place_pad( + topk_ids: fx.Tensor, + topk_w: fx.Tensor, + block_offsets: fx.Tensor, + num_valid: fx.Tensor, + sorted_expert_ids: fx.Tensor, + sorted_ids: fx.Tensor, + sorted_w: fx.Tensor, + n_tok: fx.Int32, + ): + smem = fx.SharedAllocator().allocate(Shared).peek() + cursor, total_c, padded_c = smem.count.ptr, smem.total.ptr, smem.padded.ptr + prefix_c, starts = smem.prefix.ptr, smem.starts.ptr + scan = [smem.scan.ptr, smem.scan.ptr + SCAN_W] + tx, bx = fx.thread_idx.x, fx.block_idx.x + # 1. per expert: the total and the rows the earlier CTAs place + e, k = tx // PART, tx % PART + if tx < PART * E: + tot = fx.Int32(0) + pre = fx.Int32(0) + for i in range_constexpr(SORT_CTAS // PART): + c = k * (SORT_CTAS // PART) + i + v = fx.Int32(block_offsets[e * SORT_CTAS + c]) + tot = tot + v + pre = pre + (c < bx).select(v, 0) + scan[0][tx] = tot + scan[1][tx] = pre + fx.gpu.barrier() + if tx < E: + tot = fx.Int32(0) + pre = fx.Int32(0) + for i in range_constexpr(PART): + tot = tot + fx.Int32(scan[0][tx * PART + i]) + pre = pre + fx.Int32(scan[1][tx * PART + i]) + total_c[tx] = tot + padded_c[tx] = (tot + (block_m - 1)) & ~(block_m - 1) + prefix_c[tx] = pre + fx.gpu.barrier() + # 2. inclusive scan of the padded counts -> expert start rows + in_e = tx < E + scan[0][tx] = in_e.select(fx.Int32(padded_c[in_e.select(tx, 0)]), 0) + fx.gpu.barrier() + for r in range_constexpr(scan_rounds): + d, src, dst = 1 << r, r % 2, 1 - r % 2 + mine = fx.Int32(scan[src][tx]) + has = tx >= d + other = fx.Int32(scan[src][has.select(tx - d, tx)]) + scan[dst][tx] = has.select(mine + other, mine) + fx.gpu.barrier() + incl = scan[scan_rounds % 2] + if tx < E: + start = fx.Int32(incl[tx]) - fx.Int32(padded_c[tx]) + starts[tx] = start + cursor[tx] = start + fx.Int32(prefix_c[tx]) + if tx == 0: + starts[E] = fx.Int32(incl[E - 1]) + fx.gpu.barrier() + if bx == 0: + if tx == 0: + num_valid[0] = fx.Int32(starts[E]) + num_valid[1] = fx.Int32(starts[E - 1]) # the last expert's first row + if tx < E: + for b in range( + fx.Int32(starts[tx]) >> bm_shift, + fx.Int32(starts[tx + 1]) >> bm_shift, + ): + sorted_expert_ids[fx.Int32(b)] = tx + # 3. place this CTA's pairs + start, end = pair_range(n_tok, bx) + for i in range(start + tx, end, THREADS): + p = fx.Int32(i) + row = _lds_atomic_add_i32(cursor + fx.Int32(topk_ids[p]), 1) + sorted_ids[row] = ((p // topk) & 0x00FFFFFF) | ((p % topk) << 24) + sorted_w[row] = fx.Float32(topk_w[p]) + fx.gpu.barrier() + # 4. padding: < block_m rows per expert + if tx < block_m: + for ee in range_constexpr(experts_per_cta): + e = bx * experts_per_cta + ee + if e < E: + lo = fx.Int32(starts[e]) + fx.Int32(total_c[e]) + tx + for r in range(lo, fx.Int32(starts[e + 1]), THREADS): + sorted_ids[fx.Int32(r)] = n_tok # token n_tokens, slot 0 + sorted_w[fx.Int32(r)] = fx.Float32(0.0) + + @flyc.jit + def launch_sort( + topk_ids: fx.Tensor, + topk_w: fx.Tensor, + sorted_ids: fx.Tensor, + sorted_expert_ids: fx.Tensor, + num_valid: fx.Tensor, + sorted_w: fx.Tensor, + block_offsets: fx.Tensor, + n_tokens: fx.Int32, + stream: fx.Stream, + ): + sort_count(topk_ids, block_offsets, n_tokens).launch( + grid=(SORT_CTAS, 1, 1), block=(THREADS, 1, 1), stream=stream + ) + sort_place_pad( + topk_ids, + topk_w, + block_offsets, + num_valid, + sorted_expert_ids, + sorted_ids, + sorted_w, + n_tokens, + ).launch(grid=(SORT_CTAS, 1, 1), block=(THREADS, 1, 1), stream=stream) + + return launch_sort diff --git a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/tile_map.py b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/tile_map.py new file mode 100644 index 000000000000..0753cfe80801 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/tile_map.py @@ -0,0 +1,91 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +"""gemm1's expert-major tile order: an expert's m-blocks are the run ``[lo, hi)`` of +``sorted_expert_ids``; its (m, n) tiles are listed n-major so consecutive blocks +share the W13 slab:: + + tile_map[NB_N*lo + n*(hi - lo) + (m - lo)] = m << N_BITS | n (n < NB_N) + tile_map[valid_blocks*NB_N .. grid) = -1 (idle blocks) + tile_map[grid] = valid_blocks*NB_N +""" + +import flydsl.compiler as flyc +import flydsl.expr as fx +from flydsl.expr import range_constexpr + +from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.loaders import _min + +_THREADS = 256 +_MAX_BLOCKS = 4096 # >= max_sorted / BM (1409 at 65536 tokens, BM 256) +_SEARCH_STEPS = 13 # 2^13 > _MAX_BLOCKS + + +def compile_tile_map(*, I: int, BM: int = 128): # noqa: E741 + NB_N = I // 128 + N_BITS = (NB_N - 1).bit_length() + N_CTAS = _MAX_BLOCKS // _THREADS + TAIL_ITERS = (_MAX_BLOCKS * NB_N + 8) // (_THREADS * N_CTAS) + 1 + + @flyc.kernel + def kernel_tile_map( + sorted_expert_ids: fx.Tensor, + num_valid_ids: fx.Tensor, + tile_map: fx.Tensor, + grid_entries: fx.Int32, + ): + tid = fx.thread_idx.x + bx = fx.block_idx.x + gtid = bx * _THREADS + tid + vb = fx.Int32(num_valid_ids[0]) // BM # valid blocks (num_valid is BM-padded) + + def _eid(i): + return fx.Int32(sorted_expert_ids[i]) + + def _bound(e, upper): + """First index in [0, vb) whose expert id is > e (upper) / >= e (lower)""" + lo = fx.Int32(0) + n = vb + for _ in range_constexpr(_SEARCH_STEPS): + half = n // 2 + mid = lo + half + probe = _eid(_min(mid, vb - 1)) + go_right = (n > 0) & ((probe <= e) if upper else (probe < e)) + lo = go_right.select(mid + 1, lo) + n = go_right.select(n - half - 1, half) + return lo + + m = gtid + if m < vb: + e = _eid(m) + lo = _bound(e, False) + hi = _bound(e, True) + cnt = hi - lo + for n in range_constexpr(NB_N): + tile_map[lo * NB_N + cnt * n + m - lo] = (m << N_BITS) | n + tail0 = vb * NB_N + for it in range_constexpr(TAIL_ITERS): + i = tail0 + gtid + it * (_THREADS * N_CTAS) + if i < grid_entries: + tile_map[i] = fx.Int32(-1) + if gtid == 0: + tile_map[grid_entries] = tail0 + + @flyc.jit + def launch_tile_map( + sorted_expert_ids: fx.Tensor, + num_valid_ids: fx.Tensor, + tile_map: fx.Tensor, + grid_entries: fx.Int32, + stream: fx.Stream, + ): + kernel_tile_map( + sorted_expert_ids, num_valid_ids, tile_map, grid_entries + ).launch(grid=(N_CTAS, 1, 1), block=(_THREADS, 1, 1), stream=stream) + + return launch_tile_map + + +def tile_map_grid(num_m_blocks: int, I: int) -> int: # noqa: E741 + """gemm1 grid: every (m, n) tile of the allocation, rounded up to 8 XCDs.""" + return (num_m_blocks * (I // 128) + 7) // 8 * 8 diff --git a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/utils.py b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/utils.py new file mode 100644 index 000000000000..1010ba70aa3e --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/utils.py @@ -0,0 +1,34 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +# Copyright (C) 2025-2026 FlyDSL Project Contributors +"""MiniMax-M3 FlyDSL MoE utils helpers.""" + +import flydsl.expr as fx +from flydsl._mlir.dialects import llvm + +# launch.compile_hints: preload kernel arguments into SGPRs (the first 56 bytes) +PRELOAD_HINTS = { + "llvm_options": { + "amdgpu-kernarg-preload": True, + "amdgpu-kernarg-preload-count": 16, + } +} + + +def _tensor_addr(t): + """Tensor as a device address: a tensor kernel argument ends the kernarg preload.""" + return fx.Int64(fx.ptrtoint(fx.get_iter(t))) + + +def _lds_atomic_add_i32(ptr, value): + """Workgroup-scope LDS i32 atomic add; returns the old value.""" + return fx.Int32( + llvm.AtomicRMWOp( + llvm.AtomicBinOp.add, + ptr.llvm_ptr, + fx.Int32(value).ir_value(), + llvm.AtomicOrdering.monotonic, + syncscope="workgroup", + alignment=4, + ).result + ) diff --git a/vllm/models/minimax_m3/amd/ops/moe_mxfp4/__init__.py b/vllm/models/minimax_m3/amd/ops/moe_mxfp4/__init__.py new file mode 100644 index 000000000000..e49d0462c3f7 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/moe_mxfp4/__init__.py @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""FlyDSL W4A4 MoE prefill chain for MiniMax-M3 on gfx950 (``sp_prefill``).""" diff --git a/vllm/models/minimax_m3/amd/ops/moe_mxfp4/gemm1_prefill.py b/vllm/models/minimax_m3/amd/ops/moe_mxfp4/gemm1_prefill.py new file mode 100644 index 000000000000..4710b5d17986 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/moe_mxfp4/gemm1_prefill.py @@ -0,0 +1,1192 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +"""MiniMax-M3 prefill MoE stage 1 (a4w4): the dense 4-wave fp4 GEMM per (m-tile of +sorted rows, n-tile of 128 intermediate columns), aiter ``moe_sorting`` layout: + + h[row, :] = swiglu_oai(x[tok] @ W_gate[e]^T, x[tok] @ W_up[e]^T) + out_q[row, :], out_scale[row, :] = mxfp4_quant(h[row, :]) (per 32 cols) + +A rows are gathered by token; padded rows (token == n_tokens) fall outside the +buffer resource and load zeros. The two LDS N-halves are the gate slab and the +matching up slab of W13, so SwiGLU is elementwise in registers. The epilogue +quantizes like aiter's FlyDSL stage 1 and writes the scales in the sorted +e8m0-shuffled layout gemm2 reads. + +Layouts (all bytes): + A [n_tokens, H/2] per-token fp4 (aiter per_1x32 quant) + A_scale [pad32(max_sorted), H/32] sorted rows, e8m0-shuffled + (aiter mxfp4_moe_sort) + W13 [E, 2I, H/2] aiter shuffle_weight(layout=(16,16)) + W13_sc [E*2I, H/32] aiter e8m0_shuffle + OUT_Q [num_m_blocks*BLOCK_M, I/2] sorted rows, fp4 + OUT_sc [pad32(num_m_blocks*BLOCK_M), I/32] sorted rows, e8m0-shuffled +""" + +import flydsl.compiler as flyc +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import ( + buffer_ops, # the copy shipped in the vLLM image +) +from flydsl._mlir import ir as _ir +from flydsl._mlir.dialects import llvm as _llvm +from flydsl.expr import const_expr, range_constexpr +from flydsl.expr import rocdl as _rocdl +from flydsl.expr.typing import T as _T +from flydsl.expr.typing import Vector as Vec + +_N_WAVES = 4 + + +def divmod(a, b): + """Divmod for DSL values (the builtin rejects them).""" + return (a // b, a % b) + + +def swizzle_128(row, col): + """The dense kernel's 128-B-row XOR swizzle: (row, col) -> (row', col').""" + offset = row * 128 + col + swizzle = ((offset % (16 * 128)) >> 8) << 4 + swizzled_offset = offset ^ swizzle + return swizzled_offset // 128, swizzled_offset % 128 + + +SWIGLU_ALPHA = 1.702 +SWIGLU_LIMIT = 7.0 + + +class _Buf: + def __init__(self, base_ptr, byte_off): + self.base_ptr = base_ptr + self.byte_off = byte_off + + @property + def ptr(self): + return fx.add_offset(self.base_ptr, self.byte_off) + + +_gep = buffer_ops.get_element_ptr + + +def _lds_ptr_t(): + return _ir.Type.parse("!llvm.ptr<3>") + + +def _asm_void(operands, asm_string, constraints, clobbers=""): + """Side-effecting void inline asm (LLVM sees no memory op -> no waitcnt added).""" + if clobbers: + constraints = f"{constraints},{clobbers}" + _llvm.inline_asm(None, operands, asm_string, constraints, has_side_effects=True) + + +def wait_barrier(count): + """``s_waitcnt vmcnt(count) lgkmcnt(0)`` + ``s_barrier``""" + _rocdl.s_waitcnt(vmcnt=count, lgkmcnt=0) + _rocdl.s_barrier() + + +def _uniform_i32(value): + """Cast to i32 and force a wave-uniform SGPR value for scalar inline-asm + operands.""" + raw = fx.as_ir_value(value) if not isinstance(value, _ir.Value) else value + if raw.type != _T.i32: + raw = fx.as_ir_value(fx.Int32(raw)) + return _rocdl.readfirstlane(_T.i32, raw) + + +def _swizzled_col(row, col): + """The swizzled 128-B-row byte column ``swizzle_128`` lands (row, col) on.""" + r, c = swizzle_128(row, col) + return c + + +class G2SLoaderAsm: + """global -> LDS, 16 B per lane per step; ``gl_offsets[step]`` is the + loop-invariant per-lane byte offset, the K-step goes in soffset.""" + + def __init__(self, rsrc, gl_offsets, n_load_steps, wave_id): + self.rsrc = fx.as_ir_value(rsrc) + self.gl_offsets = gl_offsets + self.n_load_steps = n_load_steps + self.wave_id = wave_id + + @property + def _step_stride(self): + # m0 (LDS byte) advance per step: 4 waves x 64 lanes x 16 B. + return _N_WAVES * 1024 + + def set_wave_base(self, base_ptr): + # The wave-uniform LDS base, readfirstlane'd into an SGPR ONCE. + wb = fx.Int32(fx.ptrtoint(base_ptr)) + fx.Int32(self.wave_id * 1024) + self._wave_base_s = _rocdl.readfirstlane(_T.i32, fx.as_ir_value(wb)) + + def _lds_base_sgpr(self, lds_dst): + m0 = fx.Int32(self._wave_base_s) + fx.Int32(lds_dst.byte_off) + return fx.as_ir_value(m0) + + def _voffset(self, step): + return fx.as_ir_value(fx.Int32(self.gl_offsets[step])) + + def _emit(self, lds_dst, k_offset, step): + # m0 idiom (gcnasm async_copy): set m0 for step 0, then s_add for the rest. + voff = self._voffset(step) + soff = _uniform_i32(k_offset) # scalar soffset (K-step) + stride = self._step_stride + # s_add_u32 writes SCC: declare it, or the compiler may keep a live SCC + # (e.g. a loop-exit compare) across this asm and branch on garbage. + if step == 0: + m0 = self._lds_base_sgpr(lds_dst) + asm = "s_mov_b32 m0, $0\nbuffer_load_dwordx4 $1, $2, $3 offen lds" + _asm_void([m0, voff, self.rsrc, soff], asm, "s,v,s,s", "~{scc}") + else: + asm = ( + f"s_add_u32 m0, {stride}, m0\nbuffer_load_dwordx4 $0, $1, $2 offen lds" + ) + _asm_void([voff, self.rsrc, soff], asm, "v,s,s", "~{scc}") + + def load(self, lds_dst, k_offset): + for step in range_constexpr(self.n_load_steps): + self._emit(lds_dst, k_offset, step) + + def load_one(self, lds_dst, k_offset, step): + self._emit(lds_dst, k_offset, step) + + +class S2RLoaderFp4: + """LDS -> reg: per tile the two K=128 fp4 MFMA operands (i32x4 each).""" + + def __init__(self, wave_idx, n_tiles): + self.lane_id = fx.thread_idx.x % 64 + self.wave_idx = wave_idx + self.n_tiles = n_tiles + + def _vec_load_16xf8(self, lds_src, dyn_offset, const_offset): + total_off = lds_src.byte_off + const_offset + window_base = (total_off // 0x10000) * 0x10000 + imm = total_off - window_base + assert 0 <= imm <= 0xFFFF + vaddr = fx.Int32(fx.ptrtoint(lds_src.base_ptr)) + fx.Int32( + window_base + dyn_offset + ) + lds_ptr = _llvm.inttoptr(_lds_ptr_t(), fx.as_ir_value(vaddr)) + if imm != 0: + lds_ptr = _gep(lds_ptr, static_byte_offset=imm) + vec4_i32 = _ir.VectorType.get([4], fx.Int32.ir_type) + load = _llvm.LoadOp(vec4_i32, lds_ptr, alignment=16) + return Vec(load.result) + + def _dyn_offset(self, step, preshuffled): + row = self.wave_idx * (self.n_tiles * 16) + self.lane_id % 16 + col = (self.lane_id // 16) * 16 + step * 64 + if const_expr(preshuffled): + return (row // 8) * 1024 + (row % 8) * 16 + (col // 16) * 128 + row_swz, col_swz = swizzle_128(row, col) + return row_swz * 128 + col_swz + + def load(self, lds_src, preshuffled=False): + frag = [] + for i in range_constexpr(self.n_tiles): + halves = [] + for step in range_constexpr(2): + dyn = self._dyn_offset(step, preshuffled) + v = self._vec_load_16xf8(lds_src, dyn, i * 2048) + halves.append(v.bitcast(fx.Int32)) + frag.append(halves) + return frag + + def load_one(self, lds_src, i, ksub, preshuffled=False): + dyn = self._dyn_offset(ksub, preshuffled) + v = self._vec_load_16xf8(lds_src, dyn, i * 2048) + return v.bitcast(fx.Int32) + + +def _flat_frag(frag): + out = [] + for t in frag: + out.append(fx.as_ir_value(t[0])) + out.append(fx.as_ir_value(t[1])) + return out + + +def _unflat_frag(flat, n_tiles): + return [[flat[2 * i], flat[2 * i + 1]] for i in range(n_tiles)] + + +def _g2s_thunks(g2s, dst, gl_off, n_steps): + return [lambda s=s: g2s.load_one(dst, gl_off, s) for s in range(n_steps)] + + +def _riffle(glb, lds): + """Interleave the global and LDS thunk lists proportionally like aiter's asm""" + if not glb or not lds: + return list(glb) + list(lds) + out = [] + step = len(lds) / len(glb) + li = 0 + for gi, t in enumerate(glb): + out.append(t) + upto = int(round((gi + 1) * step)) + out += lds[li:upto] + li = upto + return out + lds[li:] + + +def _s2r_thunks(s2r, src, holder, n, pre): + ts = [] + for i in range(n): + for ks in range(_FP4_PACK): + + def f(i=i, ks=ks): + if holder[i] is None: + holder[i] = [None, None] + holder[i][ks] = s2r.load_one(src, i, ks, preshuffled=pre) + + ts.append(f) + return ts + + +def _min(a, b): + return (a < b).select(a, b) + + +def _divmod_nonneg(a, b): + if const_expr(isinstance(b, int) and b > 0 and (b & (b - 1)) == 0): + sh = b.bit_length() - 1 + return (a >> sh, a & (b - 1)) if const_expr(sh > 0) else (a, 0) + return divmod(a, b) + + +# ── FP4 scaled MFMA ────────────────────────────────────────────────────────── +_FP4_CBSZ = 4 +_FP4_BLGP = 4 +_FP4_PACK = 2 # pack_M = pack_N = pack_K = 2 + + +class Mfma16x16x128Fp4: + """fp4 16x16x128 scaled MFMA over an (n_tiles_a x n_tiles_b) quadrant, + accumulators pinned in AGPR (inline asm ``=a,...,0``). See the dense + kernel for the opsel / operand-swap notes.""" + + def __init__(self, n_tiles_a, n_tiles_b): + assert n_tiles_a % _FP4_PACK == 0 and n_tiles_b % _FP4_PACK == 0 + self.n_tiles_a = n_tiles_a + self.n_tiles_b = n_tiles_b + self.res_ty = Vec.make_type(4, fx.Float32) + + def idx(self, i, j): + return i * self.n_tiles_b + j + + def _order(self): + order = [] + j0s = list(range(0, self.n_tiles_b, 2)) + for n, i0 in enumerate(range(0, self.n_tiles_a, 2)): + for j0 in reversed(j0s) if n % 2 else j0s: + order += [(i0 + di, j0 + dj) for di in range(2) for dj in range(2)] + return order + + def call( + self, a, b, c, sa, sb, interleave=None, zero_acc=False, late=None, late_start=8 + ): + """``interleave``: thunks spread evenly over the MFMAs (loads, LDS reads). + ``late``: thunks spread over the MFMAs from ``late_start`` on -- for work that + reads accumulators finished by the previous call: the MFMAs are inline asm, so + the + compiler inserts no MFMA -> v_accvgpr_read hazard waits; 8 MFMAs (128+ cycles) + cover the last one's latency.""" + thunks = list(interleave) if interleave else [] + lates = list(late) if late else [] + nth = [0] + nlt = [0] + mth = [0] + order = self._order() + n_mfma = _FP4_PACK * len(order) + slots = ( + {(t * n_mfma) // len(thunks) for t in range(len(thunks))} + if thunks + else set() + ) + n_late_slots = max(n_mfma - late_start, 1) + lslots = ( + {late_start + (t * n_late_slots) // len(lates) for t in range(len(lates))} + if lates + else set() + ) + for ksub in range_constexpr(_FP4_PACK): + for i, j in order: + a_op = a[i][ksub] + sa_v = sa[i // _FP4_PACK] + ia = i % _FP4_PACK + b_op = b[j][ksub] + sb_v = sb[j // _FP4_PACK] + jb = j % _FP4_PACK + if zero_acc and ksub == 0: + c[self.idx(i, j)] = self._mfma_agpr( + a_op, b_op, None, sa_v, sb_v, ksub, ia, jb + ) + else: + c[self.idx(i, j)] = self._mfma_agpr( + a_op, b_op, c[self.idx(i, j)], sa_v, sb_v, ksub, ia, jb + ) + if nth[0] < len(thunks) and mth[0] in slots: + thunks[nth[0]]() + nth[0] += 1 + if nlt[0] < len(lates) and mth[0] in lslots: + lates[nlt[0]]() + nlt[0] += 1 + mth[0] += 1 + while nth[0] < len(thunks): + thunks[nth[0]]() + nth[0] += 1 + while nlt[0] < len(lates): + lates[nlt[0]]() + nlt[0] += 1 + return c + + def _mfma_agpr(self, a_op, b_op, acc, sa_v, sb_v, ksub, ia, jb): + # feeds (B, A) instead of (A, B): C^T = B^T A^T, so lane L ends up holding + # C[row L%16, 4 consecutive cols 4*(L//16)..]. + a_op, b_op = b_op, a_op + sa_v, sb_v = sb_v, sa_v + ia, jb = jb, ia + opsel = f"op_sel:[{ia},{jb},0]" + opsel_hi = f"op_sel_hi:[{ksub},{ksub},0]" + src2 = "$0" if acc is not None else "0" + asm = ( + f"v_mfma_scale_f32_16x16x128_f8f6f4 $0, $1, $2, {src2}, $3, $4 " + f"{opsel} {opsel_hi} cbsz:4 blgp:4" + ) + ops = [ + fx.as_ir_value(a_op), + fx.as_ir_value(b_op), + fx.as_ir_value(sa_v), + fx.as_ir_value(sb_v), + ] + cons = "=a,v,v,v,v" + if acc is not None: + ops.append(fx.as_ir_value(acc)) + cons += ",0" + return _llvm.inline_asm(self.res_ty, ops, asm, cons, has_side_effects=True) + + +# ── E8M0 scales through LDS ────────────────────────────────────────────────── +_SCALE_QUARTER_BYTES = 1024 # one gather = 4 blocks = one wave's share of one operand +_SCALE_REGION_BYTES = 2 * _SCALE_QUARTER_BYTES # all of A (or all of B) for one K-step +_SCALE_SLOT_BYTES = _N_WAVES * _SCALE_QUARTER_BYTES # 4096 +_SCALE_SLOTS = 4 +_SCALE_LDS_BYTES = _SCALE_SLOTS * _SCALE_SLOT_BYTES # 16 KB +_SCALE_A_REGION = 0 +_SCALE_B_REGION = _SCALE_REGION_BYTES + + +class ScaleGatherMoE: + """One ``buffer_load_dwordx4 ... lds`` per wave per K-step: waves 0/1 fetch + the A-scale blocks (rows of the sorted scale), waves 2/3 the B-scale blocks + (gate slab + up slab of the expert). A 256-B block = 32 rows x 8 K-blocks; + lane block ``blk = lane//16`` fetches row-group + ``G_wave + (blk//2)*half_groups + blk%2``: blocks 0/1 belong to LDS half 0 + (rows R0 / gate), blocks 2/3 to half 1 (rows R1 / up).""" + + def __init__( + self, + a_scale, + b_scale, + K, + lane_id, + wave_id, + lds_base_ptr, + a_scale_bytes, + b_scale_bytes, + a_wave_groups, + a_half_groups, + b_wave_groups, + b_half_groups, + ): + self.row_i32 = (K // 256) * 64 # i32 per 32-row group (32 rows x K/32 bytes) + self.wave_id = wave_id + # aiter's buffer_ops returns the raw ROCDL resource (!llvm.ptr<8>) directly + self.a_rsrc = fx.as_ir_value( + buffer_ops.create_buffer_resource( + a_scale, max_size=False, num_records_bytes=a_scale_bytes + ) + ) + self.b_rsrc = fx.as_ir_value( + buffer_ops.create_buffer_resource( + b_scale, max_size=False, num_records_bytes=b_scale_bytes + ) + ) + self._blk = lane_id // 16 + self._in16 = lane_id % 16 + self._lds_base = fx.Int32(fx.ptrtoint(lds_base_ptr)) + self._a_wave_groups = a_wave_groups + self._a_half_groups = a_half_groups + self._b_wave_groups = b_wave_groups + self._b_half_groups = b_half_groups + + def set_wave_base(self, a_base_row, b_base_row): + """``a_base_row``: first sorted row of the m-tile; ``b_base_row``: first + W13 row (gate) of the n-tile, both multiples of 32.""" + wid = fx.Int32(_rocdl.readfirstlane(_T.i32, fx.as_ir_value(self.wave_id))) + self._wave_base_s = fx.as_ir_value( + self._lds_base + wid * fx.Int32(_SCALE_QUARTER_BYTES) + ) + is_a = wid < fx.Int32(2) + q = wid % fx.Int32(2) + g_a = a_base_row // fx.Int32(32) + q * fx.Int32(self._a_wave_groups) + g_b = b_base_row // fx.Int32(32) + q * fx.Int32(self._b_wave_groups) + self._G = _uniform_i32(is_a.select(g_a, g_b)) + self._HS = _uniform_i32( + is_a.select(fx.Int32(self._a_half_groups), fx.Int32(self._b_half_groups)) + ) + self._rsrc = fx.arith.select(is_a, self.a_rsrc, self.b_rsrc) + self._soff0 = _uniform_i32(fx.Int32(0)) + + def gather(self, kstep, slot): + grp = ( + fx.Int32(self._G) + (self._blk // 2) * fx.Int32(self._HS) + (self._blk % 2) + ) + i32_off = ( + grp * fx.Int32(self.row_i32) + + fx.Int32(kstep) * fx.Int32(64) + + self._in16 * fx.Int32(4) + ) + voff = fx.as_ir_value(i32_off * fx.Int32(4)) # bytes + addr = fx.Int32(self._wave_base_s) + fx.Int32(slot) * fx.Int32( + _SCALE_SLOT_BYTES + ) + asm = "s_mov_b32 m0, $0\nbuffer_load_dwordx4 $1, $2, $3 offen lds" + _asm_void( + [fx.as_ir_value(addr), voff, self._rsrc, self._soff0], + asm, + "s,v,s,s", + "~{m0}", + ) + + +class ScaleLoaderLDS: + def __init__(self, n_tiles, lane_id, quarter, lds_base_ptr, region_off): + assert n_tiles % _FP4_PACK == 0 + self.n_groups = n_tiles // _FP4_PACK + self.lane_id = lane_id + self._region_base = ( + fx.Int32(fx.ptrtoint(lds_base_ptr)) + + fx.Int32(region_off) + + quarter * fx.Int32(_SCALE_QUARTER_BYTES) + ) + + def _slot_wave_byte(self, slot): + return self._region_base + fx.Int32(slot) * fx.Int32(_SCALE_SLOT_BYTES) + + def read_half(self, slot, half): + L = self.lane_id + base = self._slot_wave_byte(slot) + fx.Int32((L // 4) * 16 + (L % 4) * 4) + grp_list = [] + for gi in range_constexpr(self.n_groups): + blk = half * 2 + gi + vaddr = base + fx.Int32(blk * 256) + lds_ptr = _llvm.inttoptr(_lds_ptr_t(), fx.as_ir_value(vaddr)) + load = _llvm.LoadOp(fx.Int32.ir_type, lds_ptr, alignment=4) + grp_list.append(fx.Int32(load.result)) + return grp_list + + def read(self, slot): + return self.read_half(slot, 0), self.read_half(slot, 1) + + +# ── epilogue helpers ───────────────────────────────────────────────────────── +def _fmax(a, b): + return (a > b).select(a, b) + + +def _fmin(a, b): + return (a < b).select(a, b) + + +def _swiglu_oai(g, u): + """MiniMax-M3 activation, op for op the production stage-1 epilogue (aiter + mixed_moe_gemm_2stage ``swiglu_mul_vec4``): g clamped above, u clamped both + sides, t = (g * alpha) * (-log2 e), sigmoid = rcp(1 + exp2(t)), g * sig * (u + 1). + The two separate multiplies matter: folding the constant changes the last bit.""" + lim = fx.Float32(SWIGLU_LIMIT) + g = _fmin(g, lim) + u = _fmax(_fmin(u, lim), fx.Float32(-SWIGLU_LIMIT)) + t = (g * fx.Float32(SWIGLU_ALPHA)) * fx.Float32(-1.4426950408889634) + e = fx.Float32(_rocdl.exp2(_T.f32, t.ir_value())) + sig = fx.Float32(_rocdl.rcp(_T.f32, (fx.Float32(1.0) + e).ir_value())) + return g * sig * (u + fx.Float32(1.0)) + + +def _round_bf16x2(a, b): + """(a, b) -> the f32 values of their bf16 roundings (RNE, v_cvt_pk_bf16_f32): + production stage 1 stores bf16 and quantises from it.""" + w = Vec.from_elements([a, b], fx.Float32).to(fx.BFloat16).bitcast(fx.Int32)[0] + return _as_f32(w << 16), _as_f32(w & fx.Int32(-65536)) + + +def _quant_prep_fp4(h8): + """Production's inter-stage quant on 8 values of one 32-block: round them to + bf16 and return (rounded values, this lane's |max|).""" + hb = [] + for k in range_constexpr(0, 8, 2): + lo, hi = _round_bf16x2(h8[k], h8[k + 1]) + hb += [lo, hi] + amax = fx.math.absf(hb[0]) + for v in range_constexpr(1, 8): + amax = _fmax(amax, fx.math.absf(hb[v])) + return hb, amax + + +def _e8m0_roundup_fp4(amax): + """Aiter's default MX scale rule (kDefaultMxScaleRoundMode = RoundUp): + ceil_pow2(amax / 6) as a biased exponent (fp4 max = 6): the block's max lands in + (3, 6]. Exponent 0xFF (NaN/Inf) is not bumped.""" + u = _bits(amax * fx.Float32(1.0 / 6.0)) + e = (u >> 23) & fx.Int32(0xFF) + bump = ((u & fx.Int32(0x7FFFFF)) != fx.Int32(0)) & (e < fx.Int32(0xFF)) + return bump.select(e + fx.Int32(1), e) + + +def _bits(f): + return fx.Float32(f).bitcast(fx.Int32) + + +def _as_f32(i): + return fx.Int32(i).bitcast(fx.Float32) + + +def _cvt_pk_fp4(old, a, b, scale_f32, sel): + """v_cvt_scalef32_pk_fp4_f32: two f32 / 2^(e8m0-127) -> 2 fp4 into byte ``sel``.""" + return fx.Int32(_rocdl.cvt_scalef32_pk_fp4_f32(_T.i32, old, a, b, scale_f32, sel)) + + +def _permlane16_swap(d_a, d_b): + pair_ty = _ir.Type.parse("!llvm.struct<(i32, i32)>") + res = _rocdl.permlane16_swap( + pair_ty, fx.as_ir_value(d_a), fx.as_ir_value(d_b), False, False + ) + return fx.Int32(_llvm.extractvalue(_T.i32, res, [0])), fx.Int32( + _llvm.extractvalue(_T.i32, res, [1]) + ) + + +def compile_moe_gemm1( + *, + H: int, + I: int, # noqa: E741 + E: int, + BLOCK_M: int = 128, +): + """Grouped fp4 gemm1 for one (H, I, E, BLOCK_M). ``BLOCK_M`` must equal the + ``moe_sorting`` block size the sorted inputs were built with (128 or 256). + + Block order comes from an int32 table built on the GPU by ``tile_map.py`` + (one small kernel; ``tile_map[grid_size]`` holds the number of valid entries, + so no host sync): ``tile_map[remapped block] = m_tile << 3 | n_tile`` (-1 = + nothing to do), laid out expert by expert and n-slab-major inside an expert, + so the 32 CUs of one XCD chew through one expert with the same 768 KB + gate/up slab of W13 in L2. The hardware deals + consecutive block ids round-robin over the 8 XCDs, so block id b is first + remapped to ``(b % 8) * (grid / 8) + b // 8`` = a contiguous chunk of the + table per XCD.""" + K = H + BLOCK_K = 256 + BLOCK_K_BYTES = BLOCK_K // 2 + BLOCK_N = 256 # 128 gate cols + the matching 128 up cols + LDS_BLOCK_M = BLOCK_M // 2 + LDS_BLOCK_N = BLOCK_N // 2 + N_TILES_A = LDS_BLOCK_M // 2 // 16 # 16-row tiles per wave per LDS half + N_TILES_B = LDS_BLOCK_N // 2 // 16 # = 4 + + assert BLOCK_M in (128, 256) + assert K % BLOCK_K == 0 and I % LDS_BLOCK_N == 0 and (2 * I) % 256 == 0 + K_ITERS = K // BLOCK_K + UNROLL = 4 if (K_ITERS - 4) % 4 == 0 else 2 + assert K_ITERS >= 4 and (K_ITERS - 4) % UNROLL == 0, K_ITERS + N_ACCUMS = N_TILES_A * N_TILES_B + K_BYTES = K // 2 + + a_lds_size = LDS_BLOCK_M * BLOCK_K_BYTES # 8 KB (BM128) / 16 KB (BM256) + b_lds_size = LDS_BLOCK_N * BLOCK_K_BYTES # 16 KB + A_BUFS = 4 * a_lds_size + LDS_TILES_BYTES = A_BUFS + 4 * b_lds_size + + # scale geometry (32-row groups) + A_WAVE_GROUPS = N_TILES_A // 2 # groups per wave per LDS half + A_HALF_GROUPS = LDS_BLOCK_M // 32 + B_WAVE_GROUPS = N_TILES_B // 2 + B_HALF_GROUPS = I // 32 # gate slab -> up slab + I_BYTES = I // 2 + SCALE_COLS_OUT = I // 32 # e8m0 per output row + OUT_SC_BLOCKS_PER_ROW32 = SCALE_COLS_OUT // 8 + + @fx.struct + class SharedStorage: + all_lds: fx.Array[fx.Int8, LDS_TILES_BYTES, 16] + scale_lds: fx.Array[fx.Int8, _SCALE_LDS_BYTES, 16] + + @flyc.kernel + def kernel_gemm1( + A: fx.Tensor, + W13: fx.Tensor, + OUT_Q: fx.Tensor, + A_scale: fx.Tensor, + W13_scale: fx.Tensor, + OUT_scale: fx.Tensor, + sorted_ids: fx.Tensor, + sorted_expert_ids: fx.Tensor, + n_tokens: fx.Int32, + num_m_blocks: fx.Int32, + a_scale_bytes: fx.Int32, + tile_map_t: fx.Tensor, + grid_size: fx.Int32, + ): + lds = fx.SharedAllocator().allocate(SharedStorage).peek() + _base_ptr = lds.all_lds.ptr + + a_cur0 = _Buf(_base_ptr, 0 * a_lds_size) + a_cur1 = _Buf(_base_ptr, 1 * a_lds_size) + a_next0 = _Buf(_base_ptr, 2 * a_lds_size) + a_next1 = _Buf(_base_ptr, 3 * a_lds_size) + b_cur0 = _Buf(_base_ptr, A_BUFS + 0 * b_lds_size) + b_cur1 = _Buf(_base_ptr, A_BUFS + 1 * b_lds_size) + b_next0 = _Buf(_base_ptr, A_BUFS + 2 * b_lds_size) + b_next1 = _Buf(_base_ptr, A_BUFS + 3 * b_lds_size) + + lane_id = fx.thread_idx.x % 64 + wave_id = fx.thread_idx.x // 64 + + ids_rsrc = buffer_ops.create_buffer_resource( + sorted_ids, max_size=False, num_records_bytes=num_m_blocks * (BLOCK_M * 4) + ) + eid_rsrc = buffer_ops.create_buffer_resource( + sorted_expert_ids, max_size=False, num_records_bytes=num_m_blocks * 4 + ) + # split the valid entries [0, tile_map[grid_size]) evenly over the 8 XCDs + intra_xcd, xcd = _divmod_nonneg(fx.block_idx.x, 8) + tm_rsrc = buffer_ops.create_buffer_resource( + tile_map_t, max_size=False, num_records_bytes=(grid_size + 1) * 4 + ) + n_valid = fx.Int32( + buffer_ops.buffer_load( + tm_rsrc, grid_size, vec_width=1, dtype=fx.Int32, is_scalar=True + ) + ) + per_xcd = (n_valid + fx.Int32(7)) // fx.Int32(8) + remapped = xcd * per_xcd + intra_xcd + in_chunk = (intra_xcd < per_xcd) & (remapped < n_valid) + entry = fx.Int32( + buffer_ops.buffer_load( + tm_rsrc, + in_chunk.select(remapped, fx.Int32(0)), + vec_width=1, + dtype=fx.Int32, + ) + ) + entry = in_chunk.select(entry, fx.Int32(-1)) + tile_i = entry >> 3 + tile_j = entry & 7 + block_valid = entry >= 0 + # ---- routing: this m-tile's expert ---- + expert = fx.Int32( + buffer_ops.buffer_load(eid_rsrc, tile_i, vec_width=1, dtype=fx.Int32) + ) + m_base = tile_i * BLOCK_M + + if block_valid: + wave_i = wave_id // 2 + wave_j = wave_id % 2 + + # ---- A rows: gathered. token(sorted row) * K_BYTES + swizzled col ---- + def _a_gather_offsets(half): + offs = [] + for rnd in range_constexpr(N_TILES_A): + row = lane_id // 8 + wave_id * 8 + rnd * (_N_WAVES * 8) + col = (lane_id % 8) * 16 + sid = fx.Int32( + buffer_ops.buffer_load( + ids_rsrc, + m_base + half * LDS_BLOCK_M + row, + vec_width=1, + dtype=fx.Int32, + ) + ) + tok = sid & fx.Int32( + 0x00FFFFFF + ) # padded rows: tok == n_tokens -> OOB -> zeros + offs.append(tok * fx.Int32(K_BYTES) + _swizzled_col(row, col)) + return offs + + gl_off_a0 = _a_gather_offsets(0) + gl_off_a1 = _a_gather_offsets(1) + + # ---- B: gate slab rows [e*2I + j*128, +128), up slab +I ---- + def _b_offsets(): + offs = [] + for rnd in range_constexpr(N_TILES_B): + row = lane_id % 8 + wave_id * 8 + rnd * (_N_WAVES * 8) + col = (lane_id // 8) * 16 + offs.append( + (row // 16) * (K_BYTES * 16) + + (row % 16) * 16 + + (col // 64) * 1024 + + ((col % 64) // 16) * 256 + + (col % 16) + ) + return offs + + gl_off_b = _b_offsets() + b_row0 = expert * (2 * I) + tile_j * LDS_BLOCK_N + B0_gl_offset = b_row0 * K_BYTES + B1_gl_offset = B0_gl_offset + I * K_BYTES + A_K_STEP = BLOCK_K_BYTES + B_K_STEP = 2 * 1024 + + mfma = Mfma16x16x128Fp4(N_TILES_A, N_TILES_B) + + _scale_base_ptr = lds.scale_lds.ptr + scale_gather = ScaleGatherMoE( + A_scale, + W13_scale, + K, + lane_id, + wave_id, + _scale_base_ptr, + a_scale_bytes, + E * 2 * I * (K // 32), + A_WAVE_GROUPS, + A_HALF_GROUPS, + B_WAVE_GROUPS, + B_HALF_GROUPS, + ) + scale_gather.set_wave_base(m_base, b_row0) + a_scale_ld = ScaleLoaderLDS( + N_TILES_A, lane_id, wave_i, _scale_base_ptr, _SCALE_A_REGION + ) + b_scale_ld = ScaleLoaderLDS( + N_TILES_B, lane_id, wave_j, _scale_base_ptr, _SCALE_B_REGION + ) + + def _slot(k): + return fx.Int32(k) % fx.Int32(_SCALE_SLOTS) + + def _gather_scale_thunks(k, slot): + return [lambda: scale_gather.gather(k, slot)] + + a_rsrc = buffer_ops.create_buffer_resource( + A, max_size=False, num_records_bytes=n_tokens * K_BYTES + ) + b_rsrc = buffer_ops.create_buffer_resource( + W13, max_size=False, num_records_bytes=E * (2 * I) * K_BYTES + ) + a0_g2s = G2SLoaderAsm(a_rsrc, gl_off_a0, N_TILES_A, wave_id) + a1_g2s = G2SLoaderAsm(a_rsrc, gl_off_a1, N_TILES_A, wave_id) + b_g2s = G2SLoaderAsm(b_rsrc, gl_off_b, N_TILES_B, wave_id) + a0_g2s.set_wave_base(_base_ptr) + a1_g2s.set_wave_base(_base_ptr) + b_g2s.set_wave_base(_base_ptr) + a_s2r = S2RLoaderFp4(wave_i, N_TILES_A) + b_s2r = S2RLoaderFp4(wave_j, N_TILES_B) + + scale_gather.gather(0, _slot(0)) + scale_gather.gather(1, _slot(1)) + scale_gather.gather(2, _slot(2)) + + a0_g2s.load(a_cur0, fx.Int32(0 * A_K_STEP)) + b_g2s.load(b_cur0, B0_gl_offset + 0 * B_K_STEP) + b_g2s.load(b_cur1, B1_gl_offset + 0 * B_K_STEP) + a1_g2s.load(a_cur1, fx.Int32(0 * A_K_STEP)) + + a0_g2s.load(a_next0, fx.Int32(1 * A_K_STEP)) + b_g2s.load(b_next0, B0_gl_offset + 1 * B_K_STEP) + b_g2s.load(b_next1, B1_gl_offset + 1 * B_K_STEP) + a1_g2s.load(a_next1, fx.Int32(1 * A_K_STEP)) + + # 3 gathers + a_cur0 landed: b0/b1/a1 + the 4 next batches may fly + wait_barrier((3 * N_TILES_A) + (4 * N_TILES_B)) + a0_frag = a_s2r.load(a_cur0) + # b_cur0 AND b_cur1 landed: a1 + the 4 next batches may fly + wait_barrier((3 * N_TILES_A) + (2 * N_TILES_B)) + b0_frag = b_s2r.load(b_cur0, preshuffled=True) + b1_frag = b_s2r.load(b_cur1, preshuffled=True) + + sc0_saR0, sc0_saR1 = a_scale_ld.read(_slot(0)) + sc0_sbC0, sc0_sbC1 = b_scale_ld.read(_slot(0)) + sc0 = (sc0_saR0, sc0_saR1, sc0_sbC0, sc0_sbC1) + + # a step issues a0 (NA), b0 (NB), [SEG2], b1 (NB), gather (1), a1 (NA); + # the waits are exact: one load too many stalls on a fetch from HBM + _MAIN_VMCNT = 2 * N_TILES_A + 2 * N_TILES_B + 1 + _SEG2_VMCNT = 2 * N_TILES_A + N_TILES_B + 1 + # step 0 follows the prologue's issue order; one count looser races + _STEP0_VMCNT = 2 * N_TILES_A + 2 * N_TILES_B + _STEP0_SEG2_VMCNT = 2 * N_TILES_A + N_TILES_B + + def _read_scale_thunks(kc_idx, holder): + s = _slot(kc_idx) + + def _r(dst, ld, half, _s=s): + holder[dst] = ld.read_half(_s, half) + + return [ + lambda: _r(0, a_scale_ld, 0), + lambda: _r(1, a_scale_ld, 1), + lambda: _r(2, b_scale_ld, 0), + lambda: _r(3, b_scale_ld, 1), + ] + + def _one_step( + kc, + a0f, + b0f, + b1f_in, + sc, + accs, + bufs, + zero_acc=False, + top_vmcnt=None, + seg2_vmcnt=None, + ): + top_vmcnt = _MAIN_VMCNT if top_vmcnt is None else top_vmcnt + seg2_vmcnt = _SEG2_VMCNT if seg2_vmcnt is None else seg2_vmcnt + ac0, ac1, an0, an1, bc0, bc1, bn0, bn1 = bufs + saR0, saR1, sbC0, sbC1 = sc + c00f, c01f, c10f, c11f = accs + kc_i = fx.Int32(kc) + + _a1 = [None] * N_TILES_A + _a0n = [None] * N_TILES_A + _b0n = [None] * N_TILES_B + _b1n = [None] * N_TILES_B + ak = (kc_i + fx.Int32(2)) * fx.Int32(A_K_STEP) + bk = (kc_i + fx.Int32(2)) * fx.Int32(B_K_STEP) + a0_off = ak + a1_off = ak + b0_off = fx.Int32(B0_gl_offset) + bk + b1_off = fx.Int32(B1_gl_offset) + bk + + _scn = [None, None, None, None] + _rd_scn = _read_scale_thunks(kc_i + 1, _scn) + _gk = _min(kc_i + fx.Int32(3), fx.Int32(K_ITERS - 1)) + _sc_gather = _gather_scale_thunks(_gk, _slot(_gk)) + + wait_barrier(top_vmcnt) + il = ( + _riffle( + _g2s_thunks(a0_g2s, ac0, a0_off, N_TILES_A), + _s2r_thunks(a_s2r, ac1, _a1, N_TILES_A, False), + ) + + _rd_scn[:2] + ) + c00f = mfma.call( + a0f, b0f, c00f, saR0, sbC0, interleave=il, zero_acc=zero_acc + ) + + il = _riffle(_g2s_thunks(b_g2s, bc0, b0_off, N_TILES_B), _rd_scn[2:]) + c01f = mfma.call( + a0f, b1f_in, c01f, saR0, sbC1, interleave=il, zero_acc=zero_acc + ) + a1f = _a1 + + wait_barrier(seg2_vmcnt) + il = ( + _riffle( + _g2s_thunks(b_g2s, bc1, b1_off, N_TILES_B), + _s2r_thunks(a_s2r, an0, _a0n, N_TILES_A, False), + ) + + _sc_gather + ) + c10f = mfma.call( + a1f, b0f, c10f, saR1, sbC0, interleave=il, zero_acc=zero_acc + ) + a0nf = _a0n + + il = _riffle( + _g2s_thunks(a1_g2s, ac1, a1_off, N_TILES_A), + _s2r_thunks(b_s2r, bn0, _b0n, N_TILES_B, True) + + _s2r_thunks(b_s2r, bn1, _b1n, N_TILES_B, True), + ) + c11f = mfma.call( + a1f, b1f_in, c11f, saR1, sbC1, interleave=il, zero_acc=zero_acc + ) + b0nf = _b0n + b1nf = _b1n + + sc_next = (_scn[0], _scn[1], _scn[2], _scn[3]) + new_bufs = (an0, an1, ac0, ac1, bn0, bn1, bc0, bc1) + return a0nf, b0nf, b1nf, sc_next, (c00f, c01f, c10f, c11f), new_bufs + + bufs0 = (a_cur0, a_cur1, a_next0, a_next1, b_cur0, b_cur1, b_next0, b_next1) + + def _swap_bufs(bufs): + ac0, ac1, an0, an1, bc0, bc1, bn0, bn1 = bufs + return (an0, an1, ac0, ac1, bn0, bn1, bc0, bc1) + + n_a = 2 * N_TILES_A + n_b = 2 * N_TILES_B + n_ga = N_TILES_A // _FP4_PACK + n_gb = N_TILES_B // _FP4_PACK + n_sc = 2 * n_ga + 2 * n_gb + _R = fx.as_ir_value + + def _flat_sc(sc): + saR0, saR1, sbC0, sbC1 = sc + return ( + [_R(v) for v in saR0] + + [_R(v) for v in saR1] + + [_R(v) for v in sbC0] + + [_R(v) for v in sbC1] + ) + + def _unflat_sc(flat): + o = 0 + saR0 = list(flat[o : o + n_ga]) + o += n_ga + saR1 = list(flat[o : o + n_ga]) + o += n_ga + sbC0 = list(flat[o : o + n_gb]) + o += n_gb + sbC1 = list(flat[o : o + n_gb]) + o += n_gb + return (saR0, saR1, sbC0, sbC1) + + _accs0 = ( + [None] * N_ACCUMS, + [None] * N_ACCUMS, + [None] * N_ACCUMS, + [None] * N_ACCUMS, + ) + a0f, b0f, b1f, sc, accs, _ = _one_step( + 0, + a0_frag, + b0_frag, + b1_frag, + sc0, + _accs0, + bufs0, + zero_acc=True, + top_vmcnt=_STEP0_VMCNT, + seg2_vmcnt=_STEP0_SEG2_VMCNT, + ) + a0f, b0f, b1f, sc, accs, _ = _one_step( + 1, a0f, b0f, b1f, sc, accs, _swap_bufs(bufs0) + ) + + init_state = ( + _flat_frag(a0f) + + _flat_frag(b0f) + + _flat_frag(b1f) + + _flat_sc(sc) + + [_R(x) for x in accs[0]] + + [_R(x) for x in accs[1]] + + [_R(x) for x in accs[2]] + + [_R(x) for x in accs[3]] + ) + for kk, state in range(2, K_ITERS - 2, UNROLL, init=init_state): + off = 0 + a0f = _unflat_frag(state[off : off + n_a], N_TILES_A) + off += n_a + b0f = _unflat_frag(state[off : off + n_b], N_TILES_B) + off += n_b + b1f = _unflat_frag(state[off : off + n_b], N_TILES_B) + off += n_b + sc = _unflat_sc(state[off : off + n_sc]) + off += n_sc + c00f = list(state[off : off + N_ACCUMS]) + off += N_ACCUMS + c01f = list(state[off : off + N_ACCUMS]) + off += N_ACCUMS + c10f = list(state[off : off + N_ACCUMS]) + off += N_ACCUMS + c11f = list(state[off : off + N_ACCUMS]) + off += N_ACCUMS + accs = (c00f, c01f, c10f, c11f) + + bufs = bufs0 + for u in range_constexpr(UNROLL): + a0f, b0f, b1f, sc, accs, bufs = _one_step( + kk + u, a0f, b0f, b1f, sc, accs, bufs + ) + + new_state = ( + _flat_frag(a0f) + + _flat_frag(b0f) + + _flat_frag(b1f) + + _flat_sc(sc) + + [_R(x) for x in accs[0]] + + [_R(x) for x in accs[1]] + + [_R(x) for x in accs[2]] + + [_R(x) for x in accs[3]] + ) + state = yield new_state + + off = 0 + a0_frag = _unflat_frag(state[off : off + n_a], N_TILES_A) + off += n_a + b0_frag = _unflat_frag(state[off : off + n_b], N_TILES_B) + off += n_b + b1_frag = _unflat_frag(state[off : off + n_b], N_TILES_B) + off += n_b + sc = _unflat_sc(state[off : off + n_sc]) + off += n_sc + c00_frag = list(state[off : off + N_ACCUMS]) + off += N_ACCUMS + c01_frag = list(state[off : off + N_ACCUMS]) + off += N_ACCUMS + c10_frag = list(state[off : off + N_ACCUMS]) + off += N_ACCUMS + c11_frag = list(state[off : off + N_ACCUMS]) + off += N_ACCUMS + + # Tail step K_ITERS - 2 + saR0, saR1, sbC0, sbC1 = sc + _scn = [None, None, None, None] + _rd_scn = _read_scale_thunks(fx.Int32(K_ITERS - 1), _scn) + _a1 = [None] * N_TILES_A + wait_barrier((2 * N_TILES_A) + (2 * N_TILES_B)) + il = _s2r_thunks(a_s2r, a_cur1, _a1, N_TILES_A, False) + _rd_scn + c00_frag = mfma.call(a0_frag, b0_frag, c00_frag, saR0, sbC0, interleave=il) + a1_frag = _a1 + c01_frag = mfma.call(a0_frag, b1_frag, c01_frag, saR0, sbC1) + _a0n = [None] * N_TILES_A + _b0n = [None] * N_TILES_B + _b1n = [None] * N_TILES_B + wait_barrier(1 * N_TILES_A) + il = ( + _s2r_thunks(a_s2r, a_next0, _a0n, N_TILES_A, False) + + _s2r_thunks(b_s2r, b_next0, _b0n, N_TILES_B, True) + + _s2r_thunks(b_s2r, b_next1, _b1n, N_TILES_B, True) + ) + c10_frag = mfma.call(a1_frag, b0_frag, c10_frag, saR1, sbC0, interleave=il) + c11_frag = mfma.call(a1_frag, b1_frag, c11_frag, saR1, sbC1) + a0_frag = _a0n + b0_frag = _b0n + b1_frag = _b1n + + # Tail step K_ITERS - 1 (its A half 1 sits in a_next1; the scf.if + # rewriter must not see the outer buffer names reassigned here). + _a1 = [None] * N_TILES_A + wait_barrier(0) + saR0, saR1, sbC0, sbC1 = (_scn[0], _scn[1], _scn[2], _scn[3]) + il = _s2r_thunks(a_s2r, a_next1, _a1, N_TILES_A, False) + c00_frag = mfma.call(a0_frag, b0_frag, c00_frag, saR0, sbC0, interleave=il) + a1_frag = _a1 + c01_frag = mfma.call(a0_frag, b1_frag, c01_frag, saR0, sbC1) + c10_frag = mfma.call(a1_frag, b0_frag, c10_frag, saR1, sbC0) + c11_frag = mfma.call(a1_frag, b1_frag, c11_frag, saR1, sbC1) + + # ---- epilogue: swiglu-OAI + MXFP4 quant, sorted-row output ---- + out_rsrc = buffer_ops.create_buffer_resource( + OUT_Q, + max_size=False, + num_records_bytes=num_m_blocks * (BLOCK_M * I_BYTES), + ) + osc_rsrc = buffer_ops.create_buffer_resource( + OUT_scale, + max_size=False, + num_records_bytes=num_m_blocks * (BLOCK_M * SCALE_COLS_OUT), + ) + g = lane_id // 16 + r16 = lane_id % 16 + # gate column (in I units) this wave starts at; scale col group of it + col_base = tile_j * LDS_BLOCK_N + wave_j * (N_TILES_B * 16) + colgrp_base = col_base // 32 + + def _epilogue(c_gate, c_up, base_row): + """One quadrant pair (rows base_row + ti*16 + r16, wave's 64 gate + cols).""" + for p in range_constexpr(N_TILES_B // 2): # 32-col group p + colgrp = colgrp_base + p + sc_in_block = (colgrp % 4) * 64 + r16 * 4 + ((colgrp % 8) // 4) * 2 + e8m0_of_ti = [] + for ti in range_constexpr(N_TILES_A): + gv = Vec(c_gate[mfma.idx(ti, 2 * p)]) + gw = Vec(c_gate[mfma.idx(ti, 2 * p + 1)]) + uv = Vec(c_up[mfma.idx(ti, 2 * p)]) + uw = Vec(c_up[mfma.idx(ti, 2 * p + 1)]) + h = [ + _swiglu_oai(fx.Float32(gv[v]), fx.Float32(uv[v])) + for v in range_constexpr(4) + ] + [ + _swiglu_oai(fx.Float32(gw[v]), fx.Float32(uw[v])) + for v in range(4) + ] + h, amax = _quant_prep_fp4(h) + # the 4 lanes {L, L^16, L^32, L^48} hold the same row + amax = _fmax(amax, amax.shuffle_xor(16, 64)) + amax = _fmax(amax, amax.shuffle_xor(32, 64)) + e8m0 = _e8m0_roundup_fp4(amax) + e8m0_of_ti.append(e8m0) + scale_f = _as_f32(e8m0 << 23) + pa = _cvt_pk_fp4(fx.Int32(0), h[0], h[1], scale_f, 0) + pa = _cvt_pk_fp4(pa, h[2], h[3], scale_f, 1) + pb = _cvt_pk_fp4(fx.Int32(0), h[4], h[5], scale_f, 0) + pb = _cvt_pk_fp4(pb, h[6], h[7], scale_f, 1) + pa, pb = _permlane16_swap(pa, pb) + dword = pa | (pb << 16) + row = base_row + ti * 16 + r16 + # after the swap lane group g holds tile (2p + g%2), cols + # (g//2)*8 .. +8 + col = col_base + (2 * p + (g % 2)) * 16 + (g // 2) * 8 + buffer_ops.buffer_store( + dword, + out_rsrc, + row * I_BYTES + col // 2, + offset_is_bytes=True, + ) + # scales: rows ti (h=0) and ti+1 (h=1) of the same 32-row group -> + # i16 + for tp in range_constexpr(N_TILES_A // 2): + row32 = (base_row // 32) + tp + blk = row32 * OUT_SC_BLOCKS_PER_ROW32 + colgrp // 8 + pair = e8m0_of_ti[2 * tp] | (e8m0_of_ti[2 * tp + 1] << 8) + pair16 = fx.Int32(pair).to(fx.Int16) + buffer_ops.buffer_store( + pair16, + osc_rsrc, + blk * 256 + sc_in_block, + offset_is_bytes=True, + ) + + row_r0 = m_base + wave_i * (N_TILES_A * 16) + row_r1 = row_r0 + LDS_BLOCK_M + _epilogue(c00_frag, c01_frag, row_r0) + _epilogue(c10_frag, c11_frag, row_r1) + + @flyc.jit + def launch_gemm1( + A: fx.Tensor, + W13: fx.Tensor, + OUT_Q: fx.Tensor, + A_scale: fx.Tensor, + W13_scale: fx.Tensor, + OUT_scale: fx.Tensor, + sorted_ids: fx.Tensor, + sorted_expert_ids: fx.Tensor, + n_tokens: fx.Int32, + num_m_blocks: fx.Int32, + a_scale_bytes: fx.Int32, + tile_map_t: fx.Tensor, + grid_size: fx.Int32, + stream: fx.Stream, + ): + grid_x = grid_size + kernel_gemm1( + A, + W13, + OUT_Q, + A_scale, + W13_scale, + OUT_scale, + sorted_ids, + sorted_expert_ids, + n_tokens, + num_m_blocks, + a_scale_bytes, + tile_map_t, + grid_size, + value_attrs={ + "rocdl.waves_per_eu": 1, + "rocdl.flat_work_group_size": "256,256", + }, + ).launch(grid=(grid_x, 1, 1), block=(256, 1, 1), stream=stream) + + return launch_gemm1 diff --git a/vllm/models/minimax_m3/amd/ops/moe_mxfp4/gemm2_prefill.py b/vllm/models/minimax_m3/amd/ops/moe_mxfp4/gemm2_prefill.py new file mode 100644 index 000000000000..7725aecd1a49 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/moe_mxfp4/gemm2_prefill.py @@ -0,0 +1,1088 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +"""MiniMax-M3 prefill MoE stage 2 (a4w4, down projection), token-major output. + + y[tok, slot, :] = h[row, :] @ W2[e]^T row = sorted row of (tok, slot) + +``out_dtype`` "bf16": out[tok*topk + slot, :] = bf16(y * sorted_weights[row]), summed +by the bf16 reduce; "fp8": MXFP8 rows with the routing weights left to the reduce. + +One CTA owns an m-tile of 128 sorted rows and sweeps ``NT`` n-tiles of 256 columns: +K = I = 768 is only 3 K-steps, so the A tile stays in AGPRs for the whole sweep and +the (n-tile, k-step) sequence is one depth-3 pipeline. The epilogue runs in the MFMA +shadow and writes token-major 128-B lines; padded rows fall outside the buffer +resource. Consecutive m-tiles (same expert) go to the same XCD. + +Layouts (bytes): + A [num_m_blocks*BM, I/2] sorted rows, fp4 (gemm1 OUT_Q) + A_scale [num_m_blocks*BM, I/32] sorted rows, e8m0-shuffled (gemm1 OUT_sc) + W2 [E, H, I/2] aiter shuffle_weight(layout=(16,16)) + W2_sc [E*H, I/32] aiter e8m0_shuffle + sorted_w [num_m_blocks*BM] f32 routing weight per sorted row (bf16 mode) + OUT [n_tokens*topk, H] bf16, or fp8 e4m3 (OCP) + OUT_sc [n_tokens*topk, H/32] e8m0 (fp8 mode; any buffer in bf16 mode) +""" + +import flydsl.compiler as flyc +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import buffer_ops +from flydsl._mlir import ir as _ir +from flydsl._mlir.dialects import arith as _arith +from flydsl._mlir.dialects import llvm as _llvm +from flydsl.expr import const_expr, range_constexpr +from flydsl.expr import rocdl as _rocdl +from flydsl.expr.typing import T as _T +from flydsl.expr.typing import Vector as Vec + +from .gemm1_prefill import ( + _N_WAVES, + G2SLoaderAsm, + Mfma16x16x128Fp4, + S2RLoaderFp4, + _as_f32, + _asm_void, + _bits, + _Buf, + _divmod_nonneg, + _g2s_thunks, + _lds_ptr_t, + _min, + _permlane16_swap, + _s2r_thunks, + _swizzled_col, + _uniform_i32, + wait_barrier, +) + +_NUM_XCDS = 8 + + +class _MfmaAgprAB(Mfma16x16x128Fp4): + """Same MFMA, but both matrix fragments come from AGPRs (A pinned there for the + whole n-sweep, B loaded there by ds_read) and the accumulator lives in VGPRs, so the + epilogue reads it without v_accvgpr_read copies.""" + + def _mfma_agpr(self, a_op, b_op, acc, sa_v, sb_v, ksub, ia, jb): + a_op, b_op = ( + b_op, + a_op, + ) # feeds (B, A): lane L holds C[row L%16, cols 4*(L//16)..] + sa_v, sb_v = sb_v, sa_v + ia, jb = jb, ia + opsel = f"op_sel:[{ia},{jb},0]" + opsel_hi = f"op_sel_hi:[{ksub},{ksub},0]" + src2 = "$0" if acc is not None else "0" + asm = ( + f"v_mfma_scale_f32_16x16x128_f8f6f4 $0, $1, $2, {src2}, $3, $4 " + f"{opsel} {opsel_hi} cbsz:4 blgp:4" + ) + ops = [ + fx.as_ir_value(a_op), + fx.as_ir_value(b_op), + fx.as_ir_value(sa_v), + fx.as_ir_value(sb_v), + ] + cons = "=v,a,a,v,v" + if acc is not None: + ops.append(fx.as_ir_value(acc)) + cons += ",0" + return _llvm.inline_asm(self.res_ty, ops, asm, cons, has_side_effects=True) + + +def _lds_ptr(addr_i32): + return _llvm.inttoptr(_lds_ptr_t(), fx.as_ir_value(addr_i32)) + + +def _lds_load_i32(addr_i32): + return fx.Int32( + _llvm.LoadOp(fx.Int32.ir_type, _lds_ptr(addr_i32), alignment=4).result + ) + + +def _lds_load_vec(addr_i32, n): + ty = _ir.VectorType.get([n], _T.i32) + return _llvm.LoadOp(ty, _lds_ptr(addr_i32), alignment=4 * n).result + + +def _lds_store_vec(vec, addr_i32, n): + _llvm.StoreOp(vec, _lds_ptr(addr_i32), alignment=4 * n) + + +def _bf16x2(a, b): + """Two f32 -> one i32 of 2 bf16 (RNE, v_cvt_pk_bf16_f32: the same conversion as + production's arith.truncf)""" + return Vec.from_elements([a, b], fx.Float32).to(fx.BFloat16).bitcast(fx.Int32)[0] + + +def _cvt_pk_fp8(old, a, b, scale_f32, hi: bool): + """v_cvt_scalef32_pk_fp8_f32: (a, b) / scale -> 2 x e4m3 into the low (hi=False) + or high 16 bits of ``old`` (the intrinsic works on <2 x i16>; i32 in/out here).""" + v2i16 = _ir.VectorType.get([2], _ir.IntegerType.get_signless(16)) + old_v = _llvm.bitcast(v2i16, fx.as_ir_value(old)) + res = _llvm.call_intrinsic( + v2i16, + "llvm.amdgcn.cvt.scalef32.pk.fp8.f32", + [ + old_v, + fx.as_ir_value(a), + fx.as_ir_value(b), + fx.as_ir_value(scale_f32), + fx.Boolean(hi).ir_value(), + ], + [], + [], + ) + return fx.Int32(_llvm.bitcast(_T.i32, res)) + + +def _e8m0_fp8(amax): + """floor(log2 amax) - 7, floored at 0: amax / 2^(e-127) lands in [128, 256), + inside e4m3 (max 448) with one bit of headroom, never saturates.""" + e = (_bits(amax) >> 23) - fx.Int32(7) + return (e > fx.Int32(0)).select(e, fx.Int32(0)) + + +def _fabs(v): + return fx.math.absf(v) + + +def _maxf(a, b): + """v_max_f32 (arith.maxnumf), not the select-based gemm1 helper""" + return fx.Float32(fx.arith.maxnumf(fx.as_ir_value(a), fx.as_ir_value(b))) + + +def _permlane32_swap(d_a, d_b): + pair_ty = _ir.Type.parse("!llvm.struct<(i32, i32)>") + res = _rocdl.permlane32_swap( + pair_ty, fx.as_ir_value(d_a), fx.as_ir_value(d_b), False, False + ) + return fx.Int32(_llvm.extractvalue(_T.i32, res, [0])), fx.Int32( + _llvm.extractvalue(_T.i32, res, [1]) + ) + + +def _maxf_nn(a, b): + """v_max_f32 with nnan. Without the flag LLVM canonicalizes both inputs first + (``v_max x, x, x``, maxnum must quiet sNaNs): 2 extra VALU per max in the + epilogue.""" + fm = _ir.Attribute.parse("#arith.fastmath") + return fx.Float32( + _arith.MaxNumFOp(fx.as_ir_value(a), fx.as_ir_value(b), fastmath=fm).result + ) + + +def _xlane_max4_pair(x, y): + """4-lane max (lanes L, L^16, L^32, L^48) of two values at once, both broadcast to + every lane, in 3 permlane swaps (2 x 2 done separately, plus 2 copies): + swap32(x, y) -> [x_lo|y_lo], [x_hi|y_hi]; max -> m = [X2 | Y2]; + swap16(m, m) + max -> M = [X4 X4 | Y4 Y4]; swap32(M, M) -> [X4|X4], [Y4|Y4].""" + a, b = _permlane32_swap(_bits(x), _bits(y)) + m = _bits(_maxf_nn(_as_f32(a), _as_f32(b))) + a, b = _permlane16_swap(m, m) + big = _bits(_maxf_nn(_as_f32(a), _as_f32(b))) + a, b = _permlane32_swap(big, big) + return _as_f32(a), _as_f32(b) + + +def _undef_i32(): + """Cvt destination whose other half is overwritten anyway: no v_mov 0 for it""" + return _llvm.mlir_undef(_T.i32) + + +def _lds_store_i16(v_i32, addr_i32): + h = _arith.TruncIOp(_ir.IntegerType.get_signless(16), fx.as_ir_value(v_i32)).result + _llvm.StoreOp(h, _lds_ptr(addr_i32), alignment=2) + + +def _ld_dword_asm(rsrc, voff_bytes): + """buffer_load_dword whose completion we account for ourselves: LLVM sees no load, + so it adds no vmcnt wait (which would drain the whole DMA stream). The result must + go through ``_wait_pin`` before any use; it stays live until then, so LLVM cannot + reuse the register while the load is in flight.""" + return fx.Int32( + _llvm.inline_asm( + _T.i32, + [ + fx.as_ir_value(voff_bytes), + fx.as_ir_value(rsrc), + _uniform_i32(fx.Int32(0)), + ], + "buffer_load_dword $0, $1, $2, $3 offen", + "=v,v,s,s", + has_side_effects=True, + ) + ) + + +def _wait_pin(vals, vmcnt): + """``s_waitcnt vmcnt(n)`` with every value tied through it: uses of the returned + values cannot be scheduled before the wait.""" + n = len(vals) + ty = _ir.Type.parse("!llvm.struct<(" + ", ".join(["i32"] * n) + ")>") + cons = ",".join(["=v"] * n + [str(i) for i in range(n)]) + res = _llvm.inline_asm( + ty, + [fx.as_ir_value(v) for v in vals], + f"s_waitcnt vmcnt({vmcnt})", + cons, + has_side_effects=True, + ) + return [fx.Int32(_llvm.extractvalue(_T.i32, res, [i])) for i in range(n)] + + +def _pin_vec4(v): + """Route an accumulator through a side-effecting no-op asm (tied VGPR operand): its + consumers cannot be scheduled before the asm, and the asm keeps its place among the + MFMA asms, so the reads happen 8+ MFMAs after the one that produced the value (the + compiler cannot see inline-asm MFMAs -> inserts no hazard wait states).""" + ty = Vec.make_type(4, fx.Float32) + return _llvm.inline_asm( + ty, [fx.as_ir_value(v)], "; pin $0", "=v,0", has_side_effects=True + ) + + +def _v2i32(a, b): + return Vec.from_elements([a, b], fx.Int32).ir_value() + + +class _BScaleGather: + """Per pipeline step the 8 e8m0 blocks (256 B = 32 W2 rows x 8 K-groups) of + the n-tile's 256 rows for one K-step, 2 ``buffer_load_dword ... lds`` per + wave (wave w fetches row-groups 2w, 2w+1 into slot bytes [2w*256, +512)).""" + + def __init__(self, rsrc, lane_id, wave_id, region_base_i32): + self.rsrc = fx.as_ir_value(rsrc) + self.voff = [ + fx.as_ir_value((wave_id * 2 + q) * fx.Int32(768) + lane_id * fx.Int32(4)) + for q in range(2) + ] + wave_u = fx.Int32(_rocdl.readfirstlane(_T.i32, fx.as_ir_value(wave_id))) + self.base_s = _uniform_i32(region_base_i32 + wave_u * fx.Int32(512)) + + def gather(self, slot_byte_off, soff_bytes): + m0 = fx.as_ir_value(fx.Int32(self.base_s) + slot_byte_off) + soff = _uniform_i32(soff_bytes) + asm = ( + "s_mov_b32 m0, $0\n" + "buffer_load_dword $1, $2, $3 offen lds\n" + "s_add_u32 m0, 256, m0\n" + "buffer_load_dword $4, $2, $3 offen lds" + ) + _asm_void( + [m0, self.voff[0], self.rsrc, soff, self.voff[1]], + asm, + "s,v,s,s,v", + "~{scc}", + ) + + +# non-temporal row stores (3-8% faster); the 4-B scale stores need L2 write combining +_STORE_CPOL = 0x2 +_STORE_CPOL_SC = 0 + + +def compile_moe_gemm2( + *, + H: int, + I: int, # noqa: E741 + E: int, + topk: int, + n_split: int = 2, + out_dtype: str = "bf16", + sort_block_m: int = 128, +): + """fp4 grouped down-projection with token-major output (see the module doc). + The CTA tile is always 128 sorted rows; ``sort_block_m`` (128 or 256) is the + block size of the sort that produced the rows: with 256, ``sorted_expert_ids`` + has one entry per 256 rows (index ``tile_i >> 1``) and a 128-row tile that + starts with a padding sentinel is all padding and is skipped.""" + assert out_dtype in ("bf16", "fp8"), out_dtype + FP8 = out_dtype == "fp8" + BM = 128 + assert sort_block_m in (128, 256), sort_block_m + EID_SHIFT = (sort_block_m // BM).bit_length() - 1 # 0 or 1 + BN = 256 + K = I + K_BYTES = K // 2 + BLOCK_K = 256 + BLOCK_K_BYTES = BLOCK_K // 2 + assert K % BLOCK_K == 0 + K_ITERS = K // BLOCK_K # 3 + assert K_ITERS == 3, "the flat pipeline uses LDS set = k-step (3 sets)" + N_TILES_ALL = H // BN # 24 + assert N_TILES_ALL % n_split == 0 + NT = N_TILES_ALL // n_split # n-tiles per CTA + assert NT % 2 == 0, "the n loop is unrolled by 2" + LDS_BLOCK_M = BM // 2 # 64 rows per A half + LDS_BLOCK_N = BN // 2 # 128 W2 rows per B half + N_TILES_A = LDS_BLOCK_M // 2 // 16 # 2 + N_TILES_B = LDS_BLOCK_N // 2 // 16 # 4 + N_ACCUMS = N_TILES_A * N_TILES_B + SC_COLS = K // 32 # 24 e8m0 per A row + SC_BLOCKS_PER_G = SC_COLS // 8 # 3 blocks of 256 B per 32-row group + OUT_ELEM = 1 if FP8 else 2 + OUT_ROW_BYTES = H * OUT_ELEM + OUT_SC_COLS = H // 32 + WAVE_COLS = BN // 2 # 128 output columns per wave per n-tile + + a_lds_size = LDS_BLOCK_M * BLOCK_K_BYTES # 8 KB + b_lds_size = LDS_BLOCK_N * BLOCK_K_BYTES # 16 KB + A_BYTES = K_ITERS * 2 * a_lds_size # 48 KB, whole A tile (prologue only) + B_SET_BYTES = 2 * b_lds_size # 32 KB + # set 2 lives in the A region (A is in registers before B(2) is issued) + B_SET_OFF = [A_BYTES, A_BYTES + B_SET_BYTES, 0] + LDS_TILES_BYTES = A_BYTES + 2 * B_SET_BYTES # 112 KB + A_SC_BYTES = 4096 # 12 blocks used (4 groups x 3 K-blocks), 4 waves x 1 KB DMA + B_SC_SLOT = 2048 # 8 blocks + B_SC_SLOTS = 4 + SC_LDS_BYTES = A_SC_BYTES + B_SC_SLOTS * B_SC_SLOT # 12 KB + B_SC_OFF = A_SC_BYTES + # staging: per wave 32 rows x 128 columns of the output element (+ fp8 scale bytes) + STG_ROW = WAVE_COLS * OUT_ELEM # 128 (fp8) / 256 (bf16) B per staged row + CH = STG_ROW // 16 # 16-B chunks per row: 8 / 16 + STG_DATA = 32 * STG_ROW + STG_SC = 32 * 4 if FP8 else 0 # 4 e8m0 per row per wave + STG_WAVE = (STG_DATA + STG_SC + 255) // 256 * 256 + STG_LDS_BYTES = _N_WAVES * STG_WAVE + ROWS_PER_ST = 64 // CH # rows covered by one dwordx4 wave store: 8 / 4 + N_ST = 32 // ROWS_PER_ST # data stores per flushed row half: 4 / 8 + assert LDS_TILES_BYTES + SC_LDS_BYTES + STG_LDS_BYTES <= 160 * 1024 + + NB = N_TILES_B + NG = 2 # gather loads per wave per step + P_STEP = 2 * NB + NG # loads per lane per step + ST = N_ST + (1 if FP8 else 0) # stores per lane per flush + + B_TILE_BYTES = BN * K_BYTES # W2 bytes per n-tile + B_K_STEP = 2 * 1024 # preshuffled: 128 B of K = 2 x (16 rows x 64 B) + + @fx.struct + class SharedStorage: + all_lds: fx.Array[fx.Int8, LDS_TILES_BYTES, 16] + scale_lds: fx.Array[fx.Int8, SC_LDS_BYTES, 16] + stage_lds: fx.Array[fx.Int8, STG_LDS_BYTES, 16] + + @flyc.kernel + def kernel_gemm2( + A: fx.Tensor, + W2: fx.Tensor, + OUT: fx.Tensor, + A_scale: fx.Tensor, + W2_scale: fx.Tensor, + OUT_scale: fx.Tensor, + sorted_ids: fx.Tensor, + sorted_expert_ids: fx.Tensor, + sorted_weights: fx.Tensor, + num_valid_ids: fx.Tensor, + n_tokens: fx.Int32, + num_m_blocks: fx.Int32, + grid_size: fx.Int32, + ): + lds = fx.SharedAllocator().allocate(SharedStorage).peek() + _base_ptr = lds.all_lds.ptr + _sc_ptr = lds.scale_lds.ptr + _stg_ptr = lds.stage_lds.ptr + + def a_buf(kb, half): + return _Buf(_base_ptr, (kb * 2 + half) * a_lds_size) + + def b_buf(s, half): + return _Buf(_base_ptr, B_SET_OFF[s] + half * b_lds_size) + + lane_id = fx.thread_idx.x % 64 + wave_id = fx.thread_idx.x // 64 + wave_i = wave_id // 2 + wave_j = wave_id % 2 + g4 = lane_id // 16 + r16 = lane_id % 16 + + # ---- work item: (m-tile, n-chunk); consecutive m-tiles share an XCD ---- + nv_rsrc = buffer_ops.create_buffer_resource( + num_valid_ids, max_size=False, num_records_bytes=4 + ) + num_valid = fx.Int32( + buffer_ops.buffer_load( + nv_rsrc, fx.Int32(0), vec_width=1, dtype=fx.Int32, is_scalar=True + ) + ) + n_work = (num_valid // fx.Int32(BM)) * fx.Int32(n_split) + per_xcd = (n_work + fx.Int32(_NUM_XCDS - 1)) // fx.Int32(_NUM_XCDS) + intra, xcd = _divmod_nonneg(fx.block_idx.x, _NUM_XCDS) + work = xcd * per_xcd + intra + block_valid = (intra < per_xcd) & (work < n_work) + work_safe = block_valid.select(work, fx.Int32(0)) + tile_i, chunk = _divmod_nonneg(work_safe, n_split) + m_base = tile_i * BM + eid_rsrc = buffer_ops.create_buffer_resource( + sorted_expert_ids, max_size=False, num_records_bytes=num_m_blocks * 4 + ) + expert = fx.Int32( + buffer_ops.buffer_load( + eid_rsrc, + tile_i >> EID_SHIFT, + vec_width=1, + dtype=fx.Int32, + is_scalar=True, + ) + ) + if const_expr(EID_SHIFT > 0): + # a 256-sort pads each expert to 256 rows: a 128-row tile whose first + # row is the sentinel (tok == n_tokens) holds nothing to compute + ids_pre = buffer_ops.create_buffer_resource( + sorted_ids, max_size=False, num_records_bytes=num_m_blocks * (BM * 4) + ) + first_sid = fx.Int32( + buffer_ops.buffer_load( + ids_pre, m_base, vec_width=1, dtype=fx.Int32, is_scalar=True + ) + ) + block_valid = block_valid & ((first_sid & fx.Int32(0x00FFFFFF)) < n_tokens) + chunk_n0 = chunk * NT # first n-tile (global index) of this CTA + # rotated n-tile sweep: CTA j starts at n-tile 2*j, so the tile it needs next + # was just read by CTA j+1 and sits in L2 (32768 tokens: 830 -> 669 us); only + # inside runs of >= 4 same-expert m-tiles + ROT_STRIDE, ROT_GATE = 2, 3 + _d = fx.Int32(ROT_GATE) + _lo_ok = tile_i >= _d + _hi_ok = tile_i + _d < num_m_blocks + _e_lo = fx.Int32( + buffer_ops.buffer_load( + eid_rsrc, + _lo_ok.select(tile_i - _d, fx.Int32(0)) >> EID_SHIFT, + vec_width=1, + dtype=fx.Int32, + is_scalar=True, + ) + ) + _e_hi = fx.Int32( + buffer_ops.buffer_load( + eid_rsrc, + _hi_ok.select(tile_i + _d, fx.Int32(0)) >> EID_SHIFT, + vec_width=1, + dtype=fx.Int32, + is_scalar=True, + ) + ) + rot_on = (_lo_ok & (_e_lo == expert)) | (_hi_ok & (_e_hi == expert)) + nt_rot = rot_on.select( + _divmod_nonneg(tile_i * fx.Int32(ROT_STRIDE), NT)[1], fx.Int32(0) + ) + + def _pn(nt): + """CTA-local logical n-tile (sweep order) -> physical n-tile of the chunk""" + x = nt + nt_rot + return (x >= fx.Int32(NT)).select(x - fx.Int32(NT), x) + + if block_valid: + ids_rsrc = buffer_ops.create_buffer_resource( + sorted_ids, max_size=False, num_records_bytes=num_m_blocks * (BM * 4) + ) + sw_rsrc = buffer_ops.create_buffer_resource( + sorted_weights, + max_size=False, + num_records_bytes=num_m_blocks * (BM * 4), + ) + a_rsrc = buffer_ops.create_buffer_resource( + A, max_size=False, num_records_bytes=num_m_blocks * (BM * K_BYTES) + ) + as_rsrc = buffer_ops.create_buffer_resource( + A_scale, max_size=False, num_records_bytes=num_m_blocks * (BM * SC_COLS) + ) + b_rsrc = buffer_ops.create_buffer_resource( + W2, max_size=False, num_records_bytes=E * H * K_BYTES + ) + bs_rsrc = buffer_ops.create_buffer_resource( + W2_scale, max_size=False, num_records_bytes=E * H * SC_COLS + ) + + # ---- A: contiguous sorted rows, swizzled 128-B LDS rows ---- + def _a_offsets(half): + offs = [] + for rnd in range_constexpr(N_TILES_A): + row = lane_id // 8 + wave_id * 8 + rnd * (_N_WAVES * 8) + col = (lane_id % 8) * 16 + offs.append( + (m_base + half * LDS_BLOCK_M + row) * fx.Int32(K_BYTES) + + _swizzled_col(row, col) + ) + return offs + + # B: LDS half hb, row r -> W2 row (r//64)*128 + hb*64 + r%64 of the n-tile + def _b_offsets(hb): + offs = [] + for rnd in range_constexpr(NB): + r = lane_id % 8 + wave_id * 8 + rnd * (_N_WAVES * 8) + col = (lane_id // 8) * 16 + w2row = (r // 64) * 128 + hb * 64 + (r % 64) + offs.append( + (w2row // 16) * (K_BYTES * 16) + + (w2row % 16) * 16 + + (col // 64) * 1024 + + ((col % 64) // 16) * 256 + + (col % 16) + ) + return offs + + a0_g2s = G2SLoaderAsm(a_rsrc, _a_offsets(0), N_TILES_A, wave_id) + a1_g2s = G2SLoaderAsm(a_rsrc, _a_offsets(1), N_TILES_A, wave_id) + b0_g2s = G2SLoaderAsm(b_rsrc, _b_offsets(0), NB, wave_id) + b1_g2s = G2SLoaderAsm(b_rsrc, _b_offsets(1), NB, wave_id) + for ld in (a0_g2s, a1_g2s, b0_g2s, b1_g2s): + ld.set_wave_base(_base_ptr) + # A scales: 4 x 1 KB for the 3 KB of this m-tile + as_g2s = G2SLoaderAsm( + as_rsrc, + [ + (m_base // 32) * fx.Int32(SC_BLOCKS_PER_G * 256) + + wave_id * 1024 + + lane_id * 16 + ], + 1, + wave_id, + ) + as_g2s.set_wave_base(_sc_ptr) + sc_base_i32 = fx.Int32(fx.ptrtoint(_sc_ptr)) + bsg = _BScaleGather( + bs_rsrc, lane_id, wave_id, sc_base_i32 + fx.Int32(B_SC_OFF) + ) + + a_s2r = S2RLoaderFp4(wave_i, N_TILES_A) + b_s2r = S2RLoaderFp4(wave_j, NB) + mfma = _MfmaAgprAB(N_TILES_A, NB) + + expert_rows = expert * fx.Int32(H) + b_base_bytes = expert_rows * fx.Int32(K_BYTES) + bs_base_bytes = expert_rows * fx.Int32(SC_COLS) + + def _b_soff(nt, kb): + """W2 byte offset of (n-tile nt [CTA-local], K-step kb)""" + return ( + b_base_bytes + + (chunk_n0 + _pn(nt)) * fx.Int32(B_TILE_BYTES) + + fx.Int32(kb * B_K_STEP) + ) + + def _g_soff(nt, kb): + return ( + bs_base_bytes + + (chunk_n0 + _pn(nt)) * fx.Int32(BN * SC_COLS) + + fx.Int32(kb * 256) + ) + + def _slot_off(nt, kb): + """Scale slot of flat step 3*nt + kb""" + s = (nt * fx.Int32(K_ITERS) + fx.Int32(kb)) & fx.Int32(B_SC_SLOTS - 1) + return s * fx.Int32(B_SC_SLOT) + + def _gather(nt, kb): + bsg.gather(_slot_off(nt, kb), _g_soff(nt, kb)) + + def _load_b(nt, kb): + """Both halves of B(nt, kb) into LDS set kb (issue order b0 then b1)""" + b0_g2s.load(b_buf(kb, 0), _b_soff(nt, kb)) + b1_g2s.load(b_buf(kb, 1), _b_soff(nt, kb)) + + # row ids / routing weights: issued ahead of the DMA stream + def _wave_row(h, r): + return h * LDS_BLOCK_M + wave_i * 32 + r + + _id_rows = [ + _wave_row(h, lane_id // CH + ROWS_PER_ST * k) + for h in range(2) + for k in range(N_ST) + ] + ([_wave_row(h, lane_id % 32) for h in range(2)] if FP8 else []) + _raw_ids = [ + _ld_dword_asm(ids_rsrc, (m_base + r) * fx.Int32(4)) for r in _id_rows + ] + _raw_w = ( + [ + _ld_dword_asm( + sw_rsrc, (m_base + _wave_row(h, ti * 16 + r16)) * fx.Int32(4) + ) + for h in range(2) + for ti in range(N_TILES_A) + ] + if not FP8 + else [] + ) + + # ---- prologue: A (12) + A scales (1), g(0), B(0), B(1), g(1) ---- + for kb in range_constexpr(K_ITERS): + a0_g2s.load(a_buf(kb, 0), fx.Int32(kb * BLOCK_K_BYTES)) + a1_g2s.load(a_buf(kb, 1), fx.Int32(kb * BLOCK_K_BYTES)) + as_g2s.load(_Buf(_sc_ptr, 0), fx.Int32(0)) + n0 = fx.Int32(0) + _gather(n0, 0) + _load_b(n0, 0) + _load_b(n0, 1) + _gather(n0, 1) + + # A + A scales landed (g(0), B(0), B(1), g(1) may fly) + wait_barrier(NG + 2 * NB + 2 * NB + NG) + aF = [[a_s2r.load(a_buf(kb, h)) for h in range(2)] for kb in range(K_ITERS)] + lane_sc = (lane_id // 4) * 16 + (lane_id % 4) * 4 + saA = [ + [ + _lds_load_i32( + sc_base_i32 + + ((h * 2 + wave_i) * SC_BLOCKS_PER_G + kb) * fx.Int32(256) + + lane_sc + ) + for kb in range(K_ITERS) + ] + for h in range(2) + ] + # every wave's A reads are done before B(2) overwrites the A region + wait_barrier(NG + 2 * NB + 2 * NB + NG) + _gather(n0, 2) + _load_b(n0, 2) + + def _read_bsc_thunks(nt, kb, holder): + base = sc_base_i32 + fx.Int32(B_SC_OFF) + _slot_off(nt, kb) + lane_sc + + def _rd(idx, hb, sub): + gi = wave_j * 4 + hb * 2 + sub + holder[idx] = _lds_load_i32(base + fx.Int32(gi * 256)) + + return [ + lambda: _rd(0, 0, 0), + lambda: _rd(1, 0, 1), + lambda: _rd(2, 1, 0), + lambda: _rd(3, 1, 1), + ] + + # B(0) + g(0) landed (B(1), g(1), g(2), B(2) may fly) + wait_barrier(2 * NB + NG + NG + 2 * NB) + b0f = b_s2r.load(b_buf(0, 0), preshuffled=True) + b1f = b_s2r.load(b_buf(0, 1), preshuffled=True) + _sc0 = [None] * 4 + for t in _read_bsc_thunks(n0, 0, _sc0): + t() + + # ---- output rows (token-major) of the rows this lane touches ---- + out_rsrc = buffer_ops.create_buffer_resource( + OUT, max_size=False, num_records_bytes=n_tokens * (topk * OUT_ROW_BYTES) + ) + osc_rsrc = buffer_ops.create_buffer_resource( + OUT_scale, + max_size=False, + num_records_bytes=n_tokens * (topk * OUT_SC_COLS), + ) + + _pinned = _wait_pin(_raw_ids + _raw_w, 2 * NB + NG + NG + 2 * NB) + _pid, _pw = _pinned[: len(_raw_ids)], _pinned[len(_raw_ids) :] + + def _orow(sid): + tok = sid & fx.Int32( + 0x00FFFFFF + ) # padded rows: tok == n_tokens -> OOB -> dropped + slot = (sid >> 24) & fx.Int32(0xFF) + return tok * fx.Int32(topk) + slot + + # data flush: lane L stores staged rows L//CH + ROWS_PER_ST*k, chunk L%CH + out_off = [ + [ + _orow(_pid[h * N_ST + k]) * fx.Int32(OUT_ROW_BYTES) + for k in range(N_ST) + ] + for h in range(2) + ] + # conditional expressions: the DSL rewriter drops non-IR values set in an if + sc_off = ( + [_orow(_pid[2 * N_ST + h]) * fx.Int32(OUT_SC_COLS) for h in range(2)] + if FP8 + else None + ) + # bf16: routing weight of the lane's accumulator rows (ti*16 + r16) + wA = ( + [ + [_as_f32(_pw[h * N_TILES_A + ti]) for ti in range(N_TILES_A)] + for h in range(2) + ] + if not FP8 + else None + ) + + stg_base = fx.Int32(fx.ptrtoint(_stg_ptr)) + wave_id * fx.Int32(STG_WAVE) + stg_sc_base = stg_base + fx.Int32(STG_DATA) + + def _stg_addr(row, chunk, half): + """Staged (row, 16-B chunk, 8-B half); chunks XOR-swizzled by the row so + the column-wise writes and the row-wise reads both spread over the + banks""" + return ( + stg_base + + row * fx.Int32(STG_ROW) + + ((chunk ^ (row % CH)) * 16 + half * 8) + ) + + def _stage_bf16(cq, h, hb, ti, tj): + """One 16x16 tile: 4 f32 -> bf16(v * w_row), 8 B into the staging + buffer""" + cv = Vec(_pin_vec4(cq[mfma.idx(ti, tj)])) + w = wA[h][ti] + v = [fx.Float32(cv[k]) * w for k in range_constexpr(4)] + row = ti * 16 + r16 + chunk = ( + hb * 8 + tj * 2 + g4 // 2 + ) # (hb*64 + tj*16 + g4*4) cols * 2 B / 16 + _lds_store_vec( + _v2i32(_bf16x2(v[0], v[1]), _bf16x2(v[2], v[3])), + _stg_addr(row, chunk, g4 % 2), + 2, + ) + + def _stage_fp8_pair(cq, hb, ti): + """The two 16-row x 32-col groups of (ti, hb) -- tiles (0, 1) and (2, + 3) -- + at once. The fp8 epilogue is VALU-issue bound (1 wave / SIMD; the ATT + showed ~35 sequential instructions per group between two MFMAs), so: one + amax butterfly serves both groups (3 swaps, not 4), nnan maxes (no + canonicalizing self-max), undef cvt destinations (no v_mov 0), the two + e8m0 bytes of a row go out as one 16-bit LDS write. Per group: amax over + the row's 4 lanes, e8m0, 8 fp8 per lane after a permlane16 swap.""" + v = [] + for p in range_constexpr(2): + cv = Vec(_pin_vec4(cq[mfma.idx(ti, 2 * p)])) + cw = Vec(_pin_vec4(cq[mfma.idx(ti, 2 * p + 1)])) + v.append( + [fx.Float32(cv[k]) for k in range_constexpr(4)] + + [fx.Float32(cw[k]) for k in range_constexpr(4)] + ) + am = [] + for p in range_constexpr(2): + a = _maxf_nn(_fabs(v[p][0]), _fabs(v[p][1])) + for k in range_constexpr(2, 8): + a = _maxf_nn(a, _fabs(v[p][k])) + am.append(a) + amax = _xlane_max4_pair(am[0], am[1]) + row = ti * 16 + r16 + e8s = [] + for p in range_constexpr(2): + e8 = _e8m0_fp8(amax[p]) + sf = _as_f32(e8 << 23) + da = _cvt_pk_fp8(_undef_i32(), v[p][0], v[p][1], sf, False) + da = _cvt_pk_fp8(da, v[p][2], v[p][3], sf, True) + db = _cvt_pk_fp8(_undef_i32(), v[p][4], v[p][5], sf, False) + db = _cvt_pk_fp8(db, v[p][6], v[p][7], sf, True) + da, db = _permlane16_swap(da, db) + # lane group g now holds tile (2p + g%2), cols (g//2)*8 .. +8 + chunk = hb * 4 + 2 * p + g4 % 2 + _lds_store_vec(_v2i32(da, db), _stg_addr(row, chunk, g4 // 2), 2) + e8s.append(e8) + _lds_store_i16( + e8s[0] | (e8s[1] << 8), stg_sc_base + row * fx.Int32(4) + hb * 2 + ) + + def _stage_thunks(cq, h, hb): + ts = [] + for ti in range_constexpr(N_TILES_A): + if const_expr(FP8): + ts.append(lambda ti=ti: _stage_fp8_pair(cq, hb, ti)) + else: + for tj in range_constexpr(NB): + ts.append( + lambda ti=ti, tj=tj: _stage_bf16(cq, h, hb, ti, tj) + ) + return ts + + def _flush_thunks(h, nt, mask): + """The wave's staged 32 x 128 outputs -> token-major rows, full lines""" + col_wave = ( + (chunk_n0 + _pn(nt)) * fx.Int32(BN) + wave_j * WAVE_COLS + ) * OUT_ELEM + ts = [] + for k in range_constexpr(N_ST): + + def _st(k=k): + row = lane_id // CH + ROWS_PER_ST * k + chunk = lane_id % CH + data = _lds_load_vec(_stg_addr(row, chunk, 0), 4) + buffer_ops.buffer_store( + data, + out_rsrc, + out_off[h][k] + col_wave + chunk * 16, + mask=mask, + offset_is_bytes=True, + cache_modifier=_STORE_CPOL, + ) + + ts.append(_st) + if const_expr(FP8): + + def _st_sc(): + scv = _lds_load_i32(stg_sc_base + (lane_id % 32) * 4) + sc_col = (chunk_n0 + _pn(nt)) * fx.Int32(BN // 32) + wave_j * 4 + buffer_ops.buffer_store( + scv, + osc_rsrc, + sc_off[h] + sc_col, + mask=mask, + offset_is_bytes=True, + cache_modifier=_STORE_CPOL_SC, + ) + + ts.append(_st_sc) + return ts + + def _wb2(first, c_first, c_other): + """``first`` is a Python bool (static) or a wave-uniform DSL bool""" + if const_expr(isinstance(first, bool)): + wait_barrier(c_first if first else c_other) + elif const_expr(c_first == c_other): + wait_barrier(c_first) + else: + if first: + wait_barrier(c_first) + else: + wait_barrier(c_other) + + # vmcnt allowances (loads and stores retire in issue order) + TOP_K0, SEG_K0 = P_STEP + ST, NG + P_STEP + ST + NB + TOP_K1, SEG_K1 = ST + P_STEP + ST, NG + ST + P_STEP + ST + NB + TOP_K2, SEG_K2 = ST + P_STEP, NG + ST + P_STEP + NB + # first tile: after the prologue [.. B(0), B(1), g(1), g(2), B(2)] + TOP_K0_F = NG + 2 * NB # after g(1): g(2), B(2) + SEG_K0_F = NG + NG + 2 * NB + NB # after b1(1): g(1), g(2), B(2), b0(3) + TOP_K1_F = 2 * NB + P_STEP + ST # after g(2): B(2), step 0 + SEG_K1_F = P_STEP + ST + NB # after b1(2): step 0, b0(4) + for c in ( + TOP_K0, + SEG_K0, + TOP_K1, + SEG_K1, + TOP_K2, + SEG_K2, + TOP_K0_F, + SEG_K0_F, + TOP_K1_F, + SEG_K1_F, + ): + assert c <= 63, c + + def _one_step(nt, nt_next, kb, first, b0f, b1f, sc, accs, epi): + """Flat step s = (nt, kb): B(s) in LDS set kb; issues B(s+3) = (nt+1, + kb) into + the same set and its scales. ``epi``: {phase: thunk-list factory(accs)} + for + the epilogue work hidden in that phase's MFMA shadow.""" + kb1 = (kb + 1) % K_ITERS + nt1 = nt if (kb + 1) < K_ITERS else nt_next + bn0, bn1 = b_buf(kb1, 0), b_buf(kb1, 1) + sbC0, sbC1 = sc + c00, c01, c10, c11 = accs + a0f, a1f = aF[kb][0], aF[kb][1] + zero = kb == 0 + + def _late(ph): + return epi[ph](accs) if ph in epi else None + + _scn = [None] * 4 + rd_scn = _read_bsc_thunks(nt1, kb1, _scn) + b_off3 = _b_soff(nt_next, kb) + + if kb == 0: + _wb2(first, TOP_K0_F, TOP_K0) + elif kb == 1: + _wb2(first, TOP_K1_F, TOP_K1) + else: + wait_barrier(TOP_K2) + il = _g2s_thunks(b0_g2s, b_buf(kb, 0), b_off3, NB) + rd_scn[:2] + mfma.call( + a0f, + b0f, + c00, + [saA[0][kb]], + sbC0, + interleave=il, + zero_acc=zero, + late=_late(1), + ) + mfma.call( + a0f, + b1f, + c01, + [saA[0][kb]], + sbC1, + interleave=rd_scn[2:], + zero_acc=zero, + late=_late(2), + ) + + if kb == 0: + _wb2(first, SEG_K0_F, SEG_K0) + elif kb == 1: + _wb2(first, SEG_K1_F, SEG_K1) + else: + wait_barrier(SEG_K2) + _b0n = [None] * NB + _b1n = [None] * NB + # the gather sets m0: it goes after the m0-relative DMAs + il = _g2s_thunks(b1_g2s, b_buf(kb, 1), b_off3, NB) + [ + lambda: _gather(nt_next, kb) + ] + mfma.call( + a1f, + b0f, + c10, + [saA[1][kb]], + sbC0, + interleave=il, + zero_acc=zero, + late=_late(3), + ) + il = _s2r_thunks(b_s2r, bn0, _b0n, NB, True) + _s2r_thunks( + b_s2r, bn1, _b1n, NB, True + ) + mfma.call( + a1f, + b1f, + c11, + [saA[1][kb]], + sbC1, + interleave=il, + zero_acc=zero, + late=_late(4), + ) + return _b0n, _b1n, (_scn[:2], _scn[2:]) + + _R = fx.as_ir_value + + def _flat_b(frag): + return [_R(t[0]) for t in frag] + [_R(t[1]) for t in frag] + + def _unflat_b(flat): + return [[flat[i], flat[NB + i]] for i in range(NB)] + + def _flat_state(b0f, b1f, sc, c11): + return ( + _flat_b(b0f) + + _flat_b(b1f) + + [_R(v) for v in sc[0]] + + [_R(v) for v in sc[1]] + + [_R(v) for v in c11] + ) + + def _unflat_state(st): + o = 0 + b0f = _unflat_b(st[o : o + 2 * NB]) + o += 2 * NB + b1f = _unflat_b(st[o : o + 2 * NB]) + o += 2 * NB + sc = (list(st[o : o + 2]), list(st[o + 2 : o + 4])) + o += 4 + c11 = list(st[o : o + N_ACCUMS]) + return b0f, b1f, sc, c11 + + def _n_tile(nt, nt_next, first, b0f, b1f, sc, c11_prev, nt_prev, mask_prev): + """Epilogue placement (P = phase): tile t's c00 staged in (t,2) P2, c01 + in + (t,2) P3, rows h0 flushed + c10 staged in (t,2) P4, c11 staged in + (t+1,0) + P1, rows h1 flushed in (t+1,0) P4. Returns (b0f, b1f, sc, c11).""" + accs = tuple([None] * N_ACCUMS for _ in range(4)) + epi_by_kb = { + 0: { + 1: lambda a: _stage_thunks(c11_prev, 1, 1), + 4: lambda a: _flush_thunks(1, nt_prev, mask_prev), + }, + 1: {}, + 2: { + 2: lambda a: _stage_thunks(a[0], 0, 0), + 3: lambda a: _stage_thunks(a[1], 0, 1), + 4: lambda a: ( + _flush_thunks(0, nt, None) + _stage_thunks(a[2], 1, 0) + ), + }, + } + for kb in range_constexpr(K_ITERS): + b0f, b1f, sc = _one_step( + nt, nt_next, kb, first, b0f, b1f, sc, accs, epi_by_kb[kb] + ) + return b0f, b1f, sc, accs[3] + + zero_v4 = Vec.filled(4, 0.0, fx.Float32).ir_value() # accumulator zero + init_state = _flat_state( + b0f, b1f, (_sc0[:2], _sc0[2:]), [zero_v4] * N_ACCUMS + ) + for np_, state in range(0, NT // 2, init=init_state): + b0f, b1f, sc, c11p = _unflat_state(state) + np_i = fx.Int32(np_) + first = np_i == fx.Int32(0) + nt_e = np_i * fx.Int32(2) + nt_o = nt_e + fx.Int32(1) + nt_o_next = _min( + nt_e + fx.Int32(2), fx.Int32(NT - 1) + ) # last pair: redundant reloads + pend_valid = fx.as_ir_value(np_i > fx.Int32(0)) + b0f, b1f, sc, c11e = _n_tile( + nt_e, + nt_o, + first, + b0f, + b1f, + sc, + c11p, + nt_e - fx.Int32(1), + pend_valid, + ) + b0f, b1f, sc, c11o = _n_tile( + nt_o, nt_o_next, False, b0f, b1f, sc, c11e, nt_e, None + ) + state = yield _flat_state(b0f, b1f, sc, c11o) + + # the last tile's c11 has no next step to hide in + b0f, b1f, sc, c11p = _unflat_state(state) + for t in _stage_thunks(c11p, 1, 1) + _flush_thunks( + 1, fx.Int32(NT - 1), None + ): + t() + + # never retire with LDS DMA in flight (the CU reuses the LDS) + wait_barrier(0) + + @flyc.jit + def launch_gemm2( + A: fx.Tensor, + W2: fx.Tensor, + OUT: fx.Tensor, + A_scale: fx.Tensor, + W2_scale: fx.Tensor, + OUT_scale: fx.Tensor, + sorted_ids: fx.Tensor, + sorted_expert_ids: fx.Tensor, + sorted_weights: fx.Tensor, + num_valid_ids: fx.Tensor, + n_tokens: fx.Int32, + num_m_blocks: fx.Int32, + grid_size: fx.Int32, + stream: fx.Stream, + ): + kernel_gemm2( + A, + W2, + OUT, + A_scale, + W2_scale, + OUT_scale, + sorted_ids, + sorted_expert_ids, + sorted_weights, + num_valid_ids, + n_tokens, + num_m_blocks, + grid_size, + value_attrs={ + "rocdl.waves_per_eu": 1, + "rocdl.flat_work_group_size": "256,256", + }, + ).launch(grid=(grid_size, 1, 1), block=(256, 1, 1), stream=stream) + + return launch_gemm2 + + +def gemm2_grid(num_m_blocks: int, n_split: int) -> int: + """Blocks to launch: every (m-tile, chunk) of the allocation, rounded to the 8 XCDs + (the kernel drops the fully padded tail tiles at runtime).""" + return (num_m_blocks * n_split + _NUM_XCDS - 1) // _NUM_XCDS * _NUM_XCDS diff --git a/vllm/models/minimax_m3/amd/ops/moe_mxfp4/prefill.py b/vllm/models/minimax_m3/amd/ops/moe_mxfp4/prefill.py new file mode 100644 index 000000000000..2740ab78f01c --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/moe_mxfp4/prefill.py @@ -0,0 +1,217 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""FlyDSL W4A4 MoE prefill chain at TP4 on the ``AITER_MXFP4_MXFP4`` weights: sort, +aiter's scale sort, gemm1 (gate/up + SwiGLU-OAI + MXFP4 quant), gemm2 +(routing-weighted partials), fixed-order reduce. +""" + +import functools + +import torch + +from vllm.models.minimax_m3.amd.ops.flydsl_utils import run_compiled +from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.launch import ( + _get_reduce_bf16, + _get_sort, + _get_tile_map, + _u8_flat, +) + +MIN_PREFILL_TOKENS = 3072 +MAX_PREFILL_TOKENS = 65536 +BM256_FROM_TOKENS = 16384 +GEMM2_N_SPLIT = 2 +GEMM1_SWIGLU_ALPHA = 1.702 +GEMM1_SWIGLU_LIMIT = 7.0 +_GEMM1_BLOCK_K = 256 +# gemm2's K pipeline is written for 3 K-steps of 256 +_GEMM2_INTERMEDIATE = 768 + + +def supports_shapes(hidden_size: int, intermediate_size: int) -> bool: + """gemm1 peels 4 K-steps of 256 and unrolls the rest by 4.""" + k_iters = hidden_size // _GEMM1_BLOCK_K + return ( + hidden_size % _GEMM1_BLOCK_K == 0 + and k_iters >= 8 + and (k_iters - 4) % 4 == 0 + and intermediate_size == _GEMM2_INTERMEDIATE + ) + + +def block_m_for(n_tokens: int) -> int: + return 256 if n_tokens >= BM256_FROM_TOKENS else 128 + + +@functools.cache +def _get_gemm1(hidden_size: int, intermediate_size: int, num_experts: int, bm: int): + from .gemm1_prefill import compile_moe_gemm1 + + return compile_moe_gemm1( + H=hidden_size, I=intermediate_size, E=num_experts, BLOCK_M=bm + ) + + +@functools.cache +def _get_gemm2( + hidden_size: int, intermediate_size: int, num_experts: int, topk: int, bm: int +): + from .gemm2_prefill import compile_moe_gemm2 + + return compile_moe_gemm2( + H=hidden_size, + I=intermediate_size, + E=num_experts, + topk=topk, + n_split=GEMM2_N_SPLIT, + out_dtype="bf16", + sort_block_m=bm, + ) + + +def a4w4_prefill_moe( + x_quant: tuple[torch.Tensor, torch.Tensor], + w13: torch.Tensor, + w13_scale: torch.Tensor, + w2: torch.Tensor, + w2_scale: torch.Tensor, + topk_weights: torch.Tensor, + topk_ids: torch.Tensor, + *, + hidden_size: int, + intermediate_size: int, + num_experts: int, + out: torch.Tensor | None = None, +) -> torch.Tensor: + """``x_quant`` = (fp4 ``[M, H/2]``, e8m0 ``[M, H/32]``) of aiter's per-token + MXFP4 quant -> ``[M, H]`` bf16, on ``AiterMxfp4Experts``' weights.""" + from aiter import dtypes + from aiter.ops.quant import mxfp4_moe_sort_hip + + from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.sort import SortBuffers + from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.tile_map import ( + tile_map_grid, + ) + + from .gemm2_prefill import gemm2_grid + + a_q, x_s = x_quant + n_tokens = a_q.shape[0] + hidden = hidden_size + assert MIN_PREFILL_TOKENS <= n_tokens <= MAX_PREFILL_TOKENS, n_tokens + assert a_q.shape == (n_tokens, hidden // 2) and a_q.is_contiguous() + assert x_s.shape == (n_tokens, hidden // 32) and x_s.is_contiguous() + inter = intermediate_size + topk = topk_ids.shape[1] + topk_ids = topk_ids.to(torch.int32).contiguous() + topk_weights = topk_weights.to(torch.float32).contiguous() + device = topk_ids.device + stream = torch.cuda.current_stream() + bm = block_m_for(n_tokens) + + bufs = SortBuffers.allocate(n_tokens, num_experts, topk, bm, device) + _get_sort(num_experts, topk, bm)( + *bufs.launch_args(topk_ids, topk_weights, n_tokens) + ) + a_s = torch.empty( + ((bufs.sorted_ids.shape[0] + 31) // 32 * 32, (hidden // 32 + 7) // 8 * 8), + dtype=dtypes.fp8_e8m0, + device=device, + ) + mxfp4_moe_sort_hip( + a_s, + x_s.view(dtypes.fp8_e8m0), + bufs.sorted_ids, + bufs.num_valid_ids, + n_tokens, + hidden, + ) + num_m_blocks = bufs.max_sorted // bm + rows = num_m_blocks * bm + grid1 = tile_map_grid(num_m_blocks, inter) + tile_map = torch.empty((grid1 + 1,), dtype=torch.int32, device=device) + run_compiled( + _get_tile_map(inter, bm), + bufs.sorted_expert_ids, + bufs.num_valid_ids, + tile_map, + grid1, + stream, + ) + h_q = torch.empty((rows, inter // 2), dtype=torch.uint8, device=device) + h_s = torch.empty((rows * (inter // 32),), dtype=torch.uint8, device=device) + run_compiled( + _get_gemm1(hidden, inter, num_experts, bm), + _u8_flat(a_q), + _u8_flat(w13), + h_q.view(-1), + _u8_flat(a_s), + _u8_flat(w13_scale), + h_s, + bufs.sorted_ids, + bufs.sorted_expert_ids, + n_tokens, + num_m_blocks, + int(a_s.numel() * a_s.element_size()), + tile_map, + grid1, + stream, + ) + + partial = torch.empty( + (n_tokens * topk, hidden), dtype=torch.bfloat16, device=device + ) + # read only by gemm2's fp8-partial mode + partial_scale = torch.empty((16,), dtype=torch.uint8, device=device) + num_m_blocks2 = rows // 128 + run_compiled( + _get_gemm2(hidden, inter, num_experts, topk, bm), + h_q.view(-1), + _u8_flat(w2), + partial.view(-1), + h_s, + _u8_flat(w2_scale), + partial_scale, + bufs.sorted_ids, + bufs.sorted_expert_ids, + bufs.sorted_weights, + bufs.num_valid_ids, + n_tokens, + num_m_blocks2, + gemm2_grid(num_m_blocks2, GEMM2_N_SPLIT), + stream, + ) + if out is None: + out = torch.empty((n_tokens, hidden), dtype=torch.bfloat16, device=device) + run_compiled( + _get_reduce_bf16(hidden, topk), + partial.view(-1), + out.view(-1), + n_tokens, + stream, + ) + return out + + +def mxfp4_quant( + x: torch.Tensor, q_out: torch.Tensor | None, scale_out: torch.Tensor | None +) -> tuple[torch.Tensor, torch.Tensor]: + """Per-token MXFP4 quant of bf16 ``[M, H]`` by aiter's kernel (the regular + path's from 512 tokens) into ``q_out`` ``[M, H/2]`` / ``scale_out`` + ``[M, H/32]`` uint8.""" + from aiter import dtypes + from aiter.ops.quant import dynamic_per_group_scaled_quant + + m, h = x.shape + if q_out is None: + q_out = torch.empty((m, h // 2), dtype=torch.uint8, device=x.device) + if scale_out is None: + scale_out = torch.empty((m, h // 32), dtype=torch.uint8, device=x.device) + dynamic_per_group_scaled_quant( + q_out.view(dtypes.fp4x2), + x, + scale_out.view(dtypes.fp8_e8m0), + 32, + shuffle_scale=False, + ) + return q_out, scale_out diff --git a/vllm/models/minimax_m3/amd/ops/moe_mxfp8/__init__.py b/vllm/models/minimax_m3/amd/ops/moe_mxfp8/__init__.py new file mode 100644 index 000000000000..af74a2a464c0 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/moe_mxfp8/__init__.py @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""FlyDSL MXFP8 MoE prefill chain for MiniMax-M3 on gfx950 (``sp_prefill``).""" diff --git a/vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm1_prefill.py b/vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm1_prefill.py new file mode 100644 index 000000000000..67cdba3c0093 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm1_prefill.py @@ -0,0 +1,822 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Prefill MoE gate/up GEMM (fp8 x fp8, MXFP8 scales) on sorted rows, with +SwiGLU-OAI and the MXFP8 quant of its output (the gemm2 input). + +Layouts (bytes): + A [n_tokens, H] per-token fp8 (aiter per_1x32 quant) + A_scale [pad32(max_sorted), H/32] sorted rows, e8m0-shuffled + W13 [E, I/16, 2, H/64, 4, 16, 16] shuffle_weight(is_guinterleave, gate_up) + W13_sc [E*I/16, H/256, 4, 16] dwords shuffle_scale(..., True, True) + OUT_Q [num_m_blocks*BLOCK_M, I] sorted rows, fp8 e4m3 + OUT_sc [pad32(num_m_blocks*BLOCK_M), I/32] sorted rows, e8m0-shuffled +""" + +import flydsl.compiler as flyc +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import buffer_ops +from flydsl._mlir.dialects import llvm as _llvm +from flydsl.expr import range_constexpr +from flydsl.expr.typing import Vector as Vec + +from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.epilogue import ( + _cvt_pk_fp8, + _maxf_nn, + _undef_i32, + _v2i32, +) +from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.loaders import ( + _N_WAVES, + _SCALE_A_REGION, + _SCALE_B_REGION, + _SCALE_LDS_BYTES, + _SCALE_SLOTS, + G2SLoaderAsm, + S2RLoader128B, + ScaleGatherMoE, + ScaleLoaderLDS, + _as_f32, + _bits, + _Buf, + _divmod_nonneg, + _flat_frag, + _fmax, + _g2s_thunks, + _min, + _permlane16_swap, + _riffle, + _s2r_thunks, + _swiglu_oai, + _swizzled_col, + _unflat_frag, + wait_barrier, +) + +BLOCK_K = 128 # K bytes per pipeline step +# LLVM does not see the inline-asm MFMA -> v_accvgpr_read hazard and may read a final +# accumulator too early (BLOCK_M 256 lost the last K-step). The last step releases +# each group through ``hold`` one group later; 24 wait states cover one MFMA. +_MFMA_RESULT_WAIT = "s_nop 7\n s_nop 7\n s_nop 7" + + +def _e8m0_roundup_fp8(amax): + """Biased e8m0 of ceil_pow2(amax / 448), at least 1 (0 would give NaN codes).""" + u = _bits(amax * fx.Float32(1.0 / 448.0)) + e = (u >> 23) & fx.Int32(0xFF) + bump = ((u & fx.Int32(0x7FFFFF)) != fx.Int32(0)) & (e < fx.Int32(0xFF)) + e = bump.select(e + fx.Int32(1), e) + return (e < fx.Int32(1)).select(fx.Int32(1), e) + + +def _pack8(h0, h1): + """K [16*klane, +16) and [64 + 16*klane, +16) -> one 8 x i32 MFMA operand.""" + a, b = Vec(h0), Vec(h1) + return Vec.from_elements( + [a[k] for k in range(4)] + [b[k] for k in range(4)], fx.Int32 + ) + + +class Mfma16x16x128Fp8: + """Scaled fp8 MFMAs over an (n_tiles_a x n_tiles_b) quadrant, AGPR accumulators.""" + + def __init__(self, n_tiles_a, n_tiles_b): + assert n_tiles_a % 2 == 0 + self.n_tiles_a = n_tiles_a + self.n_tiles_b = n_tiles_b + self.res_ty = Vec.make_type(4, fx.Float32) + + def idx(self, i, j): + return i * self.n_tiles_b + j + + def _order(self): + order = [] + j0s = list(range(0, self.n_tiles_b, 2)) + for n, i0 in enumerate(range(0, self.n_tiles_a, 2)): + for j0 in reversed(j0s) if n % 2 else j0s: + order += [(i0 + di, j0 + dj) for di in range(2) for dj in range(2)] + return order + + def call( + self, + a, + b, + c, + sa, + sb, + gu, + k2, + interleave=None, + zero_acc=False, + late=None, + late_start=4, + sb_index=None, + ): + """``a[i]`` / ``b[j]``: [half0, half1]; ``sa[i // 2]``: A scale dword of a + 32-row group; ``sb_index(j, gu) -> (dword, byte)`` of the B scale. + ``interleave`` / ``late``: thunks spread over the MFMAs.""" + if sb_index is None: + sb_index = lambda j, gu: (j, gu) # noqa: E731 + thunks = list(interleave) if interleave else [] + late_thunks = list(late) if late else [] + order = self._order() + n_mfma = len(order) + by_slot = {} # type: dict[int, list] + for t, th in enumerate(thunks): + by_slot.setdefault((t * n_mfma) // len(thunks), []).append(th) + n_late_slots = max(n_mfma - late_start, 1) + for t, th in enumerate(late_thunks): + by_slot.setdefault( + late_start + (t * n_late_slots) // len(late_thunks), [] + ).append(th) + for m, (i, j) in enumerate(order): + a_op = _pack8(a[i][0], a[i][1]) + b_op = _pack8(b[j][0], b[j][1]) + acc = None if zero_acc else c[self.idx(i, j)] + sbj, sbb = sb_index(j, gu) + c[self.idx(i, j)] = self._mfma_agpr( + a_op, b_op, acc, sa[i // 2], sb[sbj], i % 2, sbb, k2 + ) + for th in by_slot.get(m, ()): + th() + for m in range( + n_mfma, n_mfma + max(len(thunks), len(late_thunks)) + late_start + 1 + ): + for th in by_slot.get(m, ()): + th() + return c + + def hold(self, c, wait=""): + """Pins ``c`` here (after asm ``wait``): reads cannot move above this point.""" + if wait: + _llvm.inline_asm(None, [], wait, "", has_side_effects=True) + return [ + _llvm.inline_asm( + self.res_ty, [fx.as_ir_value(v)], "", "=a,0", has_side_effects=True + ) + for v in c + ] + + def _mfma_agpr(self, a_op, b_op, acc, sa_v, sb_v, ia, jb, k2): + # (B, A) order: lane L holds C[L % 16, 4 * (L // 16) : +4] + a_op, b_op = b_op, a_op + sa_v, sb_v = sb_v, sa_v + ia, jb = jb, ia + opsel = f"op_sel:[{ia},{jb},0]" + opsel_hi = f"op_sel_hi:[{k2},{k2},0]" + src2 = "$0" if acc is not None else "0" + asm = ( + f"v_mfma_scale_f32_16x16x128_f8f6f4 $0, $1, $2, {src2}, $3, $4 " + f"{opsel} {opsel_hi} cbsz:0 blgp:0" + ) + ops = [ + fx.as_ir_value(a_op), + fx.as_ir_value(b_op), + fx.as_ir_value(sa_v), + fx.as_ir_value(sb_v), + ] + cons = "=a,v,v,v,v" + if acc is not None: + ops.append(fx.as_ir_value(acc)) + cons += ",0" + return _llvm.inline_asm(self.res_ty, ops, asm, cons, has_side_effects=True) + + +def compile_moe_gemm1( + *, + H: int, + I: int, # noqa: E741 + E: int, + BLOCK_M: int = 128, +): + """``BLOCK_M``: the ``moe_sorting`` block size of the inputs (128 or 256).""" + K = H + BLOCK_K_BYTES = BLOCK_K + BLOCK_N = 256 # 128 gate + 128 up cols + LDS_BLOCK_M = BLOCK_M // 2 + LDS_BLOCK_N = BLOCK_N // 2 + N_TILES_A = LDS_BLOCK_M // 2 // 16 # 16-row tiles per wave per LDS half + N_TILES_B = LDS_BLOCK_N // 2 // 16 + + assert BLOCK_M in (128, 256) + assert K % 256 == 0 and I % LDS_BLOCK_N == 0 + K_ITERS = K // BLOCK_K + UNROLL = 4 if (K_ITERS - 4) % 4 == 0 else 2 + assert K_ITERS >= 4 and (K_ITERS - 4) % UNROLL == 0, K_ITERS + N_ACCUMS = N_TILES_A * N_TILES_B + K_BYTES = K + N_BITS = (I // 128 - 1).bit_length() + N0 = I // 16 # 16-column (gate + up) groups per expert + + a_lds_size = LDS_BLOCK_M * BLOCK_K_BYTES + b_lds_size = LDS_BLOCK_N * BLOCK_K_BYTES + A_BUFS = 4 * a_lds_size + LDS_TILES_BYTES = A_BUFS + 4 * b_lds_size + + # scales: A in 32-row groups, W13 in 16-column groups (256 B = 8 K-groups) + A_WAVE_GROUPS = N_TILES_A // 2 # groups per wave per LDS half + A_HALF_GROUPS = LDS_BLOCK_M // 32 + B_WAVE_GROUPS = 4 # consecutive groups per wave quarter + B_HALF_GROUPS = 2 + SCALE_COLS_OUT = I // 32 + OUT_SC_BLOCKS_PER_ROW32 = SCALE_COLS_OUT // 8 + W_BYTES = (2 * I) * K + assert W_BYTES <= 0xFFFFFFFF, "buffer resources address 4 GB" + + @fx.struct + class SharedStorage: + all_lds: fx.Array[fx.Int8, LDS_TILES_BYTES, 16] + scale_lds: fx.Array[fx.Int8, _SCALE_LDS_BYTES, 16] + + @flyc.kernel + def kernel_gemm1( + A: fx.Tensor, + W13: fx.Tensor, + OUT_Q: fx.Tensor, + A_scale: fx.Tensor, + W13_scale: fx.Tensor, + OUT_scale: fx.Tensor, + sorted_ids: fx.Tensor, + sorted_expert_ids: fx.Tensor, + n_tokens: fx.Int32, + num_m_blocks: fx.Int32, + a_scale_bytes: fx.Int32, + tile_map_t: fx.Tensor, + grid_size: fx.Int32, + ): + lds = fx.SharedAllocator().allocate(SharedStorage).peek() + _base_ptr = lds.all_lds.ptr + + a_cur0 = _Buf(_base_ptr, 0 * a_lds_size) + a_cur1 = _Buf(_base_ptr, 1 * a_lds_size) + a_next0 = _Buf(_base_ptr, 2 * a_lds_size) + a_next1 = _Buf(_base_ptr, 3 * a_lds_size) + b_cur0 = _Buf(_base_ptr, A_BUFS + 0 * b_lds_size) + b_cur1 = _Buf(_base_ptr, A_BUFS + 1 * b_lds_size) + b_next0 = _Buf(_base_ptr, A_BUFS + 2 * b_lds_size) + b_next1 = _Buf(_base_ptr, A_BUFS + 3 * b_lds_size) + + lane_id = fx.thread_idx.x % 64 + wave_id = fx.thread_idx.x // 64 + + ids_rsrc = buffer_ops.create_buffer_resource( + sorted_ids, max_size=False, num_records_bytes=num_m_blocks * (BLOCK_M * 4) + ) + eid_rsrc = buffer_ops.create_buffer_resource( + sorted_expert_ids, max_size=False, num_records_bytes=num_m_blocks * 4 + ) + # tile_map[grid_size] = valid entries, split evenly over the 8 XCDs + intra_xcd, xcd = _divmod_nonneg(fx.block_idx.x, 8) + tm_rsrc = buffer_ops.create_buffer_resource( + tile_map_t, max_size=False, num_records_bytes=(grid_size + 1) * 4 + ) + n_valid = fx.Int32( + buffer_ops.buffer_load( + tm_rsrc, grid_size, vec_width=1, dtype=fx.Int32, is_scalar=True + ) + ) + per_xcd = (n_valid + fx.Int32(7)) // fx.Int32(8) + remapped = xcd * per_xcd + intra_xcd + in_chunk = (intra_xcd < per_xcd) & (remapped < n_valid) + entry = fx.Int32( + buffer_ops.buffer_load( + tm_rsrc, + in_chunk.select(remapped, fx.Int32(0)), + vec_width=1, + dtype=fx.Int32, + ) + ) + entry = in_chunk.select(entry, fx.Int32(-1)) + tile_i = entry >> N_BITS + tile_j = entry & ((1 << N_BITS) - 1) + block_valid = entry >= 0 + expert = fx.Int32( + buffer_ops.buffer_load( + eid_rsrc, tile_i, vec_width=1, dtype=fx.Int32, is_scalar=True + ) + ) + m_base = tile_i * BLOCK_M + + if block_valid: + wave_i = wave_id // 2 + wave_j = wave_id % 2 + + def _a_gather_offsets(half): + offs = [] + for rnd in range_constexpr(N_TILES_A): + row = lane_id // 8 + wave_id * 8 + rnd * (_N_WAVES * 8) + col = (lane_id % 8) * 16 + sid = fx.Int32( + buffer_ops.buffer_load( + ids_rsrc, + m_base + half * LDS_BLOCK_M + row, + vec_width=1, + dtype=fx.Int32, + ) + ) + # padded rows: tok == n_tokens, out of bounds -> zeros + tok = sid & fx.Int32(0x00FFFFFF) + offs.append(tok * fx.Int32(K_BYTES) + _swizzled_col(row, col)) + return offs + + gl_off_a0 = _a_gather_offsets(0) + gl_off_a1 = _a_gather_offsets(1) + + # B: LDS row r of half gu (gate 0 / up 1) is in W13 block n0 * 2 + gu, + # n0 = tile_j * 8 + r // 16 + weight_group0 = tile_j * fx.Int32(LDS_BLOCK_N // 16) + group0 = expert * fx.Int32(N0) + weight_group0 + + def _b_offsets(gu): + offs = [] + for rnd in range_constexpr(N_TILES_B): + row = lane_id % 8 + wave_id * 8 + rnd * (_N_WAVES * 8) + col = (lane_id // 8) * 16 + blk = (weight_group0 + fx.Int32(row // 16)) * fx.Int32( + 2 + ) + fx.Int32(gu) + offs.append( + blk * fx.Int32(K_BYTES * 16) + + fx.Int32( + (row % 16) * 16 + + (col // 64) * 1024 + + ((col % 64) // 16) * 256 + + (col % 16) + ) + ) + return offs + + gl_off_b0 = _b_offsets(0) + gl_off_b1 = _b_offsets(1) + A_K_STEP = BLOCK_K_BYTES + B_K_STEP = 2 * 1024 # 128 B of K = two 1 KB blocks + + mfma = Mfma16x16x128Fp8(N_TILES_A, N_TILES_B) + + _scale_base_ptr = lds.scale_lds.ptr + scale_gather = ScaleGatherMoE( + A_scale, + W13_scale, + K, + lane_id, + wave_id, + _scale_base_ptr, + a_scale_bytes, + E * 2 * I * (K // 32), + A_WAVE_GROUPS, + A_HALF_GROUPS, + B_WAVE_GROUPS, + B_HALF_GROUPS, + ) + scale_gather.set_wave_base(m_base, group0 * fx.Int32(32)) + a_scale_ld = ScaleLoaderLDS( + N_TILES_A, lane_id, wave_i, _scale_base_ptr, _SCALE_A_REGION + ) + b_scale_ld = ScaleLoaderLDS( + N_TILES_B, lane_id, wave_j, _scale_base_ptr, _SCALE_B_REGION + ) + + def _slot(g): + return fx.Int32(g) % fx.Int32(_SCALE_SLOTS) + + a_rsrc = buffer_ops.create_buffer_resource( + A, max_size=False, num_records_bytes=n_tokens * K_BYTES + ) + b_rsrc = buffer_ops.create_buffer_resource( + W13, + max_size=False, + num_records_bytes=W_BYTES, + base_byte_offset=fx.Int64(expert) * W_BYTES, + ) + a0_g2s = G2SLoaderAsm(a_rsrc, gl_off_a0, N_TILES_A, wave_id) + a1_g2s = G2SLoaderAsm(a_rsrc, gl_off_a1, N_TILES_A, wave_id) + b0_g2s = G2SLoaderAsm(b_rsrc, gl_off_b0, N_TILES_B, wave_id) + b1_g2s = G2SLoaderAsm(b_rsrc, gl_off_b1, N_TILES_B, wave_id) + for ld in (a0_g2s, a1_g2s, b0_g2s, b1_g2s): + ld.set_wave_base(_base_ptr) + a_s2r = S2RLoader128B(wave_i, N_TILES_A) + b_s2r = S2RLoader128B(wave_j, N_TILES_B) + + # scale block g covers steps 2g, 2g + 1; block g >= 2 is gathered on + # step 2g - 3 + scale_gather.gather(0, _slot(0)) + scale_gather.gather(1, _slot(1)) + + a0_g2s.load(a_cur0, fx.Int32(0 * A_K_STEP)) + b0_g2s.load(b_cur0, fx.Int32(0 * B_K_STEP)) + b1_g2s.load(b_cur1, fx.Int32(0 * B_K_STEP)) + a1_g2s.load(a_cur1, fx.Int32(0 * A_K_STEP)) + + a0_g2s.load(a_next0, fx.Int32(1 * A_K_STEP)) + b0_g2s.load(b_next0, fx.Int32(1 * B_K_STEP)) + b1_g2s.load(b_next1, fx.Int32(1 * B_K_STEP)) + a1_g2s.load(a_next1, fx.Int32(1 * A_K_STEP)) + + # gathers + a_cur0 landed: b0/b1/a1 + the 4 next batches may fly + wait_barrier((3 * N_TILES_A) + (4 * N_TILES_B)) + a0_frag = a_s2r.load(a_cur0) + # b_cur0 AND b_cur1 landed: a1 + the 4 next batches may fly + wait_barrier((3 * N_TILES_A) + (2 * N_TILES_B)) + b0_frag = b_s2r.load(b_cur0, preshuffled=True) + b1_frag = b_s2r.load(b_cur1, preshuffled=True) + + sc0_saR0, sc0_saR1 = a_scale_ld.read(_slot(0)) + sc0_sbC0, sc0_sbC1 = b_scale_ld.read(_slot(0)) + sc0 = (sc0_saR0, sc0_saR1, sc0_sbC0 + sc0_sbC1) + + # Step kc issues a0, b0, [SEG2] b1, the scale gather (odd kc), a1 for step + # kc + 2. Top wait: step kc - 2 complete; SEG2 wait: a0 / b0 / b1 of step + # kc - 1 landed. Step kc - 1 gathered iff its parity k2 == 0. + def _top_vmcnt(k2): + return 2 * N_TILES_A + 2 * N_TILES_B + (1 - k2) + + def _seg2_vmcnt(k2): + return 2 * N_TILES_A + N_TILES_B + (1 - k2) + + # step 0 follows the prologue, which has no gather after a_cur1 + _STEP0_VMCNT = 2 * N_TILES_A + 2 * N_TILES_B + _STEP0_SEG2_VMCNT = 2 * N_TILES_A + N_TILES_B + + def _read_scale_thunks(kc_idx, holder): + s = _slot(fx.Int32(kc_idx) // fx.Int32(2)) + + def _r(dst, ld, half, _s=s): + holder[dst] = ld.read_half(_s, half) + + return [ + lambda: _r(0, a_scale_ld, 0), + lambda: _r(1, a_scale_ld, 1), + lambda: _r(2, b_scale_ld, 0), + lambda: _r(3, b_scale_ld, 1), + ] + + def _one_step( + kc, + k2, + a0f, + b0f, + b1f_in, + sc, + accs, + bufs, + zero_acc=False, + top_vmcnt=None, + seg2_vmcnt=None, + ): + """``kc``: step index; ``k2``: its parity as a Python int.""" + kc_i = fx.Int32(kc) + top_vmcnt = _top_vmcnt(k2) if top_vmcnt is None else top_vmcnt + seg2_vmcnt = _seg2_vmcnt(k2) if seg2_vmcnt is None else seg2_vmcnt + ac0, ac1, an0, an1, bc0, bc1, bn0, bn1 = bufs + saR0, saR1, sbC = sc + c00f, c01f, c10f, c11f = accs + + _a1 = [None] * N_TILES_A + _a0n = [None] * N_TILES_A + _b0n = [None] * N_TILES_B + _b1n = [None] * N_TILES_B + a_off = (kc_i + fx.Int32(2)) * fx.Int32(A_K_STEP) + b_off = (kc_i + fx.Int32(2)) * fx.Int32(B_K_STEP) + + _scn = [None, None, None, None] # type: list + _rd_scn = _read_scale_thunks(kc_i + fx.Int32(1), _scn) + # odd steps only: a list repeat, as an if would become an scf dispatch + _gk = _min( + (kc_i + fx.Int32(3)) // fx.Int32(2), fx.Int32(K_ITERS // 2 - 1) + ) + _sc_gather = [lambda: scale_gather.gather(_gk, _slot(_gk))] * k2 + + wait_barrier(top_vmcnt) + il = ( + _riffle( + _g2s_thunks(a0_g2s, ac0, a_off, N_TILES_A), + _s2r_thunks(a_s2r, ac1, _a1, N_TILES_A, False), + ) + + _rd_scn[:2] + ) + c00f = mfma.call( + a0f, b0f, c00f, saR0, sbC, 0, k2, interleave=il, zero_acc=zero_acc + ) + + il = _riffle(_g2s_thunks(b0_g2s, bc0, b_off, N_TILES_B), _rd_scn[2:]) + c01f = mfma.call( + a0f, + b1f_in, + c01f, + saR0, + sbC, + 1, + k2, + interleave=il, + zero_acc=zero_acc, + ) + a1f = _a1 + + wait_barrier(seg2_vmcnt) + il = ( + _riffle( + _g2s_thunks(b1_g2s, bc1, b_off, N_TILES_B), + _s2r_thunks(a_s2r, an0, _a0n, N_TILES_A, False), + ) + + _sc_gather + ) + c10f = mfma.call( + a1f, b0f, c10f, saR1, sbC, 0, k2, interleave=il, zero_acc=zero_acc + ) + a0nf = _a0n + + il = _riffle( + _g2s_thunks(a1_g2s, ac1, a_off, N_TILES_A), + _s2r_thunks(b_s2r, bn0, _b0n, N_TILES_B, True) + + _s2r_thunks(b_s2r, bn1, _b1n, N_TILES_B, True), + ) + c11f = mfma.call( + a1f, + b1f_in, + c11f, + saR1, + sbC, + 1, + k2, + interleave=il, + zero_acc=zero_acc, + ) + b0nf = _b0n + b1nf = _b1n + + sc_next = (_scn[0], _scn[1], _scn[2] + _scn[3]) + new_bufs = (an0, an1, ac0, ac1, bn0, bn1, bc0, bc1) + return a0nf, b0nf, b1nf, sc_next, (c00f, c01f, c10f, c11f), new_bufs + + bufs0 = (a_cur0, a_cur1, a_next0, a_next1, b_cur0, b_cur1, b_next0, b_next1) + + def _swap_bufs(bufs): + ac0, ac1, an0, an1, bc0, bc1, bn0, bn1 = bufs + return (an0, an1, ac0, ac1, bn0, bn1, bc0, bc1) + + n_a = 2 * N_TILES_A + n_b = 2 * N_TILES_B + n_ga = N_TILES_A // 2 + n_sc = 2 * n_ga + N_TILES_B + _R = fx.as_ir_value + + def _flat_sc(sc): + saR0, saR1, sbC = sc + return ( + [_R(v) for v in saR0] + [_R(v) for v in saR1] + [_R(v) for v in sbC] + ) + + def _unflat_sc(flat): + o = 0 + saR0 = list(flat[o : o + n_ga]) + o += n_ga + saR1 = list(flat[o : o + n_ga]) + o += n_ga + sbC = list(flat[o : o + N_TILES_B]) + return (saR0, saR1, sbC) + + _accs0 = tuple([None] * N_ACCUMS for _ in range(4)) + a0f, b0f, b1f, sc, accs, _ = _one_step( + 0, + 0, + a0_frag, + b0_frag, + b1_frag, + sc0, + _accs0, + bufs0, + zero_acc=True, + top_vmcnt=_STEP0_VMCNT, + seg2_vmcnt=_STEP0_SEG2_VMCNT, + ) + a0f, b0f, b1f, sc, accs, _ = _one_step( + 1, 1, a0f, b0f, b1f, sc, accs, _swap_bufs(bufs0) + ) + + init_state = ( + _flat_frag(a0f) + + _flat_frag(b0f) + + _flat_frag(b1f) + + _flat_sc(sc) + + [_R(x) for x in accs[0]] + + [_R(x) for x in accs[1]] + + [_R(x) for x in accs[2]] + + [_R(x) for x in accs[3]] + ) + # FlyDSL rewrites range(init=...) to a loop carrying state. + for kk, state in range( # type: ignore[call-overload] + 2, K_ITERS - 2, UNROLL, init=init_state + ): + off = 0 + a0f = _unflat_frag(state[off : off + n_a], N_TILES_A) + off += n_a + b0f = _unflat_frag(state[off : off + n_b], N_TILES_B) + off += n_b + b1f = _unflat_frag(state[off : off + n_b], N_TILES_B) + off += n_b + sc = _unflat_sc(state[off : off + n_sc]) + off += n_sc + c00f = list(state[off : off + N_ACCUMS]) + off += N_ACCUMS + c01f = list(state[off : off + N_ACCUMS]) + off += N_ACCUMS + c10f = list(state[off : off + N_ACCUMS]) + off += N_ACCUMS + c11f = list(state[off : off + N_ACCUMS]) + off += N_ACCUMS + accs = (c00f, c01f, c10f, c11f) + + bufs = bufs0 + for u in range_constexpr(UNROLL): + # kk is even: kk + u has u's parity + a0f, b0f, b1f, sc, accs, bufs = _one_step( + kk + u, u % 2, a0f, b0f, b1f, sc, accs, bufs + ) + + new_state = ( + _flat_frag(a0f) + + _flat_frag(b0f) + + _flat_frag(b1f) + + _flat_sc(sc) + + [_R(x) for x in accs[0]] + + [_R(x) for x in accs[1]] + + [_R(x) for x in accs[2]] + + [_R(x) for x in accs[3]] + ) + state = yield new_state + + off = 0 + a0_frag = _unflat_frag(state[off : off + n_a], N_TILES_A) + off += n_a + b0_frag = _unflat_frag(state[off : off + n_b], N_TILES_B) + off += n_b + b1_frag = _unflat_frag(state[off : off + n_b], N_TILES_B) + off += n_b + sc = _unflat_sc(state[off : off + n_sc]) + off += n_sc + c00_frag = list(state[off : off + N_ACCUMS]) + off += N_ACCUMS + c01_frag = list(state[off : off + N_ACCUMS]) + off += N_ACCUMS + c10_frag = list(state[off : off + N_ACCUMS]) + off += N_ACCUMS + c11_frag = list(state[off : off + N_ACCUMS]) + off += N_ACCUMS + + # tail step K_ITERS - 2 (even) + saR0, saR1, sbC = sc + _scn = [None, None, None, None] # type: list + _rd_scn = _read_scale_thunks(fx.Int32(K_ITERS - 1), _scn) + _a1 = [None] * N_TILES_A + wait_barrier((2 * N_TILES_A) + (2 * N_TILES_B)) + il = _s2r_thunks(a_s2r, a_cur1, _a1, N_TILES_A, False) + _rd_scn + c00_frag = mfma.call( + a0_frag, b0_frag, c00_frag, saR0, sbC, 0, 0, interleave=il + ) + a1_frag = _a1 + c01_frag = mfma.call(a0_frag, b1_frag, c01_frag, saR0, sbC, 1, 0) + _a0n = [None] * N_TILES_A + _b0n = [None] * N_TILES_B + _b1n = [None] * N_TILES_B + wait_barrier(1 * N_TILES_A) + il = ( + _s2r_thunks(a_s2r, a_next0, _a0n, N_TILES_A, False) + + _s2r_thunks(b_s2r, b_next0, _b0n, N_TILES_B, True) + + _s2r_thunks(b_s2r, b_next1, _b1n, N_TILES_B, True) + ) + c10_frag = mfma.call( + a1_frag, b0_frag, c10_frag, saR1, sbC, 0, 0, interleave=il + ) + c11_frag = mfma.call(a1_frag, b1_frag, c11_frag, saR1, sbC, 1, 0) + a0_frag = _a0n + b0_frag = _b0n + b1_frag = _b1n + + # tail step K_ITERS - 1 (odd; A half 1 in a_next1) + _a1 = [None] * N_TILES_A + wait_barrier(0) + saR0, saR1, sbC = (_scn[0], _scn[1], _scn[2] + _scn[3]) + il = _s2r_thunks(a_s2r, a_next1, _a1, N_TILES_A, False) + # each final group is released one group later (_MFMA_RESULT_WAIT) + c00_frag = mfma.call( + a0_frag, b0_frag, c00_frag, saR0, sbC, 0, 1, interleave=il + ) + a1_frag = _a1 + c01_frag = mfma.call(a0_frag, b1_frag, c01_frag, saR0, sbC, 1, 1) + c00_frag = mfma.hold(c00_frag) + c10_frag = mfma.call(a1_frag, b0_frag, c10_frag, saR1, sbC, 0, 1) + c01_frag = mfma.hold(c01_frag) + c11_frag = mfma.call(a1_frag, b1_frag, c11_frag, saR1, sbC, 1, 1) + c10_frag = mfma.hold(c10_frag) + c11_frag = mfma.hold(c11_frag, wait=_MFMA_RESULT_WAIT) + + out_rsrc = buffer_ops.create_buffer_resource( + OUT_Q, max_size=False, num_records_bytes=num_m_blocks * (BLOCK_M * I) + ) + osc_rsrc = buffer_ops.create_buffer_resource( + OUT_scale, + max_size=False, + num_records_bytes=num_m_blocks * (BLOCK_M * SCALE_COLS_OUT), + ) + g = lane_id // 16 + r16 = lane_id % 16 + col_base = tile_j * LDS_BLOCK_N + wave_j * (N_TILES_B * 16) + colgrp_base = col_base // 32 + + def _epilogue(c_gate, c_up, base_row): + """Rows ``base_row + ti * 16 + r16`` x the wave's 64 gate columns.""" + for p in range_constexpr(N_TILES_B // 2): + colgrp = colgrp_base + p + sc_in_block = (colgrp % 4) * 64 + r16 * 4 + ((colgrp % 8) // 4) * 2 + e8m0_of_ti = [] + for ti in range_constexpr(N_TILES_A): + gv = Vec(c_gate[mfma.idx(ti, 2 * p)]) + gw = Vec(c_gate[mfma.idx(ti, 2 * p + 1)]) + uv = Vec(c_up[mfma.idx(ti, 2 * p)]) + uw = Vec(c_up[mfma.idx(ti, 2 * p + 1)]) + h = [ + _swiglu_oai(fx.Float32(gv[v]), fx.Float32(uv[v])) + for v in range_constexpr(4) + ] + [ + _swiglu_oai(fx.Float32(gw[v]), fx.Float32(uw[v])) + for v in range(4) + ] + amax = _maxf_nn(fx.math.absf(h[0]), fx.math.absf(h[1])) + for v in range_constexpr(2, 8): + amax = _maxf_nn(amax, fx.math.absf(h[v])) + # the 4 lanes {L, L^16, L^32, L^48} hold the same row + amax = _fmax(amax, amax.shuffle_xor(16, 64)) + amax = _fmax(amax, amax.shuffle_xor(32, 64)) + e8m0 = _e8m0_roundup_fp8(amax) + e8m0_of_ti.append(e8m0) + scale_f = _as_f32(e8m0 << 23) + da = _cvt_pk_fp8(_undef_i32(), h[0], h[1], scale_f, False) + da = _cvt_pk_fp8(da, h[2], h[3], scale_f, True) + db = _cvt_pk_fp8(_undef_i32(), h[4], h[5], scale_f, False) + db = _cvt_pk_fp8(db, h[6], h[7], scale_f, True) + da, db = _permlane16_swap(da, db) + row = base_row + ti * 16 + r16 + # after the swap: tile 2p + g % 2, cols (g // 2) * 8 + [0, 8) + col = col_base + (2 * p + (g % 2)) * 16 + (g // 2) * 8 + buffer_ops.buffer_store( + _v2i32(da, db), + out_rsrc, + row * I + col, + offset_is_bytes=True, + ) + # the e8m0 of tiles 2tp, 2tp + 1 (one 32-row group) as one i16 + for tp in range_constexpr(N_TILES_A // 2): + row32 = (base_row // 32) + tp + blk = row32 * OUT_SC_BLOCKS_PER_ROW32 + colgrp // 8 + pair = e8m0_of_ti[2 * tp] | (e8m0_of_ti[2 * tp + 1] << 8) + pair16 = fx.Int32(pair).to(fx.Int16) + buffer_ops.buffer_store( + pair16, + osc_rsrc, + blk * 256 + sc_in_block, + offset_is_bytes=True, + ) + + row_r0 = m_base + wave_i * (N_TILES_A * 16) + row_r1 = row_r0 + LDS_BLOCK_M + _epilogue(c00_frag, c01_frag, row_r0) + _epilogue(c10_frag, c11_frag, row_r1) + + @flyc.jit + def launch_gemm1( + A: fx.Tensor, + W13: fx.Tensor, + OUT_Q: fx.Tensor, + A_scale: fx.Tensor, + W13_scale: fx.Tensor, + OUT_scale: fx.Tensor, + sorted_ids: fx.Tensor, + sorted_expert_ids: fx.Tensor, + n_tokens: fx.Int32, + num_m_blocks: fx.Int32, + a_scale_bytes: fx.Int32, + tile_map_t: fx.Tensor, + grid_size: fx.Int32, + stream: fx.Stream, + ): + grid_x = grid_size + kernel_gemm1( + A, + W13, + OUT_Q, + A_scale, + W13_scale, + OUT_scale, + sorted_ids, + sorted_expert_ids, + n_tokens, + num_m_blocks, + a_scale_bytes, + tile_map_t, + grid_size, + value_attrs={ + "rocdl.waves_per_eu": 1, + "rocdl.flat_work_group_size": "256,256", + }, + ).launch(grid=(grid_x, 1, 1), block=(256, 1, 1), stream=stream) + + return launch_gemm1 diff --git a/vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm2_prefill.py b/vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm2_prefill.py new file mode 100644 index 000000000000..0751680e016e --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm2_prefill.py @@ -0,0 +1,682 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Prefill MoE down GEMM (fp8 x fp8, MXFP8 scales) on sorted rows: routing-weighted +bf16 partials ``OUT[tok * topk + slot]``, summed by ``moe_flydsl_common.reduce_bf16``. +A CTA owns a 128-row m-tile and sweeps ``NT`` n-tiles of 256 W2 rows as one K-step +sequence; W2 runs three steps ahead (3 LDS stages), A two. + +Layouts (bytes): + A [num_m_blocks*BM, I] sorted rows, fp8 (gemm1 OUT_Q) + A_scale [pad32(num_m_blocks*BM), I/32] sorted rows, e8m0-shuffled (gemm1 OUT_sc) + W2 [E, H, I] aiter shuffle_weight (16 x 64 K blocks) + W2_sc [E*H/32, I/256, 4, 16] dwords aiter shuffle_scale + sorted_w [num_m_blocks*BM] f32 routing weight per sorted row + OUT [n_tokens*topk, H] bf16 +""" + +import flydsl.compiler as flyc +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import buffer_ops +from flydsl.expr import const_expr, range_constexpr +from flydsl.expr.typing import Vector as Vec + +from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.epilogue import ( + _NUM_XCDS, + _STORE_CPOL, + _bf16x2, + _lds_load_vec, + _lds_store_vec, + _v2i32, +) +from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.loaders import ( + _N_WAVES, + _SCALE_A_REGION, + _SCALE_B_REGION, + _SCALE_SLOT_BYTES, + G2SLoaderAsm, + S2RLoader128B, + ScaleGatherMoE, + ScaleLoaderLDS, + _asm_void, + _Buf, + _divmod_nonneg, + _flat_frag, + _g2s_thunks, + _riffle, + _s2r_thunks, + _swizzled_col, + _unflat_frag, + wait_barrier, +) + +from .gemm1_prefill import BLOCK_K, Mfma16x16x128Fp8 + +_SCALE_SLOTS2 = 4 + + +def compile_moe_gemm2( + *, + H: int, + I: int, # noqa: E741 + E: int, + topk: int, + n_split: int = 2, + sort_block_m: int = 128, +): + """``sort_block_m``: the sort block of the inputs (128 or 256); the kernel tiles + 128 rows and skips the all-padding halves of a 256-sort.""" + BM = 128 + BN = 256 + K = I + K_BYTES = K + BLOCK_K_BYTES = BLOCK_K + EID_SHIFT = (sort_block_m // BM).bit_length() - 1 + assert sort_block_m in (BM, 2 * BM) + N_TILES_ALL = H // BN + assert H % BN == 0 and N_TILES_ALL % n_split == 0 + NT = N_TILES_ALL // n_split # n-tiles per CTA + K_ITERS = K // BLOCK_K + assert K_ITERS in (6, 12, 24) and K % 256 == 0 + SCALE_BLOCKS = K_ITERS // 2 + LDS_BLOCK_M = BM // 2 + LDS_BLOCK_N = BN // 2 + N_TILES_A = LDS_BLOCK_M // 2 // 16 + N_TILES_B = LDS_BLOCK_N // 2 // 16 + N_ACCUMS = N_TILES_A * N_TILES_B + NB = N_TILES_B + NA = N_TILES_A + OUT_ROW_BYTES = H * 2 + W2_BYTES = H * K + assert W2_BYTES <= 0xFFFFFFFF + B_TILE_BYTES = BN * K_BYTES + + B_STAGES = 3 + a_lds_size = LDS_BLOCK_M * BLOCK_K_BYTES + b_lds_size = LDS_BLOCK_N * BLOCK_K_BYTES + A_BUFS = 4 * a_lds_size # 2 stages x 2 halves + LDS_TILES_BYTES = A_BUFS + 2 * B_STAGES * b_lds_size + SCALE_LDS_BYTES2 = _SCALE_SLOTS2 * _SCALE_SLOT_BYTES + # wave-private epilogue staging: 16 rows x the wave's 128 bf16 cols + STG_ROW = 2 * N_TILES_B * 16 * 2 # the wave's two 128-B line segments + STG_CH = STG_ROW // 16 + STG_ROWS = 16 # one (row half, a-tile) at a time + STG_WAVE = STG_ROWS * STG_ROW + STG_LDS_BYTES = _N_WAVES * STG_WAVE + N_FLUSH = (STG_ROWS * 2) // 8 # dwordx4 stores per lane per staged block + assert LDS_TILES_BYTES + SCALE_LDS_BYTES2 + STG_LDS_BYTES <= 160 * 1024 + + A_WAVE_GROUPS = N_TILES_A // 2 + A_HALF_GROUPS = LDS_BLOCK_M // 32 + B_WAVE_GROUPS = 2 # 32-row groups per wave (64 W2 rows) + B_HALF_GROUPS = LDS_BLOCK_N // 32 + SC_COLS = K // 32 + W2_SC_BYTES = E * H * SC_COLS + + @fx.struct + class SharedStorage: + all_lds: fx.Array[fx.Int8, LDS_TILES_BYTES, 16] + scale_lds: fx.Array[fx.Int8, SCALE_LDS_BYTES2, 16] + stage_lds: fx.Array[fx.Int8, STG_LDS_BYTES, 16] + + @flyc.kernel + def kernel_gemm2( + A: fx.Tensor, + W2: fx.Tensor, + OUT: fx.Tensor, + A_scale: fx.Tensor, + W2_scale: fx.Tensor, + sorted_ids: fx.Tensor, + sorted_expert_ids: fx.Tensor, + sorted_weights: fx.Tensor, + num_valid_ids: fx.Tensor, + n_tokens: fx.Int32, + num_m_blocks: fx.Int32, + grid_size: fx.Int32, + ): + lds = fx.SharedAllocator().allocate(SharedStorage).peek() + _base_ptr = lds.all_lds.ptr + _scale_base_ptr = lds.scale_lds.ptr + _stg_ptr = lds.stage_lds.ptr + + a_cur0 = _Buf(_base_ptr, 0 * a_lds_size) + a_cur1 = _Buf(_base_ptr, 1 * a_lds_size) + a_next0 = _Buf(_base_ptr, 2 * a_lds_size) + a_next1 = _Buf(_base_ptr, 3 * a_lds_size) + # B: 3 stages x 2 halves + b_st = [ + [_Buf(_base_ptr, A_BUFS + (2 * st + hf) * b_lds_size) for hf in range(2)] + for st in range(B_STAGES) + ] + + lane_id = fx.thread_idx.x % 64 + wave_id = fx.thread_idx.x // 64 + wave_i = wave_id // 2 + wave_j = wave_id % 2 + g4 = lane_id // 16 + r16 = lane_id % 16 + + # work item (m-tile, n-chunk); consecutive m-tiles share an XCD + nv_rsrc = buffer_ops.create_buffer_resource( + num_valid_ids, max_size=False, num_records_bytes=4 + ) + num_valid = fx.Int32( + buffer_ops.buffer_load( + nv_rsrc, fx.Int32(0), vec_width=1, dtype=fx.Int32, is_scalar=True + ) + ) + n_work = (num_valid // fx.Int32(BM)) * fx.Int32(n_split) + per_xcd = (n_work + fx.Int32(_NUM_XCDS - 1)) // fx.Int32(_NUM_XCDS) + intra, xcd = _divmod_nonneg(fx.block_idx.x, _NUM_XCDS) + work = xcd * per_xcd + intra + block_valid = (intra < per_xcd) & (work < n_work) + work_safe = block_valid.select(work, fx.Int32(0)) + tile_i, chunk = _divmod_nonneg(work_safe, n_split) + m_base = tile_i * BM + eid_rsrc = buffer_ops.create_buffer_resource( + sorted_expert_ids, max_size=False, num_records_bytes=num_m_blocks * 4 + ) + expert = fx.Int32( + buffer_ops.buffer_load( + eid_rsrc, + tile_i >> EID_SHIFT, + vec_width=1, + dtype=fx.Int32, + is_scalar=True, + ) + ) + ids_rsrc = buffer_ops.create_buffer_resource( + sorted_ids, max_size=False, num_records_bytes=num_m_blocks * (BM * 4) + ) + if const_expr(EID_SHIFT > 0): + # a 256-sort pads each expert: a 128-row tile starting with padding is empty + first_sid = fx.Int32( + buffer_ops.buffer_load( + ids_rsrc, m_base, vec_width=1, dtype=fx.Int32, is_scalar=True + ) + ) + block_valid = block_valid & ((first_sid & fx.Int32(0x00FFFFFF)) < n_tokens) + chunk_n0 = chunk * NT + # rotate the n-tile sweep inside same-expert runs: neighbours find W2 in L2 + ROT_STRIDE, ROT_GATE = 2, 3 + _d = fx.Int32(ROT_GATE) + _lo_ok = tile_i >= _d + _hi_ok = tile_i + _d < num_m_blocks + _e_lo = fx.Int32( + buffer_ops.buffer_load( + eid_rsrc, + _lo_ok.select(tile_i - _d, fx.Int32(0)) >> EID_SHIFT, + vec_width=1, + dtype=fx.Int32, + is_scalar=True, + ) + ) + _e_hi = fx.Int32( + buffer_ops.buffer_load( + eid_rsrc, + _hi_ok.select(tile_i + _d, fx.Int32(0)) >> EID_SHIFT, + vec_width=1, + dtype=fx.Int32, + is_scalar=True, + ) + ) + rot_on = (_lo_ok & (_e_lo == expert)) | (_hi_ok & (_e_hi == expert)) + nt_rot = rot_on.select( + _divmod_nonneg(tile_i * fx.Int32(ROT_STRIDE), NT)[1], fx.Int32(0) + ) + + def _pn(nt): + """Sweep-order n-tile -> n-tile of the chunk.""" + x = nt + nt_rot + return (x >= fx.Int32(NT)).select(x - fx.Int32(NT), x) + + def _n_glob(nt): + """Global n-tile of sweep-order ``nt``, clamped to the last one.""" + ntc = (nt >= fx.Int32(NT)).select(fx.Int32(NT - 1), nt) + return chunk_n0 + _pn(ntc) + + if block_valid: + sw_rsrc = buffer_ops.create_buffer_resource( + sorted_weights, + max_size=False, + num_records_bytes=num_m_blocks * (BM * 4), + ) + a_rsrc = buffer_ops.create_buffer_resource( + A, max_size=False, num_records_bytes=num_m_blocks * (BM * K_BYTES) + ) + b_rsrc = buffer_ops.create_buffer_resource( + W2, + max_size=False, + num_records_bytes=W2_BYTES, + base_byte_offset=fx.Int64(expert) * W2_BYTES, + ) + # padded rows (tok == n_tokens) fall outside the resource + out_rows = n_tokens * fx.Int32(topk) + out_rsrc = buffer_ops.create_buffer_resource( + OUT, max_size=False, num_records_bytes=out_rows * OUT_ROW_BYTES + ) + + def _a_offsets(half): + offs = [] + for rnd in range_constexpr(N_TILES_A): + row = lane_id // 8 + wave_id * 8 + rnd * (_N_WAVES * 8) + col = (lane_id % 8) * 16 + grow = m_base + half * LDS_BLOCK_M + row + offs.append(grow * fx.Int32(K_BYTES) + _swizzled_col(row, col)) + return offs + + gl_off_a0 = _a_offsets(0) + gl_off_a1 = _a_offsets(1) + + # W2 offsets inside an n-tile; the n-tile goes in soffset + e_row0 = expert * fx.Int32(H) + + def _b_offsets(hf): + offs = [] + for rnd in range_constexpr(N_TILES_B): + row = lane_id % 8 + wave_id * 8 + rnd * (_N_WAVES * 8) + col = (lane_id // 8) * 16 + wrow = fx.Int32(hf * LDS_BLOCK_N + row) + offs.append( + (wrow // fx.Int32(16)) * fx.Int32(K_BYTES * 16) + + fx.Int32( + (row % 16) * 16 + + (col // 64) * 1024 + + ((col % 64) // 16) * 256 + + (col % 16) + ) + ) + return offs + + gl_off_b0 = _b_offsets(0) + gl_off_b1 = _b_offsets(1) + A_K_STEP = BLOCK_K_BYTES + B_K_STEP = 2 * 1024 + + mfma = Mfma16x16x128Fp8(N_TILES_A, N_TILES_B) + sb_index = lambda j, hf: (j // 2, j % 2) # noqa: E731 (32-row groups) + + scale_gather = ScaleGatherMoE( + A_scale, + W2_scale, + K, + lane_id, + wave_id, + _scale_base_ptr, + num_m_blocks * (BM * SC_COLS), + W2_SC_BYTES, + A_WAVE_GROUPS, + A_HALF_GROUPS, + B_WAVE_GROUPS, + B_HALF_GROUPS, + ) + + def _set_scale_tile(nt): + scale_gather.set_wave_base(m_base, e_row0 + _n_glob(nt) * fx.Int32(BN)) + + a_scale_ld = ScaleLoaderLDS( + N_TILES_A, lane_id, wave_i, _scale_base_ptr, _SCALE_A_REGION + ) + b_scale_ld = ScaleLoaderLDS( + N_TILES_B, lane_id, wave_j, _scale_base_ptr, _SCALE_B_REGION + ) + + def _slot(nt, g): + return (fx.Int32(nt) * fx.Int32(SCALE_BLOCKS) + fx.Int32(g)) % fx.Int32( + _SCALE_SLOTS2 + ) + + a0_g2s = G2SLoaderAsm(a_rsrc, gl_off_a0, N_TILES_A, wave_id) + a1_g2s = G2SLoaderAsm(a_rsrc, gl_off_a1, N_TILES_A, wave_id) + b0_g2s = G2SLoaderAsm(b_rsrc, gl_off_b0, N_TILES_B, wave_id) + b1_g2s = G2SLoaderAsm(b_rsrc, gl_off_b1, N_TILES_B, wave_id) + for ld in (a0_g2s, a1_g2s, b0_g2s, b1_g2s): + ld.set_wave_base(_base_ptr) + a_s2r = S2RLoader128B(wave_i, N_TILES_A) + b_s2r = S2RLoader128B(wave_j, N_TILES_B) + + def _orow(sid): + tok = sid & fx.Int32(0x00FFFFFF) # padded: tok == n_tokens -> OOB + slot = (sid >> 24) & fx.Int32(0xFF) + return tok * fx.Int32(topk) + slot + + # routing weights of the lane's rows; output offsets of the rows it + # flushes (store k: staged row 4k + lane // 16) + wave_row0 = m_base + wave_i * (N_TILES_A * 16) + row_w = [] + for h in range_constexpr(2): + for ti in range_constexpr(N_TILES_A): + row = wave_row0 + fx.Int32(h * LDS_BLOCK_M + ti * 16) + r16 + row_w.append( + fx.Float32( + buffer_ops.buffer_load( + sw_rsrc, row, vec_width=1, dtype=fx.Float32 + ) + ) + ) + flush_off = [] + for h in range_constexpr(2): + for ti in range_constexpr(NA): + for k in range_constexpr(N_FLUSH): + row = ( + wave_row0 + + fx.Int32(h * LDS_BLOCK_M + ti * 16 + 4 * k) + + lane_id // 16 + ) + sid = fx.Int32( + buffer_ops.buffer_load( + ids_rsrc, row, vec_width=1, dtype=fx.Int32 + ) + ) + flush_off.append(_orow(sid) * fx.Int32(OUT_ROW_BYTES)) + stg_base = fx.Int32(fx.ptrtoint(_stg_ptr)) + wave_id * fx.Int32(STG_WAVE) + + def _stg_addr(row, chunk, half): + """Staged (row, 16-B chunk, 8-B half), chunks XOR-swizzled by row.""" + return ( + stg_base + + row * fx.Int32(STG_ROW) + + ((chunk ^ (row % STG_CH)) * 16 + half * 8) + ) + + # prologue = steps -3, -2, -1 of the steady-state issue order + _set_scale_tile(fx.Int32(0)) + scale_gather.gather(0, _slot(0, 0)) + b_soff0 = _n_glob(fx.Int32(0)) * fx.Int32(B_TILE_BYTES) + b0_g2s.load(b_st[0][0], b_soff0 + fx.Int32(0 * B_K_STEP)) + b1_g2s.load(b_st[0][1], b_soff0 + fx.Int32(0 * B_K_STEP)) + b0_g2s.load(b_st[1][0], b_soff0 + fx.Int32(1 * B_K_STEP)) + b1_g2s.load(b_st[1][1], b_soff0 + fx.Int32(1 * B_K_STEP)) + a0_g2s.load(a_cur0, fx.Int32(0 * A_K_STEP)) + a1_g2s.load(a_cur1, fx.Int32(0 * A_K_STEP)) + b0_g2s.load(b_st[2][0], b_soff0 + fx.Int32(2 * B_K_STEP)) + b1_g2s.load(b_st[2][1], b_soff0 + fx.Int32(2 * B_K_STEP)) + a0_g2s.load(a_next0, fx.Int32(1 * A_K_STEP)) + scale_gather.gather(1, _slot(0, 1)) + a1_g2s.load(a_next1, fx.Int32(1 * A_K_STEP)) + + # gather 0, B(0) and a0(0) landed: a1(0), B(2), a0(1), gather, a1(1) may fly + wait_barrier(NA + 2 * NB + NA + 1 + NA) + a0_frag = a_s2r.load(a_cur0) + b0_frag = b_s2r.load(b_st[0][0], preshuffled=True) + b1_frag = b_s2r.load(b_st[0][1], preshuffled=True) + sc0_saR0, sc0_saR1 = a_scale_ld.read(_slot(0, 0)) + sc0_sbC0, sc0_sbC1 = b_scale_ld.read(_slot(0, 0)) + sc0 = (sc0_saR0, sc0_saR1, sc0_sbC0, sc0_sbC1) + + # Step kc issues B(kc + 3), a0(kc + 2), [MID] the scale gather (odd kc), + # a1(kc + 2). Top wait: a1(kc) landed; MID wait: a0(kc + 1) landed. The + # counts leave out the epilogue stores: they retire out of order. + def _top_vmcnt(kc): + return 2 * NB + 2 * NA + (1 - kc % 2) + + def _mid_vmcnt(kc): + return NA + 2 * NB + NA + (1 - kc % 2) + + def _read_scale_thunks(nt, kc_next, holder): + # the next flat step's scales; Python ints only (an ``if`` here would + # become an scf.if) + s = _slot(nt + fx.Int32(kc_next // K_ITERS), (kc_next % K_ITERS) // 2) + + def _r(dst, ld, half, _s=s): + holder[dst] = ld.read_half(_s, half) + + return [ + lambda: _r(0, a_scale_ld, 0), + lambda: _r(1, a_scale_ld, 1), + lambda: _r(2, b_scale_ld, 0), + lambda: _r(3, b_scale_ld, 1), + ] + + def _one_step(nt, kc, a0f, b0f, b1f_in, sc, accs, abufs): + """``nt`` is the n-tile; ``kc`` is a constexpr K-step within it.""" + k2 = kc % 2 + ac0, ac1, an0, an1 = abufs + bst = b_st[kc % 3] # read now, refilled for step kc + 3 + bnx = b_st[(kc + 1) % 3] + saR0, saR1, sbC0, sbC1 = sc + c00f, c01f, c10f, c11f = accs + zero_acc = kc == 0 + + _a1 = [None] * NA + _a0n = [None] * NA + _b0n = [None] * NB + _b1n = [None] * NB + # A for flat step kc + 2, B for kc + 3 (possibly in tile nt + 1) + ka = (kc + 2) % K_ITERS + kb = (kc + 3) % K_ITERS + nt_b = nt + fx.Int32((kc + 3) // K_ITERS) + a_off = fx.Int32(ka * A_K_STEP) + b_off = _n_glob(nt_b) * fx.Int32(B_TILE_BYTES) + fx.Int32(kb * B_K_STEP) + + _scn = [None, None, None, None] + _rd_scn = _read_scale_thunks(nt, kc + 1, _scn) + # Gather scales three steps ahead, crossing n-tiles as needed. + future_block = (kc + 3) // 2 + _g_blk = future_block % SCALE_BLOCKS + _g_slot = _slot(nt + fx.Int32(future_block // SCALE_BLOCKS), _g_blk) + _sc_gather = [lambda: scale_gather.gather(_g_blk, _g_slot)] * k2 + + wait_barrier(_top_vmcnt(kc)) + il = ( + _riffle( + _g2s_thunks(b0_g2s, bst[0], b_off, NB), + _s2r_thunks(a_s2r, ac1, _a1, NA, False), + ) + + _rd_scn[:2] + ) + c00f = mfma.call( + a0f, + b0f, + c00f, + saR0, + sbC0, + 0, + k2, + interleave=il, + zero_acc=zero_acc, + sb_index=sb_index, + ) + # never riffle two G2S loaders: each one's steps share m0, so + # interleaving them corrupts the LDS destinations + il = ( + _g2s_thunks(b1_g2s, bst[1], b_off, NB) + + _g2s_thunks(a0_g2s, ac0, a_off, NA) + + _rd_scn[2:] + ) + c01f = mfma.call( + a0f, + b1f_in, + c01f, + saR0, + sbC1, + 1, + k2, + interleave=il, + zero_acc=zero_acc, + sb_index=sb_index, + ) + a1f = _a1 + + wait_barrier(_mid_vmcnt(kc)) + il = _s2r_thunks(a_s2r, an0, _a0n, NA, False) + _sc_gather + c10f = mfma.call( + a1f, + b0f, + c10f, + saR1, + sbC0, + 0, + k2, + interleave=il, + zero_acc=zero_acc, + sb_index=sb_index, + ) + a0nf = _a0n + il = _riffle( + _g2s_thunks(a1_g2s, ac1, a_off, NA), + _s2r_thunks(b_s2r, bnx[0], _b0n, NB, True) + + _s2r_thunks(b_s2r, bnx[1], _b1n, NB, True), + ) + c11f = mfma.call( + a1f, + b1f_in, + c11f, + saR1, + sbC1, + 1, + k2, + interleave=il, + zero_acc=zero_acc, + sb_index=sb_index, + ) + sc_next = (_scn[0], _scn[1], _scn[2], _scn[3]) + return ( + a0nf, + _b0n, + _b1n, + sc_next, + (c00f, c01f, c10f, c11f), + (an0, an1, ac0, ac1), + ) + + def _stage(accs, h, ti): + """Routing-weighted bf16 of rows (``h``, ``ti``) into the staging + buffer; a wave's LDS ops run in order, after the last flush's reads.""" + w = row_w[h * NA + ti] + for hf in range_constexpr(2): + cq = accs[h * 2 + hf] + for j in range_constexpr(NB): + v = Vec(cq[mfma.idx(ti, j)]) + d0 = _bf16x2(fx.Float32(v[0]) * w, fx.Float32(v[1]) * w) + d1 = _bf16x2(fx.Float32(v[2]) * w, fx.Float32(v[3]) * w) + chunk = fx.Int32(hf * 8 + j * 2) + g4 // 2 + _lds_store_vec(_v2i32(d0, d1), _stg_addr(r16, chunk, g4 % 2), 2) + + def _flush(nt, h, ti): + """The staged rows -> full token-major 128-B lines, non-temporal.""" + col_wave = (_n_glob(nt) * fx.Int32(BN) + wave_j * (N_TILES_B * 16)) * 2 + hf_l = (lane_id // 8) % 2 + ch_l = lane_id % 8 + _asm_void([], "s_waitcnt lgkmcnt(0)", "") + for k in range_constexpr(N_FLUSH): + row = fx.Int32(4 * k) + lane_id // 16 + data = _lds_load_vec(_stg_addr(row, hf_l * 8 + ch_l, 0), 4) + buffer_ops.buffer_store( + data, + out_rsrc, + flush_off[(h * NA + ti) * N_FLUSH + k] + + col_wave + + hf_l * fx.Int32(LDS_BLOCK_N * 2) + + ch_l * fx.Int32(16), + offset_is_bytes=True, + cache_modifier=_STORE_CPOL, + ) + + def _epilogue(nt, accs): + for h in range_constexpr(2): + for ti in range_constexpr(NA): + _stage(accs, h, ti) + _flush(nt, h, ti) + + abufs0 = (a_cur0, a_cur1, a_next0, a_next1) + n_a = 2 * NA + n_b = 2 * NB + n_sc = 2 * (NA // 2) + 2 * (NB // 2) + _R = fx.as_ir_value + + def _flat_sc(sc): + return [_R(v) for part in sc for v in part] + + def _unflat_sc(flat): + sizes = (NA // 2, NA // 2, NB // 2, NB // 2) + out, o = [], 0 + for n in sizes: + out.append(list(flat[o : o + n])) + o += n + return tuple(out) + + init_state = ( + _flat_frag(a0_frag) + + _flat_frag(b0_frag) + + _flat_frag(b1_frag) + + _flat_sc(sc0) + ) + # FlyDSL rewrites range(init=...) to a loop carrying state. + for nt_idx, state in range( # type: ignore[call-overload] + 0, NT, 1, init=init_state + ): + nt = fx.Int32(nt_idx) + off = 0 + a0f = _unflat_frag(state[off : off + n_a], NA) + off += n_a + b0f = _unflat_frag(state[off : off + n_b], NB) + off += n_b + b1f = _unflat_frag(state[off : off + n_b], NB) + off += n_b + sc = _unflat_sc(state[off : off + n_sc]) + accs = ( + [None] * N_ACCUMS, + [None] * N_ACCUMS, + [None] * N_ACCUMS, + [None] * N_ACCUMS, + ) + abufs = abufs0 + # Switch the scale base before the first next-tile gather. + _set_scale_tile(nt) + for kc in range_constexpr(K_ITERS): + if const_expr(kc == K_ITERS - 4): + _set_scale_tile(nt + fx.Int32(1)) + a0f, b0f, b1f, sc, accs, abufs = _one_step( + nt, kc, a0f, b0f, b1f, sc, accs, abufs + ) + _epilogue(nt, accs) + state = ( + yield _flat_frag(a0f) + + _flat_frag(b0f) + + _flat_frag(b1f) + + _flat_sc(sc) + ) + # the redundant loads after the last tile must land before the LDS is reused + wait_barrier(0) + + @flyc.jit + def launch_gemm2( + A: fx.Tensor, + W2: fx.Tensor, + OUT: fx.Tensor, + A_scale: fx.Tensor, + W2_scale: fx.Tensor, + sorted_ids: fx.Tensor, + sorted_expert_ids: fx.Tensor, + sorted_weights: fx.Tensor, + num_valid_ids: fx.Tensor, + n_tokens: fx.Int32, + num_m_blocks: fx.Int32, + grid_size: fx.Int32, + stream: fx.Stream, + ): + kernel_gemm2( + A, + W2, + OUT, + A_scale, + W2_scale, + sorted_ids, + sorted_expert_ids, + sorted_weights, + num_valid_ids, + n_tokens, + num_m_blocks, + grid_size, + value_attrs={ + "rocdl.waves_per_eu": 1, + "rocdl.flat_work_group_size": "256,256", + }, + ).launch(grid=(grid_size, 1, 1), block=(256, 1, 1), stream=stream) + + return launch_gemm2 + + +def gemm2_grid(num_m_blocks: int, n_split: int) -> int: + """Every (m-tile, chunk), rounded up to the 8 XCDs; padded tiles exit early.""" + return (num_m_blocks * n_split + _NUM_XCDS - 1) // _NUM_XCDS * _NUM_XCDS diff --git a/vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm2_prefill_bm256.py b/vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm2_prefill_bm256.py new file mode 100644 index 000000000000..289584059196 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm2_prefill_bm256.py @@ -0,0 +1,697 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""``gemm2_prefill`` on 256-row m-tiles (each wave 128 x 128, 256 AGPR accumulators): +W2 streams once per 256 sorted rows. W2 and A run two K-steps ahead (2 LDS stages) to +fit 160 KB of LDS. Same partials as the 128-row kernel. + +Layouts (bytes): + A [num_m_blocks*BM, I] sorted rows, fp8 (gemm1 OUT_Q) + A_scale [pad32(num_m_blocks*BM), I/32] sorted rows, e8m0-shuffled (gemm1 OUT_sc) + W2 [E, H, I] aiter shuffle_weight (16 x 64 K blocks) + W2_sc [E*H/32, I/256, 4, 16] dwords aiter shuffle_scale + sorted_w [num_m_blocks*BM] f32 routing weight per sorted row + OUT [n_tokens*topk, H] bf16 +""" + +import flydsl.compiler as flyc +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import buffer_ops +from flydsl._mlir.dialects import llvm as _llvm +from flydsl.expr import const_expr, range_constexpr +from flydsl.expr.typing import Vector as Vec + +from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.epilogue import ( + _NUM_XCDS, + _STORE_CPOL, + _bf16x2, + _lds_load_vec, + _lds_store_vec, + _v2i32, +) +from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.loaders import ( + _N_WAVES, + _SCALE_A_REGION, + _SCALE_B_REGION, + _SCALE_SLOT_BYTES, + G2SLoaderAsm, + S2RLoader128B, + ScaleGatherMoE, + ScaleLoaderLDS, + _asm_void, + _Buf, + _divmod_nonneg, + _flat_frag, + _g2s_thunks, + _riffle, + _s2r_thunks, + _swizzled_col, + _unflat_frag, + wait_barrier, +) + +from .gemm1_prefill import BLOCK_K, Mfma16x16x128Fp8 + +_SCALE_SLOTS2 = 4 + + +def compile_moe_gemm2_bm256( + *, + H: int, + I: int, # noqa: E741 + E: int, + topk: int, + n_split: int = 2, + sort_block_m: int = 128, +): + """``compile_moe_gemm2`` on 256-row tiles; ``sort_block_m`` must be 256.""" + BM = 256 + BN = 256 + K = I + K_BYTES = K + BLOCK_K_BYTES = BLOCK_K + EID_SHIFT = (sort_block_m // BM).bit_length() - 1 + assert sort_block_m in (BM, 2 * BM) + N_TILES_ALL = H // BN + assert H % BN == 0 and N_TILES_ALL % n_split == 0 + NT = N_TILES_ALL // n_split # n-tiles per CTA + K_ITERS = K // BLOCK_K + assert K_ITERS in (6, 12, 24) and K % 256 == 0 + SCALE_BLOCKS = K_ITERS // 2 + LDS_BLOCK_M = BM // 2 + LDS_BLOCK_N = BN // 2 + N_TILES_A = LDS_BLOCK_M // 2 // 16 + N_TILES_B = LDS_BLOCK_N // 2 // 16 + N_ACCUMS = N_TILES_A * N_TILES_B + NB = N_TILES_B + NA = N_TILES_A + OUT_ROW_BYTES = H * 2 + W2_BYTES = H * K + assert W2_BYTES <= 0xFFFFFFFF + B_TILE_BYTES = BN * K_BYTES + + B_STAGES = 2 + a_lds_size = LDS_BLOCK_M * BLOCK_K_BYTES + b_lds_size = LDS_BLOCK_N * BLOCK_K_BYTES + A_BUFS = 4 * a_lds_size # 2 stages x 2 halves + LDS_TILES_BYTES = A_BUFS + 2 * B_STAGES * b_lds_size + SCALE_LDS_BYTES2 = _SCALE_SLOTS2 * _SCALE_SLOT_BYTES + # wave-private epilogue staging: 16 rows x the wave's 128 bf16 cols + STG_ROW = 2 * N_TILES_B * 16 * 2 # the wave's two 128-B line segments + STG_CH = STG_ROW // 16 + STG_ROWS = 16 # one (row half, a-tile) at a time + STG_WAVE = STG_ROWS * STG_ROW + STG_LDS_BYTES = _N_WAVES * STG_WAVE + N_FLUSH = (STG_ROWS * 2) // 8 # dwordx4 stores per lane per staged block + assert LDS_TILES_BYTES + SCALE_LDS_BYTES2 + STG_LDS_BYTES <= 160 * 1024 + + A_WAVE_GROUPS = N_TILES_A // 2 + A_HALF_GROUPS = LDS_BLOCK_M // 32 + B_WAVE_GROUPS = 2 # 32-row groups per wave (64 W2 rows) + B_HALF_GROUPS = LDS_BLOCK_N // 32 + SC_COLS = K // 32 + W2_SC_BYTES = E * H * SC_COLS + + @fx.struct + class SharedStorage: + all_lds: fx.Array[fx.Int8, LDS_TILES_BYTES, 16] + scale_lds: fx.Array[fx.Int8, SCALE_LDS_BYTES2, 16] + stage_lds: fx.Array[fx.Int8, STG_LDS_BYTES, 16] + + @flyc.kernel + def kernel_gemm2_bm256( + A: fx.Tensor, + W2: fx.Tensor, + OUT: fx.Tensor, + A_scale: fx.Tensor, + W2_scale: fx.Tensor, + sorted_ids: fx.Tensor, + sorted_expert_ids: fx.Tensor, + sorted_weights: fx.Tensor, + num_valid_ids: fx.Tensor, + n_tokens: fx.Int32, + num_m_blocks: fx.Int32, + grid_size: fx.Int32, + ): + lds = fx.SharedAllocator().allocate(SharedStorage).peek() + _base_ptr = lds.all_lds.ptr + _scale_base_ptr = lds.scale_lds.ptr + _stg_ptr = lds.stage_lds.ptr + + a_cur0 = _Buf(_base_ptr, 0 * a_lds_size) + a_cur1 = _Buf(_base_ptr, 1 * a_lds_size) + a_next0 = _Buf(_base_ptr, 2 * a_lds_size) + a_next1 = _Buf(_base_ptr, 3 * a_lds_size) + # B: 2 stages x 2 halves + b_st = [ + [_Buf(_base_ptr, A_BUFS + (2 * st + hf) * b_lds_size) for hf in range(2)] + for st in range(B_STAGES) + ] + + lane_id = fx.thread_idx.x % 64 + wave_id = fx.thread_idx.x // 64 + wave_i = wave_id // 2 + wave_j = wave_id % 2 + g4 = lane_id // 16 + r16 = lane_id % 16 + + # work item (m-tile, n-chunk); consecutive m-tiles share an XCD + nv_rsrc = buffer_ops.create_buffer_resource( + num_valid_ids, max_size=False, num_records_bytes=4 + ) + num_valid = fx.Int32( + buffer_ops.buffer_load( + nv_rsrc, fx.Int32(0), vec_width=1, dtype=fx.Int32, is_scalar=True + ) + ) + n_work = (num_valid // fx.Int32(BM)) * fx.Int32(n_split) + per_xcd = (n_work + fx.Int32(_NUM_XCDS - 1)) // fx.Int32(_NUM_XCDS) + intra, xcd = _divmod_nonneg(fx.block_idx.x, _NUM_XCDS) + work = xcd * per_xcd + intra + block_valid = (intra < per_xcd) & (work < n_work) + work_safe = block_valid.select(work, fx.Int32(0)) + tile_i, chunk = _divmod_nonneg(work_safe, n_split) + m_base = tile_i * BM + eid_rsrc = buffer_ops.create_buffer_resource( + sorted_expert_ids, max_size=False, num_records_bytes=num_m_blocks * 4 + ) + expert = fx.Int32( + buffer_ops.buffer_load( + eid_rsrc, + tile_i >> EID_SHIFT, + vec_width=1, + dtype=fx.Int32, + is_scalar=True, + ) + ) + ids_rsrc = buffer_ops.create_buffer_resource( + sorted_ids, max_size=False, num_records_bytes=num_m_blocks * (BM * 4) + ) + if const_expr(EID_SHIFT > 0): + # a 256-sort pads each expert: a 128-row tile starting with padding is empty + first_sid = fx.Int32( + buffer_ops.buffer_load( + ids_rsrc, m_base, vec_width=1, dtype=fx.Int32, is_scalar=True + ) + ) + block_valid = block_valid & ((first_sid & fx.Int32(0x00FFFFFF)) < n_tokens) + chunk_n0 = chunk * NT + # rotate the n-tile sweep inside same-expert runs: neighbours find W2 in L2 + ROT_STRIDE, ROT_GATE = 2, 3 + _d = fx.Int32(ROT_GATE) + _lo_ok = tile_i >= _d + _hi_ok = tile_i + _d < num_m_blocks + _e_lo = fx.Int32( + buffer_ops.buffer_load( + eid_rsrc, + _lo_ok.select(tile_i - _d, fx.Int32(0)) >> EID_SHIFT, + vec_width=1, + dtype=fx.Int32, + is_scalar=True, + ) + ) + _e_hi = fx.Int32( + buffer_ops.buffer_load( + eid_rsrc, + _hi_ok.select(tile_i + _d, fx.Int32(0)) >> EID_SHIFT, + vec_width=1, + dtype=fx.Int32, + is_scalar=True, + ) + ) + rot_on = (_lo_ok & (_e_lo == expert)) | (_hi_ok & (_e_hi == expert)) + nt_rot = rot_on.select( + _divmod_nonneg(tile_i * fx.Int32(ROT_STRIDE), NT)[1], fx.Int32(0) + ) + + def _pn(nt): + """Sweep-order n-tile -> n-tile of the chunk.""" + x = nt + nt_rot + return (x >= fx.Int32(NT)).select(x - fx.Int32(NT), x) + + def _n_glob(nt): + """Global n-tile of sweep-order ``nt``, clamped to the last one.""" + ntc = (nt >= fx.Int32(NT)).select(fx.Int32(NT - 1), nt) + return chunk_n0 + _pn(ntc) + + if block_valid: + sw_rsrc = buffer_ops.create_buffer_resource( + sorted_weights, + max_size=False, + num_records_bytes=num_m_blocks * (BM * 4), + ) + a_rsrc = buffer_ops.create_buffer_resource( + A, max_size=False, num_records_bytes=num_m_blocks * (BM * K_BYTES) + ) + b_rsrc = buffer_ops.create_buffer_resource( + W2, + max_size=False, + num_records_bytes=W2_BYTES, + base_byte_offset=fx.Int64(expert) * W2_BYTES, + ) + # padded rows (tok == n_tokens) fall outside the resource + out_rows = n_tokens * fx.Int32(topk) + out_rsrc = buffer_ops.create_buffer_resource( + OUT, max_size=False, num_records_bytes=out_rows * OUT_ROW_BYTES + ) + + def _a_offsets(half): + offs = [] + for rnd in range_constexpr(N_TILES_A): + row = lane_id // 8 + wave_id * 8 + rnd * (_N_WAVES * 8) + col = (lane_id % 8) * 16 + grow = m_base + half * LDS_BLOCK_M + row + offs.append(grow * fx.Int32(K_BYTES) + _swizzled_col(row, col)) + return offs + + # rounds and halves move whole 32-row groups (same swizzle): one per-lane + # base plus soffset strides + gl_off_a = _a_offsets(0)[:1] + A_RND_BYTES = _N_WAVES * 8 * K_BYTES + A_HALF_BYTES = LDS_BLOCK_M * K_BYTES + + # W2 offsets inside an n-tile; the n-tile goes in soffset + e_row0 = expert * fx.Int32(H) + + def _b_offsets(hf): + offs = [] + for rnd in range_constexpr(N_TILES_B): + row = lane_id % 8 + wave_id * 8 + rnd * (_N_WAVES * 8) + col = (lane_id // 8) * 16 + wrow = fx.Int32(hf * LDS_BLOCK_N + row) + offs.append( + (wrow // fx.Int32(16)) * fx.Int32(K_BYTES * 16) + + fx.Int32( + (row % 16) * 16 + + (col // 64) * 1024 + + ((col % 64) // 16) * 256 + + (col % 16) + ) + ) + return offs + + gl_off_b = _b_offsets(0)[:1] + B_RND_BYTES = (_N_WAVES * 8 // 16) * K_BYTES * 16 + B_HALF_BYTES = (LDS_BLOCK_N // 16) * K_BYTES * 16 + A_K_STEP = BLOCK_K_BYTES + B_K_STEP = 2 * 1024 + + mfma = Mfma16x16x128Fp8(N_TILES_A, N_TILES_B) + sb_index = lambda j, hf: (j // 2, j % 2) # noqa: E731 (32-row groups) + + scale_gather = ScaleGatherMoE( + A_scale, + W2_scale, + K, + lane_id, + wave_id, + _scale_base_ptr, + num_m_blocks * (BM * SC_COLS), + W2_SC_BYTES, + A_WAVE_GROUPS, + A_HALF_GROUPS, + B_WAVE_GROUPS, + B_HALF_GROUPS, + ) + + def _set_scale_tile(nt): + scale_gather.set_wave_base(m_base, e_row0 + _n_glob(nt) * fx.Int32(BN)) + + a_scale_ld = ScaleLoaderLDS( + N_TILES_A, lane_id, wave_i, _scale_base_ptr, _SCALE_A_REGION + ) + b_scale_ld = ScaleLoaderLDS( + N_TILES_B, lane_id, wave_j, _scale_base_ptr, _SCALE_B_REGION + ) + + def _slot(nt, g): + return (fx.Int32(nt) * fx.Int32(SCALE_BLOCKS) + fx.Int32(g)) % fx.Int32( + _SCALE_SLOTS2 + ) + + a0_g2s = G2SLoaderAsm(a_rsrc, gl_off_a, N_TILES_A, wave_id, A_RND_BYTES) + a1_g2s = G2SLoaderAsm( + a_rsrc, gl_off_a, N_TILES_A, wave_id, A_RND_BYTES, A_HALF_BYTES + ) + b0_g2s = G2SLoaderAsm(b_rsrc, gl_off_b, N_TILES_B, wave_id, B_RND_BYTES) + b1_g2s = G2SLoaderAsm( + b_rsrc, gl_off_b, N_TILES_B, wave_id, B_RND_BYTES, B_HALF_BYTES + ) + for ld in (a0_g2s, a1_g2s, b0_g2s, b1_g2s): + ld.set_wave_base(_base_ptr) + a_s2r = S2RLoader128B(wave_i, N_TILES_A) + b_s2r = S2RLoader128B(wave_j, N_TILES_B) + + def _orow(sid): + tok = sid & fx.Int32(0x00FFFFFF) # padded: tok == n_tokens -> OOB + slot = (sid >> 24) & fx.Int32(0xFF) + return tok * fx.Int32(topk) + slot + + # routing weights of the lane's rows; output offsets of the rows it + # flushes (store k: staged row 8 (k % 2) + lane // 8, segment k // 2) + wave_row0 = m_base + wave_i * (N_TILES_A * 16) + row_w = [] + for h in range_constexpr(2): + for ti in range_constexpr(N_TILES_A): + row = wave_row0 + fx.Int32(h * LDS_BLOCK_M + ti * 16) + r16 + row_w.append( + fx.Float32( + buffer_ops.buffer_load( + sw_rsrc, row, vec_width=1, dtype=fx.Float32 + ) + ) + ) + flush_off = [] + for h in range_constexpr(2): + for ti in range_constexpr(NA): + for k in range_constexpr(2): + row = ( + wave_row0 + + fx.Int32(h * LDS_BLOCK_M + ti * 16 + 8 * k) + + lane_id // 8 + ) + sid = fx.Int32( + buffer_ops.buffer_load( + ids_rsrc, row, vec_width=1, dtype=fx.Int32 + ) + ) + flush_off.append(_orow(sid) * fx.Int32(OUT_ROW_BYTES)) + stg_base = fx.Int32(fx.ptrtoint(_stg_ptr)) + wave_id * fx.Int32(STG_WAVE) + + def _stg_addr(row, chunk, half): + """Staged (row, 16-B chunk, 8-B half), chunks XOR-swizzled by row; + inline asm keeps it at the use instead of in hoisted VGPRs.""" + base = stg_base + row * fx.Int32(STG_ROW) + fx.Int32(half * 8) + x = fx.Int32( + _llvm.inline_asm( + fx.Int32.ir_type, + [fx.as_ir_value(fx.Int32(chunk)), fx.as_ir_value(row % STG_CH)], + "v_xor_b32 $0, $1, $2", + "=v,v,v", + has_side_effects=True, + ) + ) + return fx.Int32( + _llvm.inline_asm( + fx.Int32.ir_type, + [fx.as_ir_value(x), fx.as_ir_value(base)], + "v_lshl_add_u32 $0, $1, 4, $2", + "=v,v,v", + has_side_effects=True, + ) + ) + + # prologue = steps -2, -1 of the steady-state issue order + _set_scale_tile(fx.Int32(0)) + scale_gather.gather(0, _slot(0, 0)) + b_soff0 = _n_glob(fx.Int32(0)) * fx.Int32(B_TILE_BYTES) + b0_g2s.load(b_st[0][0], b_soff0 + fx.Int32(0 * B_K_STEP)) + b1_g2s.load(b_st[0][1], b_soff0 + fx.Int32(0 * B_K_STEP)) + a0_g2s.load(a_cur0, fx.Int32(0 * A_K_STEP)) + a1_g2s.load(a_cur1, fx.Int32(0 * A_K_STEP)) + b0_g2s.load(b_st[1][0], b_soff0 + fx.Int32(1 * B_K_STEP)) + b1_g2s.load(b_st[1][1], b_soff0 + fx.Int32(1 * B_K_STEP)) + a0_g2s.load(a_next0, fx.Int32(1 * A_K_STEP)) + scale_gather.gather(1, _slot(0, 1)) + a1_g2s.load(a_next1, fx.Int32(1 * A_K_STEP)) + + # gather 0, B(0) and a0(0) landed: a1(0), B(1), a0(1), gather, a1(1) may fly + wait_barrier(NA + 2 * NB + NA + 1 + NA) + a0_frag = a_s2r.load(a_cur0) + b0_frag = b_s2r.load(b_st[0][0], preshuffled=True) + b1_frag = b_s2r.load(b_st[0][1], preshuffled=True) + sc0_saR0, sc0_saR1 = a_scale_ld.read(_slot(0, 0)) + sc0_sbC0, sc0_sbC1 = b_scale_ld.read(_slot(0, 0)) + sc0 = (sc0_saR0, sc0_saR1, sc0_sbC0, sc0_sbC1) + + # Step kc issues B(kc + 2), a0(kc + 2), [MID] the scale gather (odd kc), + # a1(kc + 2). Top wait: a1(kc) landed; MID wait: a0(kc + 1) landed. The + # counts leave out the epilogue stores: they retire out of order. + def _top_vmcnt(kc): + return 2 * NB + 2 * NA + (1 - kc % 2) + + def _mid_vmcnt(kc): + return NA + 2 * NB + NA + (1 - kc % 2) + + def _read_scale_thunks(nt, kc_next, holder): + # the next flat step's scales; Python ints only (an ``if`` here would + # become an scf.if) + s = _slot(nt + fx.Int32(kc_next // K_ITERS), (kc_next % K_ITERS) // 2) + + def _r(dst, ld, half, _s=s): + holder[dst] = ld.read_half(_s, half) + + return [ + lambda: _r(0, a_scale_ld, 0), + lambda: _r(1, a_scale_ld, 1), + lambda: _r(2, b_scale_ld, 0), + lambda: _r(3, b_scale_ld, 1), + ] + + def _one_step(nt, kc, a0f, b0f, b1f_in, sc, accs, abufs): + """``nt`` is the n-tile; ``kc`` is a constexpr K-step within it.""" + k2 = kc % 2 + ac0, ac1, an0, an1 = abufs + bst = b_st[kc % B_STAGES] # read now, refilled for step kc + 2 + bnx = b_st[(kc + 1) % B_STAGES] + saR0, saR1, sbC0, sbC1 = sc + c00f, c01f, c10f, c11f = accs + zero_acc = kc == 0 + + _a1 = [None] * NA + _a0n = [None] * NA + _b0n = [None] * NB + _b1n = [None] * NB + # A and B for flat step kc + 2 (B possibly in tile nt + 1) + ka = (kc + 2) % K_ITERS + kb = (kc + B_STAGES) % K_ITERS + nt_b = nt + fx.Int32((kc + B_STAGES) // K_ITERS) + a_off = fx.Int32(ka * A_K_STEP) + b_off = _n_glob(nt_b) * fx.Int32(B_TILE_BYTES) + fx.Int32(kb * B_K_STEP) + + _scn = [None, None, None, None] + _rd_scn = _read_scale_thunks(nt, kc + 1, _scn) + # Gather scales three steps ahead, crossing n-tiles as needed. + future_block = (kc + 3) // 2 + _g_blk = future_block % SCALE_BLOCKS + _g_slot = _slot(nt + fx.Int32(future_block // SCALE_BLOCKS), _g_blk) + _sc_gather = [lambda: scale_gather.gather(_g_blk, _g_slot)] * k2 + + wait_barrier(_top_vmcnt(kc)) + il = ( + _riffle( + _g2s_thunks(b0_g2s, bst[0], b_off, NB), + _s2r_thunks(a_s2r, ac1, _a1, NA, False), + ) + + _rd_scn[:2] + ) + c00f = mfma.call( + a0f, + b0f, + c00f, + saR0, + sbC0, + 0, + k2, + interleave=il, + zero_acc=zero_acc, + sb_index=sb_index, + ) + # never riffle two G2S loaders: each one's steps share m0, so + # interleaving them corrupts the LDS destinations + il = ( + _g2s_thunks(b1_g2s, bst[1], b_off, NB) + + _g2s_thunks(a0_g2s, ac0, a_off, NA) + + _rd_scn[2:] + ) + c01f = mfma.call( + a0f, + b1f_in, + c01f, + saR0, + sbC1, + 1, + k2, + interleave=il, + zero_acc=zero_acc, + sb_index=sb_index, + ) + a1f = _a1 + + wait_barrier(_mid_vmcnt(kc)) + il = _s2r_thunks(a_s2r, an0, _a0n, NA, False) + _sc_gather + c10f = mfma.call( + a1f, + b0f, + c10f, + saR1, + sbC0, + 0, + k2, + interleave=il, + zero_acc=zero_acc, + sb_index=sb_index, + ) + a0nf = _a0n + il = _riffle( + _g2s_thunks(a1_g2s, ac1, a_off, NA), + _s2r_thunks(b_s2r, bnx[0], _b0n, NB, True) + + _s2r_thunks(b_s2r, bnx[1], _b1n, NB, True), + ) + c11f = mfma.call( + a1f, + b1f_in, + c11f, + saR1, + sbC1, + 1, + k2, + interleave=il, + zero_acc=zero_acc, + sb_index=sb_index, + ) + sc_next = (_scn[0], _scn[1], _scn[2], _scn[3]) + return ( + a0nf, + _b0n, + _b1n, + sc_next, + (c00f, c01f, c10f, c11f), + (an0, an1, ac0, ac1), + ) + + def _stage(accs, h, ti): + """Routing-weighted bf16 of rows (``h``, ``ti``) into the staging + buffer; a wave's LDS ops run in order, after the last flush's reads.""" + w = row_w[h * NA + ti] + for hf in range_constexpr(2): + cq = accs[h * 2 + hf] + for j in range_constexpr(NB): + v = Vec(cq[mfma.idx(ti, j)]) + d0 = _bf16x2(fx.Float32(v[0]) * w, fx.Float32(v[1]) * w) + d1 = _bf16x2(fx.Float32(v[2]) * w, fx.Float32(v[3]) * w) + chunk = fx.Int32(hf * 8 + j * 2) + g4 // 2 + _lds_store_vec(_v2i32(d0, d1), _stg_addr(r16, chunk, g4 % 2), 2) + + def _flush(nt, h, ti): + """The staged rows -> full token-major 128-B lines, non-temporal.""" + col_wave = (_n_glob(nt) * fx.Int32(BN) + wave_j * (N_TILES_B * 16)) * 2 + ch_l = lane_id % 8 + _asm_void([], "s_waitcnt lgkmcnt(0)", "") + for k in range_constexpr(N_FLUSH): + hf = k // 2 + row = fx.Int32(8 * (k % 2)) + lane_id // 8 + data = _lds_load_vec(_stg_addr(row, hf * 8 + ch_l, 0), 4) + buffer_ops.buffer_store( + data, + out_rsrc, + flush_off[(h * NA + ti) * 2 + k % 2] + + col_wave + + fx.Int32(hf * LDS_BLOCK_N * 2) + + ch_l * fx.Int32(16), + offset_is_bytes=True, + cache_modifier=_STORE_CPOL, + ) + + def _epilogue(nt, accs): + for h in range_constexpr(2): + for ti in range_constexpr(NA): + _stage(accs, h, ti) + _flush(nt, h, ti) + + abufs0 = (a_cur0, a_cur1, a_next0, a_next1) + n_a = 2 * NA + n_b = 2 * NB + n_sc = 2 * (NA // 2) + 2 * (NB // 2) + _R = fx.as_ir_value + + def _flat_sc(sc): + return [_R(v) for part in sc for v in part] + + def _unflat_sc(flat): + sizes = (NA // 2, NA // 2, NB // 2, NB // 2) + out, o = [], 0 + for n in sizes: + out.append(list(flat[o : o + n])) + o += n + return tuple(out) + + init_state = ( + _flat_frag(a0_frag) + + _flat_frag(b0_frag) + + _flat_frag(b1_frag) + + _flat_sc(sc0) + ) + # FlyDSL rewrites range(init=...) to a loop carrying state. + for nt_idx, state in range( # type: ignore[call-overload] + 0, NT, 1, init=init_state + ): + nt = fx.Int32(nt_idx) + off = 0 + a0f = _unflat_frag(state[off : off + n_a], NA) + off += n_a + b0f = _unflat_frag(state[off : off + n_b], NB) + off += n_b + b1f = _unflat_frag(state[off : off + n_b], NB) + off += n_b + sc = _unflat_sc(state[off : off + n_sc]) + accs = ( + [None] * N_ACCUMS, + [None] * N_ACCUMS, + [None] * N_ACCUMS, + [None] * N_ACCUMS, + ) + abufs = abufs0 + # Switch the scale base before the first next-tile gather. + _set_scale_tile(nt) + for kc in range_constexpr(K_ITERS): + if const_expr(kc == K_ITERS - 4): + _set_scale_tile(nt + fx.Int32(1)) + a0f, b0f, b1f, sc, accs, abufs = _one_step( + nt, kc, a0f, b0f, b1f, sc, accs, abufs + ) + _epilogue(nt, accs) + state = ( + yield _flat_frag(a0f) + + _flat_frag(b0f) + + _flat_frag(b1f) + + _flat_sc(sc) + ) + # the redundant loads after the last tile must land before the LDS is reused + wait_barrier(0) + + @flyc.jit + def launch_gemm2_bm256( + A: fx.Tensor, + W2: fx.Tensor, + OUT: fx.Tensor, + A_scale: fx.Tensor, + W2_scale: fx.Tensor, + sorted_ids: fx.Tensor, + sorted_expert_ids: fx.Tensor, + sorted_weights: fx.Tensor, + num_valid_ids: fx.Tensor, + n_tokens: fx.Int32, + num_m_blocks: fx.Int32, + grid_size: fx.Int32, + stream: fx.Stream, + ): + kernel_gemm2_bm256( + A, + W2, + OUT, + A_scale, + W2_scale, + sorted_ids, + sorted_expert_ids, + sorted_weights, + num_valid_ids, + n_tokens, + num_m_blocks, + grid_size, + value_attrs={ + "rocdl.waves_per_eu": 1, + "rocdl.flat_work_group_size": "256,256", + }, + ).launch(grid=(grid_size, 1, 1), block=(256, 1, 1), stream=stream) + + return launch_gemm2_bm256 diff --git a/vllm/models/minimax_m3/amd/ops/moe_mxfp8/prefill.py b/vllm/models/minimax_m3/amd/ops/moe_mxfp8/prefill.py new file mode 100644 index 000000000000..19a4931b658f --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/moe_mxfp8/prefill.py @@ -0,0 +1,228 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""FlyDSL MXFP8 MoE prefill chain on AITER's MXFP8 weights: sort, gemm1 (gate/up + +SwiGLU-OAI + MXFP8 quant), gemm2 (routing-weighted partials), fixed-order reduce.""" + +import functools + +import torch + +from vllm.models.minimax_m3.amd.ops.flydsl_utils import run_compiled +from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.launch import ( + _get_reduce_bf16, + _get_sort, + _get_tile_map, + _u8_flat, +) + +MIN_PREFILL_TOKENS = 3072 +MAX_PREFILL_TOKENS = 65536 +BM256_FROM_TOKENS = 16384 + +GEMM1_SWIGLU_ALPHA = 1.702 +GEMM1_SWIGLU_LIMIT = 7.0 +# CTAs sharing one m-block's n-tiles in gemm2 +GEMM2_N_SPLIT = 6 +GEMM2_N_SPLIT_LARGE = 4 +GEMM2_N_SPLIT_LARGE_FROM_TOKENS = 32768 +GEMM2_BM256_MIN_INTERMEDIATE = 768 +GEMM2_BM256_FROM_TOKENS = 16384 + +_GEMM1_BLOCK_K = 128 +_GEMM2_INTERMEDIATES = (768, 1536, 3072) + + +def block_m_for( + n_tokens: int, hidden_size: int, intermediate_size: int, num_experts: int, topk: int +) -> int: + if (hidden_size, intermediate_size, num_experts, topk) == (6144, 3072, 128, 4): + threshold = 8192 + elif (hidden_size, intermediate_size) == (6144, 768): + threshold = 4096 + else: + threshold = BM256_FROM_TOKENS + return 256 if n_tokens >= threshold else 128 + + +def gemm2_n_split_for(n_tokens: int) -> int: + if n_tokens >= GEMM2_N_SPLIT_LARGE_FROM_TOKENS: + return GEMM2_N_SPLIT_LARGE + return GEMM2_N_SPLIT + + +def gemm2_block_m_for(sort_block_m: int, n_tokens: int, intermediate_size: int) -> int: + if ( + sort_block_m == 256 + and intermediate_size >= GEMM2_BM256_MIN_INTERMEDIATE + and n_tokens >= GEMM2_BM256_FROM_TOKENS + ): + return 256 + return 128 + + +def supports_shapes(hidden_size: int, intermediate_size: int) -> bool: + """gemm1 peels 4 K-steps of 128 and unrolls the rest by 4.""" + k_iters = hidden_size // _GEMM1_BLOCK_K + return ( + hidden_size % 256 == 0 + and k_iters >= 8 + and (k_iters - 4) % 4 == 0 + and intermediate_size in _GEMM2_INTERMEDIATES + ) + + +@functools.cache +def _get_gemm1(hidden_size: int, intermediate_size: int, num_experts: int, bm: int): + from .gemm1_prefill import compile_moe_gemm1 + + return compile_moe_gemm1( + H=hidden_size, I=intermediate_size, E=num_experts, BLOCK_M=bm + ) + + +@functools.cache +def _get_gemm2( + hidden_size: int, + intermediate_size: int, + num_experts: int, + topk: int, + bm: int, + n_split: int, + gemm2_bm: int, +): + if gemm2_bm == 256: + from .gemm2_prefill_bm256 import compile_moe_gemm2_bm256 as compile_moe_gemm2 + else: + from .gemm2_prefill import compile_moe_gemm2 + + return compile_moe_gemm2( + H=hidden_size, + I=intermediate_size, + E=num_experts, + topk=topk, + n_split=n_split, + sort_block_m=bm, + ) + + +def a8w8_prefill_moe( + x_quant: tuple[torch.Tensor, torch.Tensor], + w13: torch.Tensor, + w13_scale: torch.Tensor, + w2: torch.Tensor, + w2_scale: torch.Tensor, + topk_weights: torch.Tensor, + topk_ids: torch.Tensor, + *, + hidden_size: int, + intermediate_size: int, + num_experts: int, + out: torch.Tensor | None = None, +) -> torch.Tensor: + """``x_quant`` = (fp8 ``[M, H]``, e8m0 ``[M, H/32]``) -> ``[M, H]`` bf16, on + ``AiterMxfp8Experts``' weights.""" + from aiter import dtypes + from aiter.ops.quant import mxfp4_moe_sort_hip + + from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.sort import SortBuffers + from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.tile_map import ( + tile_map_grid, + ) + + from .gemm2_prefill import gemm2_grid + + a_q, x_s = x_quant + n_tokens, hidden = a_q.shape + assert MIN_PREFILL_TOKENS <= n_tokens <= MAX_PREFILL_TOKENS, n_tokens + assert hidden == hidden_size and a_q.is_contiguous() and x_s.is_contiguous() + assert x_s.shape == (n_tokens, hidden // 32), x_s.shape + inter = intermediate_size + topk = topk_ids.shape[1] + topk_ids = topk_ids.to(torch.int32).contiguous() + topk_weights = topk_weights.to(torch.float32).contiguous() + device = topk_ids.device + stream = torch.cuda.current_stream() + bm = block_m_for(n_tokens, hidden_size, inter, num_experts, topk) + + bufs = SortBuffers.allocate(n_tokens, num_experts, topk, bm, device) + _get_sort(num_experts, topk, bm)( + *bufs.launch_args(topk_ids, topk_weights, n_tokens) + ) + a_s = torch.empty( + ((bufs.sorted_ids.shape[0] + 31) // 32 * 32, (hidden // 32 + 7) // 8 * 8), + dtype=dtypes.fp8_e8m0, + device=device, + ) + mxfp4_moe_sort_hip( + a_s, + x_s.view(dtypes.fp8_e8m0), + bufs.sorted_ids, + bufs.num_valid_ids, + n_tokens, + hidden, + ) + num_m_blocks = bufs.max_sorted // bm + rows = num_m_blocks * bm + grid1 = tile_map_grid(num_m_blocks, inter) + tile_map = torch.empty((grid1 + 1,), dtype=torch.int32, device=device) + run_compiled( + _get_tile_map(inter, bm), + bufs.sorted_expert_ids, + bufs.num_valid_ids, + tile_map, + grid1, + stream, + ) + h_q = torch.empty((rows, inter), dtype=torch.uint8, device=device) + h_s = torch.empty((rows * (inter // 32),), dtype=torch.uint8, device=device) + run_compiled( + _get_gemm1(hidden_size, inter, num_experts, bm), + _u8_flat(a_q), + w13.view(torch.int64).view(-1), + h_q.view(-1), + _u8_flat(a_s), + _u8_flat(w13_scale), + h_s, + bufs.sorted_ids, + bufs.sorted_expert_ids, + n_tokens, + num_m_blocks, + int(a_s.numel() * a_s.element_size()), + tile_map, + grid1, + stream, + ) + + if out is None: + out = torch.empty((n_tokens, hidden_size), dtype=torch.bfloat16, device=device) + gemm2_out = torch.empty( + (n_tokens * topk, hidden_size), dtype=torch.bfloat16, device=device + ) + n_split = gemm2_n_split_for(n_tokens) + gemm2_bm = gemm2_block_m_for(bm, n_tokens, inter) + num_m_blocks2 = rows // gemm2_bm + # 4 GB of partials at 65536 tokens: a byte view would exceed 2^31 elements + run_compiled( + _get_gemm2(hidden_size, inter, num_experts, topk, bm, n_split, gemm2_bm), + h_q.view(-1), + w2.view(torch.int64).view(-1), + gemm2_out.view(-1), + h_s, + _u8_flat(w2_scale), + bufs.sorted_ids, + bufs.sorted_expert_ids, + bufs.sorted_weights, + bufs.num_valid_ids, + n_tokens, + num_m_blocks2, + gemm2_grid(num_m_blocks2, n_split), + stream, + ) + run_compiled( + _get_reduce_bf16(hidden_size, topk), + gemm2_out.view(-1), + out.view(-1), + n_tokens, + stream, + ) + return out diff --git a/vllm/models/minimax_m3/amd/ops/norm_rope_nvfp4_insert/__init__.py b/vllm/models/minimax_m3/amd/ops/norm_rope_nvfp4_insert/__init__.py new file mode 100644 index 000000000000..208f01a7cb5e --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/norm_rope_nvfp4_insert/__init__.py @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project diff --git a/vllm/models/minimax_m3/amd/ops/norm_rope_nvfp4_insert/host.py b/vllm/models/minimax_m3/amd/ops/norm_rope_nvfp4_insert/host.py new file mode 100644 index 000000000000..d6590ee458a4 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/norm_rope_nvfp4_insert/host.py @@ -0,0 +1,91 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Launch wrapper of the fused norm / RoPE / NVFP4 insert.""" + +import functools +import struct + +import torch + +from vllm.models.minimax_m3.amd.ops.flydsl_utils import ( + run_compiled, +) + +from . import kernel as _kernel + + +@functools.cache +def _get_kernel(nq: int, nkv: int, niq: int, rotary_dim: int, tp: int): + return _kernel.compile_norm_rope_insert(nq, nkv, niq, rotary_dim, tp) + + +def _token_pairs_per_wave(n: int) -> int: + return 1 if n <= 512 else 4 + + +def minimax_m3_norm_rope_nvfp4_insert( + qkv: torch.Tensor, # [n, (nq + 2 nkv + niq + 1) * 128] bf16 + q_norm_weight: torch.Tensor, + k_norm_weight: torch.Tensor, + index_q_norm_weight: torch.Tensor, + index_k_norm_weight: torch.Tensor, + cos_sin_cache: torch.Tensor, # [max_pos, rotary_dim] bf16 + positions: torch.Tensor, # [n] int64 + slot_mapping: torch.Tensor, # [n] int64, -1 skips the token + index_slot_mapping: torch.Tensor, # [n] int64, -1 skips the token + kv_cache: torch.Tensor, # [blocks, 2 nkv, 128, 72] uint8 + index_cache: torch.Tensor, # [blocks, 128, 72] uint8 + k_scale: torch.Tensor, # fp32 global scales + v_scale: torch.Tensor, + q_out: torch.Tensor, # [n, nq * 128] bf16 + index_q_out: torch.Tensor, # [n, niq * 128] e4m3, row stride free + num_heads: int, + num_kv_heads: int, + num_index_heads: int, + eps: float, +) -> None: + """Norm + RoPE of q / k / index-q / index-k and the NVFP4 K/V and index-K + inserts in one launch; k and index-k are not written back into ``qkv``.""" + n = qkv.shape[0] + if n == 0: + return + nq, nkv, niq = num_heads, num_kv_heads, num_index_heads + rotary_dim = cos_sin_cache.shape[1] + assert eps >= 2.0**-126 # the kernel's rsqrt skips ocml's denormal scaling + assert qkv.dtype == torch.bfloat16 and qkv.is_contiguous() + assert qkv.shape[1] == (nq + 2 * nkv + niq + 1) * _kernel.D + assert cos_sin_cache.dtype == torch.bfloat16 and cos_sin_cache.is_contiguous() + for w in (q_norm_weight, k_norm_weight, index_q_norm_weight, index_k_norm_weight): + assert w.dtype == torch.bfloat16 and w.is_contiguous() + assert q_out.dtype == torch.bfloat16 and q_out.is_contiguous() + assert index_q_out.dtype == torch.float8_e4m3fn and index_q_out.stride(1) == 1 + assert index_q_out.stride(0) % 4 == 0 + assert kv_cache.shape[1:] == (2 * nkv, _kernel.BLK, 72) + assert kv_cache.stride(1) == _kernel.BLK * 72 and kv_cache.stride(3) == 1 + assert index_cache.shape[1:] == (_kernel.BLK, 72) and index_cache.stride(2) == 1 + assert index_cache.stride(1) == 72 + run_compiled( + _get_kernel(nq, nkv, niq, rotary_dim, _token_pairs_per_wave(n)), + qkv.data_ptr(), + q_out.data_ptr(), + index_q_out.data_ptr(), + q_norm_weight.data_ptr(), + k_norm_weight.data_ptr(), + index_q_norm_weight.data_ptr(), + index_k_norm_weight.data_ptr(), + cos_sin_cache.data_ptr(), + positions.data_ptr(), + slot_mapping.data_ptr(), + index_slot_mapping.data_ptr(), + kv_cache.data_ptr(), + index_cache.data_ptr(), + k_scale.data_ptr(), + v_scale.data_ptr(), + n, + index_q_out.stride(0), + kv_cache.stride(0), + index_cache.stride(0), + cos_sin_cache.shape[0], + struct.unpack(" 4 fp32.""" + cos, sin = css_t + e = _bf16x4(xws_t) + ss = e[0] * e[0] + e[1] * e[1] + ss = ss + e[2] * e[2] + ss = ss + e[3] * e[3] + for m in (16, 8, 4, 2, 1): + ss = _xsum(ss, m) + r = _rsq(fx.math.fma(ss, fx.Float32(0.0078125), eps)) + nrm = [(e[i] * r) * (fx.Float32(1.0) + w[i]) for i in range_constexpr(4)] + out = [] + for i in range_constexpr(4): + pr = _xor_lane(bits(nrm[i]), half4, hi16).bitcast(fx.Float32) + ps = pr * sin[i] + roped = fx.math.fma(nrm[i], cos[i], first.select(-ps, ps)) + out.append(in_rope.select(roped, nrm[i])) + return out + + +def _maxnum(a, b): + return fx.Float32(_arith.MaxNumFOp(fx.as_ir_value(a), fx.as_ir_value(b)).result) + + +def _minnum(a, b): + return fx.Float32(_arith.MinNumFOp(fx.as_ir_value(a), fx.as_ir_value(b)).result) + + +def _dpp(src, ctrl, old=None, bank_mask=0xF): + """v_mov_b32_dpp; an undef ``old`` lets the move fold into its consumer.""" + o = _llvm.mlir_undef(T.i32) if old is None else fx.as_ir_value(old) + full = old is None and bank_mask == 0xF + return fx.Int32( + fx.rocdl.update_dpp(T.i32, o, fx.as_ir_value(src), ctrl, 0xF, bank_mask, full) + ) + + +def _swap16(v): + """permlane16_swap(v, v): (own, lane ^ 16) in rows 0 / 2, swapped in 1 / 3.""" + return permlane_swap(fx.rocdl.permlane16_swap, v, v) + + +def _xor_lane(v, m, hi16): + """Lane l ^ m of the 32-lane half; ``hi16`` is this lane's bit 4.""" + if m == 1: + return _dpp(v, 0xB1) # quad_perm [1, 0, 3, 2] + if m == 2: + return _dpp(v, 0x4E) # quad_perm [2, 3, 0, 1] + if m == 4: # row_shr:4 into banks 1, 3, then row_shl:4 into banks 0, 2 + return _dpp(v, 0x104, old=_dpp(v, 0x114, bank_mask=0xA), bank_mask=0x5) + if m == 8: + return _dpp(v, 0x128) # row_ror:8 + assert m == 16 + a, b = _swap16(v) + return hi16.select(a, b) + + +def _xsum(x, m): + """Adds lane l ^ m's value to ``x``.""" + if m == 16: + a, b = _swap16(bits(x)) + return a.bitcast(fx.Float32) + b.bitcast(fx.Float32) + return x + _xor_lane(bits(x), m, None).bitcast(fx.Float32) + + +def _xmax(x, m): + return _maxnum(x, _xor_lane(bits(x), m, None).bitcast(fx.Float32)) + + +def _rsq(x): + """v_rsq_f32; ocml's denormal scaling never applies as x >= eps >= 2^-126.""" + return fx.Float32(fx.rocdl.rsq(T.f32, fx.as_ir_value(x))) + + +def _e4m3_byte(x): + """RNE e4m3 byte of ``x``.""" + pk = fx.rocdl.cvt_scalef32_pk_fp8_f32( + T.vec(2, T.i16), + fx.as_ir_value(Vec.filled(2, 0, fx.Int16)), + fx.as_ir_value(x), + fx.as_ir_value(x), + fx.as_ir_value(fx.Float32(1.0)), + False, + ) + return Vec(pk).bitcast(fx.Int32)[0] & 0xFF + + +def _e4m3_value(byte): + pk = fx.rocdl.cvt_scalef32_pk_f32_fp8( + T.vec(2, T.f32), + fx.as_ir_value(fx.Int32(byte)), + fx.as_ir_value(fx.Float32(1.0)), + False, + ) + return fx.Float32(Vec(pk)[0]) + + +def _iq_fp8(a, b, old, hi): + """Two fp32 -> e4m3 bytes in the low (``hi``: high) half of ``old``.""" + return fx.Int32( + fx.rocdl.cvt_pk_fp8_f32( + T.i32, + fx.as_ir_value(fx.Float32(a)), + fx.as_ir_value(fx.Float32(b)), + fx.as_ir_value(fx.Int32(old)), + hi, + ) + ) + + +def _e2m1x2(a, b, old, sel): + """E2M1 codes of ``a``, ``b`` into byte ``sel`` of ``old``, ``a`` low.""" + return fx.Int32( + fx.rocdl.cvt_scalef32_pk_fp4_f32( + T.i32, + fx.as_ir_value(fx.Int32(old)), + fx.as_ir_value(a), + fx.as_ir_value(b), + fx.as_ir_value(fx.Float32(1.0)), + sel, + ) + ) + + +def _quant4(xs, gs, inv_gs): + """E2M1 codes of this lane's 4 values (16 bits) and the e4m3 scale byte of + their 16-value group (lanes l ^ 0..3).""" + a = [fx.math.absf(x) for x in xs] + m = _maxnum(_maxnum(a[0], a[1]), _maxnum(a[2], a[3])) + m = _xmax(_xmax(m, 1), 2) + sf = _minnum((m * as_f32(RCP6)) * inv_gs, as_f32(F448)) + byte = _e4m3_byte(sf) + sv = _e4m3_value(byte) + quant = (sv != 0.0).select(fx.Float32(1.0) / (gs * sv), fx.Float32(0.0)) + y = [x * quant for x in xs] + return _e2m1x2(y[2], y[3], _e2m1x2(y[0], y[1], fx.Int32(0), 0), 1), byte + + +def _v_row(state, row, r, n_run, p0, vs, inv_vs): + """Adds row ``r`` of a V run at octet positions p0.. to ``state``: new + nibbles and scale bytes, with their masks.""" + words, written = state[0:4], state[4] + sc, sc_mask = state[5:7], state[7:9] + nib, sf = _quant4(_bf16x4(row), vs, inv_vs) + in_run = n_run > r + p = p0 + r + sh = p * 4 + words = [ + wd | in_run.select(((nib >> (4 * i)) & 15) << sh, fx.Int32(0)) + for i, wd in enumerate(words) + ] + written = written | in_run.select(fx.Int32(15) << sh, fx.Int32(0)) + bsh = (p % 4) * 8 + for k in range_constexpr(2): + here = in_run & ((p // 4) == k) + sc[k] = sc[k] | here.select(sf << bsh, fx.Int32(0)) + sc_mask[k] = sc_mask[k] | here.select(fx.Int32(255) << bsh, fx.Int32(0)) + return [*words, written, *sc, *sc_mask] + + +def _gptr(addr, ty, align): + return fx.inttoptr( + fx.PointerType.get(ty, address_space=fx.AddressSpace.Global, alignment=align), + fx.Int64(addr), + ) + + +def _k_scale_off(tok, grp): + """Byte of (token, group) in a head's K scale region.""" + r = tok % 32 + n = (r // 8) * 4 + r % 4 + return ((((tok // 32) * 4 + grp // 2) * 16 + n) * 2 + (r % 8) // 4) * 2 + grp % 2 + + +def compile_norm_rope_insert(nq: int, nkv: int, niq: int, rotary_dim: int, tp: int): + """Build the kernel; ``tp`` token pairs per norm / RoPE wave, one per V wave.""" + assert rotary_dim in (8, 16, 32, 64, 128) + NR = nq + nkv + 1 + niq # norm + RoPE waves + S = NR + nkv * tp # waves per 2 * tp tokens + ROW = (nq + 2 * nkv + niq + 1) * D + HALF = rotary_dim // 2 + SIDE = nkv * BLK * 72 # bytes of one side of a main page + TPW = 2 * tp + name = f"m3_norm_rope_nvfp4_insert_q{nq}_kv{nkv}_iq{niq}_r{rotary_dim}_t{tp}" + + @flyc.kernel(name=name, known_block_size=[64 * NW, 1, 1]) + def kernel( + i32_n: fx.Int32, + i32_cs_rows: fx.Int32, + arg_qkv: fx.Int64, # [n, ROW] bf16 + arg_pos: fx.Int64, # positions [n] i64 + arg_slot: fx.Int64, # main slots [n] i64, -1 skips + arg_islot: fx.Int64, # index slots [n] i64, -1 skips + arg_cs: fx.Int64, # cos_sin_cache [i32_cs_rows, rotary_dim] bf16 + arg_qw: fx.Int64, # norm weights [128] bf16: q, k, index-q, index-k + arg_kw: fx.Int64, + arg_iqw: fx.Int64, + arg_ikw: fx.Int64, + arg_q: fx.Int64, # q_out [n, nq * 128] bf16 + arg_iq: fx.Int64, # index_q_out [n, niq * 128] e4m3, row stride i32_iq_st + arg_kv: fx.Int64, # [blocks, 2 * nkv, 128, 72] u8 + arg_idx: fx.Int64, # [blocks, 128, 72] u8 + arg_ks: fx.Int64, # fp32 global scales + arg_vs: fx.Int64, + i64_kv_st: fx.Int64, + i64_idx_st: fx.Int64, + i32_iq_st: fx.Int32, + i32_eps: fx.Int32, # fp32 bits + ): + tx, bx = fx.thread_idx.x, fx.block_idx.x + lane = tx % 64 + wave = fx.Int32(fx.rocdl.readfirstlane(T.i32, tx // 64)) + wid = bx * NW + wave + s = wid % S + hl = lane % 32 + hi16 = (hl & 16) != 0 + dim0 = hl * 4 + toks = [(wid // S) * TPW + t * 2 + lane // 32 for t in range_constexpr(tp)] + lives = [tk < i32_n for tk in toks] + + qkv = buffer_ops.create_buffer_resource_from_addr( + arg_qkv, num_records_bytes=fx.Int64(i32_n) * (ROW * 2) + ) + sl_r = buffer_ops.create_buffer_resource_from_addr( + arg_slot, num_records_bytes=fx.Int64(i32_n) * 8 + ) + + if s < NR: + is_q = s < nq + is_k = (s >= nq) & (s < nq + nkv) + is_ik = s == nq + nkv + is_kq = is_k | is_ik + # This wave's head column in the qkv row. + col = (s <= nq + nkv).select( + is_ik.select(fx.Int32(nq + 2 * nkv + niq), s), + s - (nq + nkv + 1) + (nq + 2 * nkv), + ) + w_addr = is_q.select( + arg_qw, is_k.select(arg_kw, is_ik.select(arg_ikw, arg_iqw)) + ) + wr = buffer_ops.create_buffer_resource_from_addr( + w_addr, num_records_bytes=D * 2 + ) + pos_r = buffer_ops.create_buffer_resource_from_addr( + arg_pos, num_records_bytes=fx.Int64(i32_n) * 8 + ) + isl_r = buffer_ops.create_buffer_resource_from_addr( + arg_islot, num_records_bytes=fx.Int64(i32_n) * 8 + ) + cs_r = buffer_ops.create_buffer_resource_from_addr( + arg_cs, num_records_bytes=fx.Int64(i32_cs_rows) * (rotary_dim * 2) + ) + xws, poss, slots = [], [], [] + for t in range_constexpr(tp): + xws.append( + Vec( + buffer_ops.buffer_load( + qkv, + toks[t] * (ROW // 2) + col * (D // 2) + hl * 2, + vec_width=2, + dtype=fx.Int32, + mask=lives[t], + ) + ) + ) + poss.append( + fx.Int32( + buffer_ops.buffer_load( + pos_r, + toks[t] * 2, + vec_width=1, + dtype=fx.Int32, + mask=lives[t], + ) + ) + ) + kslot = fx.Int32( + buffer_ops.buffer_load( + sl_r, + toks[t] * 2, + vec_width=1, + dtype=fx.Int32, + mask=lives[t] & is_k, + ) + ) + islot = fx.Int32( + buffer_ops.buffer_load( + isl_r, + toks[t] * 2, + vec_width=1, + dtype=fx.Int32, + mask=lives[t] & is_ik, + ) + ) + slots.append(is_k.select(kslot, islot)) + w = _bf16x4( + Vec(buffer_ops.buffer_load(wr, hl * 2, vec_width=2, dtype=fx.Int32)) + ) + first = dim0 < HALF + in_rope = dim0 < rotary_dim + ib = first.select(dim0, dim0 - HALF) + css = [] + for t in range_constexpr(tp): + cs_off = (poss[t] * rotary_dim + ib) // 2 + css.append( + ( + _bf16x4( + Vec( + buffer_ops.buffer_load( + cs_r, + cs_off, + vec_width=2, + dtype=fx.Int32, + mask=lives[t] & in_rope, + ) + ) + ), + _bf16x4( + Vec( + buffer_ops.buffer_load( + cs_r, + cs_off + HALF // 2, + vec_width=2, + dtype=fx.Int32, + mask=lives[t] & in_rope, + ) + ) + ), + ) + ) + eps = i32_eps.bitcast(fx.Float32) + qvs = [] + for t in range_constexpr(tp): + out = _norm_rope_out4( + xws[t], css[t], w, eps, hi16, first, in_rope, HALF // 4 + ) + lo, hi = pk_bf16(out[0], out[1]), pk_bf16(out[2], out[3]) + qvs.append(Vec.from_elements([lo, hi], fx.Int32)) + if is_q: + q_r = buffer_ops.create_buffer_resource_from_addr( + arg_q, num_records_bytes=fx.Int64(i32_n) * (nq * D * 2) + ) + for t in range_constexpr(tp): + buffer_ops.buffer_store( + qvs[t], + q_r, + toks[t] * (nq * D // 2) + s * (D // 2) + hl * 2, + mask=lives[t], + ) + if s > nq + nkv: + iq_r = buffer_ops.create_buffer_resource_from_addr( + arg_iq, num_records_bytes=fx.Int64(i32_n) * fx.Int64(i32_iq_st) + ) + iq_col = (s - (nq + nkv + 1)) * D + for t in range_constexpr(tp): + f = [ + _minnum(_maxnum(x, as_f32(F448N)), as_f32(F448)) + for x in _bf16x4(qvs[t]) + ] + word = _iq_fp8( + f[2], f[3], _iq_fp8(f[0], f[1], fx.Int32(0), False), True + ) + buffer_ops.buffer_store( + word, + iq_r, + toks[t] * i32_iq_st + iq_col + dim0, + mask=lives[t], + offset_is_bytes=True, + ) + if is_kq: + gs = is_k.select( + fx.Float32(_gptr(arg_ks, T.f32, 4)[0]), fx.Float32(1.0) + ) + inv_gs = fx.Float32(1.0) / gs + quants = [ + _quant4(_bf16x4(qvs[t]), gs, inv_gs) for t in range_constexpr(tp) + ] + h = s - nq + grp = hl // 4 + for t in range_constexpr(tp): + slot = slots[t] + tp_ = slot & (BLK - 1) + page = is_k.select( + arg_kv + fx.Int64(slot >> 7) * i64_kv_st, + arg_idx + fx.Int64(slot >> 7) * i64_idx_st, + ) + d_off = is_k.select(h * (BLK * 64), fx.Int32(0)) + tp_ * 64 + hl * 2 + s_off = is_k.select( + nkv * BLK * 64 + h * (BLK * 8) + _k_scale_off(tp_, grp), + BLK * 64 + tp_ * 8 + grp, + ) + d_ptr = _gptr(page + fx.Int64(d_off), T.i16, 2) + s_ptr = _gptr(page + fx.Int64(s_off), T.i8, 1) + packed = quants[t][0].to(fx.Int16) + sf8 = quants[t][1].to(fx.Int8) + if lives[t] & (slot >= 0): + d_ptr[0] = packed + if hl % 4 == 0: + s_ptr[0] = sf8 + else: + vh = (s - NR) // tp + tok = (wid // S) * TPW + ((s - NR) % tp) * 2 + lane // 32 + live = tok < i32_n + vcol = (nq + nkv + vh) * (D // 2) # V head column (dwords) + vs = fx.Float32(_gptr(arg_vs, T.f32, 4)[0]) + near_t = tok - 7 + hl + has_near = (hl < 16) & (near_t >= 0) & (near_t < i32_n) + near = has_near.select( + fx.Int32( + buffer_ops.buffer_load( + sl_r, near_t * 2, vec_width=1, dtype=fx.Int32, mask=has_near + ) + ), + fx.Int32(-1), + ) + slot = fx.Int32( + buffer_ops.buffer_load( + sl_r, tok * 2, vec_width=1, dtype=fx.Int32, mask=live + ) + ) + has_prev = live & (tok > 0) + prev = has_prev.select( + fx.Int32( + buffer_ops.buffer_load( + sl_r, tok * 2 - 2, vec_width=1, dtype=fx.Int32, mask=has_prev + ) + ), + fx.Int32(-1), + ) + # The first token of a run in one 8-token octet writes the run and + # keeps the octet's other nibbles and scales. Rows it can cover load + # before its slot is known. + rows = [ + Vec( + buffer_ops.buffer_load( + qkv, + (tok + r) * (ROW // 2) + vcol + hl * 2, + vec_width=2, + dtype=fx.Int32, + mask=tok + r < i32_n, + ) + ) + for r in range_constexpr(8) + ] + base = slot - slot % 8 + in_oct = (near >= base) & (near < base + 8) + votes = fx.Int64(fx.rocdl.ballot(T.i64, in_oct)) + mine = (votes >> fx.Int64((lane // 32) * 32)).to(fx.Int32) & 0xFFFF + n_run = fx.Int32(fx.math.ctpop(mine)) + run_first = (prev < 0) | ((prev >> 3) != (slot >> 3)) + tp_ = slot & (BLK - 1) + v_side = arg_kv + fx.Int64(slot >> 7) * i64_kv_st + SIDE + v_data = v_side + fx.Int64(vh * (BLK * 64) + (tp_ // 8) * (D * 4)) + v_sf = v_side + fx.Int64(nkv * BLK * 64 + vh * (BLK * 8) + tp_ - tp_ % 8) + dp = _gptr(v_data + fx.Int64(dim0 * 4), T.i32, 4) + sp = _gptr(v_sf + fx.Int64((hl // 4) * BLK), T.i32, 4) + go = live & (slot >= 0) & run_first + inv_vs = fx.Float32(1.0) / vs + # Runs of <= 4 tokens (decode) take the short tile. + for run_rows, take in ( + (rows[:4], go & (n_run <= 4)), + (rows, go & (n_run > 4)), + ): + if take: + old = [fx.Int32(dp[i]) for i in range_constexpr(4)] + old_sc = [fx.Int32(sp[i]) for i in range_constexpr(2)] + st = [fx.Int32(0)] * 9 + for r in range_constexpr(len(run_rows)): + st = _v_row(st, run_rows[r], r, n_run, tp_ % 8, vs, inv_vs) + keep = ~st[4] + for i in range_constexpr(4): + dp[i] = st[i] | (old[i] & keep) + sc0 = st[5] | (old_sc[0] & ~st[7]) + sc1 = st[6] | (old_sc[1] & ~st[8]) + if hl % 4 == 0: + sp[0] = sc0 + sp[1] = sc1 + + @flyc.jit + def launch( + arg_qkv: fx.Int64, + arg_q: fx.Int64, + arg_iq: fx.Int64, + arg_qw: fx.Int64, + arg_kw: fx.Int64, + arg_iqw: fx.Int64, + arg_ikw: fx.Int64, + arg_cs: fx.Int64, + arg_pos: fx.Int64, + arg_slot: fx.Int64, + arg_islot: fx.Int64, + arg_kv: fx.Int64, + arg_idx: fx.Int64, + arg_ks: fx.Int64, + arg_vs: fx.Int64, + i32_n: fx.Int32, + i32_iq_st: fx.Int32, + i64_kv_st: fx.Int64, + i64_idx_st: fx.Int64, + i32_cs_rows: fx.Int32, + i32_eps: fx.Int32, + stream: fx.Stream, + ): + waves = (i32_n + (TPW - 1)) // TPW * S + kernel( + i32_n, + i32_cs_rows, + arg_qkv, + arg_pos, + arg_slot, + arg_islot, + arg_cs, + arg_qw, + arg_kw, + arg_iqw, + arg_ikw, + arg_q, + arg_iq, + arg_kv, + arg_idx, + arg_ks, + arg_vs, + i64_kv_st, + i64_idx_st, + i32_iq_st, + i32_eps, + ).launch( + grid=(fx.Int64((waves + (NW - 1)) // NW), 1, 1), + block=(64 * NW, 1, 1), + stream=stream, + ) + + launch.kernel_name = name + launch.compile_hints = PRELOAD_HINTS + return launch diff --git a/vllm/models/minimax_m3/amd/ops/nvfp4_index_decode/__init__.py b/vllm/models/minimax_m3/amd/ops/nvfp4_index_decode/__init__.py new file mode 100644 index 000000000000..208f01a7cb5e --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/nvfp4_index_decode/__init__.py @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project diff --git a/vllm/models/minimax_m3/amd/ops/nvfp4_index_decode/host.py b/vllm/models/minimax_m3/amd/ops/nvfp4_index_decode/host.py new file mode 100644 index 000000000000..37e260514bb0 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/nvfp4_index_decode/host.py @@ -0,0 +1,222 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Launch wrappers of the FlyDSL NVFP4 decode index scorers.""" + +import functools + +import torch + +from vllm.models.minimax_m3.amd.ops.flydsl_utils import run_compiled +from vllm.models.minimax_m3.amd.ops.nvfp4_index_prefill.host import nvfp4_e4m3_lut +from vllm.utils.math_utils import cdiv + +from . import kernel as _kernel + +# 158 VGPRs = 3 waves per SIMD; more waves add a second round of workgroups. +TARGET_WAVES = 3072 +# Scores are buffered in LDS and stored by whole rows once the batch's score +# footprint reaches this; smaller footprints store directly. +BUFFER_MIN_BYTES = 8 << 20 +UNITS_PER_SLOT = 4 + + +def _end_bytes(t: torch.Tensor) -> int: + """Bytes from the data pointer to the end of the last element.""" + return ( + sum((n - 1) * s for n, s in zip(t.shape, t.stride())) + 1 + ) * t.element_size() + + +def _unit(max_blocks: int, slots: int, umax: int, footprint: int) -> int: + """Consecutive blocks per buffered unit (a power of two, 4..umax) giving + every wave slot >= UNITS_PER_SLOT units, or 0 for direct stores.""" + if footprint < BUFFER_MIN_BYTES: + return 0 + u = umax + while u > 4 and cdiv(max_blocks, u) < UNITS_PER_SLOT * slots: + u //= 2 + return u if cdiv(max_blocks, u) >= UNITS_PER_SLOT * slots else 0 + + +@functools.cache +def _get_kernel(rows: int, heads: int, buffered: bool): + return _kernel.compile_score_decode(rows, heads, buffered) + + +def _supported( + q_idx: torch.Tensor, + index_cache: torch.Tensor, + score: torch.Tensor, + block_table: torch.Tensor, + seq_lens: torch.Tensor, + query_len: int, +) -> bool: + from vllm.platforms.rocm import on_gfx950 + + num_heads = q_idx.shape[1] + return ( + on_gfx950() + and num_heads in (1, 2, 4) + and 1 <= num_heads * query_len <= _kernel.MAX_ROWS + and q_idx.dtype == torch.float8_e4m3fn + and q_idx.shape[2] == _kernel.D + and q_idx.stride(2) == 1 + and q_idx.stride(0) % 16 == 0 + and q_idx.stride(1) % 16 == 0 + and q_idx.data_ptr() % 16 == 0 + and index_cache.dtype == torch.uint8 + and index_cache.stride(2) == 1 + and index_cache.stride(1) == _kernel.D // 2 + _kernel.D // 16 + and index_cache.stride(0) % 16 == 0 + and index_cache.data_ptr() % 16 == 0 + and score.dtype == torch.float32 + and score.stride(2) == 1 + and block_table.dtype == torch.int32 + and block_table.stride(1) == 1 + and seq_lens.dtype == torch.int32 + and seq_lens.is_contiguous() + ) + + +def minimax_m3_nvfp4_index_score_decode( + q_idx: torch.Tensor, # [num_reqs * query_len, H, 128] e4m3 + index_cache: torch.Tensor, # [num_blocks, 128, 72] uint8 + score: torch.Tensor, # [H, num_reqs * query_len, >= max_blocks] fp32 + block_table: torch.Tensor, # [num_reqs, >= max_blocks] int32 + seq_lens: torch.Tensor, # [num_reqs] int32 + init_blocks: int, + local_blocks: int, + query_len: int, + max_seq_len: int, +) -> None: + """Block scores of every decode row for blocks below cdiv(seq_len, 128).""" + total_q, num_heads, _ = q_idx.shape + num_reqs = total_q // query_len + if num_reqs == 0: + return + assert _supported(q_idx, index_cache, score, block_table, seq_lens, query_len) + rows = num_heads * query_len + max_blocks = max(1, cdiv(max_seq_len, _kernel.BLK)) + # A chunk of NW x (pages per wave) requests; with at most one page per + # wave, chunks of one request and each wave on its own positions. + pages_per_wave = cdiv(num_reqs * max_blocks, TARGET_WAVES) + s_bytes = _end_bytes(score) + assert s_bytes < 2**31 * 4, "score offsets must fit in int32 elements" + footprint = num_reqs * rows * max_blocks * 4 + chunk = 1 if pages_per_wave <= 1 else _kernel.NW * pages_per_wave + chunk_cap = _kernel.chunk_max(_kernel.padded_rows(rows)) + chunk = max(1, min(chunk, chunk_cap, num_reqs)) + nch = cdiv(num_reqs, chunk) + chunk = cdiv(num_reqs, nch) + per_wave = chunk < _kernel.NW + wanted = max(1, TARGET_WAVES // (_kernel.NW * nch)) + # Past 16 rows the buffered variant's flush costs more than it saves. + unit = ( + _unit( + max_blocks, + wanted * (_kernel.NW if per_wave else 1), + _kernel.UMAX, + footprint, + ) + if _kernel.padded_rows(rows) <= 16 + else 0 + ) + units = cdiv(max_blocks, max(1, unit)) + positions = cdiv(units, _kernel.NW) if per_wave else units + splits = max(1, min(positions, wanted)) + run_compiled( + _get_kernel(rows, num_heads, unit > 0), + q_idx.data_ptr(), + index_cache.data_ptr(), + nvfp4_e4m3_lut(q_idx.device).data_ptr(), + score.data_ptr(), + block_table.data_ptr(), + seq_lens.data_ptr(), + int(index_cache.stride(0)), + int(q_idx.stride(0)), + int(q_idx.stride(1)), + _end_bytes(q_idx), + int(score.stride(0)), + int(score.stride(1)), + s_bytes, + int(block_table.stride(0)), + _end_bytes(block_table), + int(num_reqs), + int(chunk), + int(nch), + int(splits), + int(init_blocks), + int(local_blocks), + int(per_wave), + int(unit), + torch.cuda.current_stream(), + # Keep the buffered variant at the plain one's occupancy. + waves_per_eu=3 if unit > 0 and _kernel.padded_rows(rows) <= 16 else None, + ) + + +@functools.cache +def _get_kernel_cp_push(): + from . import kernel_cp_push + + return kernel_cp_push.compile_score_push() + + +def minimax_m3_nvfp4_index_score_push_cp( + iq: torch.Tensor, # this rank's index head [num_reqs * 4, 128] e4m3 + index_cache: torch.Tensor, # [num_blocks, 128, 72] uint8 + dests: list[int], # head h's scores [rows, row_stride] fp32 on rank h + row_stride: int, + dest_bytes: int, + block_table: torch.Tensor, # [num_reqs, >= max_blocks] int32 + seq_lens: torch.Tensor, # [num_reqs] int32 + init_blocks: int, + local_blocks: int, + rank: int, + counts: torch.Tensor, # index_cp's device counters + flags: list[int], # rank p's flag words + iq_bufs: list[int], # rank p's index-q receive buffer [4, iq_rows, 128] e4m3 + iq_rows: int, + grid: int = 0, +) -> None: + """This rank's share of all four heads' decode scores, pushed to the heads' + ranks; returns once every rank's scores have arrived.""" + from . import kernel_cp_push + + rows = iq.shape[0] + assert rows % 4 == 0 and rows <= iq_rows + assert iq.dtype == torch.float8_e4m3fn and iq.shape[1] == kernel_cp_push.D + assert iq.stride(1) == 1 and iq.stride(0) == kernel_cp_push.D + num_reqs = rows // 4 + assert num_reqs <= kernel_cp_push.MAX_REQS + if not grid: + small = num_reqs <= kernel_cp_push.GRID_SMALL_REQS + grid = kernel_cp_push.GRID_SMALL if small else kernel_cp_push.GRID + assert 0 < grid <= kernel_cp_push.SC_MAX_WG + if num_reqs == 0: + return + assert dest_bytes < 2**31 * 4, "score offsets must fit in int32 elements" + run_compiled( + _get_kernel_cp_push(), + iq.data_ptr(), + index_cache.data_ptr(), + nvfp4_e4m3_lut(iq.device).data_ptr(), + *dests, + block_table.data_ptr(), + seq_lens.data_ptr(), + counts.data_ptr(), + *flags, + *iq_bufs, + int(iq_rows), + int(index_cache.stride(0)), + int(row_stride), + int(dest_bytes), + int(block_table.stride(0)), + _end_bytes(block_table), + int(num_reqs), + int(init_blocks), + int(local_blocks), + int(rank), + int(grid), + torch.cuda.current_stream(), + ) diff --git a/vllm/models/minimax_m3/amd/ops/nvfp4_index_decode/kernel.py b/vllm/models/minimax_m3/amd/ops/nvfp4_index_decode/kernel.py new file mode 100644 index 000000000000..a80f10463a51 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/nvfp4_index_decode/kernel.py @@ -0,0 +1,564 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""NVFP4 decode index scorer for MiniMax-M3 (FlyDSL, gfx950). + +Per (head, query row, block): the max of q . k over the row's visible tokens, +with AITER's init / local sentinels, on e4m3_rn_satfinite(e2m1 x scale) keys. A +workgroup takes a chunk of up to 64 requests (lane r holds request r) and every +splits-th block position. The distinct pages at a position (a shared prefix page +is one page for the whole chunk) go round robin over the 4 waves; a wave +dequantizes its page into the A fragments of v_mfma_f32_16x16x128_f8f6f4, issuing +the next page's loads into the freed registers, and scores it against every +16-column group of Q rows holding the page. +""" + +import flydsl.compiler as flyc +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import buffer_ops +from flydsl.expr import const_expr, range_constexpr +from flydsl.expr.typing import T +from flydsl.expr.typing import Vector as Vec + +from vllm.models.minimax_m3.amd.ops.flydsl_utils import ( + NT, + as_f32, + bits, + dequant8, + global_i32_ptr, + key_order4, + maxf_nn, + mfma_fp8_16x16x128, + pack8, + xlane4, +) +from vllm.models.minimax_m3.amd.ops.nvfp4_index_prefill.kernel import with_sentinels + +NW = 4 +MAX_REQS = 64 # requests per chunk, one per lane +BLK = 128 # tokens per block +D = 128 # index head dim +PAGE_CODES = BLK * D // 2 # page: [128 x 64 B] e2m1 codes, [128 x 8 B] e4m3 scales +PAGE_BYTES = PAGE_CODES + BLK * 8 +MT = BLK // 16 # token tiles per page +UMAX = 8 # max consecutive blocks per LDS-buffered unit +MAX_ROWS = 32 # H * query_len + + +def padded_rows(rows: int) -> int: + """Columns a request takes in the 16-column groups: rows rounded up to a + power of two.""" + return 1 << (rows - 1).bit_length() + + +def chunk_max(rows: int) -> int: + """Requests per chunk: one per lane, and 256 Q rows (32 KB) in LDS.""" + return min(MAX_REQS, 256 // rows) + + +def block_sentinels(mx, visible, b, i32_init, i32_local): + """AITER's sentinels on block b of a row seeing ``visible`` tokens.""" + nb = ((visible < 0).select(fx.Int32(0), visible) + (BLK - 1)) // BLK + return with_sentinels(mx, b, nb, i32_init, i32_local) + + +def compile_score_decode(rows: int, heads: int, buffered: bool = False): + """Build the scorer. + + Args: + rows: H * query_len (1..32). + heads: index heads (1, 2 or 4). + buffered: gather a unit's scores in LDS and store whole rows (large + score footprints); otherwise store them directly. + + """ + assert 1 <= rows <= MAX_ROWS and heads in (1, 2, 4) and rows % heads == 0 + H = heads + QL = rows // H + R = padded_rows(rows) # a request's columns; column j = query row j // H + RPC = max(1, 16 // R) # requests per 16-column group + CPR = max(1, R // 16) # 16-column groups per request + GMASK = (1 << RPC) - 1 + QROWS = chunk_max(R) * R + QROW_BYTES = D + name = f"m3_nvfp4_index_score_decode_r{rows}h{H}" + ("_buf" if buffered else "") + SB_STRIDE = UMAX + 1 # padded against LDS bank conflicts + + @fx.struct + class Shared: + q: fx.Array[fx.Uint8, QROWS * QROW_BYTES, 16] + lut: fx.Array[fx.Int32, 512, 16] + seq: fx.Array[fx.Int32, MAX_REQS] + # The unit's scores as f32 bits, plus 64 dummy slots. + sbuf: fx.Array[fx.Int32, (QROWS * SB_STRIDE + 64) if buffered else 16, 16] + + @flyc.kernel(name=name, known_block_size=[64 * NW, 1, 1]) + def kernel( + arg_q: fx.Int64, # [num_reqs * QL, H, 128] e4m3 + arg_kv: fx.Int64, # [num_blocks, 128, 72] uint8 + arg_lut: fx.Int64, # nvfp4_e4m3_lut [256] int64 + arg_score: fx.Int64, # [H, num_reqs * QL, S] fp32 + arg_bt: fx.Int64, # [num_reqs, >= max_blocks] int32 + arg_seq: fx.Int64, # [num_reqs] int32 + i64_page_stride: fx.Int64, + i32_q_st: fx.Int32, # q strides (bytes) + i32_q_sh: fx.Int32, + i64_q_bytes: fx.Int64, + i32_s_sh: fx.Int32, # score strides (elements) + i32_s_st: fx.Int32, + i64_s_bytes: fx.Int64, + i32_bt_stride: fx.Int32, + i64_bt_bytes: fx.Int64, + i32_num_reqs: fx.Int32, + i32_chunk: fx.Int32, # requests per chunk + i32_nch: fx.Int32, + i32_splits: fx.Int32, # workgroups per chunk + i32_init: fx.Int32, + i32_local: fx.Int32, + i32_per_wave: fx.Int32, # 1: each wave walks its own positions + i32_unit: fx.Int32, # consecutive positions per unit, 0: none + ): + smem = fx.SharedAllocator().allocate(Shared).peek() + tx, pid = fx.thread_idx.x, fx.block_idx.x + lane = tx % 64 + wave = fx.Int32(fx.rocdl.readfirstlane(T.i32, tx // 64)) + col, kl = lane % 16, lane // 16 + ch = pid % i32_nch + split = pid // i32_nch + req0 = ch * i32_chunk + left = i32_num_reqs - req0 + nr = (left < i32_chunk).select(left, i32_chunk) + + # Lane r holds request req0 + r. + r_ok = lane < nr + seq_r = fx.Int32(global_i32_ptr(arg_seq)[r_ok.select(req0 + lane, fx.Int32(0))]) + seq_r = r_ok.select(seq_r, fx.Int32(0)) + nblk_r = (seq_r + (BLK - 1)) // BLK + first_row = seq_r - (QL - 1) + # Every row sees blocks before rbf_r whole: init / local ones there only + # need their sentinel. + rbf_r = ((first_row < 0).select(fx.Int32(0), first_row) + (BLK - 1)) // BLK + ll = nblk_r - i32_local + loc_last_r = (ll < 0).select(fx.Int32(0), ll) + fm_r = seq_r - QL # tokens past this are masked for some row + + btr = buffer_ops.create_buffer_resource_from_addr( + arg_bt, num_records_bytes=i64_bt_bytes + ) + sr = buffer_ops.create_buffer_resource_from_addr( + arg_score, num_records_bytes=i64_s_bytes + ) + qr = buffer_ops.create_buffer_resource_from_addr( + arg_q, num_records_bytes=i64_q_bytes + ) + + q16 = fx.logical_divide( + fx.make_view( + fx.recast_iter(fx.Int32, smem.q.ptr), + fx.make_layout(QROWS * QROW_BYTES // 4, 1), + ), + fx.make_layout(4, 1), + ) + atom16 = fx.make_copy_atom(fx.UniversalCopy128b(), fx.Int32) + seq_l = smem.seq.ptr + scb = smem.sbuf.ptr + per_wave = i32_per_wave != fx.Int32(0) + if const_expr(buffered): + direct = per_wave | (i32_unit == fx.Int32(0)) + to_lds = (i32_per_wave == fx.Int32(0)) & (i32_unit != fx.Int32(0)) + usz = (i32_unit == fx.Int32(0)).select(fx.Int32(1), i32_unit) + else: + direct = i32_unit >= fx.Int32(0) + to_lds = i32_unit < fx.Int32(0) + usz = fx.Int32(1) + + def prologue(): + """Q rows, the e4m3 table and the request lengths -> LDS. + + Row i = request i // R, column j = i % R (query row j // H, head + j % H); 16 B column c8 sits at c8 ^ (i & 7), in the key's dim order. + """ + for k in range_constexpr(QROWS * 8 // (64 * NW)): + u = tx + k * 64 * NW + i = u // 8 + c8 = u % 8 + rr = i // R + j = i % R + # Missing requests' and padding rows stay unwritten; their + # scores are never stored. + if (rr < nr) & (j // H < QL): + tq = (req0 + rr) * QL + j // H + off = (tq * i32_q_st + (j % H) * i32_q_sh + c8 * 16) // 4 + d = Vec( + buffer_ops.buffer_load( + qr, off, vec_width=4, dtype=fx.Int32, mask=rr < nr + ) + ) + d = [fx.Int32(d[e]) for e in range_constexpr(4)] + r = fx.make_rmem_tensor(fx.make_layout(4, 1), fx.Int32) + r.store(key_order4(d)) + fx.copy(atom16, r, fx.slice(q16, (None, i * 8 + (c8 ^ (i & 7))))) + lut_g = global_i32_ptr(arg_lut) + lut_l = smem.lut.ptr + for e in range_constexpr(2): + lut_l[tx * 2 + e] = fx.Int32(lut_g[tx * 2 + e]) + seq_l[lane] = seq_r + + prologue() + fx.gpu.barrier() + + lut8 = fx.logical_divide( + fx.make_view( + fx.recast_iter(fx.Int32, smem.lut.ptr), fx.make_layout(512, 1) + ), + fx.make_layout(2, 1), + ) + lut_atom = fx.make_copy_atom(fx.UniversalCopy64b(), fx.Int32) + + def lut_load(sbyte): + r = fx.make_rmem_tensor(fx.make_layout(2, 1), fx.Int32) + fx.copy(lut_atom, fx.slice(lut8, (None, sbyte)), r) + v = Vec(r.load()) + return fx.Int32(v[0]), fx.Int32(v[1]) + + def q_frag(cg): + """B operand of column group cg (dims 32 kl .. +31 of Q row cg * 16 + + col).""" + i = cg * 16 + col + halves = [] + for h in range_constexpr(2): + r = fx.make_rmem_tensor(fx.make_layout(4, 1), fx.Int32) + fx.copy( + atom16, fx.slice(q16, (None, i * 8 + ((2 * kl + h) ^ (i & 7)))), r + ) + halves.append(r.load()) + return pack8(halves[0], halves[1]) + + code_off = (col * 64 + kl * 16) // 4 # dwords + scale_off = col * 4 + kl # u16: groups 2 kl, 2 kl + 1 of token col + + def page_rsrc(page): + return buffer_ops.create_buffer_resource_from_addr( + arg_kv + fx.Int64(page) * i64_page_stride, num_records_bytes=PAGE_BYTES + ) + + def load_tile(kr, ok, t): + """Tile t of a page: this lane's 16 B of codes (token 16 t + col) and + its two group scales; no memory access when not ``ok``.""" + c = Vec( + buffer_ops.buffer_load( + kr, + code_off, + vec_width=4, + dtype=fx.Int32, + mask=ok, + soffset_bytes=t * 1024, + cache_modifier=NT, + ) + ) + sc = fx.Int32( + fx.Int16( + buffer_ops.buffer_load( + kr, + scale_off, + vec_width=1, + dtype=fx.Int16, + mask=ok, + soffset_bytes=PAGE_CODES + t * 128, + cache_modifier=NT, + ) + ).to(fx.Int32) + ) + return c, sc + + def dequant_tile(c, sc): + """The A fragment of a tile (e4m3 keys in the key's dim order).""" + t0 = lut_load(sc & 0xFF) + t1 = lut_load((sc >> 8) & 0xFF) + f = [] + for e in range_constexpr(4): + lo, hi = dequant8(fx.Int32(Vec(c)[e]), *(t0 if e < 2 else t1)) + f += [lo, hi] + return Vec.from_elements(f, fx.Int32) + + zero4 = fx.Vector.filled(4, 0.0, fx.Float32) + neg_inf = fx.Float32(float("-inf")) + + def frag_max(frags, qfs, masked, lims): + """Per column group: the max of its column's scores over the page. + + Tile t's results are reduced under tile t + 1's MFMAs. + """ + ng = len(qfs) + runs = [neg_inf] * ng + accs = [[None] * ng for _ in range(MT)] + + def reduce(t, runs): + out = [] + for g in range_constexpr(ng): + run = runs[g] + v = accs[t][g] + for e in range_constexpr(4): + x = v[e] + if const_expr(masked): + x = (lims[g] >= t * 16 + e).select(x, neg_inf) + run = maxf_nn(run, x) + out.append(run) + return out + + for t in range_constexpr(MT): + for g in range_constexpr(ng): + accs[t][g] = mfma_fp8_16x16x128(frags[t], qfs[g], zero4) + if const_expr(t >= 1): + runs = reduce(t - 1, runs) + runs = reduce(MT - 1, runs) + return [xlane4(r, maxf_nn) for r in runs] + + def row_value(mx, seq, q_off, b): + return block_sentinels(mx, seq - QL + q_off + 1, b, i32_init, i32_local) + + def put(i_row, jpos, v, cond, addr): + """Score v of Q row i_row at unit position jpos, to memory or to the + LDS buffer; lanes with nothing to buffer write a dummy slot.""" + if const_expr(not buffered): + buffer_ops.buffer_store(v, sr, addr, mask=cond) + else: + buffer_ops.buffer_store(v, sr, addr, mask=cond & direct) + idx = (cond & to_lds).select( + i_row * SB_STRIDE + jpos, QROWS * SB_STRIDE + lane + ) + (scb + idx).store(bits(v)) # `scb[idx] = v` would rebind scb + + def flush(ub): + """Store the unit at block ub: 4 consecutive blocks per thread and + pass.""" + NCH = UMAX // 4 + k = fx.Int32(0) + while k < fx.Int32(QROWS * NCH // (64 * NW)): + item = tx + k * (64 * NW) + i = item // NCH + c = item % NCH + rr = i // R + jc = i % R + qoff = jc // H + nb_c = (fx.Int32(seq_l[rr]) + (BLK - 1)) // BLK + b0c = ub + c * 4 + ok = (rr < nr) & (qoff < QL) & (c * 4 < i32_unit) + addr = (jc % H) * i32_s_sh + ((req0 + rr) * QL + qoff) * i32_s_st + b0c + for e in range_constexpr(4): + v = as_f32(fx.Int32(scb[i * SB_STRIDE + c * 4 + e])) + buffer_ops.buffer_store( + v, + sr, + addr + e, + mask=ok & (b0c + e < nb_c) & (c * 4 + e < i32_unit), + ) + k = k + 1 + + def score_cgs(frags, hm, masked_any, cgs, b, jpos): + """Scores of column groups cgs, masked where a request is at its last + blocks, with sentinels.""" + info = [] + for cg in cgs: + i = cg * 16 + col + crr = i // R + st_j = i % R + info.append((cg, crr, st_j // H, st_j % H)) + qfs = [q_frag(cg) for cg, _, _, _ in info] + seqs = [fx.Int32(seq_l[crr]) for _, crr, _, _ in info] + mxs = [neg_inf for _ in info] + if masked_any: + lims = [ + seq_c - QL + qoff - b * BLK - kl * 4 + for seq_c, (_, _, qoff, _) in zip(seqs, info) + ] + mxs = frag_max(frags, qfs, True, lims) + else: + mxs = frag_max(frags, qfs, False, None) + for mx, seq_c, (cg, crr, qoff, head) in zip(mxs, seqs, info): + hit = ((hm >> fx.Int64(crr)) & fx.Int64(1)) != fx.Int64(0) + ov = row_value(mx, seq_c, qoff, b) + otq = (req0 + crr) * QL + qoff + put( + cg * 16 + col, + jpos, + ov, + hit & (kl == 0) & (qoff < QL), + head * i32_s_sh + otq * i32_s_st + b, + ) + + def score_groups(frags, hm, mmask, b, jpos): + """Every column group holding the page (requests hm).""" + left_m = hm + while left_m != fx.Int64(0): + lead_req = fx.Int32(fx.math.cttz(left_m).to(fx.Int32)) + if const_expr(CPR == 1): + cg = lead_req // RPC + gbits = fx.Int64(GMASK) << fx.Int64(cg * RPC) + left_m = left_m & ~gbits + score_cgs(frags, hm, (mmask & gbits) != fx.Int64(0), [cg], b, jpos) + else: + gbits = fx.Int64(1) << fx.Int64(lead_req) + left_m = left_m & ~gbits + masked_any = (mmask & gbits) != fx.Int64(0) + score_cgs( + frags, + hm, + masked_any, + [lead_req * CPR + g for g in range(CPR)], + b, + jpos, + ) + + # The waves share positions in units of i32_unit blocks; page k of + # position `it` goes to wave (k + it) % NW. In per-wave mode (fewer + # requests than waves) wave w walks its own units instead. + u_step = per_wave.select(i32_splits * NW, i32_splits) + ub = per_wave.select(split * NW + wave, split) * usz + it = fx.Int32(0) + while fx.Int64(fx.rocdl.ballot(T.i64, ub < nblk_r)) != fx.Int64(0): + b = ub + jpos = fx.Int32(0) + while (jpos < usz) & ( + fx.Int64(fx.rocdl.ballot(T.i64, b < nblk_r)) != fx.Int64(0) + ): + in_r = b < nblk_r + skip = (b < rbf_r) & ((b < i32_init) | (b >= loc_last_r)) + need_r = in_r & ~skip + bid = fx.Int32( + buffer_ops.buffer_load( + btr, + need_r.select((req0 + lane) * i32_bt_stride + b, fx.Int32(0)), + vec_width=1, + dtype=fx.Int32, + ) + ) + bid = need_r.select(bid, fx.Int32(-1)) + # Sentinel-only blocks, stored by wave 0. + if (fx.Int64(fx.rocdl.ballot(T.i64, in_r & skip)) != fx.Int64(0)) & ( + (wave == 0) | per_wave + ): + # A runtime loop: unrolled, all store addresses stay live. + jr = fx.Int32(0) + while jr < fx.Int32(QL * H): + sv = row_value(neg_inf, seq_r, jr // H, b) + stq = (req0 + lane) * QL + jr // H + put( + lane * R + jr, + jpos, + sv, + in_r & skip, + (jr % H) * i32_s_sh + stq * i32_s_st + b, + ) + jr = jr + 1 + pend = fx.Int64(fx.rocdl.ballot(T.i64, need_r)) + mmask = fx.Int64( + fx.rocdl.ballot(T.i64, need_r & (b * BLK + (BLK - 1) > fm_r)) + ) + # This wave's pages, as the mask of their first lanes. + mine = fx.Int64(0) + k = it + while pend != fx.Int64(0): + lead = fx.Int32(fx.math.cttz(pend).to(fx.Int32)) + page = fx.Int32(fx.rocdl.readlane(T.i32, bid, lead)) + pend = pend & ~fx.Int64(fx.rocdl.ballot(T.i64, bid == page)) + mine = mine | (((k % NW) == wave) | per_wave).select( + fx.Int64(1) << fx.Int64(lead), fx.Int64(0) + ) + k = k + 1 + ok0 = mine != fx.Int64(0) + l0 = fx.Int32(fx.math.cttz(mine).to(fx.Int32)) + kr0 = page_rsrc( + fx.Int32(fx.rocdl.readlane(T.i32, bid, ok0.select(l0, fx.Int32(0)))) + ) + tiles = [load_tile(kr0, ok0, t) for t in range_constexpr(MT)] + while mine != fx.Int64(0): + lead = fx.Int32(fx.math.cttz(mine).to(fx.Int32)) + page = fx.Int32(fx.rocdl.readlane(T.i32, bid, lead)) + hm = fx.Int64(fx.rocdl.ballot(T.i64, bid == page)) + mine = mine & ~(fx.Int64(1) << fx.Int64(lead)) + okn = mine != fx.Int64(0) + ln = fx.Int32(fx.math.cttz(mine).to(fx.Int32)) + krn = page_rsrc( + fx.Int32( + fx.rocdl.readlane(T.i32, bid, okn.select(ln, fx.Int32(0))) + ) + ) + # Tile t of the next page loads into the registers tile t of + # this page frees; the barriers keep LLVM from hoisting the + # loads. + frags, nxt = [], [] + for t in range_constexpr(MT): + frags.append(dequant_tile(*tiles[t])) + nxt.append(load_tile(krn, okn, t)) + fx.rocdl.sched_barrier(0) + tiles = nxt + score_groups(frags, hm, mmask, b, jpos) + b = b + 1 + jpos = jpos + 1 + it = it + 1 + if const_expr(buffered): # noqa: SIM102 (the outer if is static) + if to_lds: + fx.gpu.barrier() + flush(ub) + fx.gpu.barrier() + ub = ub + u_step * usz + + @flyc.jit + def launch( + arg_q: fx.Int64, + arg_kv: fx.Int64, + arg_lut: fx.Int64, + arg_score: fx.Int64, + arg_bt: fx.Int64, + arg_seq: fx.Int64, + i64_page_stride: fx.Int64, + i32_q_st: fx.Int32, + i32_q_sh: fx.Int32, + i64_q_bytes: fx.Int64, + i32_s_sh: fx.Int32, + i32_s_st: fx.Int32, + i64_s_bytes: fx.Int64, + i32_bt_stride: fx.Int32, + i64_bt_bytes: fx.Int64, + i32_num_reqs: fx.Int32, + i32_chunk: fx.Int32, + i32_nch: fx.Int32, + i32_splits: fx.Int32, + i32_init: fx.Int32, + i32_local: fx.Int32, + i32_per_wave: fx.Int32, + i32_unit: fx.Int32, + stream: fx.Stream, + ): + kernel( + arg_q, + arg_kv, + arg_lut, + arg_score, + arg_bt, + arg_seq, + i64_page_stride, + i32_q_st, + i32_q_sh, + i64_q_bytes, + i32_s_sh, + i32_s_st, + i64_s_bytes, + i32_bt_stride, + i64_bt_bytes, + i32_num_reqs, + i32_chunk, + i32_nch, + i32_splits, + i32_init, + i32_local, + i32_per_wave, + i32_unit, + ).launch( + grid=(fx.Int64(i32_nch * i32_splits), 1, 1), + block=(64 * NW, 1, 1), + stream=stream, + ) + + launch.kernel_name = name + return launch diff --git a/vllm/models/minimax_m3/amd/ops/nvfp4_index_decode/kernel_cp_push.py b/vllm/models/minimax_m3/amd/ops/nvfp4_index_decode/kernel_cp_push.py new file mode 100644 index 000000000000..862144426914 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/nvfp4_index_decode/kernel_cp_push.py @@ -0,0 +1,611 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Context-parallel decode index scorer for MiniMax-M3 (FlyDSL, gfx950, TP4). + +Rank ``me`` scores blocks b with (b // CP_CH) % 4 == me for all four index heads +(bit for bit as ``kernel.py``) and stores head h's scores into rank h's buffer +(``index_cp.IndexCP``); it returns once every rank's scores have arrived. +""" + +import flydsl.compiler as flyc +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import buffer_ops +from flydsl._mlir.dialects import llvm as _llvm +from flydsl.expr import const_expr, range_constexpr +from flydsl.expr.typing import T +from flydsl.expr.typing import Vector as Vec + +from vllm.models.minimax_m3.amd.ops.flydsl_utils import ( + NT, + SC0, + SC1, + bits, + dequant8, + global_i32_ptr, + key_order4, + maxf_nn, + mfma_fp8_16x16x128, + pack8, + perm, + xlane4, +) +from vllm.models.minimax_m3.amd.ops.nvfp4_index_decode.kernel import block_sentinels + +WORLD = 4 # TP ranks = index heads, one per rank +BLK = 128 # tokens per block +D = 128 +CP_CH = 16 # blocks per run of one rank +PAGE_CODES = BLK * D // 2 # e2m1 codes, then [128 x 8 B] e4m3 group scales +PAGE_BYTES = PAGE_CODES + BLK * 8 +MT = BLK // 16 # token tiles per page +SYS = SC0 | SC1 +MAX_ROWS = 1024 # decode rows (max_num_seqs x query_len) the receive buffers hold +# Flag words per rank: [SC_FLAGS + p] source p's scores arrived, [SC_DONE + w] +# workgroup w done, [SC_IQ + p * SC_MAX_REQS + r] source p's index-q of request r. +SC_FLAGS = 64 +SC_DONE = 1024 +SC_MAX_WG = 1024 +SC_IQ = 2048 +SC_MAX_REQS = 256 +FLAG_BYTES = 12288 +# Device counters (int32); [CNT_SC] holds the call count. +CNT_SC = 128 +CNT_WORDS = 512 + + +def _flag_read(addr): + """An atomic add of 0 at system scope (never hoisted out of a spin loop).""" + return fx.Int32( + _llvm.AtomicRMWOp( + _llvm.AtomicBinOp.add, + global_i32_ptr(addr).llvm_ptr, + fx.Int32(0).ir_value(), + _llvm.AtomicOrdering.monotonic, + syncscope="", + alignment=4, + ).result + ) + + +def _sel4(p, a0, a1, a2, a3): + return (p == 0).select(a0, (p == 1).select(a1, (p == 2).select(a2, a3))) + + +GRID_SMALL, GRID = 512, 768 +GRID_SMALL_REQS = 32 +NW = 4 # waves per workgroup: quarter w of every run +QD = CP_CH // NW # blocks per quarter +WIN = 64 # pages per block-table window (one VGPR) +MAX_REQS = 64 * NW # one request per thread in the prefix sum +QL = 4 # DSpark rows per request +HEADS = 4 + + +def _uni(x): + return fx.Int32(fx.rocdl.readfirstlane(T.i32, fx.Int32(x))) + + +def _min(a, b): + return (a < b).select(a, b) + + +def _max(a, b): + return (a > b).select(a, b) + + +def _wave_scan(x, lane): + """Inclusive prefix sum over the wave's 64 lanes.""" + for d in range_constexpr(6): + y = fx.Int32(fx.rocdl.ds_bpermute(T.i32, (lane - (1 << d)) * 4, x)) + x = x + (lane >= (1 << d)).select(y, fx.Int32(0)) + return x + + +def compile_score_push(): + name = "m3_nvfp4_index_score_push_cp" + + @fx.struct + class Shared: + lut: fx.Array[fx.Int32, 512, 16] + stage: fx.Array[fx.Int32, 2 * 16 * NW * QD, 16] # [run % 2][col][quarter] + incl: fx.Array[fx.Int32, MAX_REQS] # inclusive prefix of the run counts + seq: fx.Array[fx.Int32, MAX_REQS] + wsum: fx.Array[fx.Int32, NW] + + @flyc.kernel(name=name, known_block_size=[64 * NW, 1, 1]) + def kernel( + arg_iq: fx.Int64, # this rank's head: [num_reqs * QL, 128] e4m3 + arg_kv: fx.Int64, # NVFP4 index pages [num_blocks, 128, 72] u8 + arg_lut: fx.Int64, # nvfp4_e4m3_lut [256] i64 + arg_d0: fx.Int64, # head h's scores [rows, S] fp32 (rank h's receive buffer) + arg_d1: fx.Int64, + arg_d2: fx.Int64, + arg_d3: fx.Int64, + arg_bt: fx.Int64, # block table [num_reqs, >= max_blocks] i32 + arg_seq: fx.Int64, # seq_lens [num_reqs] i32 + arg_cnt: fx.Int64, # device counters (CNT_*) + arg_f0: fx.Int64, # rank p's flag words + arg_f1: fx.Int64, + arg_f2: fx.Int64, + arg_f3: fx.Int64, + arg_q0: fx.Int64, # rank p's index-q receive buffer [4, rmax, 128] e4m3 + arg_q1: fx.Int64, + arg_q2: fx.Int64, + arg_q3: fx.Int64, + i32_rmax: fx.Int32, + i64_page_stride: fx.Int64, + i32_s: fx.Int32, # score row stride (elements) + i64_d_bytes: fx.Int64, + i32_bt_stride: fx.Int32, + i64_bt_bytes: fx.Int64, + i32_num_reqs: fx.Int32, + i32_init: fx.Int32, # leading blocks forced in (sentinel 1e30) + i32_local: fx.Int32, # trailing blocks forced in (sentinel 1e29) + i32_me: fx.Int32, + i32_nwg: fx.Int32, # the grid + ): + smem = fx.SharedAllocator().allocate(Shared).peek() + tx, pid = fx.thread_idx.x, fx.block_idx.x + lane = tx % 64 + wave = _uni(tx // 64) + col, kl = lane % 16, lane // 16 + st_qoff = col // HEADS # this lane's column: row st_qoff of head st_head + st_head = col % HEADS + incl_l, seq_l = smem.incl.ptr, smem.seq.ptr + + cr = buffer_ops.create_buffer_resource_from_addr( + arg_cnt, num_records_bytes=CNT_WORDS * 4 + ) + calls = ( + _uni( + buffer_ops.buffer_load( + cr, CNT_SC, vec_width=1, dtype=fx.Int32, cache_modifier=SC1 + ) + ) + + 1 + ) + btr = buffer_ops.create_buffer_resource_from_addr( + arg_bt, num_records_bytes=i64_bt_bytes + ) + qbytes = fx.Int64(i32_rmax) * (HEADS * D) + qs = (arg_q0, arg_q1, arg_q2, arg_q3) + fs = (arg_f0, arg_f1, arg_f2, arg_f3) + mine = _sel4(i32_me, arg_f0, arg_f1, arg_f2, arg_f3) + qr = buffer_ops.create_buffer_resource_from_addr( + _sel4(i32_me, arg_q0, arg_q1, arg_q2, arg_q3), num_records_bytes=qbytes + ) + drs = [ + buffer_ops.create_buffer_resource_from_addr( + d, num_records_bytes=i64_d_bytes + ) + for d in (arg_d0, arg_d1, arg_d2, arg_d3) + ] + + # LUT to LDS; per request this rank's run count, prefix-summed. + lut_g = global_i32_ptr(arg_lut) + lut_l = smem.lut.ptr + for i in range_constexpr(2): + lut_l[tx * 2 + i] = fx.Int32(lut_g[tx * 2 + i]) + r_ok = tx < i32_num_reqs + seq_t = fx.Int32(global_i32_ptr(arg_seq)[r_ok.select(tx, fx.Int32(0))]) + seq_t = r_ok.select(seq_t, fx.Int32(0)) + # This rank's index-q rows of requests pid, pid + nwg, ... to slot me of + # every rank; their flags follow below. + ir = buffer_ops.create_buffer_resource_from_addr( + arg_iq, num_records_bytes=fx.Int64(i32_num_reqs) * (QL * D) + ) + rs = pid + while (wave == 0) & (rs < i32_num_reqs): + v = buffer_ops.buffer_load( + ir, + (rs * QL * D + lane * 16) // 4, + vec_width=4, + dtype=fx.Int32, + mask=lane < QL * D // 16, + ) + for p in range_constexpr(WORLD): + buffer_ops.buffer_store( + v, + buffer_ops.create_buffer_resource_from_addr( + qs[p], num_records_bytes=qbytes + ), + ((i32_me * i32_rmax + rs * QL) * D + lane * 16) // 4, + mask=lane < QL * D // 16, + cache_modifier=SYS, + ) + rs = rs + i32_nwg + nb_t = (seq_t + (BLK - 1)) // BLK + runs_t = (nb_t // (WORLD * CP_CH)) + ( + nb_t % (WORLD * CP_CH) > i32_me * CP_CH + ).select(fx.Int32(1), fx.Int32(0)) + x = _wave_scan(runs_t, lane) + if lane == 63: + smem.wsum.ptr[wave] = x + seq_l[tx] = seq_t + fx.gpu.barrier() + for w in range_constexpr(NW - 1): + x = x + (wave > w).select(fx.Int32(smem.wsum.ptr[w]), fx.Int32(0)) + incl_l[tx] = x + fx.gpu.barrier() + + # Runs pid, pid + grid, ...: the busy workgroups stay one per CU. + total = _uni(incl_l[MAX_REQS - 1]) + nruns = (pid < total).select((total - pid + i32_nwg - 1) // i32_nwg, 0) + nslots = nruns * QD # pages of this wave + + lut8 = fx.logical_divide( + fx.make_view( + fx.recast_iter(fx.Int32, smem.lut.ptr), fx.make_layout(512, 1) + ), + fx.make_layout(2, 1), + ) + lut_atom = fx.make_copy_atom(fx.UniversalCopy64b(), fx.Int32) + stage16 = fx.logical_divide( + fx.make_view( + fx.recast_iter(fx.Int32, smem.stage.ptr), + fx.make_layout(2 * 16 * NW * QD, 1), + ), + fx.make_layout(4, 1), + ) + atom16 = fx.make_copy_atom(fx.UniversalCopy128b(), fx.Int32) + + def lut_load(sbyte): + r = fx.make_rmem_tensor(fx.make_layout(2, 1), fx.Int32) + fx.copy(lut_atom, fx.slice(lut8, (None, sbyte)), r) + v = Vec(r.load()) + return fx.Int32(v[0]), fx.Int32(v[1]) + + code_off = (col * 64 + kl * 16) // 4 # dwords + # Scales 2 kl, 2 kl + 1 of token col as a dword: a u16 load's sign + # extension made the loop head wait for the whole next page. + scale_off = col * 2 + kl // 2 # dwords + # v_perm selectors: scale byte 2 (kl % 2) (+ 1) of the dword, zeros above + scale_sel = (kl % 2) * 2 + 0x0C0C0C00 + + def page_rsrc(page): + return buffer_ops.create_buffer_resource_from_addr( + arg_kv + fx.Int64(page) * i64_page_stride, num_records_bytes=PAGE_BYTES + ) + + def load_tile(kr, ok, t): + """Tile t: this lane's codes and scales; no memory access unless ok.""" + c = Vec( + buffer_ops.buffer_load( + kr, + code_off, + vec_width=4, + dtype=fx.Int32, + mask=ok, + soffset_bytes=t * 1024, + cache_modifier=NT, + ) + ) + sc = fx.Int32( + buffer_ops.buffer_load( + kr, + scale_off, + vec_width=1, + dtype=fx.Int32, + mask=ok, + soffset_bytes=PAGE_CODES + t * 128, + cache_modifier=NT, + ) + ) + return c, sc + + def dequant_tile(c, sc): + """The A fragment of a tile (e4m3 keys, even dims then odd dims per 8)""" + t0 = lut_load(perm(sc, sc, scale_sel)) + t1 = lut_load(perm(sc, sc, scale_sel + 1)) + f = [] + for e in range_constexpr(4): + lo, hi = dequant8(fx.Int32(Vec(c)[e]), *(t0 if e < 2 else t1)) + f += [lo, hi] + return Vec.from_elements(f, fx.Int32) + + def q_load(r, ok): + """This lane's 32 B of Q: row r * QL + st_qoff, head st_head.""" + off = ((st_head * i32_rmax + r * QL + st_qoff) * D + kl * 32) // 4 + a = Vec( + buffer_ops.buffer_load(qr, off, vec_width=4, dtype=fx.Int32, mask=ok) + ) + b = Vec( + buffer_ops.buffer_load( + qr, off + 4, vec_width=4, dtype=fx.Int32, mask=ok + ) + ) + return a, b + + def q_frag(a, b): + """B operand: the 32 B in the key's dim order.""" + halves = [] + for v in (a, b): + d = [fx.Int32(Vec(v)[e]) for e in range_constexpr(4)] + halves.append(key_order4(d)) + return pack8(halves[0], halves[1]) + + zero4 = fx.Vector.filled(4, 0.0, fx.Float32) + neg_inf = fx.Float32(float("-inf")) + + def reduce(v, t, run, masked, lim): + for e in range_constexpr(4): + x = v[e] + if const_expr(masked): + x = (lim >= t * 16 + e).select(x, neg_inf) + run = maxf_nn(run, x) + return run + + def page_pass(tiles, qf, krn, okn, masked, lim): + """Max of this lane's column over the page; tile t of the next page + loads into tile t's registers (sched barriers stop LLVM hoisting).""" + accs = [] + nxt = [] + for t in range_constexpr(MT): + f = dequant_tile(*tiles[t]) + nxt.append(load_tile(krn, okn, t)) + accs.append(mfma_fp8_16x16x128(f, qf, zero4)) + fx.rocdl.sched_barrier(0) + mx = neg_inf + if masked: + run_m = neg_inf + for t in range_constexpr(MT): + run_m = reduce(accs[t], t, run_m, True, lim) + mx = xlane4(run_m, maxf_nn) + else: + run_u = neg_inf + for t in range_constexpr(MT): + run_u = reduce(accs[t], t, run_u, False, None) + mx = xlane4(run_u, maxf_nn) + return mx, nxt + + def row_value(mx, seq, q_off, b): + return block_sentinels(mx, seq - QL + q_off + 1, b, i32_init, i32_local) + + fx.rocdl.s_waitcnt(vmcnt=0) + rs = pid + while (wave == 0) & (rs < i32_num_reqs): + for p in range_constexpr(WORLD): + buffer_ops.buffer_store( + calls, + buffer_ops.create_buffer_resource_from_addr( + fs[p], num_records_bytes=FLAG_BYTES + ), + SC_IQ + i32_me * SC_MAX_REQS + rs, + mask=lane == 0, + cache_modifier=SYS, + ) + rs = rs + i32_nwg + + w0 = fx.Int32(0) + while w0 < nslots: + # One page per lane: page s is block 4 w + s % 4 of run pid + (s // 4) + # * grid, of request rj (binary search in the prefix). + s = w0 + lane + k = pid + (s // QD) * i32_nwg + rj = fx.Int32(0) + for bs in range_constexpr(8): + step = MAX_REQS >> (bs + 1) + rj = (fx.Int32(incl_l[rj + step - 1]) <= k).select(rj + step, rj) + valid = s < nslots + rj = valid.select(rj, fx.Int32(0)) + excl = (rj > 0).select(fx.Int32(incl_l[_max(rj - 1, 0)]), fx.Int32(0)) + seqj = fx.Int32(seq_l[rj]) + nblkj = (seqj + (BLK - 1)) // BLK + bj = ((k - excl) * WORLD + i32_me) * CP_CH + wave * QD + s % QD + frow = seqj - (QL - 1) + rbf = ((frow < 0).select(fx.Int32(0), frow) + (BLK - 1)) // BLK + ll = nblkj - i32_local + loc_last = (ll < 0).select(fx.Int32(0), ll) + # Init / local blocks every row sees whole only need their sentinel. + skip = (bj < rbf) & ((bj < i32_init) | (bj >= loc_last)) + need = valid & (bj < nblkj) & ~skip + pgj = fx.Int32( + buffer_ops.buffer_load( + btr, + need.select(rj * i32_bt_stride + bj, fx.Int32(0)), + vec_width=1, + dtype=fx.Int32, + ) + ) + pgj = need.select(pgj, fx.Int32(-1)) + n = _min(nslots - w0, WIN) + + p_0 = fx.Int32(fx.rocdl.readlane(T.i32, pgj, 0)) + r_0 = fx.Int32(fx.rocdl.readlane(T.i32, rj, 0)) + ok0 = p_0 >= 0 + kr0 = page_rsrc(ok0.select(p_0, fx.Int32(0))) + fx.rocdl.sched_barrier(0) + tiles = [] + for t in range_constexpr(MT): + tiles.append(load_tile(kr0, ok0, t)) + fx.rocdl.sched_barrier(0) + # Wait for the index-q rows; lane i polls source i % 4 of its request. + word = mine + fx.Int64((SC_IQ + (lane % WORLD) * SC_MAX_REQS + rj) * 4) + want = lane < n + f = calls + if want: + f = _flag_read(word) + while fx.Int64(fx.rocdl.ballot(T.i64, want & (f < calls))) != 0: + if want & (f < calls): + f = _flag_read(word) + qa, qb = q_load(r_0, n > 0) + # Nothing pending where the loop head merges with the back edge. + fx.rocdl.s_waitcnt(vmcnt=0) + qf = q_frag(qa, qb) + qna, qnb = qa, qb + sw = n < 0 # false: Q of the next page already loaded + vq = [neg_inf] * QD + j = fx.Int32(0) + while j < n: + r = fx.Int32(fx.rocdl.readlane(T.i32, rj, j)) + b = fx.Int32(fx.rocdl.readlane(T.i32, bj, j)) + seq = fx.Int32(fx.rocdl.readlane(T.i32, seqj, j)) + if sw: + qf = q_frag(qna, qnb) + jn = j + 1 + okj = jn < n + jc = okj.select(jn, fx.Int32(0)) + pgn = fx.Int32(fx.rocdl.readlane(T.i32, pgj, jc)) + rn = fx.Int32(fx.rocdl.readlane(T.i32, rj, jc)) + okn = okj & (pgn >= 0) + krn = page_rsrc(okn.select(pgn, fx.Int32(0))) + sw = okj & (rn != r) + qna, qnb = q_load(rn, sw) + fx.rocdl.sched_barrier(0) + mx, tiles = page_pass( + tiles, + qf, + krn, + okn, + b * BLK + (BLK - 1) > seq - QL, + seq - QL + st_qoff - b * BLK - kl * 4, + ) + ov = row_value(mx, seq, st_qoff, b) + e = (w0 + j) % QD + vq = [(e == i).select(ov, v) for i, v in enumerate(vq)] + if e == QD - 1: + # The run's quarters meet in LDS; wave m % NW stores it. + m = (w0 + j) // QD + slot = m % 2 + val = fx.make_rmem_tensor(fx.make_layout(4, 1), fx.Int32) + val.store(Vec.from_elements([bits(v) for v in vq], fx.Int32)) + if kl == 0: + fx.copy( + atom16, + val, + fx.slice(stage16, (None, (slot * 16 + col) * NW + wave)), + ) + fx.gpu.barrier() + if wave == m % NW: + got = fx.make_rmem_tensor(fx.make_layout(4, 1), fx.Int32) + fx.copy( + atom16, + fx.slice(stage16, (None, (slot * 16 + col) * NW + kl)), + got, + ) + off = (r * QL + st_qoff) * i32_s + (b - b % CP_CH) + kl * QD + for h in range_constexpr(HEADS): + buffer_ops.buffer_store( + got.load(), + drs[h], + off, + mask=st_head == h, + cache_modifier=SYS, + ) + j = jn + w0 = w0 + WIN + + # sc0 sc1 stores are system-visible once vmcnt drains; a release fence + # per workgroup would write back L2. The last workgroup (dispatched last, + # so its spin cannot starve the others) collects the done words, signals + # every rank and waits for all four. + fx.rocdl.s_waitcnt(vmcnt=0) + fx.gpu.barrier() + own = buffer_ops.create_buffer_resource_from_addr( + mine, num_records_bytes=FLAG_BYTES + ) + buffer_ops.buffer_store( + calls, own, SC_DONE + pid, mask=tx == 0, cache_modifier=SYS + ) + if pid == i32_nwg - 1: + # Thread t polls done words t, t + 256, ... + def done_min(): + lo = calls + for i in range_constexpr(SC_MAX_WG // (64 * NW)): + w = tx + i * 64 * NW + f = _flag_read( + mine + fx.Int64((SC_DONE + _min(w, SC_MAX_WG - 1)) * 4) + ) + lo = _min(lo, (w < i32_nwg).select(f, calls)) + return lo + + lo = done_min() + while fx.Int64(fx.rocdl.ballot(T.i64, lo < calls)) != 0: + lo = done_min() + fx.gpu.barrier() + _llvm.FenceOp(_llvm.AtomicOrdering.release, syncscope="") + for p in range_constexpr(WORLD): + fr = buffer_ops.create_buffer_resource_from_addr( + fs[p], num_records_bytes=FLAG_BYTES + ) + buffer_ops.buffer_store( + calls, fr, SC_FLAGS + i32_me, mask=tx == 0, cache_modifier=SYS + ) + buffer_ops.buffer_store(calls, cr, CNT_SC, mask=tx == 0, cache_modifier=SYS) + if tx < WORLD: + f = _flag_read(mine + fx.Int64((SC_FLAGS + tx) * 4)) + while f < calls: + f = _flag_read(mine + fx.Int64((SC_FLAGS + tx) * 4)) + fx.gpu.barrier() + _llvm.FenceOp(_llvm.AtomicOrdering.acquire, syncscope="") + + @flyc.jit + def launch( + arg_iq: fx.Int64, + arg_kv: fx.Int64, + arg_lut: fx.Int64, + arg_d0: fx.Int64, + arg_d1: fx.Int64, + arg_d2: fx.Int64, + arg_d3: fx.Int64, + arg_bt: fx.Int64, + arg_seq: fx.Int64, + arg_cnt: fx.Int64, + arg_f0: fx.Int64, + arg_f1: fx.Int64, + arg_f2: fx.Int64, + arg_f3: fx.Int64, + arg_q0: fx.Int64, + arg_q1: fx.Int64, + arg_q2: fx.Int64, + arg_q3: fx.Int64, + i32_rmax: fx.Int32, + i64_page_stride: fx.Int64, + i32_s: fx.Int32, + i64_d_bytes: fx.Int64, + i32_bt_stride: fx.Int32, + i64_bt_bytes: fx.Int64, + i32_num_reqs: fx.Int32, + i32_init: fx.Int32, + i32_local: fx.Int32, + i32_me: fx.Int32, + i32_nwg: fx.Int32, + stream: fx.Stream, + ): + kernel( + arg_iq, + arg_kv, + arg_lut, + arg_d0, + arg_d1, + arg_d2, + arg_d3, + arg_bt, + arg_seq, + arg_cnt, + arg_f0, + arg_f1, + arg_f2, + arg_f3, + arg_q0, + arg_q1, + arg_q2, + arg_q3, + i32_rmax, + i64_page_stride, + i32_s, + i64_d_bytes, + i32_bt_stride, + i64_bt_bytes, + i32_num_reqs, + i32_init, + i32_local, + i32_me, + i32_nwg, + ).launch(grid=(fx.Int64(i32_nwg), 1, 1), block=(64 * NW, 1, 1), stream=stream) + + launch.kernel_name = name + return launch + + +assert CNT_SC < CNT_WORDS and SC_DONE + SC_MAX_WG <= FLAG_BYTES // 4 diff --git a/vllm/models/minimax_m3/amd/ops/nvfp4_index_prefill/__init__.py b/vllm/models/minimax_m3/amd/ops/nvfp4_index_prefill/__init__.py new file mode 100644 index 000000000000..208f01a7cb5e --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/nvfp4_index_prefill/__init__.py @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project diff --git a/vllm/models/minimax_m3/amd/ops/nvfp4_index_prefill/host.py b/vllm/models/minimax_m3/amd/ops/nvfp4_index_prefill/host.py new file mode 100644 index 000000000000..2530d9f87eb5 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/nvfp4_index_prefill/host.py @@ -0,0 +1,152 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Launch wrapper of the FlyDSL NVFP4 prefill index scorers.""" + +import functools +import math + +import torch + +from vllm.models.minimax_m3.amd.ops.flydsl_utils import cu_count, run_compiled +from vllm.utils.math_utils import cdiv + +from . import kernel as _kernel + +# Workgroups to aim for: more, shorter segments balance the tail of the causal +# windows; a segment keeps >= GROUP blocks. +TARGET_WORKGROUPS = 2048 +# Segments are added until the last round of workgroups is at least this full. +MIN_ROUND_FILL = 0.9 +WORKGROUPS_PER_CU = 2 +MAX_SEGMENTS = 1024 +# Small work (<= 128 query rows, or below SMALL_WORK) takes ``kernel_shared`` +# with 128-row tiles, aiming at SMALL_TARGET workgroups below MID_WORK. +SMALL_WORK = 4096 +MID_WORK = 16384 +SMALL_TARGET = 512 +# Tests: pin the kernel (True: kernel_shared) or its 32-row tiles per wave. +PIN_SHARED: bool | None = None +PIN_MQ: int | None = None + +_NVFP4_E4M3_LUT: dict[torch.device, torch.Tensor] = {} + + +def nvfp4_e4m3_lut(device: torch.device) -> torch.Tensor: + """[256] int64: byte j of entry s is e4m3_rn_satfinite(m_j * e4m3(s)) for the + E2M1 magnitudes m = 0, 0.5, 1, 1.5, 2, 3, 4, 6.""" + lut = _NVFP4_E4M3_LUT.get(device) + if lut is None: + # Device ops only, so a first call under graph capture is fine. + scales = torch.arange(256, dtype=torch.uint8, device=device) + scales = scales.view(torch.float8_e4m3fn).float() + code = torch.arange(8, device=device) + exp, man = code // 2, (code % 2).float() + mags = torch.where( + exp == 0, man * 0.5, torch.exp2((exp - 1).float()) * (1.0 + man * 0.5) + ) + # e2m1 * e4m3 is exact in fp32; saturate, then round once to E4M3. + values = (scales[:, None] * mags[None, :]).clamp(-448.0, 448.0) + lut = values.to(torch.float8_e4m3fn).view(torch.int64).reshape(256) + _NVFP4_E4M3_LUT[device] = lut + return lut + + +@functools.cache +def _get_kernel(heads: int): + return _kernel.compile_score_prefill(heads) + + +def _kernel_shared(): + # Imported late: the decode host imports this module. + from . import kernel_shared + + return kernel_shared + + +@functools.cache +def _get_kernel_shared(heads: int, mq: int): + return _kernel_shared().compile_score_prefill_shared(heads, mq) + + +def _supported(q_idx, index_cache, score, *int32_tensors) -> bool: + from vllm.platforms.rocm import on_gfx950 + + heads = q_idx.shape[1] + return ( + on_gfx950() + and q_idx.dtype == torch.float8_e4m3fn + and heads in (1, 2, 4) + and q_idx.shape[2] == _kernel.D + and q_idx.stride(2) == 1 + and q_idx.stride(1) == _kernel.D + and q_idx.stride(0) == heads * _kernel.D + and score.shape[0] == heads + and score.stride(2) == 1 + and index_cache.dtype == torch.uint8 + and index_cache.stride(2) == 1 + and index_cache.stride(1) == _kernel.D // 2 + _kernel.D // 16 + and index_cache.stride(0) % 16 == 0 + and index_cache.data_ptr() % 16 == 0 + and all(t.dtype == torch.int32 and t.is_contiguous() for t in int32_tensors) + ) + + +def minimax_m3_nvfp4_index_score_prefill( + q_idx: torch.Tensor, # [total_q, H, 128] e4m3 + index_cache: torch.Tensor, # [num_blocks, 128, 72] uint8 + score: torch.Tensor, # [H, total_q, >= cdiv(max_seq_len, 128)] fp32 + block_table: torch.Tensor, # [batch, >= max_blocks] int32 + cu_seqlens_q: torch.Tensor, # [batch + 1] int32 + seq_lens: torch.Tensor, # [batch] int32 + init_blocks: int, + local_blocks: int, + max_query_len: int, + max_seq_len: int, +) -> None: + """Block scores of every prefill row for 1, 2 or 4 index heads.""" + batch = cu_seqlens_q.shape[0] - 1 + total_q, heads, _ = q_idx.shape + if total_q == 0 or block_table.shape[0] == 0: + return + assert _supported(q_idx, index_cache, score, block_table, cu_seqlens_q, seq_lens) + max_blocks = cdiv(max_seq_len, _kernel.BLK) + assert max_blocks <= score.shape[2] + work = max_blocks * cdiv(max_query_len, 256) * batch * heads + small = max_query_len * heads <= 128 or work < SMALL_WORK + shared = small if PIN_SHARED is None else PIN_SHARED + mq = PIN_MQ or (1 if small else 2) + target = SMALL_TARGET if shared and work < MID_WORK else TARGET_WORKGROUPS + tile_q = _kernel_shared().tile_q(mq) if shared else _kernel.TILE_Q + qt = cdiv(max_query_len * heads, tile_q) + min_seg = 1 if shared else _kernel.GROUP + max_nseg = max(1, min(MAX_SEGMENTS, max_blocks // min_seg)) + nseg = max(1, min(max_nseg, target // max(1, qt * batch))) + slots = WORKGROUPS_PER_CU * cu_count(q_idx.device) + while nseg < max_nseg: + rounds = qt * batch * nseg / slots + if rounds / math.ceil(rounds) >= MIN_ROUND_FILL: + break + nseg += 1 + lut = () if shared else (nvfp4_e4m3_lut(q_idx.device).data_ptr(),) + run_compiled( + _get_kernel_shared(heads, mq) if shared else _get_kernel(heads), + q_idx.data_ptr(), + index_cache.data_ptr(), + *lut, + score.data_ptr(), + block_table.data_ptr(), + cu_seqlens_q.data_ptr(), + seq_lens.data_ptr(), + int(index_cache.stride(0)), + int(block_table.stride(0)), + int(score.stride(1)), + int(nseg), + int(qt), + int(total_q), + int(batch), + int(init_blocks), + int(local_blocks), + int(score.stride(0)), + int(cdiv(qt * nseg * batch, 8) * 8), + torch.cuda.current_stream(), + ) diff --git a/vllm/models/minimax_m3/amd/ops/nvfp4_index_prefill/kernel.py b/vllm/models/minimax_m3/amd/ops/nvfp4_index_prefill/kernel.py new file mode 100644 index 000000000000..35c8b13583f4 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/nvfp4_index_prefill/kernel.py @@ -0,0 +1,614 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""NVFP4 prefill index scorer for MiniMax-M3 (FlyDSL, gfx950). + +Per (query row, block): the max of q . k over the row's causal tokens, with +AITER's init / local sentinels, on e4m3_rn_satfinite(e2m1 x scale) keys. A +workgroup takes 512 query rows (token * H + head) x a segment of the request's +blocks; Q^T stays in VGPRs and each 16-token tile is one +v_mfma_f32_16x16x128_f8f6f4 per 16-row N-tile. Raw NVFP4 pages arrive in LDS by +DMA one block ahead, and block b + 1 is dequantized into the other key slot +under block b's MFMAs. +""" + +import flydsl.compiler as flyc +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import buffer_ops +from flydsl._mlir import ir +from flydsl._mlir.dialects import llvm +from flydsl.expr import const_expr, range_constexpr +from flydsl.expr import rocdl as _rocdl +from flydsl.expr.typing import T +from flydsl.expr.typing import Vector as Vec + +from vllm.models.minimax_m3.amd.ops.flydsl_utils import ( + as_f32, + bits, + dequant8, + global_i32_ptr, + key_order4, + maxf_nn, + mfma_fp8_16x16x128, + pack8, + permlane_swap, +) + +NW = 4 +ROWS_PER_WAVE = 128 +TILE_Q = NW * ROWS_PER_WAVE +BLK = 128 # tokens per block +D = 128 # index head dim +ROW_BYTES = D # one e4m3 key row in LDS +BLOCK_BYTES = BLK * ROW_BYTES +RS_T = ROW_BYTES // 16 # 16 B tiles per LDS row +SLOT_T = BLK * RS_T # 16 B tiles per key slot +N_SLOTS = 2 +LDS_BYTES = N_SLOTS * BLOCK_BYTES +PAGE_CODES = BLK * D // 2 # page: [128 x 64 B] e2m1 codes, [128 x 8 B] e4m3 scales +PAGE_BYTES = PAGE_CODES + BLK * 8 +GROUP = 4 # blocks per score store (16 B per row) +# SPAN groups of a row are stored back to back (the first SPAN - 1 wait in LDS): +# half-written 128 B score lines get evicted from L2 and cost extra write bytes. +SPAN = 4 +STAGE_T = (SPAN - 1) * NW * 2 * 64 # 16 B LDS tiles: (group, wave, row half, lane) +NI = ROWS_PER_WAVE // 16 # N-tiles per wave +MT = BLK // 16 # M-tiles per block +SENTINEL_INIT = 1e30 # AITER's forced-selection scores +SENTINEL_LOCAL = 1e29 +STAGE_W = 2048 + 256 # raw bytes per wave and block: 32 tokens' codes + scales +RAW_SLOTS = 2 +# M-tile -> code dwords dequantized under its MFMAs. +DQ_AT = {1: (0,), 2: (1,), 3: (2,), 4: (3,), 5: (4,), 6: (5,), 7: (6, 7)} + + +def _ir(v): + return v.ir_value() if hasattr(v, "ir_value") else v + + +def _dma(rsrc, lds_addr, voff, size): + """buffer_load ... lds: ``size`` bytes per lane into LDS at ``lds_addr``.""" + lds = llvm.IntToPtrOp(ir.Type.parse("!llvm.ptr<3>"), _ir(fx.Int32(lds_addr))) + fx.rocdl.raw_ptr_buffer_load_lds( + rsrc, + lds.result, + fx.Int32(size), + fx.Int32(voff), + fx.Int32(0), + fx.Int32(0), + aux=0, + ) + + +def _xlane_max4_pair(x, y): + """Max over lanes L, L^16, L^32, L^48 of two values at once, broadcast.""" + a, b = permlane_swap(_rocdl.permlane32_swap, bits(x), bits(y)) + m = bits(maxf_nn(as_f32(a), as_f32(b))) + a, b = permlane_swap(_rocdl.permlane16_swap, m, m) + big = bits(maxf_nn(as_f32(a), as_f32(b))) + a, b = permlane_swap(_rocdl.permlane32_swap, big, big) + return as_f32(a), as_f32(b) + + +def tile_rows(pid, i32_qt, i32_nseg, i32_nb, arg_cu, arg_seq, heads, tile_q): + """Workgroup pid's request b, query tile and context segment. + + Returns (live, b, seg, seq_start, seq_len, prefix, q_rows, row0); padded + workgroups read request 0 and are not live. + """ + n_wg = i32_qt * i32_nseg * i32_nb + q_tile = pid % i32_qt + seg = (pid // i32_qt) % i32_nseg + b = pid // (i32_qt * i32_nseg) + bc = (pid < n_wg).select(b, fx.Int32(0)) + cu = global_i32_ptr(arg_cu) + seq_start = fx.Int32(cu[bc]) + q_len = fx.Int32(cu[bc + 1]) - seq_start + seq_len = fx.Int32(global_i32_ptr(arg_seq)[bc]) + prefix = seq_len - q_len + q_rows = q_len * heads + row0 = q_tile * tile_q + live = (pid < n_wg) & (row0 < q_rows) + return live, b, seg, seq_start, seq_len, prefix, q_rows, row0 + + +def segment_blocks(prefix, row0, seq_len, seg, i32_nseg, heads, tile_q, align): + """The tile's nblk causal blocks and its segment [blk0, blk1) of them.""" + hi_pos = prefix + (row0 + tile_q) // heads + hi = (hi_pos < seq_len).select(hi_pos, seq_len) + nblk = (hi + (BLK - 1)) // BLK + seg_len = (nblk + i32_nseg - 1) // i32_nseg + if align > 1: + seg_len = (seg_len + (align - 1)) & ~(align - 1) + blk0 = seg * seg_len + blk1e = blk0 + seg_len + blk1 = (blk1e < nblk).select(blk1e, nblk) + return nblk, blk0, blk1 + + +def score_resources(arg_q, arg_score, i32_total_q, i32_hs, i32_S, heads): + """Buffer resources of the Q rows and the scores.""" + qr = buffer_ops.create_buffer_resource_from_addr( + arg_q, num_records_bytes=fx.Int64(i32_total_q) * (heads * D) + ) + sr = buffer_ops.create_buffer_resource_from_addr( + arg_score, + num_records_bytes=( + fx.Int64(i32_hs) * (heads - 1) + fx.Int64(i32_total_q) * fx.Int64(i32_S) + ) + * 4, + ) + return qr, sr + + +def page_lookup(arg_bt, bt_row, end): + """Page of a block, clamped to the last block before ``end``. + + A constant-space s_load: before an s_buffer_load LLVM would wait for the + in-flight LDS DMAs. + """ + bt = llvm.IntToPtrOp(ir.Type.parse("!llvm.ptr<4>"), _ir(fx.Int64(arg_bt))).result + + def page_of(blk): + bi = (blk < end).select(blk, end - 1) + p = buffer_ops.get_element_ptr( + bt, byte_offset=_ir((bt_row + bi) * 4), elem_type=T.i8 + ) + return fx.Int32(llvm.LoadOp(T.i32, p, alignment=4, invariant=True).result) + + return page_of + + +def with_sentinels(v, blk, nb, i32_init, i32_local): + """AITER's init / local sentinels on block blk of a row of nb causal blocks.""" + is_local = (blk >= nb - i32_local) & (blk < nb) + is_init = (blk < i32_init) & (blk < nb) + return is_local.select( + fx.Float32(SENTINEL_LOCAL), is_init.select(fx.Float32(SENTINEL_INIT), v) + ) + + +def compile_score_prefill(heads: int = 1): + """Build the scorer for 1, 2 or 4 index heads (sharing one index-K head).""" + assert heads in (1, 2, 4), heads + H = heads + name = f"m3_nvfp4_index_score_prefill_tq{TILE_Q}_h{H}" + + @fx.struct + class Shared: + a: fx.Array[fx.Uint8, LDS_BYTES, 16] # e4m3 key slots + lut: fx.Array[fx.Int32, 512, 16] + raw: fx.Array[fx.Uint8, RAW_SLOTS * NW * STAGE_W, 16] # DMA'd pages + stage: fx.Array[fx.Int32, STAGE_T * 4, 16] # staged score groups + + @flyc.kernel(name=name, known_block_size=[64 * NW, 1, 1]) + def kernel( + arg_q: fx.Int64, # [total_q, H, 128] e4m3 + arg_kv: fx.Int64, # [num_blocks, 128, 72] uint8 + arg_lut: fx.Int64, # nvfp4_e4m3_lut [256] int64 + arg_score: fx.Int64, # [H, total_q, S] fp32 + arg_bt: fx.Int64, # [batch, >= max_blocks] int32 + arg_cu: fx.Int64, # cu_seqlens_q [batch + 1] int32 + arg_seq: fx.Int64, # seq_lens [batch] int32 + i64_page_stride: fx.Int64, + i32_bt_stride: fx.Int32, + i32_S: fx.Int32, + i32_nseg: fx.Int32, + i32_qt: fx.Int32, # query tiles per request + i32_total_q: fx.Int32, + i32_nb: fx.Int32, + i32_init: fx.Int32, + i32_local: fx.Int32, + i32_hs: fx.Int32, # score head stride + ): + smem = fx.SharedAllocator().allocate(Shared).peek() + tx, pid = fx.thread_idx.x, fx.block_idx.x + lane = tx % 64 + wave = fx.Int32(fx.rocdl.readfirstlane(T.i32, tx // 64)) + l16, q16 = lane % 16, lane // 16 + live, b, seg, seq_start, seq_len, prefix, q_rows, row0 = tile_rows( + pid, i32_qt, i32_nseg, i32_nb, arg_cu, arg_seq, H, TILE_Q + ) + if live: + nblk, blk0, blk1 = segment_blocks( + prefix, row0, seq_len, seg, i32_nseg, H, TILE_Q, GROUP + ) + if blk0 < blk1: + qr, sr = score_resources( + arg_q, arg_score, i32_total_q, i32_hs, i32_S, H + ) + page_of = page_lookup(arg_bt, b * i32_bt_stride, nblk) + + # Lane l of wave w owns token 32 w + l / 2, dims 64 (l % 2) .. + # +63. The DMA writes LDS lane-linearly, so each lane reads back + # its own code and scale bytes. + raw_base_s = fx.Int32( + fx.rocdl.readfirstlane(T.i32, fx.Int32(fx.ptrtoint(smem.raw.ptr))) + ) + code_voff = [wave * 2048 + lane * 32 + h * 16 for h in range(2)] + scale_voff = PAGE_CODES + wave * 256 + lane * 4 + + def dma_raw(page, st): + kr = buffer_ops.create_buffer_resource_from_addr( + arg_kv + fx.Int64(page) * i64_page_stride, + num_records_bytes=PAGE_BYTES, + ) + base = raw_base_s + (st * NW + wave) * STAGE_W + for h in range_constexpr(2): + _dma(kr, base + h * 1024, code_voff[h], 16) + _dma(kr, base + 2048, scale_voff, 4) + + raw_t = fx.logical_divide( + fx.make_view( + fx.recast_iter(fx.Int32, smem.raw.ptr), + fx.make_layout(RAW_SLOTS * NW * STAGE_W // 4, 1), + ), + fx.make_layout(4, 1), + ) + raw_d = smem.raw.ptr + + def read_raw(st): + """This lane's 8 code dwords and its scale dword.""" + b4 = (st * NW + wave) * (STAGE_W // 4) + out = [] + for h in range_constexpr(2): + r = fx.make_rmem_tensor(fx.make_layout(4, 1), fx.Int32) + fx.copy( + fx.make_copy_atom(fx.UniversalCopy128b(), fx.Int32), + fx.slice(raw_t, (None, b4 // 4 + h * 64 + lane)), + r, + ) + v = Vec(r.load()) + out += [fx.Int32(v[i]) for i in range_constexpr(4)] + sc = fx.Int32( + fx.make_view( + fx.recast_iter(fx.Int32, raw_d), + fx.make_layout(RAW_SLOTS * NW * STAGE_W // 4, 1), + )[b4 + 512 + lane] + ) + return out + [sc] + + pg = [page_of(blk0 + i) for i in range_constexpr(2)] + for i in range_constexpr(2): + dma_raw(pg[i], i) + pg_next = page_of(blk0 + 2) + + lut_g = global_i32_ptr(arg_lut) + lut_l = smem.lut.ptr + for i in range_constexpr(2): + lut_l[tx * 2 + i] = fx.Int32(lut_g[tx * 2 + i]) + + # Rows past q_len * H read the next request's Q and are masked at + # the store. + rows = [row0 + wave * ROWS_PER_WAVE + ni * 16 + l16 for ni in range(NI)] + qpos = [prefix + r // H for r in rows] + # Q^T in the key's dim order (even dims, then odd dims per 8). + qf = [] + for ni in range_constexpr(NI): + qrow = (seq_start * H + rows[ni]) * ROW_BYTES + halves = [] + for h in range_constexpr(2): + d = Vec( + buffer_ops.buffer_load( + qr, + (qrow + h * 64 + q16 * 16) // 4, + vec_width=4, + dtype=fx.Int32, + ) + ) + d = [fx.Int32(d[i]) for i in range_constexpr(4)] + halves.append(key_order4(d)) + qf.append(pack8(halves[0], halves[1])) + + lds16 = fx.logical_divide( + fx.make_view( + fx.recast_iter(fx.Int32, smem.a.ptr), + fx.make_layout(LDS_BYTES // 4, 1), + ), + fx.make_layout(4, 1), + ) + lds_atom = fx.make_copy_atom(fx.UniversalCopy128b(), fx.Int32) + lut8 = fx.logical_divide( + fx.make_view( + fx.recast_iter(fx.Int32, smem.lut.ptr), fx.make_layout(512, 1) + ), + fx.make_layout(2, 1), + ) + lut_atom = fx.make_copy_atom(fx.UniversalCopy64b(), fx.Int32) + + def lds_load16(tile): + r = fx.make_rmem_tensor(fx.make_layout(4, 1), fx.Int32) + fx.copy(lds_atom, fx.slice(lds16, (None, tile)), r) + return r.load() + + def lds_store16(tile, vals): + r = fx.make_rmem_tensor(fx.make_layout(4, 1), fx.Int32) + r.store(Vec.from_elements(vals, fx.Int32)) + fx.copy(lds_atom, r, fx.slice(lds16, (None, tile))) + + def lut_load(sbyte): + r = fx.make_rmem_tensor(fx.make_layout(2, 1), fx.Int32) + fx.copy(lut_atom, fx.slice(lut8, (None, sbyte)), r) + v = Vec(r.load()) + return fx.Int32(v[0]), fx.Int32(v[1]) + + # 16 B column c of key row t sits at c ^ ((t >> 1) & 7). + t_row = wave * 32 + (lane >> 1) + hh = lane & 1 + wr_base = t_row * RS_T + wr_sw = (t_row >> 1) & 7 + + def dq_tables(raw): + sc = raw[8] + return [ + lut_load((sc >> (8 * g)) & 0xFF) for g in range_constexpr(4) + ] + + def dq_step(raw, tabs, dslot, k, pend): + """Code dword k -> 8 keys; every second one stores 16 B.""" + lo, hi = dequant8(raw[k], *tabs[k // 2]) + if const_expr(k % 2 == 0): + return [lo, hi] + col = (hh * 4 + k // 2) ^ wr_sw + lds_store16(dslot * SLOT_T + wr_base + col, pend + [lo, hi]) + return [] + + zero4 = fx.Vector.filled(4, 0.0, fx.Float32) + neg_inf = fx.Float32(float("-inf")) + rd_row = l16 * RS_T + rd_col = [q16 ^ (l16 >> 1), (4 + q16) ^ (l16 >> 1)] + + def compute_block(slot, blk, masked, st, dslot): + """This wave's scores of ``blk``; dequantizes the next block's + raw page ``st`` into key slot ``dslot`` on the way.""" + if const_expr(masked): + vis = [ + qpos[ni] - (blk * BLK + q16 * 4) + for ni in range_constexpr(NI) + ] + run = [neg_inf for _ in range(NI)] + raw = read_raw(st) + tabs = dq_tables(raw) + + def read_a(mt): + base = slot * SLOT_T + mt * 16 * RS_T + rd_row + return pack8( + lds_load16(base + rd_col[0]), lds_load16(base + rd_col[1]) + ) + + accs = [[None] * NI, [None] * NI] + + def issue(mt, a): + acc = accs[mt % 2] + for ni in range_constexpr(NI): + acc[ni] = mfma_fp8_16x16x128(a, qf[ni], zero4) + + def reduce(mt): + acc = accs[mt % 2] + for ni in range_constexpr(NI): + v = acc[ni] + for i in range_constexpr(4): + x = v[i] + if const_expr(masked): + x = (vis[ni] >= mt * 16 + i).select(x, neg_inf) + run[ni] = maxf_nn(run[ni], x) + + pend = [] + a_next = read_a(0) + for mt in range_constexpr(MT): + a = a_next + if const_expr(mt + 1 < MT): + a_next = read_a(mt + 1) + issue(mt, a) + if const_expr(mt >= 1): + reduce(mt - 1) + ks = DQ_AT.get(mt, ()) + for k in ks: + pend = dq_step(raw, tabs, dslot, k, pend) + n_valu = (16 if not masked else 48) + 10 * len(ks) + n_dsw = sum(k % 2 for k in ks) + for i in range_constexpr(NI): + fx.rocdl.sched_group_barrier(0x008, 1, 0) + fx.rocdl.sched_group_barrier( + 0x002, (n_valu + NI - 1) // NI, 0 + ) + if const_expr(i < 2): + fx.rocdl.sched_group_barrier(0x100, 1, 0) + if const_expr(i == 4 and n_dsw): + fx.rocdl.sched_group_barrier(0x200, n_dsw, 0) + fx.rocdl.sched_barrier(0) + reduce(MT - 1) + out = [] + for p in range_constexpr(NI // 2): + x, y = _xlane_max4_pair(run[2 * p], run[2 * p + 1]) + out += [x, y] + return out + + stage16 = fx.logical_divide( + fx.make_view( + fx.recast_iter(fx.Int32, smem.stage.ptr), + fx.make_layout(STAGE_T * 4, 1), + ), + fx.make_layout(4, 1), + ) + + def stage_tile(k, h): + return ((k * NW + wave) * 2 + h) * 64 + lane + + def store_group(g0, sc): + """Scores sc[j][ni] of blocks g0 .. g0 + 3, sentinels applied. + + Lane q16 = k stores rows 2k and 2k + 1. A group waits in LDS + unless it ends its SPAN piece or the segment; that one stores + the piece's staged groups and itself back to back. + """ + full = g0 + GROUP <= blk1 + pos = (g0 >> 2) & (SPAN - 1) + piece0 = g0 & ~(SPAN * GROUP - 1) + first = (piece0 < blk0).select( + (blk0 >> 2) & (SPAN - 1), fx.Int32(0) + ) + flush = (pos == SPAN - 1) | (g0 + GROUP >= blk1) + + def store_now(vals, off, valid): + """16 B per row, single dwords for a partial tail.""" + if full: + buffer_ops.buffer_store( + fx.Vector.from_elements(vals, fx.Float32), + sr, + off, + mask=valid, + ) + else: + for j in range_constexpr(GROUP): + buffer_ops.buffer_store( + vals[j], sr, off + j, mask=valid & (g0 + j < blk1) + ) + + def flush_piece(h, vals, off, valid): + for k in range_constexpr(SPAN - 1): + t = fx.make_rmem_tensor(fx.make_layout(4, 1), fx.Int32) + fx.copy( + lds_atom, fx.slice(stage16, (None, stage_tile(k, h))), t + ) + buffer_ops.buffer_store( + Vec(t.load()), + sr, + off - (pos - k) * GROUP, + mask=valid & (first <= k) & (pos > k), + ) + store_now(vals, off, valid) + + def stage_group(h, vals): + t = fx.make_rmem_tensor(fx.make_layout(4, 1), fx.Int32) + t.store(Vec.from_elements([bits(x) for x in vals], fx.Int32)) + fx.copy( + lds_atom, t, fx.slice(stage16, (None, stage_tile(pos, h))) + ) + + for h in range_constexpr(2): + row = rows[h] + vals = [sc[j][h] for j in range_constexpr(GROUP)] + for k in range_constexpr(1, NW): + is_k = q16 == k + row = is_k.select(rows[2 * k + h], row) + vals = [ + is_k.select(sc[j][2 * k + h], vals[j]) + for j in range_constexpr(GROUP) + ] + valid = row < q_rows + tok = row // H + nb_row = (prefix + tok) // BLK + 1 + for j in range_constexpr(GROUP): + blk = g0 + j + vals[j] = with_sentinels( + vals[j], blk, nb_row, i32_init, i32_local + ) + off = (row % H) * i32_hs + (seq_start + tok) * i32_S + g0 + if flush: + flush_piece(h, vals, off, valid) + else: + stage_group(h, vals) + + n_groups = (blk1 - blk0 + (GROUP - 1)) // GROUP + # Groups every row of the tile sees whole need no causal mask. + v = prefix + row0 // H - (BLK - 1) + last_full = (v < 0).select(fx.Int32(-1), v // BLK) + d = last_full - (GROUP - 1) - blk0 + nf = (d < 0).select(fx.Int32(0), d // GROUP + 1) + n_full = (nf < n_groups).select(nf, n_groups) + + # Prologue: block blk0 dequantized into slot 0. + fx.rocdl.s_waitcnt(vmcnt=0, lgkmcnt=0) + fx.gpu.barrier() + raw0 = read_raw(0) + tabs0 = dq_tables(raw0) + pend = [] + for k in range_constexpr(8): + pend = dq_step(raw0, tabs0, 0, k, pend) + fx.gpu.barrier() + + def group(g0, pg_next, masked): + """Blocks g0 .. g0 + 3: per block b, DMA block b + 2's page, + score b while dequantizing b + 1, then wait and barrier.""" + sc = [] + for j in range_constexpr(GROUP): + blk = g0 + j + dma_raw(pg_next, (j + 2) % RAW_SLOTS) + pg_next = page_of(blk + 3) + sc.append( + compute_block( + j % N_SLOTS, + blk, + masked, + (j + 1) % RAW_SLOTS, + (j + 1) % N_SLOTS, + ) + ) + fx.rocdl.s_waitcnt(vmcnt=0, lgkmcnt=0) + fx.gpu.barrier() + store_group(g0, sc) + return pg_next + + def one(st): + return fx.Int32(st[0] if isinstance(st, (list, tuple)) else st) + + for g, st in range( + fx.Index(0), fx.Index(n_full), fx.Index(1), init=[_ir(pg_next)] + ): + pgn = group(blk0 + fx.Int32(g) * GROUP, one(st), False) + res = yield [_ir(pgn)] + for g, st in range( + fx.Index(n_full), + fx.Index(n_groups), + fx.Index(1), + init=[_ir(one(res))], + ): + pgn = group(blk0 + fx.Int32(g) * GROUP, one(st), True) + res = yield [_ir(pgn)] + + @flyc.jit + def launch( + arg_q: fx.Int64, + arg_kv: fx.Int64, + arg_lut: fx.Int64, + arg_score: fx.Int64, + arg_bt: fx.Int64, + arg_cu: fx.Int64, + arg_seq: fx.Int64, + i64_page_stride: fx.Int64, + i32_bt_stride: fx.Int32, + i32_S: fx.Int32, + i32_nseg: fx.Int32, + i32_qt: fx.Int32, + i32_total_q: fx.Int32, + i32_nb: fx.Int32, + i32_init: fx.Int32, + i32_local: fx.Int32, + i32_hs: fx.Int32, + i32_grid: fx.Int32, + stream: fx.Stream, + ): + kernel( + arg_q, + arg_kv, + arg_lut, + arg_score, + arg_bt, + arg_cu, + arg_seq, + i64_page_stride, + i32_bt_stride, + i32_S, + i32_nseg, + i32_qt, + i32_total_q, + i32_nb, + i32_init, + i32_local, + i32_hs, + # Without the hint LLVM picks 264 VGPRs, one wave per SIMD. + value_attrs={"rocdl.waves_per_eu": 2}, + ).launch(grid=(fx.Int64(i32_grid), 1, 1), block=(64 * NW, 1, 1), stream=stream) + + launch.kernel_name = name + return launch diff --git a/vllm/models/minimax_m3/amd/ops/nvfp4_index_prefill/kernel_shared.py b/vllm/models/minimax_m3/amd/ops/nvfp4_index_prefill/kernel_shared.py new file mode 100644 index 000000000000..390dbc075c0f --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/nvfp4_index_prefill/kernel_shared.py @@ -0,0 +1,382 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""NVFP4 prefill index scorer for small work (FlyDSL, gfx950). + +The scores of ``kernel.py`` with one dequantized block per workgroup: a +workgroup is 4 waves x 32 MQ query rows x a segment of the causal window. Per +block, wave w dequantizes token tile w into e4m3 A fragments in LDS (double +buffered, one barrier per block) while the MFMAs of the previous block run; +every wave multiplies all four token tiles against its query rows with +v_mfma_f32_32x32x64_f8f6f4. Blocks before the wave's first query position skip +the causal mask in a loop of their own. +""" + +import flydsl.compiler as flyc +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import buffer_ops +from flydsl._mlir import ir as _mlir_ir +from flydsl._mlir.dialects import arith as _arith +from flydsl.expr import const_expr, range_constexpr +from flydsl.expr import rocdl as _rocdl +from flydsl.expr.typing import T +from flydsl.expr.typing import Vector as Vec + +from vllm.models.minimax_m3.amd.ops.flydsl_utils import ( + as_f32, + bits, + cvt_fp4x2_f16, + cvt_fp8x2_f16, + maxf_nn, + permlane_swap, +) +from vllm.models.minimax_m3.amd.ops.nvfp4_index_prefill.kernel import ( + BLK, + PAGE_BYTES, + PAGE_CODES, + D, + page_lookup, + score_resources, + segment_blocks, + tile_rows, + with_sentinels, +) + +NW = 4 +MQ_CHOICES = (1, 2) # 32-row query tiles per wave +TILES = BLK // 32 # 32-token tiles per block +KS = 2 # MFMA k-steps per key row +FL = 32 # fragment bytes per lane +FRAG_BYTES = TILES * KS * 64 * FL # one block's A fragments +RING = 4 # fragment reads in flight ahead of the MFMA + + +def _sat448_fp8x2(x): + """Clamp 2 x f16 to +-448; the hardware fp8 convert does not saturate.""" + fm = _mlir_ir.Attribute.parse("#arith.fastmath") + hi = fx.as_ir_value(fx.Vector.filled(2, 448.0, fx.Float16)) + lo = fx.as_ir_value(fx.Vector.filled(2, -448.0, fx.Float16)) + v = _arith.MaxNumFOp(fx.as_ir_value(x), lo, fastmath=fm).result + return _arith.MinNumFOp(v, hi, fastmath=fm).result + + +def _fp8_pair(w, sv): + """Code dword w x splat scale sv -> 2 dwords of e4m3.""" + out = [] + for h in range_constexpr(2): + p = fx.as_ir_value(fx.Vector.filled(2, 0, fx.Int16)) + for k in range_constexpr(2): + x = _sat448_fp8x2(cvt_fp4x2_f16(w, 2 * h + k) * sv) + p = fx.rocdl.cvt_scalef32_pk_fp8_f16( + Vec.make_type(2, fx.Int16), + p, + x, + fx.as_ir_value(fx.Float32(1.0)), + k == 1, + ) + out.append(fx.Int32(Vec(p).bitcast(fx.Int32)[0])) + return out + + +def _mfma_fp8_32x32x64(a8, b8, acc16): + """v_mfma_f32_32x32x64_f8f6f4 on e4m3; lane (r, h) gets + D[8 (i // 4) + 4 h + i % 4][r].""" + return Vec( + fx.rocdl.mfma_scale_f32_32x32x64_f8f6f4( + Vec.make_type(16, fx.Float32), [a8, b8, acc16, 0, 0, 0, 0, 0, 0] + ) + ) + + +def _xlane_max32(x): + """max(x[L], x[L ^ 32]).""" + a, b = permlane_swap(_rocdl.permlane32_swap, bits(x), bits(x)) + return maxf_nn(as_f32(a), as_f32(b)) + + +def tile_q(mq: int) -> int: + """Query rows per workgroup.""" + return NW * 32 * mq + + +def compile_score_prefill_shared(heads: int = 1, mq: int = 2): + """Build the scorer for 1, 2 or 4 index heads and ``mq`` 32-row query tiles + per wave.""" + assert heads in (1, 2, 4) and mq in MQ_CHOICES, (heads, mq) + H, MQ = heads, mq + ROWS_PER_WAVE = 32 * MQ + TILE_Q = tile_q(MQ) + name = f"m3_nvfp4_index_score_prefill_fp8_shared_tq{TILE_Q}_h{H}" + + @fx.struct + class Shared: + frag: fx.Array[fx.Uint8, 2 * FRAG_BYTES, 16] # A fragments of 2 blocks + + @flyc.kernel(name=name, known_block_size=[64 * NW, 1, 1]) + def kernel( + arg_q: fx.Int64, # [total_q, H, 128] e4m3 + arg_kv: fx.Int64, # [num_blocks, 128, 72] uint8 + arg_score: fx.Int64, # [H, total_q, S] fp32 + arg_bt: fx.Int64, # [batch, >= max_blocks] int32 + arg_cu: fx.Int64, # cu_seqlens_q [batch + 1] int32 + arg_seq: fx.Int64, # seq_lens [batch] int32 + i64_page_stride: fx.Int64, + i32_bt_stride: fx.Int32, + i32_S: fx.Int32, + i32_nseg: fx.Int32, + i32_qt: fx.Int32, # query tiles per request + i32_total_q: fx.Int32, + i32_nb: fx.Int32, + i32_init: fx.Int32, + i32_local: fx.Int32, + i32_hs: fx.Int32, # score head stride + ): + smem = fx.SharedAllocator().allocate(Shared).peek() + tx, pid = fx.thread_idx.x, fx.block_idx.x + lane = tx % 64 + wave = fx.Int32(fx.rocdl.readfirstlane(T.i32, tx // 64)) + r32, h = lane % 32, lane // 32 + live, b, seg, seq_start, seq_len, prefix, q_rows, row0 = tile_rows( + pid, i32_qt, i32_nseg, i32_nb, arg_cu, arg_seq, H, TILE_Q + ) + if live: + nblk, blk0, blk1 = segment_blocks( + prefix, row0, seq_len, seg, i32_nseg, H, TILE_Q, 1 + ) + if blk0 < blk1: + qr, sr = score_resources( + arg_q, arg_score, i32_total_q, i32_hs, i32_S, H + ) + page_of = page_lookup(arg_bt, b * i32_bt_stride, blk1) + + tok = wave * 32 + r32 + + def load_raw(blk): + """Token tok's codes and scales of dims 64 h .. +63; zeros past + the segment.""" + ok = blk < blk1 + kr = buffer_ops.create_buffer_resource_from_addr( + arg_kv + fx.Int64(page_of(blk)) * i64_page_stride, + num_records_bytes=PAGE_BYTES, + ) + w = [] + for i in range_constexpr(2): + v = Vec( + buffer_ops.buffer_load( + kr, + (tok * 64 + h * 32 + i * 16) // 4, + vec_width=4, + dtype=fx.Int32, + mask=ok, + ) + ) + w += [fx.Int32(v[e]) for e in range_constexpr(4)] + sc = fx.Int32( + buffer_ops.buffer_load( + kr, + (PAGE_CODES + tok * 8 + h * 4) // 4, + vec_width=1, + dtype=fx.Int32, + mask=ok, + ) + ) + return w + [sc] + + frag128 = fx.logical_divide( + fx.make_view( + fx.recast_iter(fx.Int32, smem.frag.ptr), + fx.make_layout(2 * FRAG_BYTES // 4, 1), + ), + fx.make_layout(4, 1), + ) + atom16 = fx.make_copy_atom(fx.UniversalCopy128b(), fx.Int32) + + def frag_slot(buf, n, s, half=0): + return ( + buf * (FRAG_BYTES // 16) + + ((n * KS + s) * 64 + lane) * (FL // 16) + + half + ) + + def store16(words, slot): + r = fx.make_rmem_tensor(fx.make_layout(4, 1), fx.Int32) + r.store(Vec.from_elements(words, fx.Int32)) + fx.copy(atom16, r, fx.slice(frag128, (None, slot))) + + def load16(slot): + r = fx.make_rmem_tensor(fx.make_layout(4, 1), fx.Int32) + fx.copy(atom16, fx.slice(frag128, (None, slot)), r) + return [fx.Int32(x) for x in Vec(r.load())] + + def dequant_step(raw, buf, s): + """K-step s (dims 64 h + 32 s .. +31) of this wave's tile.""" + scl = cvt_fp8x2_f16(raw[8], s == 1) + sv = [ + Vec.from_elements([scl[g], scl[g]], fx.Float16) for g in (0, 1) + ] + k = [] + for e in range_constexpr(4): + k += _fp8_pair(raw[4 * s + e], sv[e // 2]) + store16(k[:4], frag_slot(buf, wave, s, 0)) + store16(k[4:], frag_slot(buf, wave, s, 1)) + + def read_frag(buf, n, s): + return Vec.from_elements( + load16(frag_slot(buf, n, s, 0)) + + load16(frag_slot(buf, n, s, 1)), + fx.Int32, + ) + + # Rows past q_len * H are zero and never stored. + rows = [row0 + wave * ROWS_PER_WAVE + 32 * m + r32 for m in range(MQ)] + qpos = [prefix + rw // H for rw in rows] + qf = [] + for m in range_constexpr(MQ): + qrow = (seq_start * H + rows[m]) * D + d = [] + for i in range_constexpr(4): + v = Vec( + buffer_ops.buffer_load( + qr, + (qrow + h * 64 + i * 16) // 4, + vec_width=4, + dtype=fx.Int32, + mask=rows[m] < q_rows, + ) + ) + d += [fx.Int32(v[e]) for e in range_constexpr(4)] + qf.append( + [ + Vec.from_elements(d[8 * s : 8 * s + 8], fx.Int32) + for s in range(KS) + ] + ) + + zero16 = fx.Vector.filled(16, 0.0, fx.Float32) + neg_inf = fx.Float32(float("-inf")) + st_tok = [rw // H for rw in rows] + st_out = [ + (rw % H) * i32_hs + (seq_start + t) * i32_S + for rw, t in zip(rows, st_tok) + ] + st_nb = [qp // BLK + 1 for qp in qpos] + qpos_min = prefix + (row0 + wave * ROWS_PER_WAVE) // H + + def max16(acc): + v = acc[0] + for i in range_constexpr(1, 16): + v = maxf_nn(v, acc[i]) + return v + + def max16_masked(acc, lim): + v = neg_inf + for i in range_constexpr(16): + x = (lim >= 8 * (i // 4) + i % 4).select(acc[i], neg_inf) + v = maxf_nn(v, x) + return v + + def block(blk, buf, raw_next, masked): + """Scores of block blk for this wave's rows; dequantizes + raw_next into the other buffer meanwhile.""" + runs = [neg_inf] * MQ + jobs = [(n, s) for n in range(TILES) for s in range(KS)] + ring = [None] * len(jobs) + for j in range_constexpr(RING - 1): + ring[j] = read_frag(buf, *jobs[j]) + for n in range_constexpr(TILES): + accs = [zero16] * MQ + for s in range_constexpr(KS): + j = n * KS + s + if const_expr(j + RING - 1 < len(jobs)): + ring[j + RING - 1] = read_frag(buf, *jobs[j + RING - 1]) + if const_expr(j % TILES == 0): + dequant_step(raw_next, 1 - buf, j // TILES) + for m in range_constexpr(MQ): + accs[m] = _mfma_fp8_32x32x64(ring[j], qf[m][s], accs[m]) + base = blk * BLK + 32 * n + 4 * h + for m in range_constexpr(MQ): + if const_expr(masked): + mx = max16_masked(accs[m], qpos[m] - base) + else: + mx = max16(accs[m]) + runs[m] = maxf_nn(runs[m], mx) + for m in range_constexpr(MQ): + v = _xlane_max32(runs[m]) + v = with_sentinels(v, blk, st_nb[m], i32_init, i32_local) + buffer_ops.buffer_store( + v, + sr, + st_out[m] + blk, + mask=(rows[m] < q_rows) & (h == 0), + ) + + raw0 = load_raw(blk0) + for s in range_constexpr(KS): + dequant_step(raw0, 0, s) + raw = load_raw(blk0 + 1) + fx.gpu.barrier() + + # Blocks below dsplit need no causal mask. Two loops rather than a + # branch per block keep the wave within 256 registers; waves split + # at different blocks but pass the same barriers. + dfirst = (qpos_min + 1) // BLK + dsplit = (dfirst < blk0).select(blk0, dfirst) + dsplit = (dsplit > blk1).select(blk1, dsplit) + blk = blk0 + buf = fx.Int32(0) + while blk < dsplit: + nxt = load_raw(blk + 2) + block(blk, buf, raw, False) + raw = nxt + fx.gpu.barrier() + blk = blk + 1 + buf = 1 - buf + while blk < blk1: + nxt = load_raw(blk + 2) + block(blk, buf, raw, True) + raw = nxt + fx.gpu.barrier() + blk = blk + 1 + buf = 1 - buf + + @flyc.jit + def launch( + arg_q: fx.Int64, + arg_kv: fx.Int64, + arg_score: fx.Int64, + arg_bt: fx.Int64, + arg_cu: fx.Int64, + arg_seq: fx.Int64, + i64_page_stride: fx.Int64, + i32_bt_stride: fx.Int32, + i32_S: fx.Int32, + i32_nseg: fx.Int32, + i32_qt: fx.Int32, + i32_total_q: fx.Int32, + i32_nb: fx.Int32, + i32_init: fx.Int32, + i32_local: fx.Int32, + i32_hs: fx.Int32, + i32_grid: fx.Int32, + stream: fx.Stream, + ): + kernel( + arg_q, + arg_kv, + arg_score, + arg_bt, + arg_cu, + arg_seq, + i64_page_stride, + i32_bt_stride, + i32_S, + i32_nseg, + i32_qt, + i32_total_q, + i32_nb, + i32_init, + i32_local, + i32_hs, + ).launch(grid=(fx.Int64(i32_grid), 1, 1), block=(64 * NW, 1, 1), stream=stream) + + launch.kernel_name = name + return launch diff --git a/vllm/models/minimax_m3/amd/ops/nvfp4_prefill/__init__.py b/vllm/models/minimax_m3/amd/ops/nvfp4_prefill/__init__.py new file mode 100644 index 000000000000..208f01a7cb5e --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/nvfp4_prefill/__init__.py @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project diff --git a/vllm/models/minimax_m3/amd/ops/nvfp4_prefill/host.py b/vllm/models/minimax_m3/amd/ops/nvfp4_prefill/host.py new file mode 100644 index 000000000000..27052b662673 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/nvfp4_prefill/host.py @@ -0,0 +1,102 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Launch wrapper of the FlyDSL NVFP4 sparse prefill attention.""" + +import functools + +import numpy as np +import torch + +from vllm.models.minimax_m3.amd.ops.flydsl_utils import ( + LOG2E, + cu_count, + run_compiled, + unit_scale, +) + +from . import kernel as _kernel +from .kernel import BLK, HG, TOPK, D + + +@functools.cache +def _get_kernel(rounds: int): + return _kernel.compile_nvfp4_prefill_fp16(rounds) + + +def supports_nvfp4_sparse_prefill( + num_heads: int, num_kv_heads: int, head_dim: int, topk_blocks: int, block_size: int +) -> bool: + from vllm.platforms.rocm import on_gfx950 + + return ( + on_gfx950() + and head_dim == D + and num_heads == num_kv_heads * HG + and topk_blocks == TOPK + and block_size == BLK + ) + + +def minimax_m3_nvfp4_sparse_prefill( + q: torch.Tensor, # [T, H, 128] bf16 + kv_cache: torch.Tensor, # [pages, 2 * Hkv, 128, 72] uint8 + topk: torch.Tensor, # [Hkv, T, 16] int32 logical blocks, -1 = none + block_table: torch.Tensor, # [reqs, max_blocks] int32 + query_req_id: torch.Tensor, # [T] int32 + query_abs_pos: torch.Tensor, # [T] int32 + num_kv_heads: int, + sm_scale: float, + out: torch.Tensor, # [T, H, 128] bf16 + k_scale: torch.Tensor | None = None, + v_scale: torch.Tensor | None = None, +) -> None: + """Token t attends to the causal tokens of its ``topk`` blocks.""" + n_tok, n_heads, head_dim = q.shape + if n_tok == 0: + return + assert head_dim == D and n_heads == num_kv_heads * HG + assert q.dtype == torch.bfloat16 and out.dtype == torch.bfloat16 + assert out.shape == q.shape + assert q.is_contiguous() and out.is_contiguous() + assert kv_cache.dtype == torch.uint8 and tuple(kv_cache.shape[1:]) == ( + 2 * num_kv_heads, + BLK, + 72, + ) + assert kv_cache.stride(1) == BLK * 72 and kv_cache.stride(3) == 1 + assert topk.dtype == torch.int32 and tuple(topk.shape) == ( + num_kv_heads, + n_tok, + TOPK, + ) + assert topk.stride(2) == 1 and topk.stride(1) == TOPK + for t in (block_table, query_req_id, query_abs_pos): + assert t.dtype == torch.int32 and t.stride(-1) == 1 + assert kv_cache.stride(0) < 2**31 + unit = unit_scale(q.device) + ks = unit if k_scale is None else k_scale + vs = unit if v_scale is None else v_scale + c = float(np.float32(sm_scale) * np.float32(LOG2E)) + # Up to one workgroup per CU the one-round combine is ~1 us faster. + n_wg = (n_tok + 3) // 4 * num_kv_heads + rounds = 2 if n_wg > cu_count(q.device) else 1 + run_compiled( + _get_kernel(rounds), + q.data_ptr(), + kv_cache.data_ptr(), + topk.data_ptr(), + block_table.data_ptr(), + query_req_id.data_ptr(), + query_abs_pos.data_ptr(), + out.data_ptr(), + ks.data_ptr(), + vs.data_ptr(), + n_tok, + n_heads, + num_kv_heads, + topk.stride(0), + block_table.stride(0), + kv_cache.stride(0), + c, + torch.cuda.current_stream(q.device), + ) diff --git a/vllm/models/minimax_m3/amd/ops/nvfp4_prefill/kernel.py b/vllm/models/minimax_m3/amd/ops/nvfp4_prefill/kernel.py new file mode 100644 index 000000000000..bedf654f12c4 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/nvfp4_prefill/kernel.py @@ -0,0 +1,507 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""NVFP4 sparse prefill attention for MiniMax-M3 (FlyDSL, gfx950). + +A workgroup takes 4 query tokens x the 16 query heads of one KV head and walks +the union of the pages they selected. K and V are the exact e2m1 x e4m3 +products in fp16; Q and P are fp16; scores, softmax and accumulation are fp32; +the output is bf16. +""" + +import flydsl.compiler as flyc +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import buffer_ops +from flydsl.expr import const_expr, range_constexpr +from flydsl.expr.typing import T +from flydsl.expr.typing import Vector as Vec + +from vllm.models.minimax_m3.amd.ops.flydsl_utils import ( + cvt_fp4x2_f16, + cvt_fp8x2_f16, + exp2, + global_i32_ptr, + maxf_nn, + mfma_16x16x32, + pk_bf16, + pk_f16, + xlane4, +) + +BLK = 128 # tokens per page +D = 128 +HG = 16 # query heads per KV head (the MFMA N dimension) +NW = 4 +KPW = BLK // NW # keys per wave +TOK_PER_WG = 4 +TOPK = 16 +MAXU = TOK_PER_WG * TOPK # union capacity: one lane per (token, slot) +DATA_B = BLK * D // 2 # e2m1 bytes per head per side +SCALE_B = BLK * D // 16 # e4m3 scale bytes per head per side +NDT = D // 16 # d-tiles of O^T +NKS = D // 32 # k-steps of S^T +RAW = 2 * 4 + 1 + 8 + 2 # NVFP4 dwords a lane loads per page +Q_ROW = D * 2 // 16 + 1 # 16 B LDS tiles per Q^T row, padded by one + + +def _bf16_to_f16(v): + return Vec(v).bitcast(fx.BFloat16).to(fx.Float32).to(fx.Float16).bitcast(fx.Int32) + + +def kv_lane_loader(arg_cache, page_bytes, kvh, hkv, w, n, g): + """The loader of this lane's NVFP4 K/V dwords of a page. + + S^T tile st row r is key 32 w + 8 (r // 4) + 4 st + r % 4, so lane + (n, g)'s P^T / V^T key slots are keys 32 w + 8 g + j. + """ + side_b = hkv * (DATA_B + SCALE_B) + k_data = kvh * DATA_B + k_scl = hkv * DATA_B + kvh * SCALE_B + v_data = side_b + kvh * DATA_B + v_scl = side_b + hkv * DATA_B + kvh * SCALE_B + k_rows = [w * KPW + 8 * (n // 4) + 4 * st + n % 4 for st in range_constexpr(2)] + k_load = [(k_data + r * (D // 2) + g * 16) // 4 for r in k_rows] + k_scale_load = (k_scl + ((w * 4 + g) * 16 + n) * 4) // 4 + v_load = (v_data + ((w * KPW + 8 * g) // 8 * 16 + n) * 32) // 4 + v_scale_load = (v_scl + (n // 2) * BLK + w * KPW + 8 * g) // 4 + + def load(page): + """This lane's RAW NVFP4 dwords of ``page``.""" + pr = buffer_ops.create_buffer_resource_from_addr( + arg_cache + fx.Int64(page) * fx.Int64(page_bytes), + num_records_bytes=page_bytes, + ) + raw = [] + for st in range_constexpr(2): + kd = fx.Vector( + buffer_ops.buffer_load(pr, k_load[st], vec_width=4, dtype=fx.Int32) + ) + raw += [kd[i] for i in range_constexpr(4)] + raw.append( + fx.Int32( + buffer_ops.buffer_load(pr, k_scale_load, vec_width=1, dtype=fx.Int32) + ) + ) + for h in range_constexpr(2): + vd = fx.Vector( + buffer_ops.buffer_load(pr, v_load + 4 * h, vec_width=4, dtype=fx.Int32) + ) + raw += [vd[i] for i in range_constexpr(4)] + vs = fx.Vector( + buffer_ops.buffer_load(pr, v_scale_load, vec_width=2, dtype=fx.Int32) + ) + raw += [vs[i] for i in range_constexpr(2)] + return raw + + return load + + +def compile_nvfp4_prefill_fp16(rounds: int = 2): + """Build the prefill kernel. + + Args: + rounds: rounds of the cross-wave combine. 2 halves its LDS so two + workgroups share a CU; 1 keeps Q^T in registers and combines all + tokens at once (grids of at most one workgroup per CU). + + """ + assert rounds in (1, 2) + tpr = TOK_PER_WG // rounds # tokens per combine round + wpe = rounds # waves per SIMD + name = f"m3_nvfp4_sparse_prefill_fp16matched_tq{TOK_PER_WG}_ksplit" + if rounds == 1: + name += "_r1" + + @fx.struct + class Shared: + # Q^T during the page loop, then the partial O per (wave, token, d-tile, + # lane) in 16 B tiles; (max, sum) per (wave, token, lane). + o: fx.Array[fx.Int32, NW * tpr * NDT * 64 * 4, 16] + ml: fx.Array[fx.Float32, NW * TOK_PER_WG * 2 * 64] + + @flyc.kernel(name=name, known_block_size=[64 * NW, 1, 1]) + def kernel( + arg_q: fx.Int64, # [T, H, 128] bf16 + arg_cache: fx.Int64, # [pages, 2 * Hkv, 128, 72] uint8 + arg_topk: fx.Int64, # [Hkv, T, 16] int32 logical blocks, -1 = none + arg_bt: fx.Int64, # [reqs, stride] int32 + arg_req: fx.Int64, # [T] int32 + arg_pos: fx.Int64, # [T] int32 + arg_out: fx.Int64, # [T, H, 128] bf16 + arg_ks: fx.Int64, # fp32 global K scale + arg_vs: fx.Int64, # fp32 global V scale + i32_T: fx.Int32, + i32_H: fx.Int32, + i32_hkv: fx.Int32, + i32_topk_hs: fx.Int32, # topk stride over KV heads + i32_bt_s: fx.Int32, + i32_page_byte: fx.Int32, + f32_c: fx.Float32, # sm_scale * log2(e) + ): + smem = fx.SharedAllocator().allocate(Shared).peek() + tx = fx.thread_idx.x + bidx, kvh = fx.block_idx.x, fx.block_idx.y + lane = tx % 64 + w = fx.Int32(fx.rocdl.readfirstlane(T.i32, tx // 64)) + n, g = lane % 16, lane // 16 + topk = global_i32_ptr(arg_topk) + bt = global_i32_ptr(arg_bt) + req_p = global_i32_ptr(arg_req) + pos_p = global_i32_ptr(arg_pos) + f32p = fx.PointerType.get( + T.f32, address_space=fx.AddressSpace.Global, alignment=4 + ) + c = f32_c * fx.Float32(fx.inttoptr(f32p, fx.Int64(arg_ks))[0]) + v_scale = fx.Float32(fx.inttoptr(f32p, fx.Int64(arg_vs))[0]) + neg_inf = fx.Float32(float("-inf")) + topk_base = kvh * i32_topk_hs + + lds = fx.logical_divide( + fx.make_view( + fx.recast_iter(fx.Int32, smem.o.ptr), + fx.make_layout(NW * tpr * NDT * 64 * 4, 1), + ), + fx.make_layout(4, 1), + ) + lds_atom = fx.make_copy_atom(fx.UniversalCopy128b(), fx.Int32) + qr = buffer_ops.create_buffer_resource_from_addr( + arg_q, num_records_bytes=fx.Int64(i32_T) * fx.Int64(i32_H) * (D * 2) + ) + if const_expr(rounds == 2): + # Q^T in LDS; thread (token, head, quarter) stages 64 B. + tq, hq, qq = tx // 64, (tx // 4) % HG, tx % 4 + tok_q = bidx * TOK_PER_WG + tq + tok_q = (tok_q < i32_T).select(tok_q, fx.Int32(0)) + q_src = (tok_q * i32_H + kvh * HG + hq) * (D // 2) + qq * 16 + for i in range_constexpr(4): + r = fx.make_rmem_tensor(fx.make_layout(4, 1), fx.Int32) + q4 = buffer_ops.buffer_load( + qr, q_src + 4 * i, vec_width=4, dtype=fx.Int32 + ) + r.store(_bf16_to_f16(q4)) + q_tile = (tq * HG + hq) * Q_ROW + qq * 4 + i + fx.copy(lds_atom, r, fx.slice(lds, (None, q_tile))) + + def q_frags(t): + """Token t's Q^T, one B operand per k-step.""" + if const_expr(rounds == 1): + return q_regs[t] + out = [] + for ks in range_constexpr(NKS): + r = fx.make_rmem_tensor(fx.make_layout(4, 1), fx.Int32) + q_tile = (t * HG + n) * Q_ROW + g * 4 + ks + fx.copy(lds_atom, fx.slice(lds, (None, q_tile)), r) + out.append(Vec(r.load())) + return out + + # Per token: the page of its own block and its causal limit. + diag, lim, q_regs = [], [], [] + for t in range_constexpr(TOK_PER_WG): + tok = bidx * TOK_PER_WG + t + ok = tok < i32_T + tc = ok.select(tok, fx.Int32(0)) + pos = fx.Int32(fx.rocdl.readfirstlane(T.i32, fx.Int32(pos_p[tc]))) + req = fx.Int32(fx.rocdl.readfirstlane(T.i32, fx.Int32(req_p[tc]))) + diag.append( + fx.Int32( + fx.rocdl.readfirstlane( + T.i32, fx.Int32(bt[req * i32_bt_s + pos // BLK]) + ) + ) + ) + lim.append(pos % BLK - w * KPW) + if const_expr(rounds == 1): + q_row = (tc * i32_H + kvh * HG + n) * (D // 2) + g * 16 + q_regs.append( + [ + _bf16_to_f16( + buffer_ops.buffer_load( + qr, q_row + ks * 4, vec_width=4, dtype=fx.Int32 + ) + ) + for ks in range_constexpr(NKS) + ] + ) + + load_page = kv_lane_loader(arg_cache, i32_page_byte, kvh, i32_hkv, w, n, g) + + # Lane (token lane // 16, slot lane % 16): the page it selected, -1 none. + lane_tok = bidx * TOK_PER_WG + lane // TOPK + lane_tok_ok = lane_tok < i32_T + lane_tok_clamped = lane_tok_ok.select(lane_tok, fx.Int32(0)) + blk = fx.Int32(topk[topk_base + lane_tok_clamped * TOPK + lane % TOPK]) + lane_blk_ok = lane_tok_ok & (blk >= 0) + lane_page = fx.Int32( + bt[ + fx.Int32(req_p[lane_tok_clamped]) * i32_bt_s + + lane_blk_ok.select(blk, fx.Int32(0)) + ] + ) + lane_page = lane_blk_ok.select(lane_page, fx.Int32(-1)) + # The union's first page is the lowest valid lane's: load it before the + # dedup runs. + valid = fx.Int64(fx.rocdl.ballot(T.i64, lane_page >= 0)) + first = (valid != fx.Int64(0)).select( + fx.Int32(fx.math.cttz(valid).to(fx.Int32)), fx.Int32(0) + ) + + def page_at(mask): + """Page of the lowest lane left in ``mask``, the first page when empty.""" + idx = (mask != fx.Int64(0)).select( + fx.Int32(fx.math.cttz(mask).to(fx.Int32)), first + ) + pg = fx.Int32(fx.rocdl.readlane(T.i32, lane_page, idx)) + return (pg >= 0).select(pg, fx.Int32(0)) + + raw0 = load_page(page_at(valid)) + fx.rocdl.sched_barrier(0) + # Union: the first lane of each distinct page. + n_dup = fx.Int32(0) + for j in range_constexpr(MAXU - 1): + pj = fx.Int32(fx.rocdl.readlane(T.i32, lane_page, j)) + n_dup = n_dup + ((lane_page == pj) & (lane > j)).select( + fx.Int32(1), fx.Int32(0) + ) + umask = fx.Int64(fx.rocdl.ballot(T.i64, (lane_page >= 0) & (n_dup == 0))) + n_u = fx.Int32(fx.math.ctpop(umask).to(fx.Int32)) + + def dequant(raw): + """K frags kf[st][ks] and V^T frags vf[dt] of a page in fp16.""" + kf = [] + for st in range_constexpr(2): + ksc = cvt_fp8x2_f16(raw[8], st == 1) + row = [] + for ks in range_constexpr(NKS): + sv = Vec.from_elements([ksc[ks // 2], ksc[ks // 2]], fx.Float16) + row.append( + Vec.from_elements( + [ + (cvt_fp4x2_f16(raw[st * 4 + ks], i) * sv).bitcast( + fx.Int32 + )[0] + for i in range_constexpr(4) + ], + fx.Int32, + ) + ) + kf.append(row) + vs = [] + for h in range_constexpr(2): + vs += [ + cvt_fp8x2_f16(raw[17 + h], False), + cvt_fp8x2_f16(raw[17 + h], True), + ] + # A V byte holds two consecutive keys: already the operand's fp16 pair. + vf = [ + Vec.from_elements( + [ + (cvt_fp4x2_f16(raw[9 + dt], i) * vs[i]).bitcast(fx.Int32)[0] + for i in range_constexpr(4) + ], + fx.Int32, + ) + for dt in range_constexpr(NDT) + ] + return kf, vf + + zero4 = Vec.filled(4, 0.0, fx.Float32) + key_off = [ + 8 * g + 4 * st + e for st in range_constexpr(2) for e in range_constexpr(4) + ] + if const_expr(rounds == 2): + fx.gpu.barrier() # Q^T staged + # Iteration u dequantizes page u and loads page u + 1. + init = [umask] + init += [neg_inf for _ in range_constexpr(TOK_PER_WG)] + [ + fx.Float32(0.0) for _ in range_constexpr(TOK_PER_WG) + ] + init += [zero4 for _ in range_constexpr(TOK_PER_WG * NDT)] + init += raw0 + n_st = 1 + 2 * TOK_PER_WG + TOK_PER_WG * NDT + results = init + for u, st_ in range( # type: ignore[call-overload] + fx.Index(0), + fx.Index(n_u), + fx.Index(1), + init=[fx.as_ir_value(x) for x in init], + ): + rem = fx.Int64(st_[0]) + m = [fx.Float32(st_[1 + t]) for t in range_constexpr(TOK_PER_WG)] + l_run = [ + fx.Float32(st_[1 + TOK_PER_WG + t]) for t in range_constexpr(TOK_PER_WG) + ] + o = [ + [ + Vec(st_[1 + 2 * TOK_PER_WG + t * NDT + dt]) + for dt in range_constexpr(NDT) + ] + for t in range_constexpr(TOK_PER_WG) + ] + raw = [fx.Int32(st_[n_st + i]) for i in range_constexpr(RAW)] + page = page_at(rem) + rem = rem & (rem - fx.Int64(1)) + raw_next = load_page(page_at(rem)) + kf, vf = dequant(raw) + hits = fx.Int64(fx.rocdl.ballot(T.i64, lane_page == page)) + for t in range_constexpr(TOK_PER_WG): + m_t, l_t, o_t = m[t], l_run[t], o[t] + if (hits.shrui(fx.Int64(TOPK * t)) & fx.Int64(0xFFFF)) != fx.Int64(0): + qf = q_frags(t) + a = [] + for st in range_constexpr(2): + acc = zero4 + for ks in range_constexpr(NKS): + acc = mfma_16x16x32(kf[st][ks], qf[ks], acc, True) + a += [acc[e] for e in range_constexpr(4)] + if page == diag[t]: + a = [ + (key_off[i] <= lim[t]).select(a[i], neg_inf) + for i in range_constexpr(8) + ] + mx = a[0] + for i in range_constexpr(1, 8): + mx = maxf_nn(mx, a[i]) + # The running max is kept in scaled units (c > 0). + m_new = maxf_nn(m_t, xlane4(mx, maxf_nn) * c) + m_use = (m_new == neg_inf).select(fx.Float32(0.0), m_new) + alpha = exp2(m_t - m_use) + p = [exp2(fx.math.fma(x, c, -m_use)) for x in a] + ps = p[0] + for i in range_constexpr(1, 8): + ps = ps + p[i] + l_t = l_t * alpha + ps + pf = Vec.from_elements( + [pk_f16(p[2 * j], p[2 * j + 1]) for j in range_constexpr(4)], + fx.Int32, + ) + # alpha is exactly 1 unless some row's max grew. + if fx.Int64(fx.rocdl.ballot(T.i64, m_new != m_t)) != fx.Int64(0): + av = Vec.filled(4, alpha, fx.Float32) + o_t = [x * av for x in o_t] + o_t = [ + mfma_16x16x32(vf[dt], pf, o_t[dt], True) + for dt in range_constexpr(NDT) + ] + m_t = m_new + m[t], l_run[t], o[t] = m_t, l_t, o_t + state = ( + [rem] + m + l_run + [x for token_out in o for x in token_out] + raw_next + ) + results = yield [fx.as_ir_value(x) for x in state] + + # Combine the waves' partials, tpr tokens per round; wave w finalizes + # token w in round w // tpr. + ml = smem.ml.ptr + if const_expr(rounds == 2): + fx.gpu.barrier() + for t in range_constexpr(TOK_PER_WG): + ml[((w * TOK_PER_WG + t) * 2) * 64 + lane] = fx.Float32(results[1 + t]) + ml[((w * TOK_PER_WG + t) * 2 + 1) * 64 + lane] = fx.Float32( + results[1 + TOK_PER_WG + t] + ) + for rnd in range_constexpr(rounds): + for tt in range_constexpr(tpr): + for dt in range_constexpr(NDT): + r = fx.make_rmem_tensor(fx.make_layout(4, 1), fx.Int32) + ri = 1 + 2 * TOK_PER_WG + (tpr * rnd + tt) * NDT + dt + r.store(Vec(results[ri]).bitcast(fx.Int32)) + fx.copy( + lds_atom, + r, + fx.slice(lds, (None, ((w * tpr + tt) * NDT + dt) * 64 + lane)), + ) + fx.gpu.barrier() + if w // tpr == rnd: + t = w + ms = [ + fx.Float32(ml[((ww * TOK_PER_WG + t) * 2) * 64 + lane]) + for ww in range_constexpr(NW) + ] + big = ms[0] + for ww in range_constexpr(1, NW): + big = maxf_nn(big, ms[ww]) + big = (big == neg_inf).select(fx.Float32(0.0), big) + wt = [ + fx.Float32(fx.math.exp2(ms[ww] - big)) for ww in range_constexpr(NW) + ] + l_tot = fx.Float32(0.0) + for ww in range_constexpr(NW): + l_w = ml[((ww * TOK_PER_WG + t) * 2 + 1) * 64 + lane] + l_tot = l_tot + fx.Float32(l_w) * wt[ww] + l_tot = xlane4(l_tot, lambda a, b: a + b) + inv = (l_tot > fx.Float32(0.0)).select(v_scale / l_tot, fx.Float32(0.0)) + acc = [zero4 for _ in range_constexpr(NDT)] + for ww in range_constexpr(NW): + wv = Vec.filled(4, wt[ww], fx.Float32) + for dt in range_constexpr(NDT): + r = fx.make_rmem_tensor(fx.make_layout(4, 1), fx.Int32) + o_tile = ((ww * tpr + t - tpr * rnd) * NDT + dt) * 64 + lane + fx.copy(lds_atom, fx.slice(lds, (None, o_tile)), r) + acc[dt] = acc[dt] + Vec(r.load()).bitcast(fx.Float32) * wv + # Lane (n, g) holds dims [32 g, 32 g + 32) of head n in order. + tok = bidx * TOK_PER_WG + t + words = [ + [ + pk_bf16(acc[2 * j][e] * inv, acc[2 * j + 1][e] * inv) + for j in range_constexpr(4) + ] + for e in range_constexpr(4) + ] + outr = buffer_ops.create_buffer_resource_from_addr( + arg_out, + num_records_bytes=fx.Int64(i32_T) * fx.Int64(i32_H) * (D * 2), + ) + o_row = (tok * i32_H + kvh * HG + n) * (D // 2) + g * 16 + for e in range_constexpr(4): + val = Vec.from_elements(words[e], fx.Int32) + buffer_ops.buffer_store(val, outr, o_row + e * 4, mask=tok < i32_T) + fx.gpu.barrier() + + @flyc.jit + def launch( + arg_q: fx.Int64, + arg_cache: fx.Int64, + arg_topk: fx.Int64, + arg_bt: fx.Int64, + arg_req: fx.Int64, + arg_pos: fx.Int64, + arg_out: fx.Int64, + arg_ks: fx.Int64, + arg_vs: fx.Int64, + i32_T: fx.Int32, + i32_H: fx.Int32, + i32_hkv: fx.Int32, + i32_topk_hs: fx.Int32, + i32_bt_s: fx.Int32, + i32_page_b: fx.Int32, + f32_c: fx.Float32, + stream: fx.Stream, + ): + kernel( + arg_q, + arg_cache, + arg_topk, + arg_bt, + arg_req, + arg_pos, + arg_out, + arg_ks, + arg_vs, + i32_T, + i32_H, + i32_hkv, + i32_topk_hs, + i32_bt_s, + i32_page_b, + f32_c, + value_attrs={ + "rocdl.waves_per_eu": wpe, + "rocdl.flat_work_group_size": "256,256", + }, + ).launch( + grid=((i32_T + TOK_PER_WG - 1) // TOK_PER_WG, i32_hkv, 1), + block=(64 * NW, 1, 1), + stream=stream, + ) + + launch.kernel_name = name + return launch diff --git a/vllm/models/minimax_m3/amd/ops/nvfp4_sparse_decode/__init__.py b/vllm/models/minimax_m3/amd/ops/nvfp4_sparse_decode/__init__.py new file mode 100644 index 000000000000..208f01a7cb5e --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/nvfp4_sparse_decode/__init__.py @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project diff --git a/vllm/models/minimax_m3/amd/ops/nvfp4_sparse_decode/host.py b/vllm/models/minimax_m3/amd/ops/nvfp4_sparse_decode/host.py new file mode 100644 index 000000000000..d266c4e9d00c --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/nvfp4_sparse_decode/host.py @@ -0,0 +1,182 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Launch wrapper of the FlyDSL NVFP4 sparse decode.""" + +import ctypes +import functools + +import numpy as np +import torch + +from vllm.logger import init_logger +from vllm.models.minimax_m3.amd.ops.flydsl_utils import ( + LOG2E, + cu_count, + run_compiled, + unit_scale, +) +from vllm.models.minimax_m3.amd.ops.nvfp4_index_prefill.host import nvfp4_e4m3_lut + +from . import kernel as _kernel + +logger = init_logger(__name__) + +_HIP_DEVICE_ATTRIBUTE_NUMBER_OF_XCCS = 10018 +_SUPPORTED_XCD_COUNT = 8 + +MAX_SPLITS = 8 +# Launches with more (row, KV head) workgroup rows than this do not split. +MAX_SPLIT_ROWS = 1024 + + +@functools.cache +def _get_kernel(splits: int, topk: int, xcds: int): + return _kernel.compile_nvfp4_sparse_decode(splits, topk, xcds) + + +def _query_xcd_count(device_index: int) -> int: + """The device's XCD count, or zero when HIP cannot report it.""" + try: + get_attribute = ctypes.CDLL("libamdhip64.so").hipDeviceGetAttribute + get_attribute.argtypes = [ + ctypes.POINTER(ctypes.c_int), + ctypes.c_int, + ctypes.c_int, + ] + get_attribute.restype = ctypes.c_int + value = ctypes.c_int() + status = get_attribute( + ctypes.byref(value), _HIP_DEVICE_ATTRIBUTE_NUMBER_OF_XCCS, device_index + ) + return value.value if status == 0 and value.value > 0 else 0 + except (AttributeError, OSError, TypeError, ctypes.ArgumentError): + return 0 + + +@functools.cache +def _xcd_count(device_index: int) -> int: + """8 on gfx950 (the topology the XCD grid was tuned on), else 0.""" + from vllm.platforms.rocm import on_gfx950 + + queried = _query_xcd_count(device_index) + count = queried if on_gfx950() and queried == _SUPPORTED_XCD_COUNT else 0 + logger.info( + "MiniMax-M3 NVFP4 sparse decode: XCD-aware grid %s on device %d " + "(reported XCDs=%d)", + "on" if count else "off", + device_index, + queried, + ) + return count + + +@functools.cache +def _split_buffers(device: torch.device): + """Split partials and tickets; allocated in the warm-up, before capture.""" + part = torch.empty( + MAX_SPLIT_ROWS * MAX_SPLITS * 64 * _kernel.PART_F, + dtype=torch.float32, + device=device, + ) + return part, torch.zeros(MAX_SPLIT_ROWS, dtype=torch.int32, device=device) + + +def decode_splits(num_rows: int, num_blocks: int, cus: int) -> int: + """Splits of a row's blocks. + + The kernel is VALU-bound, so the cost model is rounds of workgroups per CU + times blocks per split plus about one block of fixed cost; the fewest splits + among the minima, each split at least two blocks. + """ + best_cost, best = None, 1 + for s in range(1, MAX_SPLITS + 1): + per = -(-num_blocks // s) + if s > 1 and per < 2: + break + cost = -(-(num_rows * s) // cus) * (per + 1) + if best_cost is None or cost < best_cost: + best_cost, best = cost, s + return best + + +def minimax_m3_nvfp4_sparse_decode_fly( + q: torch.Tensor, # [rows, H, 128] bf16 + kv_cache: torch.Tensor, # [pages, 2 * Hkv, 128, 72] uint8 + topk_idx: torch.Tensor, # [Hkv, rows, topk] int32 logical blocks, -1 = none + block_table: torch.Tensor, # [reqs, max_blocks] int32 + seq_lens: torch.Tensor, # [reqs] int32 + sm_scale: float, + output: torch.Tensor, # [rows, H, 128] bf16 + k_scale: torch.Tensor | None = None, + v_scale: torch.Tensor | None = None, + decode_query_len: int = 1, + splits: int | None = None, + xcd_count: int | None = None, +) -> None: + """Sparse decode attention over the NVFP4 K/V pages. + + Row i is query row i % decode_query_len of request i // decode_query_len + and attends to the tokens of its ``topk_idx`` blocks up to its position. + """ + rows, num_heads, head_dim = q.shape + if rows == 0: + return + num_kv_heads = kv_cache.shape[1] // 2 + topk = topk_idx.shape[-1] + assert rows == seq_lens.shape[0] * decode_query_len + assert head_dim == _kernel.D and num_heads == num_kv_heads * _kernel.HG + assert q.dtype == torch.bfloat16 and output.dtype == torch.bfloat16 + assert q.is_contiguous() and output.is_contiguous() + assert kv_cache.dtype == torch.uint8 and kv_cache.stride(1) == _kernel.BLK * 72 + assert kv_cache.stride(3) == 1 and kv_cache.stride(0) < 2**31 + assert topk_idx.dtype == torch.int32 and topk_idx.shape[0] == num_kv_heads + assert topk_idx.shape[1] >= rows + assert topk_idx.stride(2) == 1 and topk_idx.stride(1) == topk + for t in (block_table, seq_lens): + assert t.dtype == torch.int32 and t.stride(-1) == 1 + if xcd_count is None: + xcd_count = _xcd_count(q.device.index) + xcds = xcd_count if xcd_count and xcd_count > 1 else 0 + if xcds: + group = xcds * decode_query_len + grid_x = -(-rows // group) * group + else: + grid_x = rows + if splits is None: + wg_rows = grid_x * num_kv_heads + splits = ( + 1 + if wg_rows > MAX_SPLIT_ROWS + else decode_splits(rows * num_kv_heads, topk, cu_count(q.device)) + ) + assert splits == 1 or grid_x * num_kv_heads <= MAX_SPLIT_ROWS + part, cnt = _split_buffers(q.device) + unit = unit_scale(q.device) + ks = unit if k_scale is None else k_scale + vs = unit if v_scale is None else v_scale + c = float(np.float32(sm_scale) * np.float32(LOG2E)) + run_compiled( + _get_kernel(splits, topk, xcds), + q.data_ptr(), + kv_cache.data_ptr(), + topk_idx.data_ptr(), + block_table.data_ptr(), + seq_lens.data_ptr(), + output.data_ptr(), + ks.data_ptr(), + vs.data_ptr(), + nvfp4_e4m3_lut(q.device).data_ptr(), + part.data_ptr(), + cnt.data_ptr(), + part.numel() * 4, + rows, + decode_query_len, + num_heads, + num_kv_heads, + topk_idx.stride(0), + block_table.stride(0), + kv_cache.stride(0), + c, + grid_x, + torch.cuda.current_stream(q.device), + ) diff --git a/vllm/models/minimax_m3/amd/ops/nvfp4_sparse_decode/kernel.py b/vllm/models/minimax_m3/amd/ops/nvfp4_sparse_decode/kernel.py new file mode 100644 index 000000000000..96188426f25c --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/nvfp4_sparse_decode/kernel.py @@ -0,0 +1,576 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""NVFP4 sparse decode attention for MiniMax-M3 (FlyDSL, gfx950). + +One workgroup = one query row x the 16 query heads of one KV head x one split of +the row's top-k blocks. K and V are dequantized in registers to +e4m3_rn_satfinite(e2m1 x block scale), the values AITER's FP8 sparse PA reads, +and widened to bf16; scores and softmax are fp32, P is bf16. Wave w owns keys +[32 w, 32 w + 32) of every block: + + S^T = K Q^T v_mfma_f32_16x16x32_bf16, A = K, B = Q^T + O^T += V^T P^T A = V^T, B = P^T straight from the S^T accumulators + +The waves combine through LDS. With ``splits`` > 1 every split stores its +unnormalized partial and the last split of a row to arrive combines them in +split order, so the result does not depend on arrival order. +""" + +import flydsl.compiler as flyc +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import buffer_ops +from flydsl._mlir import ir as _ir +from flydsl._mlir.dialects import arith as _arith +from flydsl._mlir.dialects import llvm as _llvm +from flydsl.expr import const_expr, range_constexpr +from flydsl.expr.typing import T +from flydsl.expr.typing import Vector as Vec + +from vllm.models.minimax_m3.amd.ops.flydsl_utils import ( + PRELOAD_HINTS, + SC1, + as_f32, + bits, + cvt_fp4x2_f16, + cvt_fp8x2_f16, + exp2, + global_i32_ptr, + maxf_nn, + mfma_16x16x32, + perm, + pk_bf16, + xlane4, +) +from vllm.models.minimax_m3.amd.ops.nvfp4_prefill.kernel import ( + BLK, + HG, + KPW, + NDT, + NKS, + NW, + RAW, + D, + kv_lane_loader, +) + +PART_F = 36 # fp32 per (split, row, lane) partial: O (NDT x 4), max, sum, pad +SIGN4 = 0x80808080 - (1 << 32) +MAG4 = 0x07070707 + + +def _nnan(): + return _ir.Attribute.parse("#arith.fastmath") + + +def _bf16x2_e4m3(word, hi): + """E4M3 bytes 0, 1 (``hi``: 2, 3) of ``word`` -> one dword of two bf16.""" + return Vec( + fx.rocdl.cvt_scalef32_pk_bf16_fp8( + Vec.make_type(2, fx.BFloat16), + fx.as_ir_value(fx.Int32(word)), + fx.as_ir_value(fx.Float32(1.0)), + hi, + ) + ).bitcast(fx.Int32)[0] + + +def _k_bf16x8(codes, tab_lo, tab_hi): + """Eight K codes under one block scale -> four dwords of bf16 pairs. + + ``tab_lo`` / ``tab_hi`` hold the e4m3 keys of magnitudes 0-3 / 4-7 for the + block scale (``nvfp4_e4m3_lut``). + """ + even = perm(tab_hi, tab_lo, codes & MAG4) ^ ((codes << 4) & SIGN4) + odd = perm(tab_hi, tab_lo, (codes >> 4) & MAG4) ^ (codes & SIGN4) + lo = perm(odd, even, 0x05010400) + hi = perm(odd, even, 0x07030602) + return [ + _bf16x2_e4m3(lo, False), + _bf16x2_e4m3(lo, True), + _bf16x2_e4m3(hi, False), + _bf16x2_e4m3(hi, True), + ] + + +def _v_bf16x8(codes, scale_pairs): + """One V dword (eight keys of one dim) -> four dwords of bf16 pairs. + + The fp16 products are exact; they are clamped to +-448 and rounded once to + e4m3. + """ + big = Vec.filled(2, 448.0, fx.Float16) + small = Vec.filled(2, -448.0, fx.Float16) + f8 = [None, None] + for j in range_constexpr(4): + v = cvt_fp4x2_f16(codes, j) * scale_pairs[j] + v = _arith.MinNumFOp( + fx.as_ir_value(v), fx.as_ir_value(big), fastmath=_nnan() + ).result + v = _arith.MaxNumFOp(v, fx.as_ir_value(small), fastmath=_nnan()).result + old = Vec.filled(2, 0, fx.Int16) if j % 2 == 0 else f8[j // 2] + f8[j // 2] = Vec( + fx.rocdl.cvt_scalef32_pk_fp8_f16( + Vec.make_type(2, fx.Int16), + fx.as_ir_value(old), + v, + fx.as_ir_value(fx.Float32(1.0)), + j % 2 == 1, + ) + ) + out = [] + for h in range_constexpr(2): + word = f8[h].bitcast(fx.Int32)[0] + out += [_bf16x2_e4m3(word, False), _bf16x2_e4m3(word, True)] + return out + + +def _global_atomic_add(addr_i64, value): + """Relaxed agent-scope atomic add on a global i32; returns the old value.""" + return fx.Int32( + _llvm.AtomicRMWOp( + _llvm.AtomicBinOp.add, + global_i32_ptr(addr_i64).llvm_ptr, + fx.Int32(value).ir_value(), + _llvm.AtomicOrdering.monotonic, + syncscope="agent", + alignment=4, + ).result + ) + + +def compile_nvfp4_sparse_decode(splits: int = 1, topk: int = 16, xcds: int = 0): + """Build the decode kernel. + + Args: + splits: workgroups per (row, KV head), each over a contiguous share of + the row's blocks. + topk: top-k width (one lane per slot). + xcds: if > 0, workgroup w runs on XCD w % xcds and a request's rows and + a row's splits are placed on one XCD. + + """ + assert 1 <= topk <= 64 and splits >= 1 + SPLITS, TOPK, XCDS = splits, topk, xcds + # Split partials need sc1 unless all splits of a row run on one XCD. + PART_SCOPE = 0 if XCDS else SC1 + name = f"m3_nvfp4_sparse_decode_k{TOPK}_s{SPLITS}" + (f"_x{XCDS}" if XCDS else "") + + @fx.struct + class Shared: + o: fx.Array[fx.Int32, NW * NDT * 64 * 4, 16] + ml: fx.Array[fx.Float32, NW * 2 * 64] + lut: fx.Array[fx.Int32, 512] + ticket: fx.Array[fx.Int32, 4] + + @flyc.kernel(name=name, known_block_size=[64 * NW, 1, 1]) + def kernel( + i32_rows: fx.Int32, + i32_ql: fx.Int32, # rows per request + i32_topk_hs: fx.Int32, # topk stride over KV heads + i32_bt_s: fx.Int32, + i32_H: fx.Int32, + i32_hkv: fx.Int32, + arg_seq: fx.Int64, # [reqs] int32 + arg_topk: fx.Int64, # [Hkv, >= rows, TOPK] int32 blocks, -1 = none + arg_bt: fx.Int64, # [reqs, stride] int32 + arg_lut: fx.Int64, # [256] int64 K magnitude tables + arg_q: fx.Int64, # [rows, H, 128] bf16 + arg_cache: fx.Int64, # [pages, 2 * Hkv, 128, 72] uint8 + arg_ks: fx.Int64, # fp32 global K scale + arg_vs: fx.Int64, # fp32 global V scale + arg_out: fx.Int64, # [rows, H, 128] bf16 + arg_part: fx.Int64, # [grid rows * Hkv, S, 64, PART_F] fp32 + arg_cnt: fx.Int64, # [grid rows * Hkv] int32 tickets, zero + i64_part_bytes: fx.Int64, + i32_page_byte: fx.Int32, + f32_c: fx.Float32, # sm_scale * log2(e) + ): + smem = fx.SharedAllocator().allocate(Shared).peek() + tx = fx.thread_idx.x + bx, kvh = fx.block_idx.x, fx.block_idx.y + lane = tx % 64 + w = fx.Int32(fx.rocdl.readfirstlane(T.i32, tx // 64)) + n, g = lane % 16, lane // 16 + topk = global_i32_ptr(arg_topk) + bt = global_i32_ptr(arg_bt) + seq_p = global_i32_ptr(arg_seq) + f32p = fx.PointerType.get( + T.f32, address_space=fx.AddressSpace.Global, alignment=4 + ) + c = f32_c * fx.Float32(fx.inttoptr(f32p, fx.Int64(arg_ks))[0]) + v_scale = fx.Float32(fx.inttoptr(f32p, fx.Int64(arg_vs))[0]) + neg_inf = fx.Float32(float("-inf")) + lut_g = global_i32_ptr(arg_lut) + smem.lut.ptr[tx] = fx.Int32(lut_g[tx]) + smem.lut.ptr[tx + 256] = fx.Int32(lut_g[tx + 256]) + + if const_expr(XCDS > 0): + # grid.x is padded to XCDS x ql so a request's rows share an XCD. + xcd = bx % XCDS + slot = bx // XCDS + row = ((slot // i32_ql) * XCDS + xcd) * i32_ql + slot % i32_ql + else: + row = bx + row_ok = row < i32_rows + rowc = row_ok.select(row, fx.Int32(0)) + req = rowc // i32_ql + pos = fx.Int32(seq_p[req]) - i32_ql + rowc % i32_ql + # Padding rows (seq_len 0 or past i32_rows) see nothing. + pos = (row_ok & (pos >= 0)).select(pos, fx.Int32(-1)) + pos = fx.Int32(fx.rocdl.readfirstlane(T.i32, pos)) + req = fx.Int32(fx.rocdl.readfirstlane(T.i32, req)) + self_blk = (pos >= 0).select(pos // BLK, fx.Int32(-1)) + + # Lane = top-k slot. + slot_ok = lane < TOPK + blk = fx.Int32( + topk[kvh * i32_topk_hs + rowc * TOPK + slot_ok.select(lane, fx.Int32(0))] + ) + ok = slot_ok & (blk >= 0) & (blk <= self_blk) + page = fx.Int32(bt[req * i32_bt_s + ok.select(blk, fx.Int32(0))]) + page = ok.select(page, fx.Int32(-1)) + blk = ok.select(blk, fx.Int32(-1)) + vmask = fx.Int64(fx.rocdl.ballot(T.i64, ok)) + n_v = fx.Int32(fx.math.ctpop(vmask).to(fx.Int32)) + if const_expr(SPLITS > 1): + below = (fx.Int64(1) << fx.Int64(lane)) - fx.Int64(1) + rank = fx.Int32(fx.math.ctpop(vmask & below).to(fx.Int32)) + chunk = (n_v + (SPLITS - 1)) // SPLITS + lo = fx.block_idx.z * chunk + vmask = fx.Int64( + fx.rocdl.ballot(T.i64, ok & (rank >= lo) & (rank < lo + chunk)) + ) + n_v = fx.Int32(fx.math.ctpop(vmask).to(fx.Int32)) + + lim = pos % BLK - w * KPW + qr = buffer_ops.create_buffer_resource_from_addr( + arg_q, num_records_bytes=fx.Int64(i32_rows) * fx.Int64(i32_H) * (D * 2) + ) + q_row = (rowc * i32_H + kvh * HG + n) * (D // 2) + g * 16 + qf = [ + fx.Vector( + buffer_ops.buffer_load(qr, q_row + ks * 4, vec_width=4, dtype=fx.Int32) + ) + for ks in range_constexpr(NKS) + ] + + load_block = kv_lane_loader(arg_cache, i32_page_byte, kvh, i32_hkv, w, n, g) + + def dequant_k(raw): + kf = [] + for st in range_constexpr(2): + tabs = [] + for grp in range_constexpr(2): + sb = raw[8].shrui(fx.Int32(8 * (2 * st + grp))) & fx.Int32(0xFF) + tabs.append( + ( + fx.Int32(smem.lut.ptr[sb * 2]), + fx.Int32(smem.lut.ptr[sb * 2 + 1]), + ) + ) + kf.append( + [ + Vec.from_elements( + _k_bf16x8(raw[st * 4 + ks], *tabs[ks // 2]), fx.Int32 + ) + for ks in range_constexpr(NKS) + ] + ) + return kf + + def dequant_v(raw): + sp = [ + cvt_fp8x2_f16(raw[17 + j // 2], j % 2 == 1) for j in range_constexpr(4) + ] + return [ + Vec.from_elements(_v_bf16x8(raw[9 + dt], sp), fx.Int32) + for dt in range_constexpr(NDT) + ] + + fx.gpu.barrier() # LUT in LDS + + zero4 = Vec.filled(4, 0.0, fx.Float32) + key_off = [ + 8 * g + 4 * st + e for st in range_constexpr(2) for e in range_constexpr(4) + ] + first = (n_v > 0).select( + fx.Int32(fx.math.cttz(vmask).to(fx.Int32)), fx.Int32(0) + ) + + def slot_at(mask): + """The lowest slot left in ``mask``, the first one when empty.""" + return (mask != fx.Int64(0)).select( + fx.Int32(fx.math.cttz(mask).to(fx.Int32)), first + ) + + def page_of(slot): + pg = fx.Int32(fx.rocdl.readlane(T.i32, page, slot)) + return (pg >= 0).select(pg, fx.Int32(0)) + + def attend(kf, vf, cur_blk, live, m_t, l_t, o_t): + """Fold one block into (max, sum, O); a dead block is fully masked.""" + a = [] + for st in range_constexpr(2): + acc = zero4 + for ks in range_constexpr(NKS): + acc = mfma_16x16x32(kf[st][ks], qf[ks], acc, False) + a += [acc[e] for e in range_constexpr(4)] + diag = cur_blk == self_blk + dead = live == fx.Int32(0) + a = [ + (dead | (diag & (key_off[i] > lim))).select(neg_inf, a[i]) + for i in range_constexpr(8) + ] + mx = a[0] + for i in range_constexpr(1, 8): + mx = maxf_nn(mx, a[i]) + # The running max is kept in scaled units (c > 0). + m_new = maxf_nn(m_t, xlane4(mx, maxf_nn) * c) + m_use = (m_new == neg_inf).select(fx.Float32(0.0), m_new) + alpha = exp2(m_t - m_use) + p = [exp2(fx.math.fma(x, c, -m_use)) for x in a] + ps = p[0] + for i in range_constexpr(1, 8): + ps = ps + p[i] + pf = Vec.from_elements( + [pk_bf16(p[2 * j], p[2 * j + 1]) for j in range_constexpr(4)], + fx.Int32, + ) + av = Vec.filled(4, alpha, fx.Float32) + o_t = [ + mfma_16x16x32(vf[dt], pf, o_t[dt] * av, False) + for dt in range_constexpr(NDT) + ] + return m_new, l_t * alpha + ps, o_t + + # Two blocks per iteration, the next pair's loads in flight; an odd last + # block is masked. + init = [vmask, neg_inf, fx.Float32(0.0)] + init += [zero4 for _ in range_constexpr(NDT)] + init += load_block(page_of(slot_at(vmask))) + n_st = 3 + NDT + results = init + for u, st_ in range( # type: ignore[call-overload] + fx.Index(0), + fx.Index((n_v + 1) // 2), + fx.Index(1), + init=[fx.as_ir_value(x) for x in init], + ): + rem = fx.Int64(st_[0]) + m_t = fx.Float32(st_[1]) + l_t = fx.Float32(st_[2]) + o_t = [Vec(st_[3 + dt]) for dt in range_constexpr(NDT)] + raw_a = [fx.Int32(st_[n_st + i]) for i in range_constexpr(RAW)] + blk_a = fx.Int32(fx.rocdl.readlane(T.i32, blk, slot_at(rem))) + rem_b = rem & (rem - fx.Int64(1)) + raw_b = load_block(page_of(slot_at(rem_b))) + fx.rocdl.sched_barrier(0) + kf_a = dequant_k(raw_a) + vf_a = dequant_v(raw_a) + rem_n = rem_b & (rem_b - fx.Int64(1)) + fx.rocdl.sched_barrier(0) + raw_n = load_block(page_of(slot_at(rem_n))) + fx.rocdl.sched_barrier(0) + res = attend(kf_a, vf_a, blk_a, fx.Int32(1), m_t, l_t, o_t) + m_t, l_t, o_t = res[0], res[1], res[2] + blk_b = fx.Int32(fx.rocdl.readlane(T.i32, blk, slot_at(rem_b))) + live_b = (rem_b != fx.Int64(0)).select(fx.Int32(1), fx.Int32(0)) + kf_b = dequant_k(raw_b) + vf_b = dequant_v(raw_b) + res = attend(kf_b, vf_b, blk_b, live_b, m_t, l_t, o_t) + m_t, l_t, o_t = res[0], res[1], res[2] + state = [rem_n, m_t, l_t] + o_t + raw_n + results = yield [fx.as_ir_value(x) for x in state] + + def store_out(acc, inv): + outr = buffer_ops.create_buffer_resource_from_addr( + arg_out, + num_records_bytes=fx.Int64(i32_rows) * fx.Int64(i32_H) * (D * 2), + ) + o_row = (row * i32_H + kvh * HG + n) * (D // 2) + g * 16 + for e in range_constexpr(4): + val = Vec.from_elements( + [ + pk_bf16(acc[2 * j][e] * inv, acc[2 * j + 1][e] * inv) + for j in range_constexpr(4) + ], + fx.Int32, + ) + buffer_ops.buffer_store(val, outr, o_row + e * 4, mask=row < i32_rows) + + # Combine the waves' partials in wave 0. + o_lds = fx.logical_divide( + fx.make_view( + fx.recast_iter(fx.Int32, smem.o.ptr), + fx.make_layout(NW * NDT * 64 * 4, 1), + ), + fx.make_layout(4, 1), + ) + lds_atom = fx.make_copy_atom(fx.UniversalCopy128b(), fx.Int32) + ml = smem.ml.ptr + ml[(w * 2) * 64 + lane] = fx.Float32(results[1]) + ml[(w * 2 + 1) * 64 + lane] = fx.Float32(results[2]) + for dt in range_constexpr(NDT): + r = fx.make_rmem_tensor(fx.make_layout(4, 1), fx.Int32) + r.store(Vec(results[3 + dt]).bitcast(fx.Int32)) + fx.copy(lds_atom, r, fx.slice(o_lds, (None, (w * NDT + dt) * 64 + lane))) + fx.gpu.barrier() + if w == 0: + ms = [fx.Float32(ml[(ww * 2) * 64 + lane]) for ww in range_constexpr(NW)] + big = ms[0] + for ww in range_constexpr(1, NW): + big = maxf_nn(big, ms[ww]) + big_raw = big + big = (big == neg_inf).select(fx.Float32(0.0), big) + wt = [fx.Float32(fx.math.exp2(ms[ww] - big)) for ww in range_constexpr(NW)] + l_tot = fx.Float32(0.0) + for ww in range_constexpr(NW): + l_tot = l_tot + fx.Float32(ml[(ww * 2 + 1) * 64 + lane]) * wt[ww] + l_tot = xlane4(l_tot, lambda x, y: x + y) + acc = [zero4 for _ in range_constexpr(NDT)] + for ww in range_constexpr(NW): + wv = Vec.filled(4, wt[ww], fx.Float32) + for dt in range_constexpr(NDT): + r = fx.make_rmem_tensor(fx.make_layout(4, 1), fx.Int32) + fx.copy( + lds_atom, + fx.slice(o_lds, (None, (ww * NDT + dt) * 64 + lane)), + r, + ) + acc[dt] = acc[dt] + Vec(r.load()).bitcast(fx.Float32) * wv + if const_expr(SPLITS > 1): + tid = row * i32_hkv + kvh + pr = buffer_ops.create_buffer_resource_from_addr( + arg_part, num_records_bytes=i64_part_bytes + ) + row_f = (tid * SPLITS + fx.block_idx.z) * 64 + lane + for dt in range_constexpr(NDT): + buffer_ops.buffer_store( + acc[dt].bitcast(fx.Int32), + pr, + row_f * PART_F + dt * 4, + cache_modifier=PART_SCOPE, + ) + buffer_ops.buffer_store( + Vec.from_elements([bits(big_raw), bits(l_tot)], fx.Int32), + pr, + row_f * PART_F + NDT * 4, + cache_modifier=PART_SCOPE, + ) + # The partial is stored before the ticket is taken. + fx.rocdl.s_waitcnt(vmcnt=0) + if lane == 0: + smem.ticket.ptr[0] = _global_atomic_add( + arg_cnt + fx.Int64(tid) * 4, 1 + ) + fx.rocdl.s_waitcnt(lgkmcnt=0) + if ( + fx.Int32( + fx.rocdl.readfirstlane(T.i32, fx.Int32(smem.ticket.ptr[0])) + ) + == SPLITS - 1 + ): + rows_f = [ + (tid * SPLITS + sp) * 64 + lane + for sp in range_constexpr(SPLITS) + ] + mls = [ + Vec( + buffer_ops.buffer_load( + pr, + rf * PART_F + NDT * 4, + vec_width=2, + dtype=fx.Int32, + cache_modifier=PART_SCOPE, + ) + ) + for rf in rows_f + ] + bigs = [as_f32(x[0]) for x in mls] + top = bigs[0] + for sp in range_constexpr(1, SPLITS): + top = maxf_nn(top, bigs[sp]) + top = (top == neg_inf).select(fx.Float32(0.0), top) + ws = [fx.Float32(fx.math.exp2(b - top)) for b in bigs] + l_all = fx.Float32(0.0) + for sp in range_constexpr(SPLITS): + l_all = l_all + as_f32(mls[sp][1]) * ws[sp] + inv_all = (l_all > fx.Float32(0.0)).select( + v_scale / l_all, fx.Float32(0.0) + ) + acc_all = [zero4 for _ in range_constexpr(NDT)] + for sp in range_constexpr(SPLITS): + wv = Vec.filled(4, ws[sp], fx.Float32) + for dt in range_constexpr(NDT): + part = Vec( + buffer_ops.buffer_load( + pr, + rows_f[sp] * PART_F + dt * 4, + vec_width=4, + dtype=fx.Int32, + cache_modifier=PART_SCOPE, + ) + ).bitcast(fx.Float32) + acc_all[dt] = acc_all[dt] + part * wv + store_out(acc_all, inv_all) + if lane == 0: + global_i32_ptr(arg_cnt + fx.Int64(tid) * 4)[0] = fx.Int32(0) + else: + inv = (l_tot > fx.Float32(0.0)).select(v_scale / l_tot, fx.Float32(0.0)) + store_out(acc, inv) + + @flyc.jit + def launch( + arg_q: fx.Int64, + arg_cache: fx.Int64, + arg_topk: fx.Int64, + arg_bt: fx.Int64, + arg_seq: fx.Int64, + arg_out: fx.Int64, + arg_ks: fx.Int64, + arg_vs: fx.Int64, + arg_lut: fx.Int64, + arg_part: fx.Int64, + arg_cnt: fx.Int64, + i64_part_bytes: fx.Int64, + i32_rows: fx.Int32, + i32_ql: fx.Int32, + i32_H: fx.Int32, + i32_hkv: fx.Int32, + i32_topk_hs: fx.Int32, + i32_bt_s: fx.Int32, + i32_page_b: fx.Int32, + f32_c: fx.Float32, + i32_grid_x: fx.Int32, + stream: fx.Stream, + ): + kernel( + i32_rows, + i32_ql, + i32_topk_hs, + i32_bt_s, + i32_H, + i32_hkv, + arg_seq, + arg_topk, + arg_bt, + arg_lut, + arg_q, + arg_cache, + arg_ks, + arg_vs, + arg_out, + arg_part, + arg_cnt, + i64_part_bytes, + i32_page_b, + f32_c, + ).launch( + grid=(i32_grid_x, i32_hkv, SPLITS), + block=(64 * NW, 1, 1), + stream=stream, + ) + + launch.kernel_name = name + launch.compile_hints = PRELOAD_HINTS + return launch diff --git a/vllm/models/minimax_m3/amd/ops/sp_coll/__init__.py b/vllm/models/minimax_m3/amd/ops/sp_coll/__init__.py new file mode 100644 index 000000000000..bea7a19672b6 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/sp_coll/__init__.py @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""FlyDSL collectives of MiniMax-M3's sequence-parallel prefill (TP4, MI355X).""" + +from .host import WORLD, Collectives, Pools + +__all__ = ["WORLD", "Collectives", "Pools"] diff --git a/vllm/models/minimax_m3/amd/ops/sp_coll/host.py b/vllm/models/minimax_m3/amd/ops/sp_coll/host.py new file mode 100644 index 000000000000..c9a3cf8d6715 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/sp_coll/host.py @@ -0,0 +1,321 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Pools and collectives on the sp_coll kernels: per rank ``sets x 2`` IPC-mapped +slots, one set per DBO microbatch. Two slots suffice: slot k is rewritten for phase +c + 2 only after every peer published c + 1, i.e. finished pulling phase c.""" + +import ctypes +import functools +import math + +import torch +import torch.distributed as dist + +from vllm import _custom_ops as ops +from vllm.logger import init_logger +from vllm.models.minimax_m3.amd.ops.flydsl_utils import run_compiled as _run_compiled + +from . import kernel as _kernel + +logger = init_logger(__name__) + +WORLD = _kernel.WORLD +SLOTS = 2 +_ALIGN = 256 + + +@functools.cache +def _kernels(): + k = _kernel + return ( + k.compile_publish(), + k.compile_fence_publish(), + k.compile_pull(), + k.compile_pull_unpack(), + k.compile_sum4(), + ) + + +class _IpcHandle(ctypes.Structure): + _fields_ = [("reserved", ctypes.c_char * 64)] + + +@functools.cache +def _hip(): + lib = ctypes.CDLL("libamdhip64.so") + lib.hipMalloc.argtypes = [ctypes.POINTER(ctypes.c_void_p), ctypes.c_size_t] + lib.hipIpcGetMemHandle.argtypes = [ctypes.POINTER(_IpcHandle), ctypes.c_void_p] + lib.hipIpcOpenMemHandle.argtypes = [ + ctypes.POINTER(ctypes.c_void_p), + _IpcHandle, + ctypes.c_uint, + ] + return lib + + +class _DevicePointer: + def __init__(self, ptr: int, nbytes: int): + self.__cuda_array_interface__ = { + "data": (ptr, False), + "shape": (nbytes,), + "typestr": "|u1", + "strides": None, + "version": 3, + } + + +def _alloc_pool(nbytes: int, device: torch.device) -> tuple[int, bytes, torch.Tensor]: + """-> (pointer, IPC handle bytes, uint8 tensor); never freed.""" + hip = _hip() + ptr = ctypes.c_void_p() + with torch.cuda.device(device): + rc = hip.hipMalloc(ctypes.byref(ptr), nbytes) + assert rc == 0, f"hipMalloc({nbytes}) failed: {rc}" + handle = _IpcHandle() + rc = hip.hipIpcGetMemHandle(ctypes.byref(handle), ptr) + assert rc == 0, f"hipIpcGetMemHandle failed: {rc}" + pool = torch.as_tensor(_DevicePointer(ptr.value, nbytes), device=device) + assert pool.data_ptr() == ptr.value + # raw bytes: a c_char field reads back only up to its first NUL + raw = ctypes.string_at(ctypes.addressof(handle), ctypes.sizeof(handle)) + return ptr.value, raw, pool + + +def _open_pool(handle: bytes, device: torch.device) -> int: + hip = _hip() + ptr = ctypes.c_void_p() + h = _IpcHandle() + assert len(handle) == ctypes.sizeof(h) + ctypes.memmove(ctypes.addressof(h), handle, len(handle)) + with torch.cuda.device(device): + rc = hip.hipIpcOpenMemHandle(ctypes.byref(ptr), h, 1) # lazy peer access + assert rc == 0, f"hipIpcOpenMemHandle failed: {rc}" + return ptr.value + + +def _exchange(obj, rank: int, world: int, group) -> list: + """Every rank's ``obj``. Broadcasts: gloo's ``all_gather_object`` fails under + inference mode (the profile run).""" + out = [[None] for _ in range(world)] + out[rank][0] = obj + ranks = sorted(dist.get_process_group_ranks(group=group)) + for i, r in enumerate(ranks): + dist.broadcast_object_list(out[i], src=r, group=group, device="cpu") + return [o[0] for o in out] + + +class Pools: + """One rank's pool and flags plus the peers'; ``slot_bytes`` fits the largest + phase.""" + + def __init__( + self, + rank: int, + world: int, + group, + device: torch.device, + slot_bytes: int, + sets: int = 2, + ): + assert world == WORLD, world + self.rank, self.world, self.device = rank, world, device + self.sets, self.slot_bytes = sets, slot_bytes + nbytes = sets * SLOTS * slot_bytes + ptr, handle, self.pool = _alloc_pool(nbytes, device) + flag_ptr, flag_handle = ops.allocate_shared_buffer_and_handle(_ALIGN) + peers = _exchange((handle, flag_handle), rank, world, group) + self.pool_ptrs = [ + ptr if r == rank else _open_pool(h, device) + for r, (h, _) in enumerate(peers) + ] + self.flag_ptrs = [ + flag_ptr if r == rank else ops.open_mem_handle(h) + for r, (_, h) in enumerate(peers) + ] + self.seq = [0] * sets + self.phase = [0] * sets + publish, fence_publish, pull, pull_unpack, sum4 = _kernels() + self.fence_publish, self.pull, self.sum4 = fence_publish, pull, sum4 + self.pull_unpack = pull_unpack + stream = torch.cuda.current_stream(device) + # zero every set's flag word and ticket counter (base + 4) + for s in range(sets): + base = self.flag_ptrs[rank] + _kernel.FLAG_STRIDE * s + _run_compiled(publish, base, 0, stream) + _run_compiled(publish, base + 4, 0, stream) + torch.cuda.synchronize(device) + dist.barrier(group=group) + logger.info( + "sp_coll: %d sets x %d slots x %.0f MB pools, FlyDSL collectives on", + sets, + SLOTS, + slot_bytes / 2**20, + ) + + def slot(self, set_id: int) -> tuple[int, int]: + """Next slot of ``set_id``: (its byte offset in every pool, flag offset).""" + k = self.phase[set_id] % SLOTS + self.phase[set_id] += 1 + return (set_id * SLOTS + k) * self.slot_bytes, _kernel.FLAG_STRIDE * set_id + + def next_seq(self, set_id: int) -> int: + self.seq[set_id] += 1 + return self.seq[set_id] + + +class Collectives: + """One phase's collectives in the next slot of ``set_id``. ``alloc`` gives + producers views of the slot that the collectives read in place; inputs that do + not fit fall back to ``rccl`` (same sizes on every rank, so all ranks agree).""" + + def __init__(self, pools: Pools, set_id: int): + self.p = pools + self.set_id = set_id + self.base, self.flag_off = pools.slot(set_id) + self.off = 0 + self.stream: torch.cuda.Stream | None = None + self.rccl = None + + def bind(self, stream: torch.cuda.Stream, rccl) -> "Collectives": + self.stream, self.rccl = stream, rccl + return self + + def alloc(self, shape: tuple[int, ...], dtype: torch.dtype) -> torch.Tensor | None: + """A view of the slot for a producer to write; None when it does not fit.""" + n = math.prod(shape) * dtype.itemsize + off = self._take(n) + if off is None: + return None + return self.p.pool[off : off + n].view(dtype).view(shape) + + def _take(self, nbytes: int) -> int | None: + """Reserve ``nbytes`` of the slot (256 B aligned); None when it does not fit.""" + off = (self.off + _ALIGN - 1) // _ALIGN * _ALIGN + if off + nbytes > self.p.slot_bytes: + return None + self.off = off + nbytes + return self.base + off + + def _stage(self, x: torch.Tensor) -> int | None: + """``x``'s offset in every pool: in place if ``alloc`` placed it, else + copied in; None when it does not fit.""" + n = x.numel() * x.element_size() + start = self.p.pool.data_ptr() + self.base + if start <= x.data_ptr() < start + self.p.slot_bytes: + assert x.data_ptr() + n <= start + self.p.slot_bytes + return x.data_ptr() - self.p.pool.data_ptr() + off = self._take(n) + if off is None: + return None + dst = self.p.pool[off : off + n].view(x.dtype).view(x.shape) + dst.copy_(x) + return off + + def _publish_wait(self) -> None: + """Fence + publish this rank's slot; the pulls wait for the peers' flags.""" + p = self.p + self.seq = p.next_seq(self.set_id) + me_flag = p.flag_ptrs[p.rank] + self.flag_off + _run_compiled(p.fence_publish, me_flag, self.seq, self.stream) + + def _pull(self, dst: torch.Tensor, off: int, block: int, src_off: int) -> None: + p = self.p + srcs = [ptr + off for ptr in p.pool_ptrs] + flags = [f + self.flag_off for f in p.flag_ptrs] + _run_compiled( + p.pull, + dst.data_ptr(), + *srcs, + *flags, + block, + src_off, + self.seq, + p.rank, + self.stream, + ) + + def all_gather(self, outs: list[torch.Tensor], ins: list[torch.Tensor]) -> None: + """Each ``[rows, ...]`` shard into its ``[padded, ...]`` output.""" + ins = [i.contiguous() for i in ins] + offs = [self._stage(i) for i in ins] + if any(o is None for o in offs): + self.rccl.all_gather(outs, ins) + return + self._publish_wait() + for o, i, off in zip(outs, ins, offs): + assert o.is_contiguous() and o.dtype == i.dtype + block = i.numel() * i.element_size() + assert o.numel() * o.element_size() == WORLD * block, (o.shape, i.shape) + self._pull(o, off, block, 0) + + def all_to_all(self, out: torch.Tensor, x: torch.Tensor) -> None: + """Row block r of ``x`` to rank r; row block r of ``out`` from rank r.""" + x = x.contiguous() + n = x.numel() * x.element_size() + assert n % WORLD == 0 and out.is_contiguous() + assert out.numel() * out.element_size() == n + off = self._stage(x) + if off is None: + self.rccl.all_to_all(out, x) + return + self._publish_wait() + block = n // WORLD + self._pull(out, off, block, self.p.rank * block) + + def all_to_all_unpack( + self, x: torch.Tensor, d: int + ) -> tuple[torch.Tensor, torch.Tensor] | None: + """``all_to_all`` of packed rows ``[WORLD * rows, d + d / 32]``, unpacked: + (e4m3 codes ``[rows, WORLD * d]``, scales ``[rows, WORLD * d / 32]``), or + None when ``x`` does not fit the slot.""" + x = x.contiguous() + rows = x.shape[0] // WORLD + assert x.dtype == torch.uint8 and x.shape == (WORLD * rows, d + d // 32) + assert d % 32 == 0 and d % 16 == 0 + n = x.numel() + off = self._stage(x) + if off is None: + return None + self._publish_wait() + codes = torch.empty((rows, WORLD * d), dtype=torch.uint8, device=x.device) + scales = torch.empty( + (rows, WORLD * d // 32), dtype=torch.uint8, device=x.device + ) + p = self.p + block = n // WORLD + srcs = [ptr + off for ptr in p.pool_ptrs] + flags = [f + self.flag_off for f in p.flag_ptrs] + _run_compiled( + p.pull_unpack, + codes.data_ptr(), + scales.data_ptr(), + *srcs, + *flags, + block, + p.rank * block, + self.seq, + p.rank, + rows, + d, + self.stream, + ) + return codes.view(torch.float8_e4m3fn), scales + + def reduce_scatter(self, out: torch.Tensor, x: torch.Tensor) -> None: + """``[padded, H]`` partial sums -> this rank's ``[rows, H]`` sums (fp32, + rank order).""" + assert x.dtype == torch.bfloat16 and out.dtype == torch.bfloat16 + x = x.contiguous() + n = x.numel() * x.element_size() + block = n // WORLD + assert out.is_contiguous() and out.numel() * out.element_size() == block + off = self._stage(x) + if off is None: + self.rccl.reduce_scatter(out, x) + return + self._publish_wait() + # allocated and read on this stream only + staging = torch.empty(n, dtype=torch.uint8, device=x.device) + self._pull(staging, off, block, self.p.rank * block) + srcs = [staging.data_ptr() + r * block for r in range(WORLD)] + _run_compiled(self.p.sum4, out.data_ptr(), *srcs, block, self.stream) diff --git a/vllm/models/minimax_m3/amd/ops/sp_coll/kernel.py b/vllm/models/minimax_m3/amd/ops/sp_coll/kernel.py new file mode 100644 index 000000000000..13bca0f19978 --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/sp_coll/kernel.py @@ -0,0 +1,438 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""FlyDSL pull collectives (TP4, gfx950). ``fence_publish`` writes every XCD's L2 +back (a coarse-grained buffer's dirty lines are not flushed for peers' xGMI reads at +a kernel boundary), then the last workgroup stores the sequence into the flag; +``pull`` is a small persistent grid: CU slots are scarce next to compute kernels.""" + +import flydsl.compiler as flyc +import flydsl.expr as fx +from aiter.ops.flydsl.kernels import buffer_ops +from flydsl._mlir.dialects import llvm as _llvm +from flydsl.expr import range_constexpr +from flydsl.expr.typing import T +from flydsl.expr.typing import Vector as Vec + +WORLD = 4 +NT = 256 +UNROLL = 8 # 16 B per thread per step +STEP = NT * 4 * UNROLL # dwords per workgroup per loop step +SYS = 0x11 # sc0 | sc1: system-coherent loads / stores +# 8 workgroups per XCD (w runs on XCD w % 8, each with its own L2) +FENCE_WGS = 64 +PER_PEER = 256 # chunks per rank block +# 4 workgroups per rank reach the link rate (50 MB: 0.87 vs RCCL 0.95 ms) +PULL_WGS = 16 +SUM_WGS = 1024 +# bytes per set: the flag word, then the fence ticket counter +FLAG_STRIDE = 16 + + +def _global_i32_ptr(addr_i64): + ptr_ty = fx.PointerType.get( + T.i32, address_space=fx.AddressSpace.Global, alignment=4 + ) + return fx.inttoptr(ptr_ty, fx.Int64(addr_i64)) + + +def _flag_read(addr_i64): + """System-scope atomic add of 0: never hoisted out of the spin loop.""" + return fx.Int32( + _llvm.AtomicRMWOp( + _llvm.AtomicBinOp.add, + _global_i32_ptr(addr_i64).llvm_ptr, + fx.Int32(0).ir_value(), + _llvm.AtomicOrdering.monotonic, + syncscope="", + alignment=4, + ).result + ) + + +def _flag_add(addr_i64, v): + """System-scope atomic add; returns the old value.""" + return fx.Int32( + _llvm.AtomicRMWOp( + _llvm.AtomicBinOp.add, + _global_i32_ptr(addr_i64).llvm_ptr, + fx.Int32(v).ir_value(), + _llvm.AtomicOrdering.monotonic, + syncscope="", + alignment=4, + ).result + ) + + +def _sel4(p, a0, a1, a2, a3): + return (p == 0).select(a0, (p == 1).select(a1, (p == 2).select(a2, a3))) + + +def _as_f32(i): + return fx.Int32(i).bitcast(fx.Float32) + + +def _pk_bf16(a, b): + return fx.Int32( + fx.rocdl.cvt_pk_bf16_f32( + fx.as_ir_value(fx.Float32(a)), fx.as_ir_value(fx.Float32(b)) + ) + ) + + +def compile_publish(): + """Store a value into the flag, system-coherent (the init's zeroing).""" + + @flyc.kernel(name="sp_coll_publish", known_block_size=[64, 1, 1]) + def kernel(arg_flag: fx.Int64, i32_seq: fx.Int32): + fr = buffer_ops.create_buffer_resource_from_addr(arg_flag, num_records_bytes=64) + buffer_ops.buffer_store( + i32_seq, fr, 0, mask=fx.thread_idx.x == 0, cache_modifier=SYS + ) + + @flyc.jit + def launch(arg_flag: fx.Int64, i32_seq: fx.Int32, stream: fx.Stream): + kernel(arg_flag, i32_seq).launch( + grid=(1, 1, 1), block=(64, 1, 1), stream=stream + ) + + launch.kernel_name = "sp_coll_publish" + return launch + + +def compile_fence_publish(): + """Every workgroup releases its XCD's L2 and takes a ticket; the last one + resets the counter and stores ``seq`` into the flag.""" + + @flyc.kernel(name="sp_coll_fence_publish", known_block_size=[64, 1, 1]) + def kernel(arg_flag: fx.Int64, i32_seq: fx.Int32): + _llvm.FenceOp(_llvm.AtomicOrdering.release, syncscope="") + if fx.thread_idx.x == 0: + t = _flag_add(arg_flag + 4, 1) + if t == FENCE_WGS - 1: + _flag_add(arg_flag + 4, -FENCE_WGS) + fr = buffer_ops.create_buffer_resource_from_addr( + arg_flag, num_records_bytes=64 + ) + buffer_ops.buffer_store(i32_seq, fr, 0, cache_modifier=SYS) + + @flyc.jit + def launch(arg_flag: fx.Int64, i32_seq: fx.Int32, stream: fx.Stream): + kernel(arg_flag, i32_seq).launch( + grid=(FENCE_WGS, 1, 1), block=(64, 1, 1), stream=stream + ) + + launch.kernel_name = "sp_coll_fence_publish" + return launch + + +def compile_pull(): + """dst[p * block, (p + 1) * block) <- rank p's bytes [src_off, src_off + block). + Workgroup w serves rank w % 4: waits for its flag to reach ``seq``, then copies + chunks w // 4, w // 4 + PULL_WGS // 4, ...""" + + @flyc.kernel(name="sp_coll_pull", known_block_size=[NT, 1, 1]) + def kernel( + arg_dst: fx.Int64, + arg_s0: fx.Int64, + arg_s1: fx.Int64, + arg_s2: fx.Int64, + arg_s3: fx.Int64, + arg_f0: fx.Int64, + arg_f1: fx.Int64, + arg_f2: fx.Int64, + arg_f3: fx.Int64, + i64_block: fx.Int64, # bytes per rank block (multiple of 16) + i64_src_off: fx.Int64, # byte offset of the block inside a rank's region + i32_seq: fx.Int32, + i32_me: fx.Int32, + ): + tx = fx.thread_idx.x + bid = fx.block_idx.x + p = bid % WORLD + if (tx == 0) & (p != i32_me): + fa = _sel4(p, arg_f0, arg_f1, arg_f2, arg_f3) + f = _flag_read(fa) + while f < i32_seq: + f = _flag_read(fa) + fx.gpu.barrier() + _llvm.FenceOp(_llvm.AtomicOrdering.acquire, syncscope="") + src_a = _sel4(p, arg_s0, arg_s1, arg_s2, arg_s3) + i64_src_off + src = buffer_ops.create_buffer_resource_from_addr( + src_a, num_records_bytes=i64_block + ) + dst = buffer_ops.create_buffer_resource_from_addr( + arg_dst + fx.Int64(p) * i64_block, num_records_bytes=i64_block + ) + n_dw = fx.Int32(i64_block // 4) + per_block = (n_dw + (PER_PEER - 1)) // PER_PEER + per_block = (per_block + (STEP - 1)) // STEP * STEP + pb = bid // WORLD + while pb < PER_PEER: + start = pb * per_block + end = start + per_block + off = start + tx * 4 + while off < end: + vals = [] + for u in range_constexpr(UNROLL): + o = off + u * NT * 4 + vals.append( + Vec( + buffer_ops.buffer_load( + src, + o, + vec_width=4, + dtype=fx.Int32, + mask=o < n_dw, + cache_modifier=SYS, + ) + ) + ) + for u in range_constexpr(UNROLL): + o = off + u * NT * 4 + buffer_ops.buffer_store(vals[u], dst, o, mask=o < n_dw) + off = off + STEP + pb = pb + (PULL_WGS // WORLD) + + @flyc.jit + def launch( + arg_dst: fx.Int64, + arg_s0: fx.Int64, + arg_s1: fx.Int64, + arg_s2: fx.Int64, + arg_s3: fx.Int64, + arg_f0: fx.Int64, + arg_f1: fx.Int64, + arg_f2: fx.Int64, + arg_f3: fx.Int64, + i64_block: fx.Int64, + i64_src_off: fx.Int64, + i32_seq: fx.Int32, + i32_me: fx.Int32, + stream: fx.Stream, + ): + kernel( + arg_dst, + arg_s0, + arg_s1, + arg_s2, + arg_s3, + arg_f0, + arg_f1, + arg_f2, + arg_f3, + i64_block, + i64_src_off, + i32_seq, + i32_me, + ).launch(grid=(PULL_WGS, 1, 1), block=(NT, 1, 1), stream=stream) + + launch.kernel_name = "sp_coll_pull" + return launch + + +def compile_pull_unpack(): + """``pull`` that also unpacks (``sp_pack.mxfp8_unpack``): rank p's rows of ``d`` + codes + ``d / 32`` scales land in codes[:, p * d :] and scales[:, p * d / 32 :]. + A 16 B unit never straddles codes and scales since d % 16 == 0.""" + + @flyc.kernel(name="sp_coll_pull_unpack", known_block_size=[NT, 1, 1]) + def kernel( + arg_codes: fx.Int64, + arg_scales: fx.Int64, + arg_s0: fx.Int64, + arg_s1: fx.Int64, + arg_s2: fx.Int64, + arg_s3: fx.Int64, + arg_f0: fx.Int64, + arg_f1: fx.Int64, + arg_f2: fx.Int64, + arg_f3: fx.Int64, + i64_block: fx.Int64, # bytes per rank block = rows * row_bytes + i64_src_off: fx.Int64, + i32_seq: fx.Int32, + i32_me: fx.Int32, + i32_rows: fx.Int32, + i32_d: fx.Int32, # codes per row (bytes); scales per row = d / 32 + ): + tx = fx.thread_idx.x + bid = fx.block_idx.x + p = bid % WORLD + if (tx == 0) & (p != i32_me): + fa = _sel4(p, arg_f0, arg_f1, arg_f2, arg_f3) + f = _flag_read(fa) + while f < i32_seq: + f = _flag_read(fa) + fx.gpu.barrier() + _llvm.FenceOp(_llvm.AtomicOrdering.acquire, syncscope="") + src_a = _sel4(p, arg_s0, arg_s1, arg_s2, arg_s3) + i64_src_off + src = buffer_ops.create_buffer_resource_from_addr( + src_a, num_records_bytes=i64_block + ) + row_bytes = i32_d + i32_d // 32 + codes = buffer_ops.create_buffer_resource_from_addr( + arg_codes, num_records_bytes=fx.Int64(i32_rows) * fx.Int64(i32_d * WORLD) + ) + scales = buffer_ops.create_buffer_resource_from_addr( + arg_scales, + num_records_bytes=fx.Int64(i32_rows) * fx.Int64((i32_d // 32) * WORLD), + ) + n_dw = fx.Int32(i64_block // 4) + per_block = (n_dw + (PER_PEER - 1)) // PER_PEER + per_block = (per_block + (STEP - 1)) // STEP * STEP + pb = bid // WORLD + while pb < PER_PEER: + start = pb * per_block + end = start + per_block + off = start + tx * 4 + while off < end: + vals = [] + for u in range_constexpr(UNROLL): + o = off + u * NT * 4 + vals.append( + Vec( + buffer_ops.buffer_load( + src, + o, + vec_width=4, + dtype=fx.Int32, + mask=o < n_dw, + cache_modifier=SYS, + ) + ) + ) + for u in range_constexpr(UNROLL): + o = off + u * NT * 4 + byte = o * 4 + row = byte // row_bytes + b = byte - row * row_bytes + is_code = b < i32_d + off_c = (row * (i32_d * WORLD) + p * i32_d + b) // 4 + off_s = ( + row * ((i32_d // 32) * WORLD) + p * (i32_d // 32) + (b - i32_d) + ) // 4 + ok = o < n_dw + buffer_ops.buffer_store(vals[u], codes, off_c, mask=ok & is_code) + buffer_ops.buffer_store(vals[u], scales, off_s, mask=ok & ~is_code) + off = off + STEP + pb = pb + (PULL_WGS // WORLD) + + @flyc.jit + def launch( + arg_codes: fx.Int64, + arg_scales: fx.Int64, + arg_s0: fx.Int64, + arg_s1: fx.Int64, + arg_s2: fx.Int64, + arg_s3: fx.Int64, + arg_f0: fx.Int64, + arg_f1: fx.Int64, + arg_f2: fx.Int64, + arg_f3: fx.Int64, + i64_block: fx.Int64, + i64_src_off: fx.Int64, + i32_seq: fx.Int32, + i32_me: fx.Int32, + i32_rows: fx.Int32, + i32_d: fx.Int32, + stream: fx.Stream, + ): + kernel( + arg_codes, + arg_scales, + arg_s0, + arg_s1, + arg_s2, + arg_s3, + arg_f0, + arg_f1, + arg_f2, + arg_f3, + i64_block, + i64_src_off, + i32_seq, + i32_me, + i32_rows, + i32_d, + ).launch(grid=(PULL_WGS, 1, 1), block=(NT, 1, 1), stream=stream) + + launch.kernel_name = "sp_coll_pull_unpack" + return launch + + +def compile_sum4(): + """Sum the four staged bf16 blocks in fp32, in rank order 0..3.""" + + @flyc.kernel(name="sp_coll_sum4", known_block_size=[NT, 1, 1]) + def kernel( + arg_out: fx.Int64, + arg_s0: fx.Int64, + arg_s1: fx.Int64, + arg_s2: fx.Int64, + arg_s3: fx.Int64, + i64_block: fx.Int64, # bytes per block (bf16, multiple of 16) + ): + tx = fx.thread_idx.x + bid = fx.block_idx.x + srcs = [ + buffer_ops.create_buffer_resource_from_addr(a, num_records_bytes=i64_block) + for a in (arg_s0, arg_s1, arg_s2, arg_s3) + ] + out = buffer_ops.create_buffer_resource_from_addr( + arg_out, num_records_bytes=i64_block + ) + n_dw = fx.Int32(i64_block // 4) + per_block = (n_dw + (SUM_WGS - 1)) // SUM_WGS + per_block = (per_block + (STEP - 1)) // STEP * STEP + start = bid * per_block + end = start + per_block + off = start + tx * 4 + while off < end: + words = [] + for u in range_constexpr(UNROLL): + o = off + u * NT * 4 + words.append( + [ + Vec( + buffer_ops.buffer_load( + srcs[r], + o, + vec_width=4, + dtype=fx.Int32, + mask=o < n_dw, + ) + ) + for r in range_constexpr(WORLD) + ] + ) + for u in range_constexpr(UNROLL): + o = off + u * NT * 4 + packed = [] + for i in range_constexpr(4): + lo = fx.Float32(0.0) + hi = fx.Float32(0.0) + for r in range_constexpr(WORLD): + w = fx.Int32(words[u][r][i]) + lo = lo + _as_f32(w << 16) + hi = hi + _as_f32(w & fx.Int32(-65536)) + packed.append(_pk_bf16(lo, hi)) + buffer_ops.buffer_store( + Vec.from_elements(packed, fx.Int32), out, o, mask=o < n_dw + ) + off = off + STEP + + @flyc.jit + def launch( + arg_out: fx.Int64, + arg_s0: fx.Int64, + arg_s1: fx.Int64, + arg_s2: fx.Int64, + arg_s3: fx.Int64, + i64_block: fx.Int64, + stream: fx.Stream, + ): + kernel(arg_out, arg_s0, arg_s1, arg_s2, arg_s3, i64_block).launch( + grid=(SUM_WGS, 1, 1), block=(NT, 1, 1), stream=stream + ) + + launch.kernel_name = "sp_coll_sum4" + return launch diff --git a/vllm/models/minimax_m3/amd/ops/sp_norm_quant.py b/vllm/models/minimax_m3/amd/ops/sp_norm_quant.py new file mode 100644 index 000000000000..24ad40ad8d8d --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/sp_norm_quant.py @@ -0,0 +1,113 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Gemma RMSNorm (optionally after the residual add) + per-token MXFP8 quant in one +pass for ``sp_prefill``, with ``gemma_rmsnorm``'s sum order. The scale byte is +clamped to [0, 254] (``mxfp8_e4m3_quantize``) or [85, 254] (aiter's MoE quant).""" + +import torch + +from vllm.triton_utils import tl, triton + +# aiter's MoE input quant: scale at least 2^-42. +MOE_MIN_SCALE_BYTE = 85 + + +@triton.jit +def _rmsnorm_mx_kernel( + x_ptr, + res_ptr, + w_ptr, + out_ptr, + res_out_ptr, + q_ptr, + s_ptr, + n_cols, + eps, + HAS_RES: tl.constexpr, + STORE_OUT: tl.constexpr, + MIN_SB: tl.constexpr, + BLOCK_N: tl.constexpr, + FP8_MAX: tl.constexpr, + TINY: tl.constexpr, +): + row = tl.program_id(0) + cols = tl.arange(0, BLOCK_N) + mask = cols < n_cols + s = tl.load(x_ptr + row * n_cols + cols, mask=mask, other=0.0).to(tl.float32) + if HAS_RES: + r = tl.load(res_ptr + row * n_cols + cols, mask=mask, other=0.0) + s = s + r.to(tl.float32) + tl.store( + res_out_ptr + row * n_cols + cols, + s.to(res_out_ptr.dtype.element_ty), + mask=mask, + ) + var = tl.sum(s * s, axis=0) / n_cols + rstd = 1.0 / tl.sqrt(var + eps) + w = tl.load(w_ptr + cols, mask=mask, other=0.0).to(tl.float32) + out = (s * rstd * (1.0 + w)).to(out_ptr.dtype.element_ty) + if STORE_OUT: + tl.store(out_ptr + row * n_cols + cols, out, mask=mask) + y = tl.reshape(out.to(tl.float32), (BLOCK_N // 32, 32)) + amax = tl.maximum(tl.max(tl.abs(y), axis=1), TINY) + sb = tl.ceil(tl.log2(amax / FP8_MAX)) + 127.0 + sb = tl.minimum(tl.maximum(sb, MIN_SB), 254.0) + q = (y * tl.exp2(127.0 - sb)[:, None]).to(q_ptr.dtype.element_ty) + tl.store(q_ptr + row * n_cols + cols, tl.reshape(q, (BLOCK_N,)), mask=mask) + groups = tl.arange(0, BLOCK_N // 32) + tl.store( + s_ptr + row * (n_cols // 32) + groups, + sb.to(tl.uint8), + mask=groups < n_cols // 32, + ) + + +def _out_or_empty(out, shape, dtype, device) -> torch.Tensor: + if out is None: + return torch.empty(shape, dtype=dtype, device=device) + assert out.shape == shape and out.dtype == dtype and out.is_contiguous() + return out + + +def gemma_rmsnorm_mx( + x: torch.Tensor, + residual: torch.Tensor | None, + weight: torch.Tensor, + eps: float, + *, + min_scale_byte: int = 0, + store_out: bool = False, + q_out: torch.Tensor | None = None, + scale_out: torch.Tensor | None = None, +) -> tuple[torch.Tensor | None, torch.Tensor, torch.Tensor, torch.Tensor]: + """-> (normalized bf16 if ``store_out``, x + residual (``x`` without one), + MXFP8 codes, e8m0 scales ``[M, N/32]``); the codes / scales into ``q_out`` / + ``scale_out`` when given.""" + m, n = x.shape + assert x.is_contiguous() and n % 32 == 0 + assert residual is None or residual.is_contiguous() + out = torch.empty_like(x) if store_out else None + res_out = torch.empty_like(x) if residual is not None else x + q = _out_or_empty(q_out, (m, n), torch.float8_e4m3fn, x.device) + scale = _out_or_empty(scale_out, (m, n // 32), torch.uint8, x.device) + block_n = triton.next_power_of_2(n) + _rmsnorm_mx_kernel[(m,)]( + x, + x if residual is None else residual, + weight, + x if out is None else out, + res_out, + q, + scale, + n, + eps, + HAS_RES=residual is not None, + STORE_OUT=store_out, + MIN_SB=float(min_scale_byte), + BLOCK_N=block_n, + FP8_MAX=float(torch.finfo(torch.float8_e4m3fn).max), + TINY=float(torch.finfo(torch.float32).tiny), + # gemma_rmsnorm._num_warps (its sum order) + num_warps=16 if block_n >= 4096 else (8 if block_n >= 1024 else 4), + ) + return out, res_out, q, scale diff --git a/vllm/models/minimax_m3/amd/ops/sp_pack.py b/vllm/models/minimax_m3/amd/ops/sp_pack.py new file mode 100644 index 000000000000..099f9503594b --- /dev/null +++ b/vllm/models/minimax_m3/amd/ops/sp_pack.py @@ -0,0 +1,114 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MXFP8 pack / unpack for the all-to-all of the sequence-parallel o_proj: a row is +its e4m3 codes, then its e8m0 scales (``mxfp8_e4m3_quantize``'s quant).""" + +import torch + +from vllm.triton_utils import tl, triton + + +@triton.jit +def _quant_pack_kernel( + x_ptr, + out_ptr, + M, + D: tl.constexpr, + BLOCK_M: tl.constexpr, + FP8_MAX: tl.constexpr, + TINY: tl.constexpr, +): + pid = tl.program_id(0) + rows = pid * BLOCK_M + tl.arange(0, BLOCK_M) + cols = tl.arange(0, D) + mask = rows < M + x = tl.load( + x_ptr + rows[:, None] * D + cols[None, :], mask=mask[:, None], other=0.0 + ) + x = tl.reshape(x.to(tl.float32), (BLOCK_M, D // 32, 32)) + amax = tl.maximum(tl.max(tl.abs(x), axis=2), TINY) + sb = tl.minimum(tl.maximum(tl.ceil(tl.log2(amax / FP8_MAX)) + 127.0, 0.0), 254.0) + q = (x * tl.exp2(127.0 - sb)[:, :, None]).to(tl.float8e4nv) + row_bytes = D + D // 32 + q = tl.reshape(q.to(tl.uint8, bitcast=True), (BLOCK_M, D)) + tl.store(out_ptr + rows[:, None] * row_bytes + cols[None, :], q, mask=mask[:, None]) + groups = tl.arange(0, D // 32) + tl.store( + out_ptr + rows[:, None] * row_bytes + D + groups[None, :], + sb.to(tl.uint8), + mask=mask[:, None], + ) + + +@triton.jit +def _unpack_kernel( + in_ptr, + codes_ptr, + scales_ptr, + ROWS, + WORLD: tl.constexpr, + D: tl.constexpr, + BLOCK_M: tl.constexpr, +): + pid = tl.program_id(0) + w = tl.program_id(1) + rows = pid * BLOCK_M + tl.arange(0, BLOCK_M) + mask = rows < ROWS + row_bytes = D + D // 32 + src = in_ptr + (w * ROWS + rows[:, None]) * row_bytes + cols = tl.arange(0, D) + codes = tl.load(src + cols[None, :], mask=mask[:, None]) + tl.store( + codes_ptr + rows[:, None] * (WORLD * D) + w * D + cols[None, :], + codes, + mask=mask[:, None], + ) + groups = tl.arange(0, D // 32) + scales = tl.load(src + D + groups[None, :], mask=mask[:, None]) + tl.store( + scales_ptr + + rows[:, None] * (WORLD * D // 32) + + w * (D // 32) + + groups[None, :], + scales, + mask=mask[:, None], + ) + + +def mxfp8_quant_pack(x: torch.Tensor, out: torch.Tensor | None = None) -> torch.Tensor: + """``[M, D]`` bf16 -> ``[M, D + D/32]`` uint8.""" + m, d = x.shape + assert x.is_contiguous() and d % 32 == 0 and d & (d - 1) == 0, x.shape + if out is None: + out = torch.empty((m, d + d // 32), dtype=torch.uint8, device=x.device) + assert out.shape == (m, d + d // 32) and out.dtype == torch.uint8 + assert out.is_contiguous() + block_m = 4 + _quant_pack_kernel[(triton.cdiv(m, block_m),)]( + x, + out, + m, + D=d, + BLOCK_M=block_m, + FP8_MAX=float(torch.finfo(torch.float8_e4m3fn).max), + TINY=float(torch.finfo(torch.float32).tiny), + num_warps=8, + ) + return out + + +def mxfp8_unpack( + packed: torch.Tensor, world: int, rows: int, d: int +) -> tuple[torch.Tensor, torch.Tensor]: + """``[world * rows, d + d/32]`` (block w from rank w) -> codes + ``[rows, world * d]`` and scales ``[rows, world * d / 32]``.""" + assert packed.shape == (world * rows, d + d // 32) and packed.is_contiguous() + codes = torch.empty((rows, world * d), dtype=torch.uint8, device=packed.device) + scales = torch.empty( + (rows, world * d // 32), dtype=torch.uint8, device=packed.device + ) + block_m = 4 + _unpack_kernel[(triton.cdiv(rows, block_m), world)]( + packed, codes, scales, rows, WORLD=world, D=d, BLOCK_M=block_m, num_warps=8 + ) + return codes.view(torch.float8_e4m3fn), scales diff --git a/vllm/models/minimax_m3/amd/sp_prefill.py b/vllm/models/minimax_m3/amd/sp_prefill.py new file mode 100644 index 000000000000..6e639a059d81 --- /dev/null +++ b/vllm/models/minimax_m3/amd/sp_prefill.py @@ -0,0 +1,737 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Sequence-parallel prefill for MiniMax-M3 under pure TP (ROCm). + +From ``SP_MIN_TOKENS`` tokens (``SP_MIN_UBATCH_TOKENS`` per DBO microbatch) each rank +keeps ``rows`` tokens of the residual stream. Per layer the two bf16 all-reduces +become an all-to-all of the MXFP8 attention output (each rank applies the whole +o_proj) and a reduce-scatter of the FFN output, each followed by an all-gather of +the next MXFP8 input; norms, quants and the router run on the shard. +""" + +import ctypes +from dataclasses import dataclass, field + +import torch + +import vllm.envs as envs +from vllm.distributed import ( + get_tensor_model_parallel_rank, + get_tensor_model_parallel_world_size, + get_tp_group, +) +from vllm.logger import init_logger + +logger = init_logger(__name__) + +# TP4 isolated prefill: 4096 tokens 133 vs 140 ms. +SP_MIN_TOKENS = 4096 +# Every microbatch of a DBO step needs this many tokens (their hand-offs alternate, +# so all take one path); below, the phases overlap too little. +SP_MIN_UBATCH_TOKENS = 8192 +# The MXFP8 prefill MoE chain's limit. +SP_MAX_TOKENS = 65536 +_ROW_ALIGN = 32 + + +def _run(issue) -> None: + from vllm.v1.worker.ubatching import dbo_tp_collective + + if dbo_tp_collective(issue): + return + comm = get_tp_group().device_communicator.pynccl_comm + issue(comm, torch.cuda.current_stream()) + + +# ops.sp_coll.Pools after init_collectives; None = RCCL. +_POOLS = None +# The pools fit one microbatch of a 65536-token DBO step; larger phases use RCCL. +SP_COLL_MAX_TOKENS = SP_MAX_TOKENS // 2 + + +def collectives_slot_bytes(hidden: int, q_size: int) -> int: + """Bytes of one pool slot: the FFN phase's inputs at ``SP_COLL_MAX_TOKENS`` + (bf16 partials, codes + scales + routing, two bf16 gathers, slack).""" + world = 4 + rows = SP_COLL_MAX_TOKENS // world + padded = rows * world + assert padded * (q_size + q_size // 32) <= padded * hidden * 2 + return ( + padded * hidden * 2 + + rows * (hidden + hidden // 32 + 64 * 4) + + 2 * rows * hidden * 2 + + 8 * 256 + ) + + +def init_collectives( + hidden: int, q_size: int, device: torch.device, sets: int = 2 +) -> None: + """Create the FlyDSL pools, one slot set per DBO microbatch (TP4 on gfx950). + Collective: every TP rank calls it once.""" + global _POOLS + if _POOLS is not None: + return + from vllm.platforms.rocm import on_gfx950 + + world = get_tensor_model_parallel_world_size() + if world != 4 or not on_gfx950(): + logger.info_once( + "MiniMax-M3 sequence-parallel prefill: RCCL collectives (the FlyDSL " + "ones serve TP4 on gfx950)" + ) + return + from vllm.models.minimax_m3.amd.ops import sp_coll + + tp = get_tp_group() + _POOLS = sp_coll.Pools( + tp.rank_in_group, + world, + tp.cpu_group, + device, + collectives_slot_bytes(hidden, q_size), + sets=max(2, sets), + ) + + +def _bytes(t: torch.Tensor) -> torch.Tensor: + return t.reshape(-1).view(torch.uint8) + + +class Collectives: + """RCCL collectives of one communication phase.""" + + def __init__(self, comm, stream, world: int): + self.comm = comm + self.stream = stream + self.world = world + + def alloc(self, shape: tuple[int, ...], dtype: torch.dtype) -> torch.Tensor | None: + """RCCL reads any tensor: the producer allocates.""" + return None + + def all_gather(self, outs: list[torch.Tensor], ins: list[torch.Tensor]) -> None: + """Each ``[rows, ...]`` shard into its ``[padded, ...]`` output.""" + self.comm.group_start() + for i, o in zip(ins, outs): + self.comm.all_gather(_bytes(o), _bytes(i.contiguous()), stream=self.stream) + self.comm.group_end() + + def reduce_scatter(self, out: torch.Tensor, x: torch.Tensor) -> None: + """``[padded, H]`` partial sums -> this rank's ``[rows, H]`` sums.""" + self.comm.reduce_scatter(out, x, stream=self.stream) + + def all_to_all(self, out: torch.Tensor, x: torch.Tensor) -> None: + """Row block r of ``x`` to rank r, row block r of ``out`` from rank r.""" + from vllm.distributed.device_communicators.pynccl_wrapper import ( + cudaStream_t, + ncclDataTypeEnum, + ) + + fn = self.comm.nccl.lib.ncclAllToAll + if fn.argtypes is None: + fn.restype = ctypes.c_int + fn.argtypes = [ + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_size_t, + ctypes.c_int, + ctypes.c_void_p, + ctypes.c_void_p, + ] + xb, ob = _bytes(x), _bytes(out) + assert xb.numel() == ob.numel() and xb.numel() % self.world == 0 + res = fn( + xb.data_ptr(), + ob.data_ptr(), + xb.numel() // self.world, + ncclDataTypeEnum.ncclUint8, + self.comm.comm, + cudaStream_t(self.stream.cuda_stream), + ) + assert res == 0, f"ncclAllToAll failed: {res}" + + +class _Phase: + """The FlyDSL collectives ``begin_phase`` reserved for the next phase.""" + + coll = None + + +@dataclass(frozen=True) +class SeqShard: + num_tokens: int + rows: int + world: int + rank: int + state: _Phase = field(default_factory=_Phase, compare=False, repr=False) + + @property + def padded(self) -> int: + return self.rows * self.world + + def shard(self, x: torch.Tensor) -> torch.Tensor: + """This rank's rows of the full ``[num_tokens, ...]`` ``x`` (zero padded).""" + start = self.rank * self.rows + n = min(self.rows, max(0, self.num_tokens - start)) + if n == self.rows: + return x[start : start + n].contiguous() + out = x.new_zeros((self.rows, *x.shape[1:])) + if n: + out[:n].copy_(x[start : start + n]) + return out + + def pad(self, x: torch.Tensor) -> torch.Tensor: + """``[num_tokens, ...]`` -> ``[padded, ...]``, the padding rows zero.""" + if x.shape[0] == self.padded: + return x + out = x.new_empty((self.padded, *x.shape[1:])) + out[: x.shape[0]].copy_(x) + out[x.shape[0] :].zero_() + return out + + def _fly_collectives(self): + from vllm.models.minimax_m3.amd.ops import sp_coll + from vllm.v1.worker.ubatching import dbo_current_ubatch_id + + return sp_coll.Collectives(_POOLS, dbo_current_ubatch_id()) + + def begin_phase(self) -> None: + """Reserve the next phase's pool slot before the compute that fills it, so + its inputs land in place. Every rank calls it in the same order.""" + if _POOLS is None: + return + assert self.state.coll is None, "the previous phase did not run" + self.state.coll = self._fly_collectives() + + def alloc( + self, shape: tuple[int, ...], dtype: torch.dtype, device: torch.device + ) -> torch.Tensor: + """A view of the next phase's pool slot when it fits, else a new tensor.""" + coll = self.state.coll + t = coll.alloc(shape, dtype) if coll is not None else None + if t is None: + t = torch.empty(shape, dtype=dtype, device=device) + return t + + def phase(self, fn) -> None: + """Run ``fn(collectives)`` as one phase (one DBO hand-off). The caller + allocates the outputs: a block the comm stream allocated could be reused + while the other microbatch still reads it.""" + + def issue(comm, stream): + rccl = Collectives(comm, stream, self.world) + coll = self.state.coll + self.state.coll = None + if coll is None and _POOLS is not None: + coll = self._fly_collectives() + fn(rccl if coll is None else coll.bind(stream, rccl)) + + _run(issue) + + +def plan(num_tokens: int) -> SeqShard | None: + world = get_tensor_model_parallel_world_size() + if world == 1 or num_tokens == 0 or num_tokens > SP_MAX_TOKENS: + return None + from vllm.forward_context import get_forward_context + from vllm.v1.worker.ubatching import dbo_enabled + + if dbo_enabled(): + slices = get_forward_context().ubatch_slices + # without the step's split, this microbatch's size + smallest = num_tokens if slices is None else min(s.num_tokens for s in slices) + if smallest < SP_MIN_UBATCH_TOKENS: + return None + elif num_tokens < SP_MIN_TOKENS: + return None + rows = (num_tokens + world - 1) // world + rows = (rows + _ROW_ALIGN - 1) // _ROW_ALIGN * _ROW_ALIGN + return SeqShard(num_tokens, rows, world, get_tensor_model_parallel_rank()) + + +# Model glue, called from amd/model.py. + +_FP8 = torch.float8_e4m3fn +# DBO microbatches per step (one pool set each), set at model init. +_NUM_UBATCHES = 2 + + +def _mxfp8_kernel(layer): + """``layer``'s MXFP8 linear kernel when it takes pre-quantized input.""" + from vllm.model_executor.kernels.linear.mxfp8.rocm_native import ( + RocmDotScaledMxfp8LinearKernel, + ) + + kernel = getattr(layer.quant_method, "kernel", None) + if isinstance(kernel, RocmDotScaledMxfp8LinearKernel): + return kernel + return None + + +def _linear(layer, x_q: torch.Tensor, x_s: torch.Tensor) -> torch.Tensor: + return layer.quant_method.kernel.apply_quantized(layer, x_q, x_s, torch.bfloat16) + + +def make_o_proj_full(layer, quant_config, prefix: str): + """An unsharded copy of ``layer``'s o_proj (+3.1 GB per rank at TP4), or None + where sequence parallelism cannot run.""" + global _NUM_UBATCHES + from vllm.config import get_current_vllm_config + from vllm.distributed import get_pp_group + from vllm.model_executor.layers.linear import ReplicatedLinear + from vllm.platforms.rocm import on_gfx950 + + o_proj = layer.self_attn.o_proj + if ( + not envs.VLLM_ROCM_MINIMAX_M3_SP_PREFILL + or get_tensor_model_parallel_world_size() == 1 + or get_pp_group().world_size > 1 + or not on_gfx950() + or _mxfp8_kernel(o_proj) is None + ): + return None + _NUM_UBATCHES = max(2, get_current_vllm_config().parallel_config.num_ubatches) + return ReplicatedLinear( + o_proj.input_size, + o_proj.output_size, + bias=False, + quant_config=quant_config, + prefix=f"{prefix}.self_attn.o_proj", + ) + + +def _moe_quant(moe) -> str | None: + """The routed experts' format a FlyDSL prefill chain covers ("mxfp8" or + "mxfp4"), else None.""" + import math + + from vllm.model_executor.layers.fused_moe.experts.aiter_mxfp8_moe import ( + AiterMxfp8Experts, + ) + from vllm.model_executor.layers.fused_moe.experts.rocm_aiter_moe import ( + AiterMxfp4Experts, + ) + from vllm.models.minimax_m3.amd.ops.moe_mxfp4 import prefill as prefill4 + from vllm.models.minimax_m3.amd.ops.moe_mxfp8 import prefill as prefill8 + + runner = moe.experts + kernel = getattr(runner._quant_method, "moe_kernel", None) + cfg = runner.moe_config + if ( + kernel is None + or runner.routed_input_transform is not None + or runner.routed_output_transform is not None + or cfg.moe_parallel_config.use_ep + or not math.isclose(cfg.swiglu_alpha or 0.0, prefill8.GEMM1_SWIGLU_ALPHA) + or not math.isclose(cfg.swiglu_limit or 0.0, prefill8.GEMM1_SWIGLU_LIMIT) + ): + return None + experts = kernel.fused_experts + hidden, inter = cfg.hidden_dim, cfg.intermediate_size_per_partition + if isinstance(experts, AiterMxfp8Experts): + return "mxfp8" if prefill8.supports_shapes(hidden, inter) else None + routed = runner.routed_experts + if ( + isinstance(experts, AiterMxfp4Experts) + and experts.quant_config.use_mxfp4_w4a4 + and prefill4.supports_shapes(hidden, inter) + and routed.w13_weight.shape[1:] == (2 * inter, hidden // 2) + and routed.w2_weight.shape[1:] == (hidden, inter // 2) + ): + return "mxfp4" + return None + + +def _layer_supports_sp(layer) -> bool: + attn = layer.self_attn + linears = [attn.qkv_proj, attn.o_proj_full] + if layer.is_moe_layer: + moe = layer.block_sparse_moe + moe._sp_quant = _moe_quant(moe) + if moe._sp_quant is None: + return False + if moe.shared_experts is not None: + linears.append(moe.shared_experts.gate_up_proj) + else: + linears.append(layer.mlp.gate_up_proj) + return all( + lin is not None + and (kernel := _mxfp8_kernel(lin)) is not None + and kernel.supports_quantized_input(lin) + for lin in linears + ) + + +def plan_model(model, hidden_states: torch.Tensor) -> SeqShard | None: + """The token sharding of a sequence-parallel forward of ``model``, or None.""" + if not envs.VLLM_ROCM_MINIMAX_M3_SP_PREFILL: + return None + if getattr(model, "_sp_supported", True) is False: + return None + if torch.cuda.is_current_stream_capturing(): + return None + sp = plan(hidden_states.shape[0]) + if sp is None: + return None + if not hasattr(model, "_sp_supported"): + layers = model.layers[model.start_layer : model.end_layer] + model._sp_supported = all(_layer_supports_sp(layer) for layer in layers) + logger.info( + "MiniMax-M3 sequence-parallel prefill (from %d tokens, DBO microbatches " + "from %d): %s", + SP_MIN_TOKENS, + SP_MIN_UBATCH_TOKENS, + "on" if model._sp_supported else "off", + ) + if model._sp_supported: + init_collectives( + hidden_states.shape[1], + layers[0].self_attn.q_size, + hidden_states.device, + sets=_NUM_UBATCHES, + ) + return sp if model._sp_supported else None + + +def _input_phase(sp: SeqShard, layer, embeddings: torch.Tensor): + """First input norm + MXFP8 quant on this rank's rows -> gathered codes, + scales, residual.""" + from .ops.sp_norm_quant import gemma_rmsnorm_mx + + norm = layer.input_layernorm + hidden = embeddings.shape[1] + codes = torch.empty((sp.padded, hidden), dtype=_FP8, device=embeddings.device) + scales = torch.empty( + (sp.padded, hidden // 32), dtype=torch.uint8, device=embeddings.device + ) + box = [] + + def run(coll): + _, r, x_q, x_s = gemma_rmsnorm_mx( + sp.shard(embeddings), + None, + norm.weight, + norm.variance_epsilon, + q_out=coll.alloc((sp.rows, hidden), _FP8), + scale_out=coll.alloc((sp.rows, hidden // 32), torch.uint8), + ) + coll.all_gather([codes, scales], [x_q, x_s]) + box.append(r) + + sp.phase(run) + return codes, scales, box[0] + + +def _o_proj_all_to_all(attn, attn_output: torch.Tensor, sp: SeqShard, coll): + """This rank's heads of every token -> the whole o_proj of this rank's rows, + through an all-to-all of the MXFP8 codes + scales.""" + from .ops.sp_pack import mxfp8_quant_pack, mxfp8_unpack + + t, d = attn_output.shape + shape = (sp.padded, d + d // 32) + send = coll.alloc(shape, torch.uint8) + if send is None: + send = torch.empty(shape, dtype=torch.uint8, device=attn_output.device) + mxfp8_quant_pack(attn_output, out=send[:t]) + send[t:].zero_() + unpacked = None + if hasattr(coll, "all_to_all_unpack"): + unpacked = coll.all_to_all_unpack(send, d) + if unpacked is None: + recv = torch.empty_like(send) + coll.all_to_all(recv, send) + unpacked = mxfp8_unpack(recv, sp.world, sp.rows, d) + return _linear(attn.o_proj_full, *unpacked) + + +def _routing_width(moe) -> int: + """Columns of the gathered routing: the top-k ids, then their fp32 weights.""" + fused = moe.n_shared_experts if moe.is_fused_shared_expert_enabled else 0 + return 2 * (moe.experts.router.top_k + fused) + + +def _route(moe, x: torch.Tensor, out: torch.Tensor | None) -> torch.Tensor: + runner = moe.experts + router_logits, _ = moe.gate(x) + topk_weights, topk_ids = runner.router.select_experts( + hidden_states=x, + router_logits=router_logits, + topk_indices_dtype=runner._quant_method.topk_indices_dtype, + ) + return torch.cat( + [topk_ids.to(torch.int32), topk_weights.float().view(torch.int32)], + dim=1, + out=out, + ) + + +def _post_attention_phase(sp: SeqShard, layer, attn_output, residual): + """o_proj, post-attention norm, FFN input quant and routing on this rank's + rows -> gathered MXFP8 codes and scales (None when only MXFP4 experts read + them), routing (None for a dense MLP), MXFP4 codes and scales (MXFP4 experts + only), residual.""" + from .ops.moe_mxfp4.prefill import mxfp4_quant + from .ops.sp_norm_quant import MOE_MIN_SCALE_BYTE, gemma_rmsnorm_mx + + hidden = residual.shape[1] + device = residual.device + moe = layer.block_sparse_moe if layer.is_moe_layer else None + mxfp4 = moe is not None and moe._sp_quant == "mxfp4" + need_fp8 = not mxfp4 or moe.shared_experts is not None + codes = scales = fp4 = None + if need_fp8: + codes = torch.empty((sp.padded, hidden), dtype=_FP8, device=device) + scales = torch.empty( + (sp.padded, hidden // 32), dtype=torch.uint8, device=device + ) + if mxfp4: + fp4 = ( + torch.empty((sp.padded, hidden // 2), dtype=torch.uint8, device=device), + torch.empty((sp.padded, hidden // 32), dtype=torch.uint8, device=device), + ) + routing = None + if moe is not None: + width = _routing_width(moe) + routing = torch.empty((sp.padded, width), dtype=torch.int32, device=device) + norm = layer.post_attention_layernorm + box = [] + + def run(coll): + h = _o_proj_all_to_all(layer.self_attn, attn_output, sp, coll) + x, r, x_q, x_s = gemma_rmsnorm_mx( + h, + residual, + norm.weight, + norm.variance_epsilon, + min_scale_byte=MOE_MIN_SCALE_BYTE if moe is not None and not mxfp4 else 0, + store_out=moe is not None, + q_out=coll.alloc((sp.rows, hidden), _FP8) if need_fp8 else None, + scale_out=( + coll.alloc((sp.rows, hidden // 32), torch.uint8) if need_fp8 else None + ), + ) + outs, ins = [], [] + if need_fp8: + outs += [codes, scales] + ins += [x_q, x_s] + if mxfp4: + outs += list(fp4) + ins += mxfp4_quant( + x, + coll.alloc((sp.rows, hidden // 2), torch.uint8), + coll.alloc((sp.rows, hidden // 32), torch.uint8), + ) + if moe is not None: + rt = _route(moe, x, coll.alloc((sp.rows, width), torch.int32)) + outs.append(routing) + ins.append(rt) + coll.all_gather(outs, ins) + box.append(r) + + sp.phase(run) + return codes, scales, routing, fp4, box[0] + + +def max_regular_tokens(num_ubatches: int = 1) -> int: + """The largest forward or microbatch on the regular path. The SP profile run + skips the modular kernel, so it reserves that MoE workspace before the lock; + the last microbatch takes up to ``num_ubatches - 1`` extra tokens.""" + return max(SP_MIN_TOKENS, SP_MIN_UBATCH_TOKENS) - 1 + max(num_ubatches, 1) - 1 + + +def _reserve_moe_workspace(moe, num_tokens: int, topk: int) -> None: + """Size the workspace for a regular MoE call of ``num_tokens`` rows.""" + from vllm.v1.worker.workspace import ( + current_workspace_manager, + is_workspace_manager_initialized, + ) + + if ( + not is_workspace_manager_initialized() + or current_workspace_manager().is_locked() + ): + return + runner = moe.experts + kernel = runner._quant_method.moe_kernel + routed = runner.routed_experts + w1, w2 = routed.w13_weight, routed.w2_weight + hidden = w2.shape[1] + a1 = torch.empty((num_tokens, hidden), dtype=torch.bfloat16, device=w1.device) + topk_ids = torch.empty((num_tokens, topk), dtype=torch.int32, device=w1.device) + _, m, n, k, top_k = kernel.fused_experts.moe_problem_size(a1, w1, w2, topk_ids) + global_num_experts = routed.global_num_experts + if global_num_experts == -1: + global_num_experts = w1.shape[0] + kernel.impl._allocate_buffers( + a1.dtype, + a1.device, + m, + m, + n, + k, + top_k, + global_num_experts, + w1.shape[0], + None, + routed.activation, + ) + + +# The profile run compiles the MoE configs of these sizes, so no request waits. +_WARM_UP_TOKENS = (SP_MIN_TOKENS, 16384, 32768) +_warmed = False + + +def _moe_experts(sp: SeqShard, moe, codes, scales, routing, fp4) -> torch.Tensor: + """The MoE of every token -> its TP partial ``[padded, H]``.""" + global _warmed + runner = moe.experts + t = sp.num_tokens + topk = routing.shape[1] // 2 + _reserve_moe_workspace(moe, max_regular_tokens(_NUM_UBATCHES), topk) + w13, w2 = runner.routed_experts.w13_weight, runner.routed_experts.w2_weight + hidden = w2.shape[1] + experts = runner._quant_method.moe_kernel.fused_experts + if fp4 is None: + from .ops.moe_mxfp8.prefill import a8w8_prefill_moe as moe_chain + + x_q, x_s = codes, scales + w13_s, w2_s = experts.w1_scale_val, experts.w2_scale_val + else: + from .ops.moe_mxfp4.prefill import a4w4_prefill_moe as moe_chain + + x_q, x_s = fp4 + w13_s, w2_s = experts.quant_config.w1_scale, experts.quant_config.w2_scale + + def chain(m: int, out: torch.Tensor | None) -> torch.Tensor: + return moe_chain( + (x_q[:m], x_s[:m]), + w13, + w13_s, + w2, + w2_s, + routing[:m, topk:].view(torch.float32), + routing[:m, :topk], + hidden_size=hidden, + intermediate_size=runner.moe_config.intermediate_size_per_partition, + num_experts=w13.shape[0], + out=out, + ) + + if not _warmed: + _warmed = True + for m in _WARM_UP_TOKENS: + if m < t: + chain(m, None) + out = sp.alloc((sp.padded, hidden), torch.bfloat16, routing.device) + out[t:].zero_() + chain(t, out[:t]) + if runner.routed_scaling_factor != 1.0: + out[:t] *= runner.routed_scaling_factor + if moe.shared_experts is not None: + out[:t] += _mlp(moe.shared_experts, codes[:t], scales[:t]) + return out + + +def _mlp(mlp, x_q: torch.Tensor, x_s: torch.Tensor) -> torch.Tensor: + """A dense MLP on pre-quantized rows -> its TP partial (no reduce).""" + from .ops import swiglu_oai_split + + x = swiglu_oai_split( + _linear(mlp.gate_up_proj, x_q, x_s), + alpha=mlp.swiglu_alpha, + beta=mlp.swiglu_beta, + limit=mlp.swiglu_limit, + ) + return mlp.down_proj.quant_method.apply(mlp.down_proj, x) + + +def _ffn(sp: SeqShard, layer, codes, scales, routing, fp4) -> torch.Tensor: + """The MoE / dense MLP of every token -> its TP partial ``[padded, H]``.""" + if layer.is_moe_layer: + return _moe_experts(sp, layer.block_sparse_moe, codes, scales, routing, fp4) + t = sp.num_tokens + return sp.pad(_mlp(layer.mlp, codes[:t], scales[:t])) + + +def _ffn_out_phase(sp: SeqShard, model, partial, residual, nxt, want_aux, aux_out): + """Reduce-scatter of the FFN partial, then ``nxt``'s input norm + quant (the + final norm after the last layer) on this rank's rows and the gather; an aux + hidden state is gathered into ``aux_out``.""" + from .ops.sp_norm_quant import gemma_rmsnorm_mx + + hidden = partial.shape[1] + device = partial.device + aux = None + if want_aux: + aux = torch.empty((sp.padded, hidden), dtype=partial.dtype, device=device) + aux_out.append(aux) + scales = None + if nxt is not None: + codes = torch.empty((sp.padded, hidden), dtype=_FP8, device=device) + scales = torch.empty( + (sp.padded, hidden // 32), dtype=torch.uint8, device=device + ) + else: + codes = torch.empty((sp.padded, hidden), dtype=partial.dtype, device=device) + box = [] + + def run(coll): + h = torch.empty((sp.rows, hidden), dtype=partial.dtype, device=device) + coll.reduce_scatter(h, partial) + if nxt is not None: + norm = nxt.input_layernorm + _, r, x_q, x_s = gemma_rmsnorm_mx( + h, + residual, + norm.weight, + norm.variance_epsilon, + q_out=coll.alloc((sp.rows, hidden), _FP8), + scale_out=coll.alloc((sp.rows, hidden // 32), torch.uint8), + ) + outs, ins = [codes, scales], [x_q, x_s] + else: + normed, r = model.norm(h, residual) + outs, ins = [codes], [normed] + if aux is not None: + outs.append(aux) + ins.append(r) + coll.all_gather(outs, ins) + box.append(r) + + sp.phase(run) + return codes, scales, box[0] + + +def forward( + model, + positions: torch.Tensor, + hidden_states: torch.Tensor, + aux_hidden_states: list[torch.Tensor], + sp: SeqShard, +) -> torch.Tensor | tuple[torch.Tensor, list[torch.Tensor]]: + """Sequence-parallel forward of ``model`` from the embeddings to the final + norm.""" + layers = model.layers[model.start_layer : model.end_layer] + t = sp.num_tokens + codes, scales, residual = _input_phase(sp, layers[0], hidden_states) + aux_gathered: list[torch.Tensor] = [] + for idx, layer in enumerate(layers): + sp.begin_phase() + qkv = _linear(layer.self_attn.qkv_proj, codes[:t], scales[:t]) + attn_output = layer.self_attn.attend(positions, qkv) + codes, scales, routing, fp4, residual = _post_attention_phase( + sp, layer, attn_output, residual + ) + sp.begin_phase() + partial = _ffn(sp, layer, codes, scales, routing, fp4) + nxt = layers[idx + 1] if idx + 1 < len(layers) else None + want_aux = model.start_layer + idx + 1 in model.aux_hidden_state_layers + codes, scales, residual = _ffn_out_phase( + sp, model, partial, residual, nxt, want_aux, aux_gathered + ) + aux_hidden_states += [a[:t] for a in aux_gathered] + if aux_hidden_states: + return codes[:t], aux_hidden_states + return codes[:t] diff --git a/vllm/models/minimax_m3/amd/sparse_attention_msa.py b/vllm/models/minimax_m3/amd/sparse_attention_msa.py index a2c49d13abf0..44ad045db0d9 100644 --- a/vllm/models/minimax_m3/amd/sparse_attention_msa.py +++ b/vllm/models/minimax_m3/amd/sparse_attention_msa.py @@ -126,7 +126,6 @@ def forward( kv_cache: torch.Tensor, output: torch.Tensor, *, - query_fp8: torch.Tensor | None = None, decode_sparse_table: tuple[torch.Tensor, torch.Tensor] | None = None, ) -> torch.Tensor: from vllm.models.minimax_m3.amd.ops.sparse_pa import ( diff --git a/vllm/models/minimax_m3/amd/sparse_attention_nvfp4.py b/vllm/models/minimax_m3/amd/sparse_attention_nvfp4.py new file mode 100644 index 000000000000..72f816956438 --- /dev/null +++ b/vllm/models/minimax_m3/amd/sparse_attention_nvfp4.py @@ -0,0 +1,170 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MiniMax M3 block-sparse attention over an NVFP4 K/V cache on ROCm (gfx950). + +The cache spec is NVIDIA's, but the bytes inside a page are laid out for the +FlyDSL kernels, so pages are not interchangeable with NVIDIA's. +""" + +from dataclasses import replace +from typing import ClassVar + +import torch + +from vllm.config.cache import CacheDType +from vllm.forward_context import get_forward_context +from vllm.models.minimax_m3.common.sparse_attention import ( + MiniMaxM3SparseBackend, + MiniMaxM3SparseImpl, + MiniMaxM3SparseMetadata, + MiniMaxM3SparseMetadataBuilder, + minimax_m3_query_token_positions, +) +from vllm.utils.torch_utils import get_dtype_size, nvfp4_kv_cache_full_dim +from vllm.v1.attention.backend import AttentionLayer, CommonAttentionMetadata +from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout + + +class MiniMaxM3SparseRocmNvfp4MetadataBuilder(MiniMaxM3SparseMetadataBuilder): + """Adds each prefill token's request and absolute position.""" + + def build( + self, + common_prefix_len: int, + common_attn_metadata: CommonAttentionMetadata, + fast_build: bool = False, + ) -> MiniMaxM3SparseMetadata: + metadata = super().build(common_prefix_len, common_attn_metadata, fast_build) + p = metadata.prefill + if p is not None and p.query_req_id is None: + p.query_req_id, p.query_abs_pos = minimax_m3_query_token_positions( + p.cu_seqlens_q, p.context_lens, metadata.num_prefill_tokens + ) + return metadata + + +class MiniMaxM3SparseRocmNvfp4Backend(MiniMaxM3SparseBackend): + """MiniMax M3 sparse attend over NVFP4 K/V pages (ROCm, gfx950).""" + + supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = ["nvfp4"] + + @staticmethod + def get_builder_cls() -> type["MiniMaxM3SparseRocmNvfp4MetadataBuilder"]: + return MiniMaxM3SparseRocmNvfp4MetadataBuilder + + @classmethod + def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec: + """Store each head's K and V as two slots of packed data + block scales.""" + if spec.state_content_bytes is not None or not spec.kv_quant_mode.is_nvfp4: + return spec + return replace( + spec, + num_head_slots=2 * spec.num_kv_heads, + state_content_bytes=nvfp4_kv_cache_full_dim(spec.head_size) + * get_dtype_size(spec.dtype), + ) + + @classmethod + def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...] | None: + # The kernels read the page stride from stride(0) and address pages in + # 64 bits, so block-outer packing works too (opt in with BLHNC). + return (KVCacheLayout.LBHNC, KVCacheLayout.BLHNC) + + +def rocm_nvfp4_unsupported_reason( + num_heads: int, num_kv_heads: int, head_dim: int, topk_blocks: int, block_size: int +) -> str | None: + """Why the ROCm NVFP4 attend cannot serve this layer, None when it can.""" + from vllm.models.minimax_m3.amd.ops.nvfp4_prefill.host import ( + supports_nvfp4_sparse_prefill, + ) + + if not supports_nvfp4_sparse_prefill( + num_heads, num_kv_heads, head_dim, topk_blocks, block_size + ): + return ( + "needs gfx950, head_dim 128, 16 query heads per KV head and 16 " + f"selected 128-token blocks (got num_heads={num_heads}, " + f"num_kv_heads={num_kv_heads}, head_dim={head_dim}, " + f"topk_blocks={topk_blocks}, block_size={block_size})" + ) + return None + + +class MiniMaxM3SparseRocmNvfp4Impl(MiniMaxM3SparseImpl): + """FlyDSL NVFP4 sparse decode (bf16 compute) and prefill (fp16 compute).""" + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + reason = rocm_nvfp4_unsupported_reason( + self.num_heads, + self.num_kv_heads, + self.head_size, + self.topk_blocks, + self.block_size, + ) + if reason is not None: + raise ValueError(f"MiniMax M3 NVFP4 KV cache on ROCm {reason}") + + def forward( + self, + layer: AttentionLayer, + query: torch.Tensor, + kv_cache: torch.Tensor, + output: torch.Tensor, + ) -> torch.Tensor: + from vllm.models.minimax_m3.amd.ops.nvfp4_prefill.host import ( + minimax_m3_nvfp4_sparse_prefill, + ) + from vllm.models.minimax_m3.amd.ops.nvfp4_sparse_decode.host import ( + minimax_m3_nvfp4_sparse_decode_fly, + ) + + attn_metadata = get_forward_context().attn_metadata + if not isinstance(attn_metadata, dict): + return output # profiling run; caches unbound + md = attn_metadata[layer.layer_name] # type: ignore[attr-defined] + assert isinstance(md, MiniMaxM3SparseMetadata) + + nd = md.num_decode_tokens + num_tokens = md.num_actual_tokens + topk = layer.topk_indices_buffer # type: ignore[attr-defined] + assert topk is not None + q = query[:num_tokens].view(-1, self.num_heads, self.head_size) + out = output[:num_tokens].view(-1, self.num_heads, self.head_size) + k_scale = layer._k_scale # type: ignore[attr-defined] + v_scale = layer._v_scale # type: ignore[attr-defined] + + if md.num_decodes > 0: + d = md.decode + assert d is not None + minimax_m3_nvfp4_sparse_decode_fly( + q[:nd].contiguous(), + kv_cache, + topk[:, :nd, :], + d.block_table, + d.seq_lens, + self.scale, + out[:nd], + k_scale=k_scale, + v_scale=v_scale, + decode_query_len=d.decode_query_len, + ) + if md.num_prefills > 0: + p = md.prefill + assert p is not None + assert p.query_req_id is not None and p.query_abs_pos is not None + minimax_m3_nvfp4_sparse_prefill( + q[nd:], + kv_cache, + topk[:, nd:num_tokens, :], + p.block_table, + p.query_req_id, + p.query_abs_pos, + self.num_kv_heads, + self.scale, + out[nd:], + k_scale=k_scale, + v_scale=v_scale, + ) + return output diff --git a/vllm/models/minimax_m3/common/dspark.py b/vllm/models/minimax_m3/common/dspark.py new file mode 100644 index 000000000000..58fecf2bc353 --- /dev/null +++ b/vllm/models/minimax_m3/common/dspark.py @@ -0,0 +1,413 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MiniMax-M3.1 DSpark draft model. + +The Qwen3 DSpark block drafter (context-KV precompute, non-causal query block, +Markov and confidence heads) built from MiniMax-M3 layers: Gemma RMSNorm +(``x * (1 + w)``) everywhere, partial RoPE, and a dense SwiGLU-OAI MLP. The +checkpoint ships no token embedding or LM head; both are shared with the target. +""" + +from collections.abc import Iterable + +import torch +from torch import nn + +from vllm import _custom_ops as ops +from vllm.config import CacheConfig, VllmConfig +from vllm.model_executor.layers.activation import SiluAndMulWithClamp +from vllm.model_executor.layers.attention.attention import get_attention_context +from vllm.model_executor.layers.fusion.quant_activation import get_input_quant_key +from vllm.model_executor.layers.linear import ( + MergedColumnParallelLinear, + RowParallelLinear, +) +from vllm.model_executor.layers.quantization import QuantizationConfig +from vllm.model_executor.layers.quantization.utils.quant_utils import kMxfp8Dynamic +from vllm.model_executor.models.qwen3_dflash import ( + DFlashQwen3Attention, + DFlashQwen3DecoderLayer, + _resolve_layer_attention, +) +from vllm.model_executor.models.qwen3_dspark import ( + Qwen3DSparkForCausalLM, + Qwen3DSparkModel, +) +from vllm.model_executor.models.utils import WeightsMapper +from vllm.models.minimax_m3.common.ops.dspark_context_kv import ( + DSparkContextKVWriter, + rotary_dims_supported, +) +from vllm.platforms import current_platform +from vllm.transformers_utils.configs.minimax_m3 import MiniMaxM3TextConfig +from vllm.utils.torch_utils import ( + LayerNameType, + _encode_layer_name, + _resolve_layer_name, + direct_register_custom_op, +) + +_CHECKPOINT_PREFIX = "language_model.model.dspark." + + +def _shared_slot_mapping( + slot_mapping: torch.Tensor | list[torch.Tensor | None] | None, +) -> torch.Tensor | None: + """The context slot mapping when every draft layer shares it, else None + (dummy runs, and drafts whose layers span several KV cache groups).""" + if slot_mapping is None or isinstance(slot_mapping, torch.Tensor): + return slot_mapping + first = slot_mapping[0] + if first is None or any( + s is None or s.data_ptr() != first.data_ptr() for s in slot_mapping + ): + return None + return first + + +def _gemma_rms_norm(hidden_size: int, eps: float) -> nn.Module: + """The target's Gemma RMSNorm (fused FlashInfer kernels on CUDA). + + vLLM's GemmaRMSNorm hands the IR op an fp32 ``1 + w`` weight, which the + vllm_c kernel rejects for bf16 inputs, so every call ran the unfused native + path (about ten kernels). + """ + if current_platform.is_rocm(): + from vllm.models.minimax_m3.amd.model import MiniMAXGemmaRMSNorm + else: + from vllm.models.minimax_m3.nvidia.model import MiniMAXGemmaRMSNorm + return MiniMAXGemmaRMSNorm(hidden_size, eps=eps) + + +def dspark_qknorm_rope_kv_insert( + qkv: torch.Tensor, + q_norm_weight: torch.Tensor, + k_norm_weight: torch.Tensor, + cos_sin_cache: torch.Tensor, + positions: torch.Tensor, + num_heads: int, + num_kv_heads: int, + rotary_dim: int, + eps: float, + q_fp8_out: torch.Tensor | None, + layer_name: LayerNameType, +) -> None: + """The fused QK-norm/RoPE on ``qkv``, also storing the draft tokens' k/v. + + A custom op so the slot mapping is read when it runs: read in the compiled + forward, it is fixed at trace time, when the draft layers have none. + """ + _, layer, kv_cache, slot_mapping = get_attention_context( + _resolve_layer_name(layer_name) + ) + insert = slot_mapping is not None + ops.fused_minimax_m3_qknorm_rope_kv_insert( + qkv, + q_norm_weight, + k_norm_weight, + cos_sin_cache, + positions, + num_heads, + num_kv_heads, + rotary_dim, + eps, + slot_mapping=slot_mapping, + kv_cache=kv_cache if insert else None, + block_size=kv_cache.size(2) if insert else 0, + kv_cache_dtype="fp8" if insert and kv_cache.dtype == torch.uint8 else "auto", + q_fp8_out=q_fp8_out, + q_fp8_scale=layer._q_scale_float, + ) + + +def dspark_qknorm_rope_kv_insert_fake( + qkv: torch.Tensor, + q_norm_weight: torch.Tensor, + k_norm_weight: torch.Tensor, + cos_sin_cache: torch.Tensor, + positions: torch.Tensor, + num_heads: int, + num_kv_heads: int, + rotary_dim: int, + eps: float, + q_fp8_out: torch.Tensor | None, + layer_name: LayerNameType, +) -> None: + return + + +direct_register_custom_op( + op_name="minimax_m3_dspark_qknorm_rope_kv_insert", + op_func=dspark_qknorm_rope_kv_insert, + mutates_args=["qkv", "q_fp8_out"], + fake_impl=dspark_qknorm_rope_kv_insert_fake, +) + + +class MiniMaxM3DSparkAttention(DFlashQwen3Attention): + def __init__( + self, + config: MiniMaxM3TextConfig, + sliding_window: int | None, + causal: bool, + cache_config: CacheConfig | None, + quant_config: QuantizationConfig | None, + prefix: str, + query_pre_quantized: bool = False, + ) -> None: + super().__init__( + hidden_size=config.hidden_size, + num_heads=config.num_attention_heads, + num_kv_heads=config.num_key_value_heads, + rope_parameters={ + "rope_theta": config.rope_theta, + "partial_rotary_factor": config.partial_rotary_factor, + }, + max_position=config.max_position_embeddings, + head_dim=config.head_dim, + rms_norm_eps=config.rms_norm_eps, + sliding_window=sliding_window, + causal=causal, + cache_config=cache_config, + quant_config=quant_config, + prefix=prefix, + query_pre_quantized=query_pre_quantized, + ) + self.q_norm = _gemma_rms_norm(self.head_dim, eps=config.rms_norm_eps) + self.k_norm = _gemma_rms_norm(self.head_dim, eps=config.rms_norm_eps) + # With an FP8 KV cache the backend wants an FP8 query, and the fused + # kernel below can write one. Producing it there instead of letting the + # attention layer quantize afterwards saves a pass over q. + self._emit_fp8_query = query_pre_quantized + # FLASHINFER_TS writes an FP8 query's output as FP16 (FA4 only bf16); + # an MXFP8 o_proj quantizes FP16 as readily and writes the model dtype. + self._attn_output_dtype = ( + torch.float16 + if query_pre_quantized + and self.attn.attn_backend.get_name() == "FLASHINFER_TS" + and get_input_quant_key(self.o_proj) == kMxfp8Dynamic + else None + ) + + def forward( + self, + positions: torch.Tensor, + hidden_states: torch.Tensor, + ) -> torch.Tensor: + qkv, _ = self.qkv_proj(hidden_states) + # The target's fused per-head Gemma QK-norm + partial NeoX RoPE on q/k, + # in place: one launch instead of the q-norm, k-norm and RoPE kernels. + # q_fp8_out additionally stores the normed/roped q as E4M3, which is + # what an FP8-KV backend consumes. + q_fp8 = ( + torch.empty( + (qkv.shape[0], self.q_size), + dtype=current_platform.fp8_dtype(), + device=qkv.device, + ) + if self._emit_fp8_query + else None + ) + # Also stores the draft tokens' k/v, so the attention layer gets q alone. + torch.ops.vllm.minimax_m3_dspark_qknorm_rope_kv_insert( + qkv, + self.q_norm.weight, + self.k_norm.weight, + self.rotary_emb.cos_sin_cache, + positions, + self.num_heads, + self.num_kv_heads, + self.rotary_emb.rotary_dim, + self.q_norm.variance_epsilon, + q_fp8, + _encode_layer_name(self.attn.layer_name), + ) + q = qkv[:, : self.q_size] if q_fp8 is None else q_fp8 + # output_dtype must be stated: it otherwise follows the query, which + # may be FP8. + attn_output = self.attn( + q, None, None, output_dtype=self._attn_output_dtype or hidden_states.dtype + ) + output, _ = self.o_proj(attn_output) + return output + + +class MiniMaxM3DSparkMLP(nn.Module): + """Dense SwiGLU-OAI MLP: gate * sigmoid(alpha * gate) * (up + beta).""" + + def __init__( + self, + config: MiniMaxM3TextConfig, + quant_config: QuantizationConfig | None, + prefix: str, + ) -> None: + super().__init__() + if config.hidden_act != "swigluoai": + raise ValueError( + f"Unsupported MiniMax DSpark activation {config.hidden_act!r}; " + "only swigluoai is supported." + ) + intermediate_size = config.dspark_ffn_hidden_size + self.gate_up_proj = MergedColumnParallelLinear( + config.hidden_size, + [intermediate_size] * 2, + bias=False, + quant_config=quant_config, + prefix=f"{prefix}.gate_up_proj", + ) + self.down_proj = RowParallelLinear( + intermediate_size, + config.hidden_size, + bias=False, + quant_config=quant_config, + prefix=f"{prefix}.down_proj", + ) + self.act_fn = SiluAndMulWithClamp( + swiglu_limit=config.swiglu_limit, + alpha=config.swiglu_alpha, + beta=config.swiglu_beta, + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + gate_up, _ = self.gate_up_proj(x) + x, _ = self.down_proj(self.act_fn(gate_up)) + return x + + +class MiniMaxM3DSparkDecoderLayer(DFlashQwen3DecoderLayer): + def __init__( + self, + vllm_config: VllmConfig, + *, + config: MiniMaxM3TextConfig, + layer_idx: int, + cache_config: CacheConfig | None = None, + quant_config: QuantizationConfig | None = None, + prefix: str = "", + ) -> None: + nn.Module.__init__(self) + if not getattr(config, "dspark_use_dense_ffn", False): + raise NotImplementedError("MiniMax DSpark supports dense FFN drafts only.") + self.hidden_size = config.hidden_size + sliding_window, causal = _resolve_layer_attention(config, layer_idx) + # An FP8 draft cache means the backend reads an FP8 query, which the + # fused QK-norm/RoPE kernel emits directly. + kv_cache_dtype = getattr(cache_config, "cache_dtype", "auto") + self.self_attn = MiniMaxM3DSparkAttention( + config, + sliding_window=sliding_window, + causal=causal, + cache_config=cache_config, + quant_config=quant_config, + prefix=f"{prefix}.self_attn", + query_pre_quantized=str(kv_cache_dtype).startswith("fp8"), + ) + self.mlp = MiniMaxM3DSparkMLP(config, quant_config, prefix=f"{prefix}.mlp") + hidden_size, eps = config.hidden_size, config.rms_norm_eps + self.input_layernorm = _gemma_rms_norm(hidden_size, eps=eps) + self.post_attention_layernorm = _gemma_rms_norm(hidden_size, eps=eps) + + +class MiniMaxM3DSparkModel(Qwen3DSparkModel): + decoder_layer_cls = MiniMaxM3DSparkDecoderLayer + quant_config_mapper = WeightsMapper( + orig_to_new_prefix={_CHECKPOINT_PREFIX: "model."} + ) + + def __init__( + self, + *, + vllm_config: VllmConfig, + start_layer_id: int = 0, + prefix: str = "", + ) -> None: + super().__init__( + vllm_config=vllm_config, start_layer_id=start_layer_id, prefix=prefix + ) + hidden_size, eps = self.config.hidden_size, self.config.rms_norm_eps + self.hidden_norm = _gemma_rms_norm(hidden_size, eps=eps) + self.norm = _gemma_rms_norm(hidden_size, eps=eps) + + def _normalize_context_states(self, context_states: torch.Tensor) -> torch.Tensor: + return self.hidden_norm(context_states) + + def _normalize_context_k(self, all_k: torch.Tensor) -> torch.Tensor: + return torch.stack( + [layer.self_attn.k_norm(k) for layer, k in zip(self.layers, all_k)] + ) + + def _context_kv_writer(self) -> DSparkContextKVWriter | None: + """The fused context K/V writer, or None where the base path runs.""" + if not hasattr(self, "_ctx_kv_writer"): + if any(a.kv_cache.numel() == 0 for a in self._attn_layers): + return None # KV caches not bound yet: decide once they are + rotary_dim = self._rope_cos_sin_cache.shape[-1] + supported = ( + self._rope_is_neox + and self.layers[0].self_attn.v_scale is None + and rotary_dims_supported(rotary_dim, self._head_dim) + and self._rope_cos_sin_cache.dtype == torch.bfloat16 + and DSparkContextKVWriter.supported(self._attn_layers) + ) + self._ctx_kv_writer = ( + DSparkContextKVWriter(self._attn_layers) if supported else None + ) + return self._ctx_kv_writer + + def precompute_and_store_context_kv( + self, + context_states: torch.Tensor, + context_positions: torch.Tensor, + context_slot_mapping: torch.Tensor | list[torch.Tensor | None] | None = None, + ) -> None: + """One kernel norms, ropes and stores the context K/V of every layer, + straight from the projection output.""" + slot_mapping = _shared_slot_mapping(context_slot_mapping) + writer = ( + self._context_kv_writer() + if slot_mapping is not None + and hasattr(self, "_num_attn_layers") + and context_states.dtype == torch.bfloat16 + else None + ) + if writer is None: + super().precompute_and_store_context_kv( + context_states, context_positions, context_slot_mapping + ) + return + all_kv = self._project_context_kv_token_major( + context_states, + context_states.shape[0], + self._num_attn_layers, + self._num_kv_heads, + self._head_dim, + ) + writer( + all_kv, + self._k_norm_weights, + self._rms_norm_eps, + context_positions, + self._rope_cos_sin_cache, + self._rope_cos_sin_cache.shape[-1], + slot_mapping, + ) + + +class MiniMaxM3DSparkForCausalLM(Qwen3DSparkForCausalLM): + model_cls = MiniMaxM3DSparkModel + + @staticmethod + def _rename_checkpoint_weights( + weights: Iterable[tuple[str, torch.Tensor]], + ) -> Iterable[tuple[str, torch.Tensor]]: + for name, tensor in weights: + name = name.removeprefix(_CHECKPOINT_PREFIX) + name = name.replace(".decoder_layer.", ".") + if name.startswith("final_norm."): + name = "norm." + name.removeprefix("final_norm.") + # MiniMax stores the MXFP8 E8M0 block scales as weight_scale_inv. + name = name.replace(".weight_scale_inv", ".weight_scale") + yield name, tensor + + def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]): + return super().load_weights(self._rename_checkpoint_weights(weights)) diff --git a/vllm/models/minimax_m3/common/indexer.py b/vllm/models/minimax_m3/common/indexer.py index 0d7ee1d2f9ba..c86d1fcd7b33 100644 --- a/vllm/models/minimax_m3/common/indexer.py +++ b/vllm/models/minimax_m3/common/indexer.py @@ -115,20 +115,30 @@ def __init__( backend_cls: type[AttentionBackend] = MiniMaxM3IndexerBackend, ) -> None: super().__init__() + # Per-token storage width in elements of ``dtype``. + self.head_size = head_dim if indexer_kv_dtype in ("fp8", "fp8_e4m3"): - cache_dtype = torch.float8_e4m3fn + cache_dtype = query_dtype = torch.float8_e4m3fn elif indexer_kv_dtype == "bf16": - cache_dtype = torch.bfloat16 + cache_dtype = query_dtype = torch.bfloat16 + elif indexer_kv_dtype == "nvfp4": + # Packed NVFP4 pages scored by the MSA Q8KV4 indexer with e4m3 Q. + cache_dtype, query_dtype = torch.uint8, torch.float8_e4m3fn + self.head_size = head_dim // 2 + head_dim // 16 else: raise NotImplementedError( f"indexer_kv_dtype={indexer_kv_dtype!r} is not supported by the " - "MiniMax M3 indexer cache (only 'bf16' or 'fp8'/'fp8_e4m3')." + "MiniMax M3 indexer cache (only 'bf16', 'fp8'/'fp8_e4m3' or " + "'nvfp4')." ) self.kv_cache = torch.tensor([]) self.head_dim = head_dim self.indexer_kv_dtype = indexer_kv_dtype - # Side-cache storage dtype: bf16, or e4m3 for the fp8 score path. + # Side-cache storage dtype: bf16, e4m3 for the fp8 score path, or uint8 + # for packed NVFP4. self.dtype = cache_dtype + # Index-query dtype the fused qk-norm/rope kernel emits. + self.query_dtype = query_dtype self.prefix = prefix self.cache_config = cache_config # Impl-chosen backend -> each impl gets its own builder (get_attn_backend). @@ -147,7 +157,7 @@ def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec: return MLAAttentionSpec( block_size=vllm_config.cache_config.block_size, num_kv_heads=1, - head_size=self.head_dim, + head_size=self.head_size, dtype=self.dtype, cache_role=SparseCacheRole.INDEXER, ) @@ -392,6 +402,11 @@ def __init__( backend_cls=type(self).indexer_backend_cls, ) + def reserve_workspace(self) -> None: + """Reserve the workspace-manager scratch ``forward`` needs; called from + the memory-profiling run, which skips ``forward``.""" + return + def forward( self, index_query: torch.Tensor, @@ -501,8 +516,9 @@ def select_indexer_impl_cls( On Blackwell (SM100) with ``topk_blocks == 16`` (the only width fmha_sm100's ``sparse_topk_select`` kernel supports), the fmha_sm100 score + top-k path is - used for both bf16 and fp8 index caches. Everything else falls back to the - Triton indexer, with fp8 restricted to CUDA platforms that advertise fp8 + used for both bf16 and fp8 index caches. An nvfp4 index cache uses the MSA + Q8KV4/Q8KV8 paged indexers (SM100/SM103/SM107 only). Everything else falls back to + the Triton indexer, with fp8 restricted to CUDA platforms that advertise fp8 support. """ if get_current_vllm_config().attention_config.minimax_m3_indexer_cp: @@ -530,10 +546,9 @@ def select_indexer_impl_cls( tp_size, ) return MiniMaxM3IndexerTritonCPImpl - if indexer_kv_dtype in ("mxfp4", "nvfp4"): + if indexer_kv_dtype == "mxfp4": raise NotImplementedError( - f"indexer_kv_dtype={indexer_kv_dtype!r} needs the (not-yet-added) " - "CuteDSL indexer impl." + "indexer_kv_dtype='mxfp4' is not supported by the MiniMax M3 indexer." ) is_cuda = current_platform.is_cuda() is_fp8 = indexer_kv_dtype in ("fp8", "fp8_e4m3") @@ -542,6 +557,28 @@ def select_indexer_impl_cls( f"indexer_kv_dtype={indexer_kv_dtype!r} requires CUDA fp8 support." ) is_sm100 = is_cuda and current_platform.is_device_capability_family(100) + if indexer_kv_dtype == "nvfp4": + if not ( + is_cuda + and ( + current_platform.is_device_capability(100) + or current_platform.is_device_capability(103) + or current_platform.is_device_capability(107) + ) + ): + raise NotImplementedError( + "indexer_kv_dtype='nvfp4' requires an SM100, SM103 or SM107 GPU." + ) + from vllm.models.minimax_m3.nvidia.indexer_nvfp4 import ( + MiniMaxM3IndexerNvfp4Impl, + ) + + logger.info_once( + "MiniMax M3 indexer: selected NVFP4 (MSA Q8KV4 decode, Q8KV8 prefill) " + "[topk_blocks=%d]", + topk_blocks, + ) + return MiniMaxM3IndexerNvfp4Impl use_msa = ( is_sm100 and topk_blocks == 16 @@ -628,6 +665,9 @@ def index_cache(self) -> MiniMaxM3IndexerCache: def num_index_heads(self) -> int: return self.impl.num_index_heads + def reserve_workspace(self) -> None: + self.impl.reserve_workspace() + def forward( self, index_query: torch.Tensor, diff --git a/vllm/models/minimax_m3/common/mm_preprocess.py b/vllm/models/minimax_m3/common/mm_preprocess.py index 958e4f189b78..807701576280 100644 --- a/vllm/models/minimax_m3/common/mm_preprocess.py +++ b/vllm/models/minimax_m3/common/mm_preprocess.py @@ -40,24 +40,28 @@ ) from vllm.transformers_utils.configs.minimax_m3 import MiniMaxM3Config from vllm.transformers_utils.processors.minimax_m3 import ( - MIN_SHORT_SIDE_PIXEL, MiniMaxM3VLImageProcessor, MiniMaxM3VLVideoProcessor, MiniMaxVLProcessor, - smart_resize, + compute_aligned_size, + resolve_max_long_side_pixel, ) +# Worst-case long-side caps in pixels, matching the processor's detail=high +# tiers. Profiling budgets are sized against these; request-level +# ``detail``/``max_long_side_pixel`` kwargs cannot exceed them. +_IMAGE_MAX_LONG_SIDE_PIXEL = 3584 +_VIDEO_MAX_LONG_SIDE_PIXEL = 2188 + # Upper bound on the number of frames used to build the dummy video during # memory profiling. Sized to the worst-case video the processor accepts: -# ``max_total_pixels // max_pixels_per_frame`` = 301,056,000 // 602,112 = 500 -# frames, each at the video processor's per-frame ``max_pixels`` (768 * 28 * 28 -# = 602,112). This reaches the true worst-case ~192,000 vision tokens, but only -# because the dummy video is sized via ``get_video_size_with_most_features()`` -# (the video ``max_pixels`` bound), not the smaller image bound. Without a cap, +# ``max_total_pixels // max_pixels_per_frame`` = 301,056,000 // (2184 * 2184) +# = 63 frames, each a square at the video long-side cap (2188 px floored to +# the patch*merge factor, 28). Without a cap, # ``_get_max_video_frames(seq_len)`` with M3's large ``max_model_len`` yields # ~1400 frames, producing a multi-GB dummy tensor that overflows the # multimodal encoder cache. -_MAX_FRAMES_PER_VIDEO = 500 +_MAX_FRAMES_PER_VIDEO = 63 class MiniMaxM3VLProcessingInfo(BaseProcessingInfo): @@ -101,34 +105,46 @@ def _get_vision_info( image_height: int, num_frames: int, image_processor, + mm_kwargs: Mapping[str, object], + modality: str, ) -> tuple[ImageSize, int]: """Compute resized image size and number of vision tokens. - Mirrors the processor's Qwen-style ``smart_resize`` (area bound by - ``max_pixels``) so token counts match the actual processor output. + Mirrors the processor's ``compute_aligned_size`` so token counts + match the actual processor output. """ patch_size: int = image_processor.patch_size merge_size: int = image_processor.merge_size temporal_patch_size: int = image_processor.temporal_patch_size factor = patch_size * merge_size - max_pixels: int = image_processor.max_pixels - # Long-side resize spec (opt-in). ``image_processor`` is the *video* - # processor when counting video tokens, so read the bounds off it. - max_long_side_pixel = getattr(image_processor, "max_long_side_pixel", None) - min_short_side_pixel = getattr( - image_processor, "min_short_side_pixel", MIN_SHORT_SIDE_PIXEL + + # ``image_processor`` is the *video* processor when counting video + # tokens, so modality-scoped request kwargs (flat keys overlaid with + # ``images_kwargs``/``videos_kwargs`` via ``modality=``) and processor + # defaults are read per modality. Per-key fallback mirrors the + # processor, whose own defaults feed ``resolve_max_long_side_pixel`` + # the same way. + merged = self.ctx.get_merged_mm_kwargs(mm_kwargs) + # nho2's get_merged_mm_kwargs has no ``modality=``: overlay the scoped + # dict here, as prod's overlay_modality_mm_kwargs does. + scoped = merged.get("images_kwargs" if modality == "image" else "videos_kwargs") + if isinstance(scoped, Mapping): + merged = {**merged, **scoped} + detail = merged.get("detail", getattr(image_processor, "detail", None)) + max_long_side_pixel = merged.get( + "max_long_side_pixel", getattr(image_processor, "max_long_side_pixel", None) + ) + resolved_long_side = resolve_max_long_side_pixel( + detail, max_long_side_pixel, modality=modality ) - new_h, new_w = smart_resize( + # No volumetric cap here: token counting must not raise; the video + # processor enforces its volume cap on the real inputs. + new_h, new_w = compute_aligned_size( image_height, image_width, - factor=factor, - max_pixels=max_pixels, - max_long_side_pixel=max_long_side_pixel, - min_short_side_pixel=min_short_side_pixel, - # Token counting must not raise; the volumetric/area cap is enforced - # in the processor's _preprocess on the real inputs. - max_total_pixels=None, + factor, + max_long_side_pixel=resolved_long_side, ) grid_h = new_h // patch_size grid_w = new_w // patch_size @@ -153,6 +169,8 @@ def get_num_image_tokens( image_height=image_height, num_frames=1, image_processor=image_processor, + mm_kwargs=mm_kwargs, + modality="image", ) return n @@ -170,48 +188,27 @@ def get_num_video_tokens( image_height=image_height, num_frames=num_frames, image_processor=image_processor, + mm_kwargs=mm_kwargs, + modality="video", ) return n def get_image_size_with_most_features(self) -> ImageSize: - # Largest square (a multiple of patch_size*merge_size) whose area is - # within the image processor's bound — this yields the most vision - # tokens for one image. With the long-side spec the square side is - # capped by ``max_long_side_pixel`` (and the fixed ``max_total_pixels``); - # otherwise it is bound by the ``max_pixels`` area. + # Worst case is a detail=high image: a square whose side is the max + # long side (3584 px, a multiple of patch_size*merge_size). image_processor = self.get_image_processor() factor = image_processor.patch_size * image_processor.merge_size - max_long_side_pixel = getattr(image_processor, "max_long_side_pixel", None) - if max_long_side_pixel is not None: - side_px = min( - max_long_side_pixel, - math.isqrt(image_processor.max_total_pixels), - ) - else: - side_px = math.isqrt(image_processor.max_pixels) - side = max(factor, (side_px // factor) * factor) + side = (_IMAGE_MAX_LONG_SIDE_PIXEL // factor) * factor return ImageSize(width=side, height=side) def get_video_size_with_most_features(self) -> ImageSize: - # Per-frame size that yields the most vision tokens, bound by the - # *video* processor's ``max_pixels`` (which differs from the image - # bound). Token count depends only on area, so maximize the area - # achievable with both sides a multiple of patch_size*merge_size rather - # than picking the largest square — a square (e.g. 756x756 for M3's - # 602,112 bound) leaves area on the table, undercounting frames. + # Worst single frame is a detail=high square capped by the video + # long-side max (2188 px), floored to a patch_size*merge_size + # multiple (2184). video_processor = self.get_video_processor() factor = video_processor.patch_size * video_processor.merge_size - per_frame_pixels = video_processor.max_pixels - max_long_side_pixel = getattr(video_processor, "max_long_side_pixel", None) - if max_long_side_pixel is not None: - # Long-side spec: a frame's worst case is a square capped by - # ``max_long_side_pixel`` (per-frame area, not the volumetric cap). - per_frame_pixels = min(per_frame_pixels, max_long_side_pixel**2) - units = per_frame_pixels // (factor * factor) # h_u * w_u - h_u = math.isqrt(units) - while units % h_u: - h_u -= 1 - return ImageSize(width=(units // h_u) * factor, height=h_u * factor) + side = (_VIDEO_MAX_LONG_SIDE_PIXEL // factor) * factor + return ImageSize(width=side, height=side) def get_max_image_tokens(self) -> int: image_processor = self.get_image_processor() @@ -220,7 +217,9 @@ def get_max_image_tokens(self) -> int: image_width=size.width, image_height=size.height, image_processor=image_processor, - mm_kwargs={}, + # Budgets must cover the worst case (detail=high); the default + # detail=auto cap would undercount. + mm_kwargs={"max_long_side_pixel": _IMAGE_MAX_LONG_SIDE_PIXEL}, ) def _get_max_video_frames(self, max_tokens: int) -> int: @@ -233,7 +232,8 @@ def _get_max_video_frames(self, max_tokens: int) -> int: image_height=size.height, num_frames=num_frames + 1, image_processor=video_processor, - mm_kwargs={}, + # Worst case (detail=high); see get_max_image_tokens. + mm_kwargs={"max_long_side_pixel": _VIDEO_MAX_LONG_SIDE_PIXEL}, ) if next_n > max_tokens: break @@ -265,7 +265,8 @@ def get_max_video_tokens( image_height=size.height, num_frames=self.get_num_frames_with_most_features(seq_len, mm_counts), image_processor=video_processor, - mm_kwargs={}, + # Worst case (detail=high); see get_max_image_tokens. + mm_kwargs={"max_long_side_pixel": _VIDEO_MAX_LONG_SIDE_PIXEL}, ) @@ -487,6 +488,11 @@ def load_bytes( backend: VideoDecoderBackend = "opencv", **kwargs, ) -> tuple[npt.NDArray, dict[str, Any]]: + # fps=-1 (unspecified) falls back to the default 1 fps. + if fps == -1: + fps = 1 + if not 0.2 <= fps <= 5: + raise ValueError(f"video fps must be in [0.2, 5], got {fps}") return super().load_bytes( data, num_frames=num_frames, @@ -526,6 +532,15 @@ def compute_frames_index_to_sample( break indices.append(target_frame) prev_kept_ts = target_frame / video_fps + + # Always keep the last frame when it is far enough (>= 1/fps, up to + # eps) from the previously kept frame, matching the SFT frame + # sampler's constant-mode behavior. + last_frame_idx = total_frames - 1 + last_ts = last_frame_idx / video_fps + if indices and indices[-1] != last_frame_idx and last_ts - prev_kept_ts > eps: + indices.append(last_frame_idx) + if not indices: indices = [0] return indices diff --git a/vllm/models/minimax_m3/common/ops/dspark_context_kv.py b/vllm/models/minimax_m3/common/ops/dspark_context_kv.py new file mode 100644 index 000000000000..514f052051d6 --- /dev/null +++ b/vllm/models/minimax_m3/common/ops/dspark_context_kv.py @@ -0,0 +1,170 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Fused DSpark context-KV write for all draft layers in one CUDA kernel. + +Replaces the permute copy, per-layer K-norm launches + stack, positions.repeat, +rotary_embedding and per-layer reshape_and_cache_flash calls in +``DFlashQwen3Model.precompute_and_store_context_kv``. K/V are read straight +from the fused projection output ``all_kv`` ``[num_ctx, L, 2, nkv, 128]`` and +written into each layer's paged cache (FLASH_ATTN, FLASHINFER_TS) +``[num_blocks, nkv, block_size, 2 * 128]`` (K at ``[..., :128]``, V at +``[..., 128:]``), matching ``reshape_and_cache_flash``: fp8 e4m3 of +``x / scale`` for kv_cache_dtype fp8, raw bf16 otherwise; slots < 0 are padding +and are not written. + +K gets the Gemma RMSNorm of its layer (``x * rsqrt(mean(x^2) + eps) * (1 + w)`` +in fp32, materialized to bf16 like the unfused flashinfer path) followed by +partial NeoX RoPE with the token's position (see +``fused_minimax_m3_dspark_context_kv``). Each layer's cache is a separate +allocation, addressed as layer 0's cache plus a per-layer element offset, and +each fp8 scale as layer 0's k scale plus a float offset; the offset tables are +built once and cached (keyed by the data_ptrs) so the call stays CUDA-graph +safe. +""" + +import torch + +from vllm import _custom_ops as ops +from vllm.platforms import current_platform + +_SUPPORTED_KV_DTYPES = ("auto", "bfloat16", "fp8", "fp8_e4m3") +_HEAD_DIM = 128 + + +def rotary_dims_supported(rotary_dim: int, head_dim: int) -> bool: + """The kernel rotates the leading 16, 32 or 64 dims of a 128-dim head.""" + return head_dim == _HEAD_DIM and rotary_dim in (16, 32, 64) + + +class DSparkContextKVWriter: + """Writes precomputed context K/V into every draft layer's KV cache. + + Built from the draft's ``Attention`` layers; the cache- and scale-offset + tables are cached, keyed by their data_ptrs, so calls captured in a CUDA + graph keep addressing the same memory. + """ + + def __init__(self, attn_layers: list) -> None: + layers = list(attn_layers) + error = self._validate(layers) + if error is not None: + raise ValueError(f"unsupported DSpark context-KV layout: {error}") + self._layers = layers + cache = layers[0].kv_cache + self._num_layers = len(layers) + self._num_kv_heads = cache.shape[1] + self._kv_cache_dtype = "fp8" if cache.dtype == torch.uint8 else "auto" + self._table_key: tuple | None = None + self._cache_offsets: torch.Tensor | None = None + self._scale_offsets: torch.Tensor | None = None + + @staticmethod + def _validate(layers: list) -> str | None: + if not layers: + return "no layers" + ref = None + for a in layers: + kv_dtype = getattr(a, "kv_cache_dtype", None) + if kv_dtype not in _SUPPORTED_KV_DTYPES: + return f"kv_cache_dtype {kv_dtype!r}" + cache = getattr(a, "kv_cache", None) + if not isinstance(cache, torch.Tensor) or cache.numel() == 0: + return "KV cache not bound" + if cache.dim() != 4 or cache.shape[3] != 2 * _HEAD_DIM: + return f"unexpected cache shape {tuple(cache.shape)}" + block_size = cache.shape[2] + if block_size & (block_size - 1): + return f"block size {block_size} is not a power of two" + if not cache.is_contiguous(): + return "cache is not contiguous" + if kv_dtype in ("fp8", "fp8_e4m3"): + if cache.dtype != torch.uint8: + return f"fp8 cache has dtype {cache.dtype}" + elif cache.dtype != torch.bfloat16: + return f"cache has dtype {cache.dtype}" + for name in ("_k_scale", "_v_scale"): + scale = getattr(a, name, None) + if ( + not isinstance(scale, torch.Tensor) + or scale.dtype != torch.float32 + or not scale.is_cuda + ): + return f"{name} is not a CUDA fp32 tensor" + key = (cache.shape, cache.stride(), cache.dtype, kv_dtype) + if ref is None: + ref = key + elif key != ref: + return "layers do not share cache shape/stride/dtype" + # Caches are addressed from layer 0's as 16-element aligned offsets. + delta = cache.data_ptr() - layers[0].kv_cache.data_ptr() + if delta % (16 * cache.element_size()): + return "layer caches are not 16-element aligned to each other" + return None + + @staticmethod + def supported(attn_layers: list) -> bool: + # The fp8 store is OCP E4M3; ROCm fnuz caches keep the base path. + if not current_platform.is_cuda() or not hasattr( + torch.ops._C, "fused_minimax_m3_dspark_context_kv" + ): + return False + return DSparkContextKVWriter._validate(list(attn_layers)) is None + + def _ensure_tables(self) -> None: + layers = self._layers + key = tuple( + (a.kv_cache.data_ptr(), a._k_scale.data_ptr(), a._v_scale.data_ptr()) + for a in layers + ) + if key == self._table_key: + return + cache0, scale0 = layers[0].kv_cache, layers[0]._k_scale + + def table(offsets: list[int]) -> torch.Tensor: + return torch.tensor(offsets, dtype=torch.int64, device=cache0.device) + + self._cache_offsets = table( + [ + (a.kv_cache.data_ptr() - cache0.data_ptr()) // cache0.element_size() + for a in layers + ] + ) + # [2, L]: k scales, then v scales, as float offsets from layer 0's k. + self._scale_offsets = table( + [ + (getattr(a, name).data_ptr() - scale0.data_ptr()) // 4 + for name in ("_k_scale", "_v_scale") + for a in layers + ] + ) + self._table_key = key + + def __call__( + self, + all_kv: torch.Tensor, + k_norm_weight: torch.Tensor, + eps: float, + positions: torch.Tensor, + cos_sin_cache: torch.Tensor, + rotary_dim: int, + slot_mapping: torch.Tensor, + ) -> None: + num_ctx, L, _, nkv, _ = all_kv.shape + assert self._num_layers == L and self._num_kv_heads == nkv + if num_ctx == 0: + return + self._ensure_tables() + ops.fused_minimax_m3_dspark_context_kv( + all_kv, + k_norm_weight, + cos_sin_cache, + positions, + slot_mapping, + self._layers[0].kv_cache, + self._cache_offsets, + self._layers[0]._k_scale, + self._scale_offsets, + rotary_dim, + eps, + self._kv_cache_dtype, + ) diff --git a/vllm/models/minimax_m3/common/sparse_attention.py b/vllm/models/minimax_m3/common/sparse_attention.py index 1346765f84cb..8501dd975dea 100644 --- a/vllm/models/minimax_m3/common/sparse_attention.py +++ b/vllm/models/minimax_m3/common/sparse_attention.py @@ -255,7 +255,7 @@ def __init__( ) -> None: super().__init__(kv_cache_spec, layer_names, vllm_config, device) self._init_reorder_batch_threshold(1, supports_spec_as_decode=True) - # Stable context-length buffer for decode cudagraph replays. + # Stable context-length buffer for the prefill metadata. self.context_len_buffer = torch.empty( vllm_config.scheduler_config.max_num_batched_tokens, dtype=torch.int32, @@ -297,14 +297,13 @@ def build( assert num_decodes + num_prefills == num_reqs assert num_decode_tokens + num_prefill_tokens == num_tokens - # Decode-first batch: context lengths into the stable cudagraph buffer. - context_lens = self.context_len_buffer[:num_reqs] - context_lens.copy_( - common_attn_metadata.compute_num_computed_tokens(), non_blocking=True - ) - prefill_metadata: MiniMaxM3SparsePrefillMetadata | None = None if num_prefills > 0: + # Only prefill reads the context lengths; decode-only steps skip it. + context_lens = self.context_len_buffer[:num_reqs] + context_lens.copy_( + common_attn_metadata.compute_num_computed_tokens(), non_blocking=True + ) seq_lens_cpu = common_attn_metadata.seq_lens_cpu_upper_bound assert seq_lens_cpu is not None prefill_seq_lens_cpu = seq_lens_cpu[num_decodes:] @@ -430,11 +429,12 @@ def forward( query: torch.Tensor, kv_cache: torch.Tensor, output: torch.Tensor, - *, - query_fp8: torch.Tensor | None = None, ) -> torch.Tensor: """Attend the queries to the indexer-selected blocks. Per kernel. + ``query`` is E4M3 for impls with ``use_cutlass_decode``, else the model + dtype. + The indexer has already written the top-k block ids into ``layer.topk_indices_buffer`` (decode at ``[:, :nd]``, prefill at ``[:, nd:num_tokens]``); the attend reads them from there. @@ -454,8 +454,6 @@ def forward( query: torch.Tensor, kv_cache: torch.Tensor, output: torch.Tensor, - *, - query_fp8: torch.Tensor | None = None, ) -> torch.Tensor: attn_metadata = get_forward_context().attn_metadata if not isinstance(attn_metadata, dict): @@ -554,6 +552,17 @@ def select_main_backend_and_impl_cls( "MiniMax M3 sparse attention supports only the 'nvfp4' NVFP4 KV " f"cache dtype, got {kv_cache_dtype}" ) + if use_nvfp4 and current_platform.is_rocm(): + from vllm.models.minimax_m3.amd.sparse_attention_nvfp4 import ( + MiniMaxM3SparseRocmNvfp4Backend, + MiniMaxM3SparseRocmNvfp4Impl, + ) + + logger.info_once( + "MiniMax M3 sparse attention selected ROCm NVFP4 (topk_blocks=%s)", + topk_blocks, + ) + return MiniMaxM3SparseRocmNvfp4Backend, MiniMaxM3SparseRocmNvfp4Impl if use_nvfp4 and (use_aiter_sparse_pa or not use_msa): raise ValueError( "MiniMax M3 sparse attention supports an NVFP4 KV cache only with " @@ -581,10 +590,11 @@ def select_main_backend_and_impl_cls( MiniMaxM3SparseMSABackend, MiniMaxM3SparseMSAImpl, MiniMaxM3SparseMSANvfp4Backend, + MiniMaxM3SparseMSANvfp4Impl, ) if use_nvfp4: - return MiniMaxM3SparseMSANvfp4Backend, MiniMaxM3SparseMSAImpl + return MiniMaxM3SparseMSANvfp4Backend, MiniMaxM3SparseMSANvfp4Impl return MiniMaxM3SparseMSABackend, MiniMaxM3SparseMSAImpl return MiniMaxM3SparseBackend, MiniMaxM3SparseTritonImpl diff --git a/vllm/models/minimax_m3/common/vision_tower.py b/vllm/models/minimax_m3/common/vision_tower.py index c7aba484f2a3..b730b07093bb 100644 --- a/vllm/models/minimax_m3/common/vision_tower.py +++ b/vllm/models/minimax_m3/common/vision_tower.py @@ -59,11 +59,12 @@ def __init__(self, config: PreTrainedConfig) -> None: stride=(temporal_patch_size, patch_size, patch_size), bias=False, ) + # The checkpoint stores this weight in fp32 (the vision tower's only + # fp32 tensor); keep it that way so the conv runs at full precision. + self.patch_embedding.to(torch.float32) def forward(self, pixel_values: torch.Tensor) -> torch.Tensor: # pixel_values: (N, C * temporal_patch_size * patch_size²) - if self.patch_embedding.weight.dtype != pixel_values.dtype: - self.patch_embedding = self.patch_embedding.to(pixel_values.dtype) x = pixel_values.reshape( pixel_values.shape[0], self.num_channels, @@ -71,7 +72,8 @@ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor: self.patch_size, self.patch_size, ) - return self.patch_embedding(x).reshape(x.shape[0], -1) + out = self.patch_embedding(x.to(self.patch_embedding.weight.dtype)) + return out.reshape(x.shape[0], -1).to(pixel_values.dtype) class MiniMaxVLAttention(nn.Module): @@ -657,7 +659,9 @@ def __init__( prefix=maybe_prefix(prefix, "patch_merge_mlp"), ) - self.dtype = self.vision_model.embeddings.patch_embedding.weight.dtype + # Tower compute dtype; the patch embedding weight stays fp32 (see + # MiniMaxVLPatchEmbed), so take it from the projector instead. + self.dtype = self.multi_modal_projector.linear_1.weight.dtype self.out_hidden_size = text_hidden_size def forward( diff --git a/vllm/models/minimax_m3/nvidia/indexer_nvfp4.py b/vllm/models/minimax_m3/nvidia/indexer_nvfp4.py new file mode 100644 index 000000000000..501d81f772a7 --- /dev/null +++ b/vllm/models/minimax_m3/nvidia/indexer_nvfp4.py @@ -0,0 +1,481 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""NVFP4 index-cache indexer impl for MiniMax M3 (SM100/SM103/SM107). + +The index-K side cache holds packed NVFP4 pages ``[num_blocks, 128, 72]`` (E2M1 +codes, then E4M3 block scales, no global scale) written by the fused +qk-norm/rope insert, and index-Q is E4M3. Both sides use the MSA paged indexers +of ``fmha_sm100`` with fused top-k, which write 15 score-ranked history pages +plus the query's local page last (``init_blocks=0, local_blocks=1``) as +logical block ids: + +* Decode scores the NVFP4 pages with the Q8KV4 decode indexer, which reads the + 1..8 queries of each request in place (they take the last slots of its + 8-query tile) and writes their top-k straight into the shared buffer. + Uniform decode batches are captured in full CUDA graphs, so each padded + batch size and query length gets its own CUDA-graph wrapper whose buffers + never move; the builder re-plans it outside capture every step. +* Prefill has no NVFP4 kernel. Each layer dequantizes the history pages of the + prefill requests into compact FP8 workspace pages (what the decode kernel + scores) and runs the Q8KV8 prefill indexer on them, in request chunks whose + pages fit the gather budget. + +All index heads of the rank share the index keys and select their own pages. +Prefill and decode score every head of the rank in one launch. Prefill plans +are rebuilt every step and only run eagerly (mixed batches are never captured +whole). +""" + +from dataclasses import dataclass, field +from typing import Any, ClassVar + +import torch + +from vllm.config import VllmConfig, get_current_vllm_config +from vllm.forward_context import get_forward_context +from vllm.models.minimax_m3.common.indexer import ( + MiniMaxM3IndexerBackend, + MiniMaxM3IndexerImpl, + MiniMaxM3IndexerMetadata, + MiniMaxM3IndexerMetadataBuilder, +) +from vllm.models.minimax_m3.nvidia.indexer_nvfp4_decode_cp import ( + Nvfp4DecodeCPLayer, + Nvfp4DecodeCPPlan, + get_nvfp4_indexer_decode_cp, +) +from vllm.models.minimax_m3.nvidia.ops.gather_nvfp4_index_k import ( + minimax_m3_gather_nvfp4_index_k_fp8, +) +from vllm.utils.math_utils import cdiv +from vllm.v1.attention.backend import ( + AttentionBackend, + CommonAttentionMetadata, + max_decode_query_len, +) +from vllm.v1.attention.backends.utils import split_decodes_and_prefills +from vllm.v1.kv_cache_interface import AttentionSpec +from vllm.v1.worker.workspace import current_workspace_manager + +PAGE_SIZE = 128 +HEAD_DIM = 128 +TOPK_BLOCKS = 16 +# Queries per request the Q8KV4 decode indexer scores. +DECODE_QUERY_LEN = 8 +# Longest block table the MSA indexers accept. +MAX_PAGES = 8192 +# Index heads the Q8KV4 decode indexer scores in one launch. +DECODE_NUM_HEADS = (1, 2, 4) + + +def _msa_indexers(): + """Import the MSA indexer wrappers. + + Through ``fmha_sm100.sparse``, which binds the package's csrc JIT loader. + """ + from vllm.third_party.fmha_sm100.sparse import ( + BatchDecodeIndexerQ8KV4Wrapper, + BatchPrefillIndexerQ8KV8Wrapper, + ) + + return BatchDecodeIndexerQ8KV4Wrapper, BatchPrefillIndexerQ8KV8Wrapper + + +def max_gather_pages(vllm_config: VllmConfig) -> int: + """FP8 pages one prefill chunk may gather; always fits one full request.""" + tokens = max( + vllm_config.model_config.max_model_len, + 4 * vllm_config.scheduler_config.max_num_batched_tokens, + ) + return cdiv(tokens, PAGE_SIZE) + + +class MiniMaxM3IndexerNvfp4Backend(MiniMaxM3IndexerBackend): + """Indexer side-cache backend selecting the NVFP4 builder.""" + + @staticmethod + def get_builder_cls() -> type["MiniMaxM3IndexerNvfp4MetadataBuilder"]: + return MiniMaxM3IndexerNvfp4MetadataBuilder + + +@dataclass +class MiniMaxM3IndexerNvfp4DecodeMetadata: + wrapper: Any # planned CUDA-graph wrapper, None when decode CP is on + num_reqs: int # includes zero-length full-CUDA-graph padding requests + query_len: int # uniform, <= DECODE_QUERY_LEN + # Set instead of the wrapper when decode CP is on. + cp_plan: Nvfp4DecodeCPPlan | None = None + + +@dataclass +class MiniMaxM3IndexerNvfp4PrefillChunk: + wrapper: Any # planned BatchPrefillIndexerQ8KV8Wrapper + # Token range within the prefill region (offsets from num_decode_tokens). + token_start: int + token_end: int + block_table: torch.Tensor # [n, max_blocks] physical pages + num_pages: torch.Tensor # [n] int32 history pages to gather + page_offsets: torch.Tensor # [n] int32 first compact page of each request + total_pages: int + max_pages: int + + +@dataclass +class MiniMaxM3IndexerNvfp4Metadata(MiniMaxM3IndexerMetadata): + """The base ``prefill``/``decode`` fields are unused on this path.""" + + decode_q8kv4: MiniMaxM3IndexerNvfp4DecodeMetadata | None = None + prefill_chunks: list[MiniMaxM3IndexerNvfp4PrefillChunk] = field( + default_factory=list + ) + + +class MiniMaxM3IndexerNvfp4MetadataBuilder(MiniMaxM3IndexerMetadataBuilder): + """Plans the MSA decode and prefill indexers once per step.""" + + def __init__( + self, + kv_cache_spec: AttentionSpec, + layer_names: list[str], + vllm_config: VllmConfig, + device: torch.device, + ) -> None: + super().__init__(kv_cache_spec, layer_names, vllm_config, device) + if self.max_decode_query_len > DECODE_QUERY_LEN: + raise NotImplementedError( + "The MiniMax M3 NVFP4 indexer scores at most " + f"{DECODE_QUERY_LEN} decode queries per request, got " + f"{self.max_decode_query_len} (use num_speculative_tokens <= " + f"{DECODE_QUERY_LEN - 1})." + ) + if self.num_index_heads not in DECODE_NUM_HEADS: + raise NotImplementedError( + "The MiniMax M3 NVFP4 indexer serves " + f"{DECODE_NUM_HEADS} index heads per rank, got " + f"{self.num_index_heads}." + ) + self.max_gather_pages = max_gather_pages(vllm_config) + # Decode wrapper per padded decode batch size and query length. + self.decode_wrappers: dict[tuple[int, int], Any] = {} + # Decode CP (opt-in); static, so all ranks and graphs agree. + self.decode_cp = get_nvfp4_indexer_decode_cp( + num_index_heads=self.num_index_heads, + max_decode_query_len=self.max_decode_query_len, + ) + # Pages a request can span; decode scores at most this many. + self.max_decode_pages = min( + cdiv(vllm_config.model_config.max_model_len, PAGE_SIZE), MAX_PAGES + ) + # One page-score scratch for every decode wrapper: they never run at + # once, and a buffer per batch size would hold 256 KiB per request at a + # 1M context for every batch size the engine sees. Decode batches, + # padded to a CUDA graph size, never exceed max_decode_reqs. + self.decode_score_buffer: torch.Tensor | None = None + if self.decode_cp is None: + max_decode_reqs = max( + vllm_config.scheduler_config.max_num_seqs, + vllm_config.compilation_config.max_cudagraph_capture_size or 0, + ) + decode_wrapper_cls, _ = _msa_indexers() + self.decode_score_buffer = torch.empty( + decode_wrapper_cls.score_buffer_size( + max_decode_reqs, + self.max_decode_pages, + num_heads=self.num_index_heads, + ), + dtype=torch.float32, + device=device, + ) + + def _decode_wrapper( + self, block_table: torch.Tensor, seq_lens: torch.Tensor, query_len: int + ) -> Any: + num_reqs = seq_lens.shape[0] + wrapper = self.decode_wrappers.get((num_reqs, query_len)) + if wrapper is None: + # The runner's block table and seq_lens are persistent buffers, so + # the wrapper reads them in place and plan() copies nothing. A + # strided (width-capped) block table gets its own buffer. + if not block_table.is_contiguous(): + block_table = torch.empty( + block_table.shape, dtype=torch.int32, device=self.device + ) + decode_wrapper_cls, _ = _msa_indexers() + wrapper = self.decode_wrappers[num_reqs, query_len] = decode_wrapper_cls( + num_heads=self.num_index_heads, + use_cuda_graph=True, + block_table_buffer=block_table, + seq_lens_buffer=seq_lens, + score_buffer=self.decode_score_buffer, + ) + return wrapper + + def build( + self, + common_prefix_len: int, + common_attn_metadata: CommonAttentionMetadata, + fast_build: bool = False, + ) -> MiniMaxM3IndexerNvfp4Metadata: + num_reqs = common_attn_metadata.num_reqs + num_tokens = common_attn_metadata.num_actual_tokens + seq_lens = common_attn_metadata.seq_lens + block_table = common_attn_metadata.block_table_tensor + qsl_cpu = common_attn_metadata.query_start_loc_cpu + + num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = ( + split_decodes_and_prefills( + common_attn_metadata, + decode_threshold=self.reorder_batch_threshold, + require_uniform=True, + ) + ) + assert num_decodes + num_prefills == num_reqs + assert num_decode_tokens + num_prefill_tokens == num_tokens + + decode: MiniMaxM3IndexerNvfp4DecodeMetadata | None = None + if num_decode_tokens > 0: + # num_decodes counts the zero-length requests that pad a full CUDA + # graph batch, so it is the batch size the graph was captured with. + query_lens_cpu = qsl_cpu[1 : num_decodes + 1] - qsl_cpu[:num_decodes] + query_len = int(query_lens_cpu[0]) + assert torch.all((query_lens_cpu == query_len) | (query_lens_cpu == 0)) + num_pages = min(block_table.shape[1], self.max_decode_pages) + if self.decode_cp is not None: + decode = MiniMaxM3IndexerNvfp4DecodeMetadata( + wrapper=None, + num_reqs=num_decodes, + query_len=query_len, + cp_plan=self.decode_cp.plan( + block_table[:num_decodes, :num_pages], + seq_lens[:num_decodes], + ), + ) + else: + decode_block_table = block_table[:num_decodes, :num_pages] + decode_seq_lens = seq_lens[:num_decodes] + wrapper = self._decode_wrapper( + decode_block_table, decode_seq_lens, query_len + ) + wrapper.plan(decode_block_table, decode_seq_lens, query_len=query_len) + decode = MiniMaxM3IndexerNvfp4DecodeMetadata( + wrapper=wrapper, + num_reqs=num_decodes, + query_len=query_len, + ) + + prefill_chunks: list[MiniMaxM3IndexerNvfp4PrefillChunk] = [] + if num_prefills > 0: + prefill_chunks = self._build_prefill_chunks( + common_attn_metadata, num_decodes + ) + + return MiniMaxM3IndexerNvfp4Metadata( + seq_lens=seq_lens, + max_seq_len=common_attn_metadata.max_seq_len, + slot_mapping=common_attn_metadata.slot_mapping, + num_actual_tokens=num_tokens, + num_decodes=num_decodes, + num_decode_tokens=num_decode_tokens, + num_prefills=num_prefills, + num_prefill_tokens=num_prefill_tokens, + decode_q8kv4=decode, + prefill_chunks=prefill_chunks, + ) + + def _build_prefill_chunks( + self, common_attn_metadata: CommonAttentionMetadata, num_decodes: int + ) -> list[MiniMaxM3IndexerNvfp4PrefillChunk]: + _, prefill_wrapper_cls = _msa_indexers() + num_reqs = common_attn_metadata.num_reqs + seq_lens = common_attn_metadata.seq_lens + block_table = common_attn_metadata.block_table_tensor + qsl_cpu = common_attn_metadata.query_start_loc_cpu[num_decodes : num_reqs + 1] + # Host-side lengths keep planning free of device syncs. An upper bound + # (async spec decode) only over-sizes the plan and the gather: the + # kernels mask by the device seq_lens and never score the extra pages. + seq_lens_cpu = common_attn_metadata.seq_lens_cpu_upper_bound + assert seq_lens_cpu is not None + seq_lens_cpu = seq_lens_cpu[num_decodes:num_reqs].to(torch.int32) + query_lens_cpu = (qsl_cpu[1:] - qsl_cpu[:-1]).to(torch.int32) + # Only pages before the last query's local page are ever scored. + history_pages = (seq_lens_cpu - 1) // PAGE_SIZE + device = seq_lens.device + + chunks = [] + start, num_prefills = 0, seq_lens_cpu.shape[0] + while start < num_prefills: + end, total_pages = start, 0 + while end < num_prefills and ( + end == start + or total_pages + int(history_pages[end]) <= self.max_gather_pages + ): + total_pages += int(history_pages[end]) + end += 1 + assert total_pages <= self.max_gather_pages + num_chunk_reqs = end - start + max_seq_len = int(seq_lens_cpu[start:end].max()) + width = cdiv(max_seq_len, PAGE_SIZE) + # [cu_seqlens_q | num_pages | page_offsets | compact block table] + # in one pinned buffer, so a single H2D copy is truly asynchronous + # (a pageable one may synchronize with the stream). + staging = torch.empty( + 3 * num_chunk_reqs + 1 + num_chunk_reqs * width, + dtype=torch.int32, + pin_memory=True, + ) + cu_seqlens_q, pages, offsets, table = staging.split( + [ + num_chunk_reqs + 1, + num_chunk_reqs, + num_chunk_reqs, + num_chunk_reqs * width, + ] + ) + torch.sub(qsl_cpu[start : end + 1], qsl_cpu[start], out=cu_seqlens_q) + pages.copy_(history_pages[start:end]) + torch.cumsum(pages, 0, dtype=torch.int32, out=offsets) + offsets.sub_(pages) + cols = torch.arange(width, dtype=torch.int32) + table.view(num_chunk_reqs, width).copy_( + torch.where(cols < pages[:, None], offsets[:, None] + cols, 0) + ) + staging_gpu = staging.to(device, non_blocking=True) + cu_seqlens_q_gpu, pages_gpu, offsets_gpu, table_gpu = staging_gpu.split( + [ + num_chunk_reqs + 1, + num_chunk_reqs, + num_chunk_reqs, + num_chunk_reqs * width, + ] + ) + lo, hi = num_decodes + start, num_decodes + end + token_start = int(qsl_cpu[start] - qsl_cpu[0]) + token_end = int(qsl_cpu[end] - qsl_cpu[0]) + wrapper = prefill_wrapper_cls(num_heads=self.num_index_heads) + wrapper.plan( + cu_seqlens_q_gpu, + seq_lens[lo:hi], + table_gpu.view(num_chunk_reqs, width), + total_q=token_end - token_start, + max_seqlen_q=int(query_lens_cpu[start:end].max()), + max_seqlen_k=max_seq_len, + ) + chunks.append( + MiniMaxM3IndexerNvfp4PrefillChunk( + wrapper=wrapper, + token_start=token_start, + token_end=token_end, + block_table=block_table[lo:hi], + num_pages=pages_gpu, + page_offsets=offsets_gpu, + total_pages=total_pages, + max_pages=int(pages.max()), + ) + ) + start = end + return chunks + + +class MiniMaxM3IndexerNvfp4Impl(MiniMaxM3IndexerImpl): + """Decode: Q8KV4 on NVFP4 pages. Prefill: FP8 gather + Q8KV8.""" + + indexer_backend_cls: ClassVar[type[AttentionBackend]] = MiniMaxM3IndexerNvfp4Backend + + def __init__(self, **kwargs) -> None: + super().__init__(**kwargs) + config = ( + self.topk_blocks, + self.init_blocks, + self.local_blocks, + self.block_size, + self.index_head_dim, + self.score_type, + ) + if config != (TOPK_BLOCKS, 0, 1, PAGE_SIZE, HEAD_DIM, "max"): + raise NotImplementedError( + "The MiniMax M3 NVFP4 indexer supports topk_blocks=16, " + "init_blocks=0, local_blocks=1, 128-token blocks, index head " + "dim 128 and max scoring; got (topk_blocks, init_blocks, " + "local_blocks, block_size, index_head_dim, score_type)=" + f"{config}." + ) + vllm_config = get_current_vllm_config() + self.max_gather_pages = max_gather_pages(vllm_config) + # Per-layer decode-CP buffers (collective: same layer order on all ranks). + self.decode_cp = get_nvfp4_indexer_decode_cp( + num_index_heads=self.num_index_heads, + max_decode_query_len=max_decode_query_len(vllm_config), + ) + self.decode_cp_layer: Nvfp4DecodeCPLayer | None = ( + None if self.decode_cp is None else self.decode_cp.new_layer() + ) + + def reserve_workspace(self) -> None: + current_workspace_manager().get_simultaneous( + ((self.max_gather_pages, PAGE_SIZE, HEAD_DIM), torch.float8_e4m3fn) + ) + + def forward( + self, + index_query: torch.Tensor, + ) -> tuple[torch.Tensor | None, torch.Tensor | None]: + attn_metadata = get_forward_context().attn_metadata + if not isinstance(attn_metadata, dict): + return None, None # profiling run; caches unbound + md = attn_metadata[self.index_cache.prefix] + assert isinstance(md, MiniMaxM3IndexerNvfp4Metadata) + + nd = md.num_decode_tokens + # Not sliced to the actual tokens: a padded full-CUDA-graph decode + # batch also scores its padding rows, and every captured tensor must + # keep its address and shape. + index_q = index_query.view(-1, self.num_index_heads, self.index_head_dim) + kv = self.index_cache.kv_cache + # The kernels write logical block ids straight into the shared + # [T, H, 16] buffer the attend reads. + buf = self.topk_indices_buffer + assert buf is not None + + if md.decode_q8kv4 is not None: + d = md.decode_q8kv4 + rows = d.num_reqs * d.query_len + if d.cp_plan is not None: + assert self.decode_cp is not None and self.decode_cp_layer is not None + self.decode_cp.forward( + self.decode_cp_layer, + d.cp_plan, + index_q[:rows], + kv, + buf[:rows], + d.query_len, + ) + else: + d.wrapper.run(index_q[:rows], kv, out=buf[:rows]) + for chunk in md.prefill_chunks: + self._prefill( + index_q[nd + chunk.token_start : nd + chunk.token_end], + kv, + chunk, + buf[nd + chunk.token_start : nd + chunk.token_end], + ) + return None, None + + def _prefill( + self, + index_q: torch.Tensor, + kv: torch.Tensor, + chunk: MiniMaxM3IndexerNvfp4PrefillChunk, + out: torch.Tensor, + ) -> None: + (k_pages,) = current_workspace_manager().get_simultaneous( + ((max(chunk.total_pages, 1), PAGE_SIZE, HEAD_DIM), torch.float8_e4m3fn) + ) + minimax_m3_gather_nvfp4_index_k_fp8( + kv, + chunk.block_table, + chunk.num_pages, + chunk.page_offsets, + chunk.max_pages, + k_pages, + ) + chunk.wrapper.run(index_q, k_pages, out=out) diff --git a/vllm/models/minimax_m3/nvidia/indexer_nvfp4_decode_cp.py b/vllm/models/minimax_m3/nvidia/indexer_nvfp4_decode_cp.py new file mode 100644 index 000000000000..012515855628 --- /dev/null +++ b/vllm/models/minimax_m3/nvidia/indexer_nvfp4_decode_cp.py @@ -0,0 +1,513 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Context-parallel decode for the MiniMax M3 NVFP4 indexer (opt-in, TP4). + +At TP4 each rank owns one of the 4 index heads, but the index-K cache is +replicated, so every rank reads the whole cache per sparse layer. With +``--attention-config '{"indexer_decode_cp": true}'``, rank ``r`` +instead: + +1. exchanges index-q heads so it holds all 4 (``_q_exchange_kernel``); +2. scores all 4 heads over pages ``j * CP + r`` with the stock Q8KV4 kernel + on a compact block table, reading 1/CP of the index-K; +3. takes the exact local top 16 per (query, head) and sends it to the head's + owner (``_local_topk_push_kernel``); +4. merges the owner's ``16 * CP`` candidates into the indexer output: 15 + pages by (score desc, page asc), then the own page (``_merge_kernel``). + +The merge is exact: the global top 16 lies in the union of per-rank top 16s. +The stock decode ranks 16-bit quantized scores, so the two may differ at ties. + +The chunking is written against one contract, the MSA Q8KV4 decode scorer's: +eight query slots per request, ``(seq_len - 1) / 128`` pages scored, and only +the pages below a query's own page stored. The three places that depend on it +are ``_compact_block_table_kernel`` (the length it is handed), +``_local_topk_push_kernel`` (the cut that length drops) and ``_set_width`` +(room for the page that length invents). + +Both exchanges are NVLink stores into symmetric buffers whose payload is the +flag (``0xFF`` E4M3 NaN for queries, ``-1`` for keys); consumers restore it. +Buffers are per layer, shapes are fixed per batch size, and nothing syncs with +the host, so the path is CUDA-graph safe. It needs symmetric memory across the +tensor-parallel ranks and falls back to the stock decode without it. + +The three Triton kernels are PDL-launched and wait for their producer, so +each starts its prologue in the tail of the kernel before it. Only the push +releases its dependent early, right after its own wait, which is what lets +the merge overlap it; the exchange must not, because the score kernel after +it reads the whole tile. +""" + +from dataclasses import dataclass +from typing import Any + +import torch + +from vllm.config import get_current_vllm_config +from vllm.distributed import ( + get_tensor_model_parallel_rank, + get_tensor_model_parallel_world_size, + get_tp_group, +) +from vllm.logger import init_logger +from vllm.triton_utils import tl, triton +from vllm.utils.math_utils import cdiv +from vllm.v1.attention.ops.cp_common import direct_cp_enabled + +logger = init_logger(__name__) + +PAGE_SIZE = 128 +HEAD_DIM = 128 +TOPK_BLOCKS = 16 +DECODE_QUERY_LEN = 8 # query slots per request in a Q8KV4 decode tile +MAX_PAGES = 8192 +NUM_INDEX_HEADS = 4 +SUPPORTED_TP_SIZES = (4,) +# Rows with at most this many ranked pages take a single top-k. +TOPK_CHUNK = 256 +# Groups of the two-level top-k over longer rows. +MAX_TOPK_GROUPS = 128 + +_TOPK = tl.constexpr(TOPK_BLOCKS) +_RANKED = tl.constexpr(TOPK_BLOCKS - 1) +_PAGE = tl.constexpr(PAGE_SIZE) +_SLOTS = tl.constexpr(DECODE_QUERY_LEN) +_WORDS = tl.constexpr(HEAD_DIM // 4) # int32 words per index-q head + + +@triton.jit +def _peer_ptr(ptrs, rank, dtype: tl.constexpr): + return tl.load(ptrs + rank).to(tl.pointer_type(dtype)) + + +@triton.jit +def _compact_block_table_kernel( + bt_ptr, # [B, P] int32 + seq_lens_ptr, # [B] int32 + cbt_ptr, # [B, W] int32 out: compact page j -> global page j * CP + RANK + cseq_ptr, # [B] int32 out: lengths the score kernel sees + seq_out_ptr, # [B] int32 out: real lengths (stable buffer) + P, + W, + stride_bt, + stride_cbt, + CP: tl.constexpr, + RANK: tl.constexpr, + BLOCK: tl.constexpr, +): + """Compact page j = global page ``j * CP + RANK``, and the length the score + kernel is handed for it. + + That length is a lie: the scorer stores only the pages below a query's own + page, so ``n_local * 128 + 8`` puts all eight query slots one page past + the chunk and stores every owned page, uncausally. The real cut comes back + in ``_local_topk_push_kernel``. ``W`` keeps the invented page addressable, + since a scorer that clamps the own page to its last score column would + drop the chunk's last page.""" + b = tl.program_id(0) + seq = tl.load(seq_lens_ptr + b) + tl.store(seq_out_ptr + b, seq) + hist = tl.minimum(tl.maximum((seq - 1) // _PAGE, 0), P) + n_local = tl.minimum((hist + (CP - 1 - RANK)) // CP, W - 1) + for start in range(0, W, BLOCK): + j = start + tl.arange(0, BLOCK) + src = tl.minimum(j * CP + RANK, P - 1) + v = tl.load(bt_ptr + b.to(tl.int64) * stride_bt + src, mask=j < W) + tl.store(cbt_ptr + b.to(tl.int64) * stride_cbt + j, v, mask=j < W) + tl.store(cseq_ptr + b, n_local * _PAGE + _SLOTS) + + +@triton.jit +def _has_ff_byte(v): + u = v.to(tl.uint32, bitcast=True) + ff = ( + ((u & 0xFF) == 0xFF) + | (((u >> 8) & 0xFF) == 0xFF) + | (((u >> 16) & 0xFF) == 0xFF) + | ((u >> 24) == 0xFF) + ) + return tl.max(ff.to(tl.int32), axis=0) > 0 + + +@triton.jit +def _q_exchange_kernel( + q_ptr, # [rows, 32] int32 view of this rank's e4m3 index-q head + tile_ptrs, # [CP] int64: q tile [B, 8, H, 128] bytes of every rank + H: tl.constexpr, + CP: tl.constexpr, + RANK: tl.constexpr, + HEAD: tl.constexpr, + QLEN: tl.constexpr, +): + """Store this rank's index-q head into every rank's tile, then wait for + the other heads. The PDL wait is for index-q's producer.""" + tl.extra.cuda.gdc_wait() + t = tl.program_id(0) + b = t // QLEN + slot = (_SLOTS - QLEN) + t % QLEN + w = tl.arange(0, _WORDS) + row = tl.load(q_ptr + t * _WORDS + w) + dst_off = ((b * _SLOTS + slot) * H + HEAD) * _WORDS + w + for dst in tl.static_range(CP): + tl.store(_peer_ptr(tile_ptrs, dst, tl.int32) + dst_off, row) + local = _peer_ptr(tile_ptrs, RANK, tl.int32) + hw = tl.arange(0, H * _WORDS) + off = (b * _SLOTS + slot) * H * _WORDS + hw + v = tl.load(local + off, volatile=True) + pending = _has_ff_byte(v) + while pending: + v = tl.load(local + off, volatile=True) + pending = _has_ff_byte(v) + + +@triton.jit +def _page_keys(row_ptr, j, n, CP: tl.constexpr, RANK: tl.constexpr): + """Key ``1 << 48 | ordered(score) << 16 | (0xFFFF - page)`` for ``j < n``, + else 0. Unique; orders by score desc, then page asc.""" + valid = j < n + page = j * CP + RANK + score = tl.load(row_ptr + j, mask=valid, other=0.0) + bits = score.to(tl.uint32, bitcast=True) + ordered = bits ^ tl.where((bits >> 31) != 0, 0xFFFFFFFF, 0x80000000) + key = (1 << 48) | (ordered.to(tl.int64) << 16) | (0xFFFF - page).to(tl.int64) + return tl.where(valid, key, 0) + + +@triton.jit +def _local_topk_push_kernel( + score_ptr, # [B, 8 * H, W] fp32 compact scores (row = slot * H + head) + seq_lens_ptr, # [B] int32 + recv_ptrs, # [CP] int64: candidates [CP, rows_max, 16] int64 of every rank + rows_max, + stride_sb, + stride_sr, + H: tl.constexpr, + CP: tl.constexpr, + RANK: tl.constexpr, + QLEN: tl.constexpr, + WIDTH: tl.constexpr, + CHUNK: tl.constexpr, + NUM_GROUPS: tl.constexpr, + GROUP: tl.constexpr, +): + """Per (query, head): exact top 16 of the owned pages, sent to the head's + owner. Long rows use a two-level select (top 16 groups, then top 16). + + PDL-launched: the wait is for the scores, and releasing the merge only + after it keeps the merge's own wait a guarantee that the score kernel has + read the q tile.""" + tl.extra.cuda.gdc_wait() + tl.extra.cuda.gdc_launch_dependents() + t = tl.program_id(0) + h = tl.program_id(1) + b = t // QLEN + i = t % QLEN + slot = (_SLOTS - QLEN) + i + own = (tl.load(seq_lens_ptr + b) - QLEN + i) // _PAGE + if own + 1 > _TOPK: + # The causal cut the compact length dropped: the rank's pages below + # the query's own page, bounded by the width like the scored pages (a + # length past the page table ranks what it holds, as the stock TopK). + n_rank = tl.minimum((own + (CP - 1 - RANK)) // CP, WIDTH - 1) + row_ptr = score_ptr + b.to(tl.int64) * stride_sb + (slot * H + h) * stride_sr + if n_rank <= CHUNK: + j = tl.arange(0, CHUNK) + best = tl.topk(_page_keys(row_ptr, j, n_rank, CP, RANK), _TOPK) + else: + g = tl.arange(0, NUM_GROUPS) + s = tl.arange(0, GROUP) + keys = _page_keys( + row_ptr, g[:, None] * GROUP + s[None, :], n_rank, CP, RANK + ) + top_g = tl.topk(tl.max(keys, axis=1), _TOPK) + page = (0xFFFF - (top_g & 0xFFFF)).to(tl.int32) + grp = tl.where(top_g > 0, ((page - RANK) // CP) // GROUP, NUM_GROUPS) + cand = _page_keys( + row_ptr, grp[:, None] * GROUP + s[None, :], n_rank, CP, RANK + ) + best = tl.topk(tl.reshape(cand, [_TOPK * GROUP]), _TOPK) + k = tl.arange(0, _TOPK) + dst = _peer_ptr(recv_ptrs, h, tl.int64) + tl.store(dst + (RANK * rows_max + t) * _TOPK + k, best) + + +@triton.jit +def _merge_kernel( + seq_lens_ptr, # [B] int32 + recv_ptrs, # [CP] int64 + tile_ptrs, # [CP] int64 + out_ptr, # [rows, 1, 16] int32 + rows_max, + out_stride, + H: tl.constexpr, + CP: tl.constexpr, + RANK: tl.constexpr, + QLEN: tl.constexpr, +): + """Merge all ranks' candidates for this rank's head and restore sentinels. + + PDL-launched after every push program has started, so polling here never + blocks a push.""" + t = tl.program_id(0) + b = t // QLEN + i = t % QLEN + own = (tl.load(seq_lens_ptr + b) - QLEN + i) // _PAGE + k = tl.arange(0, _TOPK) + out = out_ptr + t.to(tl.int64) * out_stride + k + if own + 1 <= _TOPK: + tl.store(out, tl.where(k < own + 1, k, -1)) + # No push for this row: wait for the score before resetting the q tile. + tl.extra.cuda.gdc_wait() + else: + recv = _peer_ptr(recv_ptrs, RANK, tl.int64) + p = tl.arange(0, CP) + off = (p[:, None] * rows_max + t) * _TOPK + k[None, :] + keys = tl.load(recv + off, volatile=True) + pending = tl.min(tl.min(keys, axis=1), axis=0) == -1 + while pending: + keys = tl.load(recv + off, volatile=True) + pending = tl.min(tl.min(keys, axis=1), axis=0) == -1 + best = tl.topk(tl.reshape(keys, [CP * _TOPK]), _TOPK) + page = (0xFFFF - (best & 0xFFFF)).to(tl.int32) + tl.store(out, tl.where(k == _RANKED, own, page)) + tl.store(recv + off, tl.full([CP, _TOPK], -1, tl.int64)) + # The score kernel has read this q tile row; re-arm it. + slot = (_SLOTS - QLEN) + i + tile = _peer_ptr(tile_ptrs, RANK, tl.int32) + hw = tl.arange(0, H * _WORDS) + tl.store( + tile + (b * _SLOTS + slot) * H * _WORDS + hw, + tl.full(hw.shape, -1, tl.int32), + ) + + +@dataclass +class Nvfp4DecodeCPPlan: + """Per padded batch size: the 4-head score wrapper and its buffers.""" + + # The wrapper owns the compact [B, 8 * H, width] fp32 scores. + wrapper: Any # BatchDecodeIndexerQ8KV4Wrapper(num_heads=4), CUDA-graph mode + block_table: torch.Tensor # [B, width] compact pages + score_seq_lens: torch.Tensor # [B] lengths the score kernel sees + seq_lens: torch.Tensor # [B] real lengths + num_reqs: int + + +@dataclass +class Nvfp4DecodeCPLayer: + """One sparse layer's symmetric buffers.""" + + # Keep both alive: freeing one unmaps it while peers still write to it. + tile: torch.Tensor # local q tile, int32 words + recv: torch.Tensor # local candidates [CP, rows_max, 16] int64 + tile_ptrs: torch.Tensor # [CP] int64 + recv_ptrs: torch.Tensor # [CP] int64 + + +class Nvfp4IndexerDecodeCP: + """Per-process state shared by the builder and every sparse layer.""" + + def __init__(self, *, max_reqs: int, device: torch.device) -> None: + from vllm.third_party.fmha_sm100.sparse import BatchDecodeIndexerQ8KV4Wrapper + + self._wrapper_cls = BatchDecodeIndexerQ8KV4Wrapper + self.cp = get_tensor_model_parallel_world_size() + self.rank = get_tensor_model_parallel_rank() + self.head = self.rank # one index head per rank at TP4 + # Compact page width, fixed by the first plan() (see _set_width). + self.width = 0 + self.num_groups = 0 + self.group = 0 + self.max_reqs = max_reqs + self.rows_max = max_reqs * DECODE_QUERY_LEN + self.device = device + self._plans: dict[int, Nvfp4DecodeCPPlan] = {} + self._tile_words = max_reqs * DECODE_QUERY_LEN * NUM_INDEX_HEADS * HEAD_DIM // 4 + self._recv_words = self.cp * self.rows_max * TOPK_BLOCKS + + def new_layer(self) -> Nvfp4DecodeCPLayer: + """Collective: every TP rank builds its sparse layers in the same order.""" + import torch.distributed._symmetric_memory as symm_mem + + group_name = get_tp_group().device_group.group_name + tile = symm_mem.empty(self._tile_words, dtype=torch.int32, device=self.device) + tile.fill_(-1) + recv = symm_mem.empty(self._recv_words, dtype=torch.int64, device=self.device) + recv.fill_(-1) + tile_ptrs = symm_mem.rendezvous(tile, group_name).buffer_ptrs + recv_ptrs = symm_mem.rendezvous(recv, group_name).buffer_ptrs + return Nvfp4DecodeCPLayer( + tile=tile, + recv=recv, + tile_ptrs=torch.tensor(tile_ptrs, dtype=torch.int64, device=self.device), + recv_ptrs=torch.tensor(recv_ptrs, dtype=torch.int64, device=self.device), + ) + + def _set_width(self, max_pages: int) -> None: + """Fix the compact page width and the two-level top-k shape. + + One column past the pages a rank can own, so the page the compact + length invents stays inside the score buffer and the chunk's last page + is stored (see ``_compact_block_table_kernel``). Both levels of the + top-k select over power-of-two tiles that cover the width. + """ + width = cdiv(min(max_pages, MAX_PAGES), self.cp) + 1 + if self.width == 0: + padded = 1 << (width - 1).bit_length() + self.width = width + self.group = max(1, padded // MAX_TOPK_GROUPS) + self.num_groups = padded // self.group + assert width <= self.width, "the block table grew after the first plan" + + def plan( + self, block_table: torch.Tensor, seq_lens: torch.Tensor + ) -> Nvfp4DecodeCPPlan: + """Outside CUDA graph capture, once per step.""" + self._set_width(block_table.shape[1]) + num_reqs = seq_lens.shape[0] + p = self._plans.get(num_reqs) + if p is None: + assert num_reqs <= self.max_reqs + i32 = dict(dtype=torch.int32, device=self.device) + bt = torch.empty(num_reqs, self.width, **i32) + score_seq_lens = torch.empty(num_reqs, **i32) + p = self._plans[num_reqs] = Nvfp4DecodeCPPlan( + wrapper=self._wrapper_cls( + num_heads=NUM_INDEX_HEADS, + use_cuda_graph=True, + block_table_buffer=bt, + seq_lens_buffer=score_seq_lens, + ), + block_table=bt, + score_seq_lens=score_seq_lens, + seq_lens=torch.empty(num_reqs, **i32), + num_reqs=num_reqs, + ) + _compact_block_table_kernel[(num_reqs,)]( + block_table, + seq_lens, + p.block_table, + p.score_seq_lens, + p.seq_lens, + min(block_table.shape[1], MAX_PAGES), + self.width, + block_table.stride(0), + p.block_table.stride(0), + CP=self.cp, + RANK=self.rank, + BLOCK=1024, + ) + p.wrapper.plan(p.block_table, p.score_seq_lens) + return p + + def forward( + self, + layer: Nvfp4DecodeCPLayer, + plan: Nvfp4DecodeCPPlan, + index_q: torch.Tensor, # [rows, 1, 128] e4m3, this rank's head + k_cache: torch.Tensor, + out: torch.Tensor, # [rows, 1, 16] int32 + query_len: int, + ) -> None: + rows = index_q.shape[0] + assert rows == plan.num_reqs * query_len and out.shape[0] == rows + _q_exchange_kernel[(rows,)]( + index_q.view(torch.int32).view(rows, HEAD_DIM // 4), + layer.tile_ptrs, + H=NUM_INDEX_HEADS, + CP=self.cp, + RANK=self.rank, + HEAD=self.head, + QLEN=query_len, + num_warps=1, + launch_pdl=True, + ) + q_tile = layer.tile[ + : plan.num_reqs * DECODE_QUERY_LEN * NUM_INDEX_HEADS * HEAD_DIM // 4 + ] + scores = plan.wrapper._run_scores( + q_tile.view(torch.float8_e4m3fn).view(-1, NUM_INDEX_HEADS, HEAD_DIM), + k_cache, + ) + _local_topk_push_kernel[(rows, NUM_INDEX_HEADS)]( + scores, + plan.seq_lens, + layer.recv_ptrs, + self.rows_max, + scores.stride(0), + scores.stride(1), + H=NUM_INDEX_HEADS, + CP=self.cp, + RANK=self.rank, + QLEN=query_len, + WIDTH=self.width, + CHUNK=TOPK_CHUNK, + NUM_GROUPS=self.num_groups, + GROUP=self.group, + num_warps=4, + launch_pdl=True, + ) + _merge_kernel[(rows,)]( + plan.seq_lens, + layer.recv_ptrs, + layer.tile_ptrs, + out, + self.rows_max, + out.stride(0), + H=NUM_INDEX_HEADS, + CP=self.cp, + RANK=self.rank, + QLEN=query_len, + num_warps=1, + launch_pdl=True, + ) + + +_STATE: Nvfp4IndexerDecodeCP | None = None +_RESOLVED = False + + +def get_nvfp4_indexer_decode_cp( + *, num_index_heads: int, max_decode_query_len: int +) -> Nvfp4IndexerDecodeCP | None: + """The process's decode-CP state, or None (stock decode). Built once.""" + global _STATE, _RESOLVED + if _RESOLVED: + return _STATE + _RESOLVED = True + vllm_config = get_current_vllm_config() + if not vllm_config.attention_config.indexer_decode_cp: + return None + tp = get_tensor_model_parallel_world_size() + text_config = vllm_config.model_config.hf_text_config + total_heads = text_config.sparse_attention_config["sparse_num_index_heads"] + why = None + if tp not in SUPPORTED_TP_SIZES: + why = f"tensor parallel size {tp} (needs one of {SUPPORTED_TP_SIZES})" + elif total_heads != NUM_INDEX_HEADS or num_index_heads != 1: + why = f"{total_heads} index heads, {num_index_heads} per rank" + elif vllm_config.parallel_config.decode_context_parallel_size > 1: + why = "decode context parallelism is enabled" + elif max_decode_query_len > DECODE_QUERY_LEN: + why = f"decode query length {max_decode_query_len} > {DECODE_QUERY_LEN}" + elif not direct_cp_enabled(get_tp_group(), torch.int32, use_direct=None): + why = "the tensor-parallel ranks have no symmetric memory between them" + if why is not None: + logger.warning( + "indexer_decode_cp ignored: %s; using the stock NVFP4 indexer decode.", + why, + ) + return None + sched = vllm_config.scheduler_config + _STATE = Nvfp4IndexerDecodeCP( + max_reqs=sched.max_num_seqs, + device=torch.device("cuda", torch.accelerator.current_device_index()), + ) + logger.info_once( + "MiniMax M3 NVFP4 indexer: decode context parallelism over %d TP ranks " + "(each scores 1/%d of the index-K pages for all %d index heads).", + tp, + tp, + NUM_INDEX_HEADS, + ) + return _STATE diff --git a/vllm/models/minimax_m3/nvidia/model.py b/vllm/models/minimax_m3/nvidia/model.py index d67e9ea19d90..72d8219e976e 100644 --- a/vllm/models/minimax_m3/nvidia/model.py +++ b/vllm/models/minimax_m3/nvidia/model.py @@ -18,11 +18,18 @@ from torch import nn from transformers import PreTrainedConfig +import vllm.envs as envs from vllm import _custom_ops as ops from vllm.compilation.breakable_cudagraph import eager_break_during_capture from vllm.config import CacheConfig, VllmConfig, get_current_vllm_config -from vllm.distributed import get_pp_group, get_tensor_model_parallel_world_size -from vllm.forward_context import get_forward_context +from vllm.distributed import ( + get_ep_group, + get_pp_group, + get_tensor_model_parallel_rank, + get_tensor_model_parallel_world_size, +) +from vllm.forward_context import get_forward_context, is_forward_context_available +from vllm.logger import init_logger from vllm.model_executor.layers.activation import SiluAndMulWithClamp from vllm.model_executor.layers.attention import Attention from vllm.model_executor.layers.attention.attention import set_default_quant_scales @@ -35,6 +42,28 @@ GateLinear, fused_moe_make_expert_params_mapping, ) +from vllm.model_executor.layers.fused_moe.deep_gemm_mega_moe import ( + MEGA_MOE_NVFP4, + DeepGemmMegaMoEExperts, + MegaMoEActivation, +) +from vllm.model_executor.layers.fused_moe.experts.trtllm_nvfp4_moe import ( + TrtLlmNvFp4ExpertsModular, + TrtLlmNvFp4ExpertsMonolithic, +) +from vllm.model_executor.layers.fused_moe.moe_output import ( + MoEOutput, + UnfinalizedMoEOutput, +) +from vllm.model_executor.layers.fused_moe.router.fused_topk_bias_router import ( + fused_topk_bias, +) +from vllm.model_executor.layers.fused_moe.runner.moe_runner import _unpack +from vllm.model_executor.layers.fusion.quant_activation import ( + QuantizedActivation, + as_quantized_activation, + get_input_quant_key, +) from vllm.model_executor.layers.linear import ( MergedColumnParallelLinear, MinimaxM3QKVParallelLinearWithIndexer, @@ -43,6 +72,13 @@ ) from vllm.model_executor.layers.logits_processor import LogitsProcessor from vllm.model_executor.layers.quantization import QuantizationConfig +from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( + mxfp8_e4m3_quantize, +) +from vllm.model_executor.layers.quantization.utils.quant_utils import ( + kMxfp8Dynamic, + kNvfp4DynamicToken, +) from vllm.model_executor.layers.rotary_embedding import get_rope from vllm.model_executor.layers.vocab_parallel_embedding import ( ParallelLMHead, @@ -63,6 +99,7 @@ AutoWeightsLoader, PPMissingLayer, WeightsMapper, + extract_layer_index, init_vllm_registered_model, is_pp_missing_parameter, make_empty_intermediate_tensors_factory, @@ -71,6 +108,11 @@ spec_decode_needs_target_embed, ) from vllm.model_executor.models.vision import run_dp_sharded_mrope_vision_model +from vllm.models.common.ops.sequence_parallel import ( + sp_all_gather, + sp_padding_mask, + sp_shard, +) from vllm.models.minimax_m3.common.encoder_cudagraph import ( MiniMaxM3EncoderCudaGraphMixin, ) @@ -86,8 +128,19 @@ select_main_backend_and_impl_cls, ) from vllm.models.minimax_m3.common.vision_tower import MiniMaxVLVisionModel +from vllm.models.minimax_m3.nvidia.ops.finalize_allreduce_norm import ( + finalize_allreduce_gemma_rms_norm_mxfp8, + init_fused_moe_finalize, + supports_fused_moe_finalize, +) +from vllm.models.minimax_m3.nvidia.ops.qkv_index_fused_epilogue import ( + minimax_m3_qkv_index_fused_epilogue, + register_qkv_index_fused_epilogue_warmup, +) from vllm.multimodal import MULTIMODAL_REGISTRY +from vllm.platforms import current_platform from vllm.sequence import IntermediateTensors +from vllm.utils.flashinfer import is_flashinfer_autotuning from vllm.utils.torch_utils import kv_cache_dtype_str_to_dtype from vllm.v1.kv_cache_interface import ( FullAttentionSpec, @@ -95,6 +148,44 @@ get_kv_quant_mode, ) +logger = init_logger(__name__) + +# Largest batch whose MoE top-k finalize runs inside the next layer's fused +# all-reduce + input norm + MXFP8 quantization. Larger batches finalize in the +# MoE and use the regular fused all-reduce + norm. +FUSED_MOE_FINALIZE_MAX_TOKENS = 32 + +_QKV_FUSED_EPILOGUE_MIN_TOKENS = 512 + + +def _supports_qkv_fused_epilogue(attn: "MiniMaxM3SparseAttention") -> bool: + """Whether minimax_m3_qkv_index_fused_epilogue can replace this layer's + qkv_proj + norm/RoPE/cache-insert chain.""" + from vllm.model_executor.kernels.linear.mxfp8.flashinfer import ( + FlashInferCutedslMxfp8LinearKernel, + FlashInferCutlassMxfp8LinearKernel, + ) + + if not current_platform.is_device_capability_family(100): + return False + # Both keep the weight K-major and its scales F8_128x4-swizzled. + kernel = getattr(attn.qkv_proj.quant_method, "kernel", None) + if not isinstance( + kernel, (FlashInferCutedslMxfp8LinearKernel, FlashInferCutlassMxfp8LinearKernel) + ): + return False + nkv = attn.num_kv_heads + return ( + attn.use_nvfp4_kv + and attn.indexer_kv_dtype == "nvfp4" + and nkv in (1, 2, 4) + and attn.num_heads == 16 * nkv + and attn.num_idx_heads == nkv + and attn.head_dim == attn.idx_head_dim == 128 + and attn.rotary_emb.rotary_dim == 64 + and attn.hidden_size % 128 == 0 + ) + def _sparse_attention_layer_ids(config: PreTrainedConfig) -> set[int]: """Layer ids whose attention runs the extra sparse "index" branch.""" @@ -115,6 +206,73 @@ def _is_moe_layer(config: PreTrainedConfig, layer_id: int) -> bool: return moe_layer_freq[layer_id] != 0 +def _use_mega_moe(vllm_config: VllmConfig) -> bool: + """Whether MoE layers run the DeepGEMM NVFP4 MegaMoE kernel. + + Opt in with ``--kernel-config '{"moe_backend": "deep_gemm_mega_moe"}'``. Only + checkpoints with NVFP4 routed experts (MiniMax-M3.1) are supported. + """ + if vllm_config.kernel_config.moe_backend != "deep_gemm_mega_moe": + return False + moe_quant_algo = getattr(vllm_config.quant_config, "moe_quant_algo", None) + if moe_quant_algo != "NVFP4": + raise NotImplementedError( + "MiniMax M3 MegaMoE requires a checkpoint with NVFP4 routed experts " + f"(moe_quant_algo: NVFP4), got moe_quant_algo={moe_quant_algo!r}. " + "Pick a different moe backend for this checkpoint." + ) + if not vllm_config.parallel_config.enable_expert_parallel: + raise NotImplementedError( + "MiniMax M3 MegaMoE requires expert parallel. Enable it with " + "--enable-expert-parallel." + ) + return True + + +# MiniMax-M3.1 QAT quantizes the FC2 input with a fixed global scale of 16; +# checkpoints carry a placeholder ``w2.input_global_scale`` of 1.0. +MEGA_MOE_FC2_INPUT_SCALE = 1.0 / 16.0 + + +def _mega_moe_expert_params_mapping( + num_experts: int, +) -> list[tuple[str, str, int, str]]: + """Map ``experts.{e}.w{1,2,3}.*`` to the MegaMoE ``w13_*``/``w2_*`` params.""" + return [ + ( + "experts.w2_" if shard_id == "w2" else "experts.w13_", + f"experts.{expert_id}.{shard_id}.", + expert_id, + shard_id, + ) + for expert_id in range(num_experts) + for shard_id in ("w1", "w2", "w3") + ] + + +def _mega_moe_expert_weight( + name: str, weight: torch.Tensor +) -> tuple[str, torch.Tensor] | None: + """Convert a compressed-tensors NVFP4 routed-expert tensor to the ModelOpt + convention ``DeepGemmMegaMoEExperts`` loads, or None to drop it. + + The global scales become dequantization scales. The FC1 input is quantized + per token, so its input scale is dropped, and the FC2 input scale is the + fixed QAT scale whatever the checkpoint says. + """ + prefix, _, suffix = name.rpartition(".") + if suffix == "weight_packed": + return f"{prefix}.weight", weight + if suffix == "weight_global_scale": + return f"{prefix}.weight_scale_2", 1.0 / weight.float() + if suffix == "input_global_scale": + if not prefix.endswith(".w2"): + return None + scale = torch.full_like(weight, MEGA_MOE_FC2_INPUT_SCALE, dtype=torch.float32) + return f"{prefix}.input_scale", scale + return name, weight + + class MiniMAXGemmaRMSNorm(nn.Module): """Gemma-style RMS normalization backed by FlashInfer kernels. @@ -155,6 +313,7 @@ def __init__( intermediate_size: int, quant_config: QuantizationConfig | None = None, reduce_results: bool = True, + disable_tp: bool = False, prefix: str = "", ) -> None: super().__init__() @@ -163,6 +322,7 @@ def __init__( [intermediate_size] * 2, bias=False, quant_config=quant_config, + disable_tp=disable_tp, prefix=f"{prefix}.gate_up_proj", ) self.down_proj = RowParallelLinear( @@ -171,6 +331,7 @@ def __init__( bias=False, quant_config=quant_config, reduce_results=reduce_results, + disable_tp=disable_tp, prefix=f"{prefix}.down_proj", ) if config.hidden_act != "swigluoai": @@ -184,10 +345,35 @@ def __init__( alpha=config.swiglu_alpha, beta=config.swiglu_beta, ) + from vllm.models.minimax_m3.nvidia.ops import dense_gemm1_mxfp8 + + # At or below the shared-experts stream threshold the persistent kernel + # would contend with the routed experts on the aux stream. + self.fused_gemm1_min_tokens: int | None = None + if dense_gemm1_mxfp8.can_fuse_gemm1( + self.gate_up_proj, self.down_proj, self.act_fn + ): + self.fused_gemm1_min_tokens = max( + dense_gemm1_mxfp8.MIN_TOKENS, + envs.VLLM_SHARED_EXPERTS_STREAM_TOKEN_THRESHOLD, + ) def forward(self, x: torch.Tensor) -> torch.Tensor: - gate_up, _ = self.gate_up_proj(x) - x = self.act_fn(gate_up) + num_tokens = x.shape[0] + # Run unfused under FlashInfer autotuning so gate_up_proj is tuned too + if ( + self.fused_gemm1_min_tokens is not None + and num_tokens > self.fused_gemm1_min_tokens + and not is_flashinfer_autotuning() + ): + from vllm.models.minimax_m3.nvidia.ops.dense_gemm1_mxfp8 import ( + fused_gemm1, + ) + + x = fused_gemm1(x, self.gate_up_proj, self.act_fn) + else: + gate_up, _ = self.gate_up_proj(x) + x = self.act_fn(gate_up) x, _ = self.down_proj(x) return x @@ -203,6 +389,7 @@ def __init__( quant_config: QuantizationConfig | None = None, reduce_results: bool = True, prefix: str = "", + use_mega_moe: bool = False, ) -> None: super().__init__() self.tp_size = get_tensor_model_parallel_world_size() @@ -212,6 +399,10 @@ def __init__( f"the number of experts {config.num_local_experts}." ) + self.use_mega_moe = use_mega_moe + self.reduce_results = reduce_results + self.scoring_func = config.scoring_func + self.top_k = config.num_experts_per_tok self.routed_scaling_factor = getattr(config, "routed_scaling_factor", 1.0) self.n_shared_experts = getattr(config, "n_shared_experts", None) @@ -239,6 +430,10 @@ def __init__( ) self.shared_experts: MiniMaxM3MLP | None = None + if self.use_mega_moe: + self._init_mega_moe_experts(config, quant_config, prefix) + return + if self.n_shared_experts: self.shared_experts = MiniMaxM3MLP( config=config, @@ -265,20 +460,125 @@ def __init__( swiglu_beta=config.swiglu_beta, routed_scaling_factor=self.routed_scaling_factor, router_logits_dtype=self.gate.out_dtype, + # The NVFP4 routed experts are QAT'd with a per-token FC1 input + # scale; their ``input_global_scale`` is a 1.0 placeholder that + # the quantization config cannot tell from a calibrated scale. + qat_activation_key=kNvfp4DynamicToken, shared_experts=self.shared_experts, quant_config=quant_config, reduce_results=reduce_results, prefix=f"{prefix}.experts", ) + def _init_mega_moe_experts( + self, + config: PreTrainedConfig, + quant_config: QuantizationConfig | None, + prefix: str, + ) -> None: + if config.hidden_act != "swigluoai": + raise ValueError( + f"MiniMax M3 MegaMoE requires swigluoai, got {config.hidden_act}." + ) + # Hidden states are replicated across TP ranks, so each rank routes + # only its own token shard through the EP-wide kernel. + self.use_sequence_parallel = self.tp_size > 1 + + def replicated_shared_experts() -> MiniMaxM3MLP: + # Replicated, so the kernel can fuse it. + return MiniMaxM3MLP( + config=config, + intermediate_size=config.intermediate_size * self.n_shared_experts, + quant_config=quant_config, + reduce_results=False, + disable_tp=True, + prefix=f"{prefix}.shared_experts", + ) + + shared_experts = None + if self.n_shared_experts: + # Only describes the weights: a fused layer allocates its own. + with torch.device("meta"): + shared_experts = replicated_shared_experts() + ep_group = get_ep_group() + num_experts = config.num_local_experts + if num_experts % ep_group.world_size != 0: + raise ValueError( + f"MiniMax M3 MegaMoE needs num_experts={num_experts} divisible " + f"by the EP size {ep_group.world_size}." + ) + num_local_experts = num_experts // ep_group.world_size + self.experts = DeepGemmMegaMoEExperts( + get_current_vllm_config(), + num_experts=num_experts, + num_local_experts=num_local_experts, + experts_start_idx=ep_group.rank_in_group * num_local_experts, + top_k=self.top_k, + hidden_size=config.hidden_size, + intermediate_size=config.intermediate_size, + activation=MegaMoEActivation( + "swiglu", + clamp=config.swiglu_limit, + alpha=config.swiglu_alpha, + beta=config.swiglu_beta, + ), + weight_format=MEGA_MOE_NVFP4, + shared_experts=shared_experts, + prefix=f"{prefix}.experts", + ) + if shared_experts is not None and not self.experts.has_fused_shared_experts: + self.shared_experts = replicated_shared_experts() + @staticmethod def ebias_weight_loader(param: nn.Parameter, loaded_weight: torch.Tensor) -> None: assert param.size() == loaded_weight.size() param.data.copy_(loaded_weight.to(torch.float32)) + @property + def ffn_all_reduce_deferred(self) -> bool: + if self.use_mega_moe: + return not self.reduce_results + return self.experts.moe_config.skip_final_all_reduce + + def defer_finalize(self, max_num_tokens: int) -> bool: + """Leave the routed top-k reduction of calls up to ``max_num_tokens`` + to the consumer; return whether the experts accepted. + + Only the TRTLLM-Gen NVFP4 experts can stop after GEMM2. + """ + if self.use_mega_moe: + return False + experts_cls = getattr( + self.experts.routed_experts.quant_method, "experts_cls", None + ) + if experts_cls not in (TrtLlmNvFp4ExpertsMonolithic, TrtLlmNvFp4ExpertsModular): + return False + moe_config = self.experts.moe_config + moe_config.defer_moe_finalize(max_num_tokens) + return moe_config.use_deferred_moe_finalize + + def defers_finalize(self, num_tokens: int) -> bool: + return ( + not self.use_mega_moe + and self.experts.moe_config.should_defer_moe_finalize(num_tokens) + ) + + def forward_unfinalized(self, hidden_states: torch.Tensor) -> MoEOutput: + """``forward`` with the routed top-k reduction and all-reduce left open.""" + router_logits, _ = self.gate(hidden_states) + # The runner's custom op returns tensors only, so run its body directly. + shared_output, routed = _unpack( + self.experts._forward_impl(hidden_states, router_logits, hidden_states) + ) + assert shared_output is not None + assert isinstance(routed, UnfinalizedMoEOutput) + return MoEOutput(routed=routed, shared_output=shared_output) + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: num_tokens, hidden_dim = hidden_states.shape hidden_states = hidden_states.view(-1, hidden_dim) + if self.use_mega_moe: + return self._forward_mega_moe(hidden_states) # router_logits: (num_tokens, n_experts); GateLinear casts to fp32. router_logits, _ = self.gate(hidden_states) @@ -288,6 +588,54 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: return final_hidden_states.view(num_tokens, hidden_dim) + def _forward_mega_moe(self, hidden_states: torch.Tensor) -> torch.Tensor: + if not self.use_sequence_parallel: + return self._forward_mega_moe_local(hidden_states) + + num_tokens = hidden_states.shape[0] + # Routing and the experts read the padding mask from the forward + # context; hand them this rank's shard of it. + forward_context = None + if envs.VLLM_MOE_SKIP_PADDING and is_forward_context_available(): + forward_context = get_forward_context() + is_padding = forward_context.is_padding + forward_context.is_padding = sp_padding_mask( + is_padding[:num_tokens] if is_padding is not None else None, + hidden_states, + ) + try: + local_output = self._forward_mega_moe_local(sp_shard(hidden_states)) + finally: + if forward_context is not None: + forward_context.is_padding = is_padding + if self.reduce_results: + return sp_all_gather(local_output)[:num_tokens] + + # Leave the other ranks' rows zero, so the deferred TP all-reduce (fused + # into the next RMSNorm) gathers them. + shard_size, hidden_dim = local_output.shape + tp_rank = get_tensor_model_parallel_rank() + output = local_output.new_zeros(shard_size * self.tp_size, hidden_dim) + output[tp_rank * shard_size : (tp_rank + 1) * shard_size] = local_output + return output[:num_tokens] + + def _forward_mega_moe_local(self, hidden_states: torch.Tensor) -> torch.Tensor: + router_logits, _ = self.gate(hidden_states) + topk_weights, topk_ids = fused_topk_bias( + hidden_states=hidden_states, + gating_output=router_logits, + scoring_func=self.scoring_func, + e_score_correction_bias=self.e_score_correction_bias.data + if self.e_score_correction_bias is not None + else None, + topk=self.top_k, + renormalize=True, + routed_scaling_factor=self.routed_scaling_factor, + ) + return self.experts( + hidden_states, topk_weights, topk_ids, shared_experts=self.shared_experts + ) + class MiniMaxM3Attention(nn.Module): """Dense attention with per-head QK norm and partial RoPE.""" @@ -556,6 +904,22 @@ def __init__( compilation_config.static_forward_context[self.layer_name] = self self.kv_cache = torch.tensor([]) # replaced by bind_kv_cache + self.use_qkv_fused_epilogue = _supports_qkv_fused_epilogue(self) + if self.use_qkv_fused_epilogue: + logger.info_once("MiniMax-M3: QKV+indexer GEMM with fused epilogue enabled") + block_size = vllm_config.cache_config.block_size + # The query is E4M3-only when CUTLASS decode serves the layer. + q_is_fp8 = getattr(self.impl, "use_cutlass_decode", False) + if vllm_config.kernel_config.enable_jit_warmup and block_size is not None: + register_qkv_index_fused_epilogue_warmup( + has_q=not q_is_fp8, + has_qfp8=q_is_fp8, + nkv=self.num_kv_heads, + block_size=block_size, + weight_bytes=self.qkv_proj.output_size_per_partition + * self.hidden_size, + ) + def get_attn_backend(self) -> type[MiniMaxM3SparseBackend]: return self.attn_backend @@ -570,37 +934,70 @@ def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec | None: kv_quant_mode=get_kv_quant_mode(self.kv_cache_dtype), ) - def _allocate_query_fp8(self, qkv: torch.Tensor) -> torch.Tensor | None: - if not getattr(self.impl, "use_cutlass_decode", False): - return None + def _qkv_proj_fused_epilogue( + self, + hidden_states: torch.Tensor | QuantizedActivation, + positions: torch.Tensor, + q: torch.Tensor, + index_q: torch.Tensor, + slot_mapping: torch.Tensor, + index_slot_mapping: torch.Tensor, + ) -> None: + """qkv_proj + QK-norm/RoPE + KV/index-cache insert as one MXFP8 kernel, + writing q (bf16 or E4M3, as allocated) and index_q.""" + weight = self.qkv_proj.weight + if weight.shape[1] != self.hidden_size: + weight = weight.t() # the CuTe-DSL kernel keeps a [K, N] view + qa = as_quantized_activation(hidden_states, kMxfp8Dynamic) + if qa is not None: + xq, xsf = qa.data, qa.scale + else: + assert isinstance(hidden_states, torch.Tensor) + xq, xsf = mxfp8_e4m3_quantize(hidden_states, is_sf_swizzled_layout=True) + q_is_fp8 = q.dtype == torch.float8_e4m3fn + minimax_m3_qkv_index_fused_epilogue( + xq, + xsf, + weight, + self.qkv_proj.weight_scale, + positions, + self.rotary_emb.cos_sin_cache, + self.q_norm.weight, + self.k_norm.weight, + self.index_q_norm.weight, + self.index_k_norm.weight, + self.q_norm.variance_epsilon, + slot_mapping=slot_mapping, + index_slot_mapping=index_slot_mapping, + kv_cache=self.kv_cache, + index_cache=self.indexer.index_cache.kv_cache, + q_out=None if q_is_fp8 else q, + index_q_out=index_q, + q_fp8_out=q if q_is_fp8 else None, + q_fp8_scale=self._q_scale_float, + k_scale=self._k_scale_float, + v_scale=self._v_scale_float, + ) + + def _allocate_query( + self, num_tokens: int, dtype: torch.dtype, device: torch.device + ) -> torch.Tensor: + # CUTLASS decode reads an E4M3 query, so the insert emits only that. + fp8 = getattr(self.impl, "use_cutlass_decode", False) return torch.empty( - (qkv.shape[0], self.q_size), - dtype=torch.float8_e4m3fn, - device=qkv.device, + (num_tokens, self.q_size), + dtype=torch.float8_e4m3fn if fp8 else dtype, + device=device, ) def forward( self, positions: torch.Tensor, - hidden_states: torch.Tensor, + hidden_states: torch.Tensor | QuantizedActivation, ) -> torch.Tensor: - # Single fused projection emitting [q | k | v | index_q | index_k]. - qkv, _ = self.qkv_proj(hidden_states) - - # Horizontally-fused per-head Gemma QK-norm + partial NeoX RoPE on the - # main (q/k) and index (index_q/index_k) branches, all read straight out - # of the single fused ``qkv`` tensor (the "5 results"). Once the paged - # caches are bound the kernel also inserts k/v and the index key into - # them; the initial memory-profiling run (caches unbound, no slot_mapping) - # short-circuits to zeros below. k/v and index_k are rewritten in place - # inside qkv (and scatter-inserted into the caches); q and index_q are - # de-interleaved - # straight into the dedicated contiguous ``q``/``index_q`` buffers below. - cos_sin_cache = self.rotary_emb.cos_sin_cache rotary_dim = self.rotary_emb.rotary_dim eps = self.q_norm.variance_epsilon - num_tokens = qkv.shape[0] fwd_slot_mapping = get_forward_context().slot_mapping if ( @@ -608,49 +1005,83 @@ def forward( or self.layer_name not in fwd_slot_mapping ): # Memory-profiling run: caches not yet bound, slot_mapping is empty. - return qkv.new_zeros((num_tokens, self.hidden_size)) + qkv, _ = self.qkv_proj(hidden_states) + self.indexer.reserve_workspace() + return qkv.new_zeros((qkv.shape[0], self.hidden_size)) main_slot_mapping = fwd_slot_mapping[self.layer_name] index_slot_mapping = fwd_slot_mapping[self.indexer.index_cache.prefix] - q = qkv.new_empty((num_tokens, self.q_size)) - # With query_fp8, q is emitted only in fp8; the attend dequantizes it - # into ``q`` for the tokens that run on Triton decode. - query_fp8 = self._allocate_query_fp8(qkv) - # index_q matches the index-K cache dtype (e4m3 for the fp8 score path); - # the fused kernel emits fp8 directly when this buffer is e4m3. - index_q = qkv.new_empty( - (num_tokens, self.index_q_size), - dtype=self.indexer.index_cache.dtype, + # FlashInfer autotunes the GEMMs its dummy runs call: take the unfused + # path there so qkv_proj is tuned for the M < 512 fallback. + if isinstance(hidden_states, QuantizedActivation): + num_tokens = hidden_states.orig_shape[0] + dtype, device = hidden_states.orig_dtype, hidden_states.data.device + else: + num_tokens = hidden_states.shape[0] + dtype, device = hidden_states.dtype, hidden_states.device + fused = ( + self.use_qkv_fused_epilogue + and num_tokens >= _QKV_FUSED_EPILOGUE_MIN_TOKENS + and not is_flashinfer_autotuning() ) - ops.fused_minimax_m3_qknorm_rope_kv_insert( - qkv, - self.q_norm.weight, - self.k_norm.weight, - cos_sin_cache, - positions, - self.num_heads, - self.num_kv_heads, - rotary_dim, - eps, - self.index_q_norm.weight, - self.index_k_norm.weight, - self.num_idx_heads, - main_slot_mapping, - index_slot_mapping, - self.kv_cache, - self.indexer.index_cache.kv_cache, - self.kv_cache.size(2), # paged-cache block size - q if query_fp8 is None else None, - index_q, - self.kv_cache_dtype, - q_fp8_out=query_fp8, - q_fp8_scale=self._q_scale_float, - kv_k_scale=self._k_scale if self.use_nvfp4_kv else None, - kv_v_scale=self._v_scale if self.use_nvfp4_kv else None, + if not fused: + # Single fused projection emitting [q | k | v | index_q | index_k]. + qkv, _ = self.qkv_proj(hidden_states) + q = self._allocate_query(num_tokens, dtype, device) + q_is_fp8 = q.dtype == torch.float8_e4m3fn + # index_q is e4m3 for the fp8 and nvfp4 index caches, else bf16; the + # fused kernel emits fp8 directly when this buffer is e4m3. + index_q = torch.empty( + (num_tokens, self.index_q_size), + dtype=self.indexer.index_cache.query_dtype, + device=device, ) + if fused: + self._qkv_proj_fused_epilogue( + hidden_states, + positions, + q, + index_q, + main_slot_mapping, + index_slot_mapping, + ) + else: + # Horizontally-fused per-head Gemma QK-norm + partial NeoX RoPE on + # the main (q/k) and index (index_q/index_k) branches, all read + # straight out of qkv. k/v and index_k are scatter-inserted into the + # caches; q and index_q are de-interleaved into the dedicated + # contiguous buffers above. With an E4M3 q nothing reads qkv + # afterwards, so k and index_k are not rewritten in place. + ops.fused_minimax_m3_qknorm_rope_kv_insert( + qkv, + self.q_norm.weight, + self.k_norm.weight, + cos_sin_cache, + positions, + self.num_heads, + self.num_kv_heads, + rotary_dim, + eps, + self.index_q_norm.weight, + self.index_k_norm.weight, + self.num_idx_heads, + main_slot_mapping, + index_slot_mapping, + self.kv_cache, + self.indexer.index_cache.kv_cache, + self.kv_cache.size(2), # paged-cache block size + None if q_is_fp8 else q, + index_q, + self.kv_cache_dtype, + q_fp8_out=q if q_is_fp8 else None, + q_fp8_scale=self._q_scale_float, + kv_k_scale=self._k_scale if self.use_nvfp4_kv else None, + kv_v_scale=self._v_scale if self.use_nvfp4_kv else None, + write_qkv=not q_is_fp8, + ) - output = torch.empty_like(q) - attn_output = self._run_attention(q, query_fp8, index_q, output) + output = torch.empty((num_tokens, self.q_size), dtype=dtype, device=device) + attn_output = self._run_attention(q, index_q, output) output, _ = self.o_proj(attn_output) return output @@ -658,7 +1089,6 @@ def forward( def _run_attention( self, query: torch.Tensor, - query_fp8: torch.Tensor | None, index_query: torch.Tensor, output: torch.Tensor, ) -> torch.Tensor: @@ -666,13 +1096,7 @@ def _run_attention( # metadata and can't be captured into a cudagraph. The indexer writes its # top-k into the shared ``topk_indices_buffer``; the attend reads it back. self.indexer(index_query) - return self.impl.forward( - self, - query, - self.kv_cache, - output, - query_fp8=query_fp8, - ) + return self.impl.forward(self, query, self.kv_cache, output) class MiniMaxM3DecoderLayer(nn.Module): @@ -737,12 +1161,18 @@ def __init__( ) self.is_moe_layer = force_moe or _is_moe_layer(config, layer_id) if self.is_moe_layer: + use_mega_moe = _use_mega_moe(vllm_config) + if use_mega_moe and is_mtp_block: + raise NotImplementedError( + "MiniMax M3 MegaMoE does not support MTP draft layers." + ) self.block_sparse_moe = MiniMaxM3MoE( config=config, layer_id=layer_id, quant_config=quant_config, reduce_results=reduce_results, prefix=f"{prefix}.block_sparse_moe", + use_mega_moe=use_mega_moe, ) else: self.mlp = MiniMaxM3MLP( @@ -764,9 +1194,25 @@ def __init__( def forward( self, positions: torch.Tensor, - hidden_states: torch.Tensor, + hidden_states: torch.Tensor | MoEOutput, residual: torch.Tensor | None, - ) -> tuple[torch.Tensor, torch.Tensor]: + ) -> tuple[torch.Tensor | MoEOutput, torch.Tensor]: + hidden_states, residual = self.forward_input_norm(hidden_states, residual) + return self.forward_after_input_norm(positions, hidden_states, residual) + + def forward_input_norm( + self, hidden_states: torch.Tensor | MoEOutput, residual: torch.Tensor | None + ) -> tuple[torch.Tensor | QuantizedActivation, torch.Tensor]: + if isinstance(hidden_states, MoEOutput): + # The preceding MoE left a small batch unfinalized: finalize, + # all-reduce, norm and MXFP8-quantize the qkv_proj input at once. + assert residual is not None + return finalize_allreduce_gemma_rms_norm_mxfp8( + hidden_states, + residual, + self.input_layernorm.weight, + self.input_layernorm.variance_epsilon, + ) if self.fuse_input_allreduce and residual is not None: hidden_states, residual = fused_allreduce_gemma_rms_norm( hidden_states, residual, self.input_layernorm @@ -777,6 +1223,14 @@ def forward( hidden_states = self.input_layernorm(hidden_states) else: hidden_states, residual = self.input_layernorm(hidden_states, residual) + return hidden_states, residual + + def forward_after_input_norm( + self, + positions: torch.Tensor, + hidden_states: torch.Tensor | QuantizedActivation, + residual: torch.Tensor, + ) -> tuple[torch.Tensor | MoEOutput, torch.Tensor]: hidden_states = self.self_attn( positions=positions, hidden_states=hidden_states, @@ -785,6 +1239,11 @@ def forward( hidden_states, residual = fused_allreduce_gemma_rms_norm( hidden_states, residual, self.post_attention_layernorm ) + if self.is_moe_layer and self.block_sparse_moe.defers_finalize( + hidden_states.shape[0] + ): + # The next layer's input norm finalizes it with the all-reduce. + return self.block_sparse_moe.forward_unfinalized(hidden_states), residual ffn = self.block_sparse_moe if self.is_moe_layer else self.mlp hidden_states = ffn(hidden_states) return hidden_states, residual @@ -794,7 +1253,7 @@ def ffn_all_reduce_deferred(self) -> bool: """This layer's FFN output is left un-reduced; the caller fuses the all-reduce into the next RMSNorm.""" if self.is_moe_layer: - return self.block_sparse_moe.experts.moe_config.skip_final_all_reduce + return self.block_sparse_moe.ffn_all_reduce_deferred return not self.mlp.down_proj.reduce_results @@ -808,6 +1267,7 @@ def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): config = vllm_config.model_config.hf_text_config quant_config = vllm_config.quant_config self.config = config + self.use_mega_moe = _use_mega_moe(vllm_config) self.vocab_size = config.vocab_size @@ -871,6 +1331,47 @@ def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): layer.fuse_input_allreduce = idx > 0 and prev_defers prev_defers = layer.ffn_all_reduce_deferred self.fuse_final_norm_allreduce = prev_defers + if supports_fused_moe_finalize(vllm_config): + self._init_fused_moe_finalize() + + def _init_fused_moe_finalize(self) -> None: + """Let small batches leave a MoE's top-k finalize to the next layer's + input norm, which already fuses the TP all-reduce, and have it quantize + the normed rows to the MXFP8 its qkv_proj reads. + + Each MoE whose successor can take the output gets the hint here, and + ``defers_finalize`` decides per call. The final norm feeds the LM head + in BF16, so the last layer keeps its own finalize. Builds a collective + kernel: every TP rank decides alike. + """ + layers = self.layers[self.start_layer : self.end_layer] + deferring = [ + layer.block_sparse_moe + for layer, successor in zip(layers, layers[1:]) + if layer.is_moe_layer + and successor.fuse_input_allreduce + and get_input_quant_key(successor.self_attn.qkv_proj) == kMxfp8Dynamic + and layer.block_sparse_moe.defer_finalize(FUSED_MOE_FINALIZE_MAX_TOKENS) + ] + if not deferring: + return + # The modular experts return the router's FP32 routing weights; the + # monolithic kernel routes itself in BF16. + experts_cls = getattr( + deferring[0].experts.routed_experts.quant_method, "experts_cls", None + ) + init_fused_moe_finalize( + hidden_size=self.config.hidden_size, + max_num_tokens=FUSED_MOE_FINALIZE_MAX_TOKENS, + top_k=self.config.num_experts_per_tok, + fp32_weights=experts_cls is TrtLlmNvFp4ExpertsModular, + ) + logger.info_once( + "MiniMax M3: MoE top-k finalize fused into the next all-reduce + " + "input norm + MXFP8 quantization for up to %d tokens (%d layers).", + FUSED_MOE_FINALIZE_MAX_TOKENS, + len(deferring), + ) def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: return self.embed_tokens(input_ids) @@ -894,23 +1395,30 @@ def forward( residual = intermediate_tensors["residual"] remote_aux = self.collect_remote_aux_hidden_states(intermediate_tensors) + + # Aux hidden state k is the residual stream entering layer k. Under TP + # it is only complete after layer k's input norm (or the final norm) + # finishes the previous FFN's deferred all-reduce, so it is read there. + # Cloned, as the norms may update `residual` in place. aux_hidden_states: list[torch.Tensor] = [] - if get_pp_group().is_first_rank: - self._maybe_add_hidden_state( - aux_hidden_states, self.start_layer, hidden_states, residual - ) - # Preserve the entry tap before in-place residual updates. - if aux_hidden_states: - aux_hidden_states[0] = aux_hidden_states[0].clone() for idx, layer in enumerate( self.layers[self.start_layer : self.end_layer], start=self.start_layer ): - hidden_states, residual = layer(positions, hidden_states, residual) - self._maybe_add_hidden_state( - aux_hidden_states, idx + 1, hidden_states, residual + hidden_states, residual = layer.forward_input_norm(hidden_states, residual) + # A later PP stage's start boundary is captured by the stage before. + if idx in self.aux_hidden_state_layers and ( + idx > self.start_layer or get_pp_group().is_first_rank + ): + aux_hidden_states.append(residual.clone()) + hidden_states, residual = layer.forward_after_input_norm( + positions, hidden_states, residual ) if not get_pp_group().is_last_rank: + # Under PP every FFN reduces its own output: no all-reduce is pending. + self._maybe_add_hidden_state( + aux_hidden_states, self.end_layer, hidden_states, residual + ) return IntermediateTensors( { "hidden_states": hidden_states, @@ -920,11 +1428,13 @@ def forward( ) if self.fuse_final_norm_allreduce: - hidden_states, _ = fused_allreduce_gemma_rms_norm( + hidden_states, residual = fused_allreduce_gemma_rms_norm( hidden_states, residual, self.norm ) else: - hidden_states, _ = self.norm(hidden_states, residual) + hidden_states, residual = self.norm(hidden_states, residual) + if self.end_layer in self.aux_hidden_state_layers: + aux_hidden_states.append(residual.clone()) aux_hidden_states = remote_aux + aux_hidden_states if len(aux_hidden_states) > 0: @@ -932,6 +1442,8 @@ def forward( return hidden_states def get_expert_mapping(self) -> list[tuple[str, str, int, str]]: + if self.use_mega_moe: + return _mega_moe_expert_params_mapping(self.config.num_local_experts) # Checkpoint experts use w1=gate, w2=down, w3=up. return fused_moe_make_expert_params_mapping( self, @@ -975,6 +1487,23 @@ def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: if "weight_scale_inv" in name: name = name.replace("weight_scale_inv", "weight_scale") + if self.use_mega_moe and ".block_sparse_moe.experts." in name: + converted = _mega_moe_expert_weight(name, loaded_weight) + if converted is None: + continue + name, loaded_weight = converted + if self.use_mega_moe and ".shared_experts." in name: + if is_pp_missing_parameter(name, self): + continue + moe = self.layers[extract_layer_index(name)].block_sparse_moe + if moe.experts.has_fused_shared_experts: + name = name.replace(".gate_proj.", ".w1.") + name = name.replace(".up_proj.", ".w3.") + loaded_params.add( + moe.experts.load_shared_expert_weight(name, loaded_weight) + ) + continue + for param_name, weight_name, shard_id in stacked_params_mapping: if weight_name not in name: continue diff --git a/vllm/models/minimax_m3/nvidia/msa_cutlass_sparse_decode.py b/vllm/models/minimax_m3/nvidia/msa_cutlass_sparse_decode.py index 970b31c70233..f12232c0ee99 100644 --- a/vllm/models/minimax_m3/nvidia/msa_cutlass_sparse_decode.py +++ b/vllm/models/minimax_m3/nvidia/msa_cutlass_sparse_decode.py @@ -22,11 +22,22 @@ # fmha_sm100 plans one row per query head. Keep every cached plan within the # fixed planner allocation used by the MSA decode kernel. _MAX_QUERY_HEAD_ROWS = 65536 +# The Q8KV4 kernel (every NVFP4 cache) plans without that allocation. Without +# split KV it launches sequences x query tokens in gridDim.z, which also keeps +# the sequence count under its 16-bit work-item field. +_MAX_Q8KV4_QUERY_TOKENS = 65535 _MAX_DECODE_QUERY_LEN = 32 _DEFAULT_MIN_CUTLASS_BATCH_SIZE = 16 _B300_EAGLE3_QUERY_HEAD_ROWS = 1024 _B300_EAGLE3_MAX_QUERY_LEN = 8 _B300_EAGLE3_HEAD_GEOMETRIES = {(64, 4), (32, 2), (16, 1)} +# Q heads per KV head the Q8KV4 NVFP4 decode kernel serves. +_Q8KV4_GQA_RATIOS = (8, 16) +# Q8KV4 block-scale staging of the NVFP4 KV cache. MiniMax-M3.1 writes it with +# unit global scales, so block scales are e4m3(amax / 6) and every +# code * block_scale already fits E4M3: read it unstaged. Shift 3 is for block +# scales that use the full E4M3 range next to a calibrated global scale. +NVFP4_BLOCK_SCALE_SHIFT = 0 def is_nvfp4_kv_cache(kv_cache_dtype: str) -> bool: @@ -61,13 +72,37 @@ class MSACutlassDecodeMetadata: page_table: torch.Tensor +def uses_q8kv4_decode( + *, + kv_cache_dtype: str, + num_q_heads: int, + num_kv_heads: int, +) -> bool: + """Return whether sparse decode runs on the MSA Q8KV4 kernel: always for an + NVFP4 cache, which is never read with a BF16 query.""" + if not is_nvfp4_kv_cache(kv_cache_dtype): + return False + if ( + num_q_heads % num_kv_heads != 0 + or num_q_heads // num_kv_heads not in _Q8KV4_GQA_RATIOS + ): + raise ValueError( + "MiniMax M3 NVFP4 KV cache decodes only on the MSA Q8KV4 kernel, " + f"which serves {_Q8KV4_GQA_RATIOS} Q heads per KV head; got " + f"{num_q_heads} Q heads over {num_kv_heads} KV heads" + ) + return True + + @triton.jit def _update_runtime_metadata_kernel( seq_lens_ptr, kv_segment_lens_ptr, qo_offset_ptr, + request_seq_lens_ptr, num_rows: tl.constexpr, decode_query_len: tl.constexpr, + HAS_REQUEST_SEQ_LENS: tl.constexpr, BLOCK_SIZE: tl.constexpr, ): offsets = tl.program_id(0) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) @@ -81,6 +116,10 @@ def _update_runtime_metadata_kernel( seq_len - decode_query_len + local_query, mask=mask, ) + if HAS_REQUEST_SEQ_LENS: + tl.store( + request_seq_lens_ptr + request, seq_len, mask=mask & (local_query == 0) + ) @dataclass @@ -101,11 +140,14 @@ def _build_plan( num_kv_heads: int, page_size: int, topk_blocks: int, + q8kv4: bool, ) -> Any: from vllm.third_party.fmha_sm100.api import fmha_sm100_plan qo_lens_cpu = torch.full((batch,), decode_query_len, dtype=torch.int32) - kv_lens_cpu = initial_seq_lens_cpu + # Zero-length full-CUDA-graph padding requests would keep the Q8KV4 + # kernel from planning the batch; lengths are refreshed every step. + kv_lens_cpu = initial_seq_lens_cpu.clamp(min=1) plan = fmha_sm100_plan( qo_lens_cpu, kv_lens_cpu, @@ -120,12 +162,20 @@ def _build_plan( use_fp8_kvcache=True, split_prefill_decode=False, device=device, - # The Q8KV4 route keeps plan-time lengths and its own page offsets, - # which this cached plan does not refresh. - decode_backend="kv_mode3", + decode_backend="q8kv4" if q8kv4 else "kv_mode3", + block_scale_shift=NVFP4_BLOCK_SCALE_SHIFT, ) plan_info = plan[3] + # The Q8KV4 plan addresses pages per request, through the same flat + # block table as the per-token rows below. + q8kv4_plan = plan_info.get("q8kv4") + if q8kv4_plan is not None: + q8kv4_plan["kv_indptr"].copy_( + torch.arange(batch + 1, dtype=torch.int32, device=device).mul_( + page_table_stride + ) + ) row_starts = ( torch.arange(batch, dtype=torch.int32, device=device) .mul_(page_table_stride) @@ -155,6 +205,7 @@ def prepare( num_kv_heads: int, page_size: int, topk_blocks: int, + q8kv4: bool = False, ) -> MSACutlassDecodeMetadata: batch = int(seq_lens.shape[0]) if ( @@ -196,6 +247,7 @@ def prepare( num_kv_heads, page_size, topk_blocks, + q8kv4, ) plan = self.plans.get(key) if plan is None: @@ -209,17 +261,21 @@ def prepare( num_kv_heads=num_kv_heads, page_size=page_size, topk_blocks=topk_blocks, + q8kv4=q8kv4, ) self.plans[key] = plan plan_info = plan[3] + q8kv4_plan = plan_info.get("q8kv4") num_rows = batch * decode_query_len _update_runtime_metadata_kernel[(triton.cdiv(num_rows, 128),)]( seq_lens, plan_info["kv_segment_lens"], plan_info["qo_offset"], + q8kv4_plan["seq_lens"] if q8kv4_plan is not None else seq_lens, num_rows=num_rows, decode_query_len=decode_query_len, + HAS_REQUEST_SEQ_LENS=q8kv4_plan is not None, BLOCK_SIZE=128, ) return MSACutlassDecodeMetadata( @@ -288,6 +344,7 @@ def should_prepare_decode_metadata( ) -> bool: """Return whether a graph shape can use the CUTLASS decode path.""" total_q = batch_size * decode_query_len + nvfp4 = is_nvfp4_kv_cache(kv_cache_dtype) if min_batch_size is None: min_batch_size = _min_cutlass_batch_size( decode_query_len, num_q_heads, num_kv_heads @@ -302,8 +359,12 @@ def should_prepare_decode_metadata( topk_blocks=topk_blocks, ) and 1 <= decode_query_len <= _MAX_DECODE_QUERY_LEN - and (batch_size >= min_batch_size or is_nvfp4_kv_cache(kv_cache_dtype)) - and total_q * num_q_heads <= _MAX_QUERY_HEAD_ROWS + and (batch_size >= min_batch_size or nvfp4) + and ( + total_q <= _MAX_Q8KV4_QUERY_TOKENS + if nvfp4 + else total_q * num_q_heads <= _MAX_QUERY_HEAD_ROWS + ) ) @@ -318,9 +379,14 @@ def prepare_decode_metadata( num_kv_heads: int, page_size: int, topk_blocks: int, + q8kv4: bool = False, plan_cache: MSACutlassDecodePlanCache | None = None, ) -> MSACutlassDecodeMetadata: - """Prepare graph-stable runtime metadata for one sparse decode step.""" + """Prepare graph-stable runtime metadata for one sparse decode step. + + ``q8kv4`` plans the Q8KV4 kernel, which serves every NVFP4 cache (see + ``uses_q8kv4_decode``). + """ cache = plan_cache or MSACutlassDecodePlanCache() return cache.prepare( block_table, @@ -331,6 +397,7 @@ def prepare_decode_metadata( num_kv_heads=num_kv_heads, page_size=page_size, topk_blocks=topk_blocks, + q8kv4=q8kv4, ) diff --git a/vllm/models/minimax_m3/nvidia/ops/dense_gemm1_mxfp8.py b/vllm/models/minimax_m3/nvidia/ops/dense_gemm1_mxfp8.py new file mode 100644 index 000000000000..f18819269172 --- /dev/null +++ b/vllm/models/minimax_m3/nvidia/ops/dense_gemm1_mxfp8.py @@ -0,0 +1,664 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MXFP8 dense GEMM1 (gate_up) with fused clamped-SwiGLU + MXFP8 quant epilogue. + +One persistent SM100 tcgen05 MXFP8 GEMM tuned for prefill shapes (BM=128, +BN=128 per gate/up half, BK=128, cta_group=2; 6-warp CTA: warps 0-3 +epilogue, warp 4 MMA, warp 5 TMA) computes ``gate = X @ Wg^T`` and +``up = X @ Wu^T`` and applies clamped SwiGLU and MXFP8 quantization. No +BF16 intermediate. + +The tmem accumulator is double-buffered with a 32-col overlap (even tiles +[0,256), odd [224,480), SF fixed [500,512)): the epilogue reads the shared +32-col group first, so the next tile's MMA waits on a 32-col read instead +of 256. The single epilogue warpgroup processes a tile in 32-col chunks +(load -> act+quant -> store), overlap chunk first. + +Tile order: flat (n-fastest) when the B operand fits in half of L2, else +grouped m-fastest (GROUP_M=32) so B panels stay L2-resident (dense TP1: +B=151MB > 126MB L2). +""" + +from functools import cache + +import cutlass +import torch +from cuda.bindings.driver import CUstream +from cutlass import ( + Float8E4M3FN, + Float8E8M0FNU, + Float32, + Int32, + Int64, + Uint8, + Uint16, + Uint32, + Uint64, + cute, +) +from cutlass.cute.nvgpu import cpasync, tcgen05 +from cutlass.cute.runtime import make_fake_stream, make_fake_tensor + +from vllm.cute_utils import _tcgen05, mbarrier, simple_tma_copy, to_cta0_smem +from vllm.cute_utils.cvt import fp32x4_to_fp8x4 +from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation +from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( + mxfp8_e4m3_quantize, +) +from vllm.model_executor.layers.quantization.utils.quant_utils import kMxfp8Dynamic +from vllm.platforms import current_platform + + +class Sm100DenseGemm1Mxfp8: + def __init__(self, GROUP_M: int, use_pdl: bool = True) -> None: + BM, BN, BK = 128, 128, 128 + self.cta_tile = (BM, BN, BK) + self.GROUP_M = GROUP_M + self.use_pdl = use_pdl + + smem_bytes = cutlass.memory.SmemAllocator.capacity_in_bytes() + # A + Bg/2 + Bu/2 tiles + SFA + SFBg + SFBu (2-CTA: B halves, SF full) + self.stage_size = (BM + BN) * BK + (BM + 256) * (BK // 32) + self.num_stages = smem_bytes // self.stage_size + + @cute.jit + def prepare_AB(self, A: cute.Tensor, BM: int, BK: int) -> cpasync.TmaInfo: + tma_op = cpasync.CopyBulkTensorTileG2SOp(cta_group=tcgen05.CtaGroup.TWO) + swizzle_128B = cute.make_swizzle(3, 4, 3) + s_layout = cute.make_layout((BM, BK, self.num_stages), stride=(BK, 1, BM * BK)) + s_layout = cute.make_composed_layout(swizzle_128B, 0, s_layout) + return cpasync.make_tiled_tma_atom(tma_op, A, s_layout, (BM, BK)) + + @cute.jit + def prepare_SF( + self, + SF: cute.Tensor, + R: Int32, + Ksf: Int32, + BR: int, + BKsf: int, + tma_op: cpasync.CopyG2STileBaseOp, + ) -> cpasync.TmaInfo: + g_layout = cute.make_layout((Ksf * 128, cute.ceil_div(R, 128))) + SF_i64 = cute.recast_tensor(cute.make_tensor(SF.iterator, g_layout), Int64) + tiler = (128 * BKsf // 8, BR // 128) + s_layout = cute.make_layout((*tiler, self.num_stages)) + return cpasync.make_tiled_tma_atom(tma_op, SF_i64, s_layout, tiler) + + @cute.jit + def __call__( + self, + A: cute.Tensor, + B: cute.Tensor, + SFA: cute.Tensor, + SFB: cute.Tensor, + Q: cute.Tensor, + SFQ: cute.Tensor, + limit: Float32, + alpha: Float32, + beta: Float32, + grid_size: Int32, + stream: CUstream, + ) -> None: + M, K = A.shape + N2, _ = B.shape # 2 * N (gate|up) + BM, BN, BK = self.cta_tile + + A_tma = self.prepare_AB(A, BM, BK) + B_tma = self.prepare_AB(B, BN, BK) + SFA_tma = self.prepare_SF( + SFA, + M, + K // 32, + BM, + BK // 32, + cpasync.CopyBulkTensorTileG2SOp(tcgen05.CtaGroup.TWO), + ) + SFB_tma = self.prepare_SF( + SFB, + N2, + K // 32, + BN, + BK // 32, + cpasync.CopyBulkTensorTileG2SMulticastOp(tcgen05.CtaGroup.TWO), + ) + + self.kernel(A_tma, B_tma, SFA_tma, SFB_tma, Q, SFQ, limit, alpha, beta).launch( + grid=(grid_size, 1, 1), + block=(6 * 32, 1, 1), + cluster=(2, 1, 1), + stream=stream, + use_pdl=self.use_pdl, + ) + + @cute.kernel + def kernel( + self, + A_tma: cpasync.TmaInfo, + B_tma: cpasync.TmaInfo, + SFA_tma: cpasync.TmaInfo, + SFB_tma: cpasync.TmaInfo, + Q_tensor: cute.Tensor, + SFQ_tensor: cute.Tensor, + limit: Float32, + alpha: Float32, + beta: Float32, + ) -> None: + tid, _, _ = cute.arch.thread_idx() + raw_bid, _, _ = cute.arch.block_idx() + num_bids, _, _ = cute.arch.grid_dim() + warp_id = cute.arch.make_warp_uniform(tid // 32) + cta_rank = raw_bid % 2 + + BM, BN, BK = self.cta_tile + GROUP_M = self.GROUP_M + num_stages = self.num_stages + + smem = cutlass.memory.SmemAllocator() + sA = smem.allocate_tensor( + Float8E4M3FN, + A_tma.smem_layout.outer, + byte_alignment=128, + swizzle=A_tma.smem_layout.inner, + ) + sB = smem.allocate_tensor( + Float8E4M3FN, + B_tma.smem_layout.outer, + byte_alignment=128, + swizzle=B_tma.smem_layout.inner, + ) + sSFA = smem.allocate_tensor(Int64, SFA_tma.smem_layout, byte_alignment=128) + # SFB slots: rank r's multicast copy fills slot r of BOTH CTAs; + # slice shape/stride per slot matches the atom's (64,1):(1,64) tile + sSFB = smem.allocate_tensor( + Int64, + cute.make_layout((64, 1, 2, num_stages), stride=(1, 64, 64, 128)), + byte_alignment=128, + ) + + tma_full_mbar = smem.allocate_array(Int64, num_stages) + tma_empty_mbar = smem.allocate_array(Int64, num_stages) + tmem_full_mbar = smem.allocate_array(Int64, 2) + tmem_partial_mbar = smem.allocate_array(Int64, 1) + tmem_empty_mbar = smem.allocate_array(Int64, 2) + taddr = smem.allocate(Int32, 4) + + # allocate named barrier + BAR_EPI = 1 + BAR_TMEM_ALLOC = 2 + + M, K = A_tma.tma_tensor.shape + N2, _ = B_tma.tma_tensor.shape + N = N2 // 2 + grid_m = cute.ceil_div(M, BM * 2) * 2 + grid_n = N // BN + total_tiles = grid_m * grid_n + # output SF swizzle: NUM_K_TILES = ceil(N/32/4) tiles of 512B per 128 rows + NUM_KT = cute.ceil_div(N // 32, 4) + + def compute_bid(bid, GROUP_M, grid_m, grid_n): + if cutlass.const_expr(GROUP_M == 0): + bid_m = (bid // (grid_n * 2)) * 2 + bid % 2 + bid_n = (bid // 2) % grid_n + else: + group_size = GROUP_M * grid_n + group_id = bid // group_size + group_m = min(grid_m - group_id * GROUP_M, GROUP_M) + local_bid = bid - group_id * group_size + bid_m = group_id * GROUP_M + local_bid % group_m + bid_n = local_bid // group_m + return bid_m, bid_n + + if warp_id == 0: + with cute.arch.elect_one(): + for i in cutlass.range_constexpr(num_stages): + cute.arch.mbarrier_init(tma_full_mbar + i, 2) + cute.arch.mbarrier_init(tma_empty_mbar + i, 1) + for i in cutlass.range_constexpr(2): + cute.arch.mbarrier_init(tmem_full_mbar + i, 1) + cute.arch.mbarrier_init(tmem_empty_mbar + i, 256) + cute.arch.mbarrier_init(tmem_partial_mbar, 256) + cute.arch.mbarrier_init_fence() + elif warp_id == 1: + cpasync.prefetch_descriptor(A_tma.atom) + cpasync.prefetch_descriptor(B_tma.atom) + cpasync.prefetch_descriptor(SFA_tma.atom) + cpasync.prefetch_descriptor(SFB_tma.atom) + + cute.arch.cluster_arrive_relaxed() + cute.arch.cluster_wait() + + if cutlass.const_expr(self.use_pdl): + cute.arch.griddepcontrol_wait() + + if warp_id == 5: + # TMA warp + tma_stage = 0 + parity = 1 + tma_full_mbar_ = to_cta0_smem(tma_full_mbar) + + gA_tiles = cute.zipped_divide(A_tma.tma_tensor, (BM, BK)) + gB_tiles = cute.zipped_divide(B_tma.tma_tensor, (BN, BK)) + gSFA_tiles = cute.zipped_divide( + SFA_tma.tma_tensor, (128 * (BK // 32) // 8, BM // 128) + ) + gSFB_tiles = cute.zipped_divide( + SFB_tma.tma_tensor, (128 * (BK // 32) // 8, BN // 128) + ) + + for work_id in range(raw_bid, total_tiles, num_bids): + bid_m, bid_n = compute_bid(work_id, GROUP_M, grid_m, grid_n) + + for iter_k in range(cute.ceil_div(K, BK)): + mbar = tma_full_mbar_ + tma_stage + cute.arch.mbarrier_wait(tma_empty_mbar + tma_stage, parity) + with cute.arch.elect_one(): + mbarrier.arrive_expect_tx(mbar, self.stage_size, "cluster") + simple_tma_copy( + A_tma.atom, + gA_tiles[None, (bid_m, iter_k)], + sA[None, None, tma_stage], + mbar, + ) + simple_tma_copy( + B_tma.atom, + gB_tiles[None, (cta_rank * grid_n + bid_n, iter_k)], + sB[None, None, tma_stage], + mbar, + ) + simple_tma_copy( + SFA_tma.atom, + gSFA_tiles[None, (iter_k, bid_m)], + sSFA[None, None, tma_stage], + mbar, + ) + # TMA multicast. rank0 loads gate, rank1 loads up + simple_tma_copy( + SFB_tma.atom, + gSFB_tiles[None, (iter_k, bid_n + cta_rank * grid_n)], + sSFB[None, None, cta_rank, tma_stage], + mbar, + mcast_mask=Uint16(3), + ) + + tma_stage = (tma_stage + 1) % num_stages + if tma_stage == 0: + parity ^= 1 + + if cutlass.const_expr(self.use_pdl): + cute.arch.griddepcontrol_launch_dependents() + + elif warp_id == 4: + # MMA warp (2-CTA collective alloc; only cta_rank 0 issues) + cute.arch.barrier(barrier_id=BAR_TMEM_ALLOC, number_of_threads=2 * 32) + + tma_stage = 0 + tma_full_parity = 0 + + sdesc = _tcgen05.make_sdesc_128B_swizzle(0) + # SF smem descriptor: no swizzle, SBO = 8 * 16 bytes. + sdesc_sf = Uint64((8 << 32) | (1 << 46)) + idesc = _tcgen05.make_mxfp8_idesc(BM * 2, BN * 2) + multicast_mask = Uint16(3) + + # each [128,128] MXFP8 tile needs 4 tmem columns for SF + sfa_tmem = 500 + sfbg_tmem = sfa_tmem + 4 + sfbu_tmem = sfbg_tmem + 4 + + if cta_rank == 0: + tmem_stage = 0 + tmem_parity = 1 + for _ in range(raw_bid, total_tiles, num_bids): + acc_base = 224 * tmem_stage + cute.arch.mbarrier_wait(tmem_empty_mbar + tmem_stage, tmem_parity) + # wait for the previous tile's overlap-region read; the + # single partial barrier phases once per tile + cute.arch.mbarrier_wait(tmem_partial_mbar, tmem_stage ^ 1) + _tcgen05.fence_after_thread_sync() + + for iter_k in cutlass.range(cute.ceil_div(K, BK), unroll=1): + a_desc = sdesc | ( + sA[None, None, tma_stage].iterator.toint() >> 4 + ) + b_desc = sdesc | ( + sB[None, None, tma_stage].iterator.toint() >> 4 + ) + sfa_desc = sdesc_sf | ( + sSFA[None, None, tma_stage].iterator.toint() >> 4 + ) + sfbg_desc = sdesc_sf | ( + sSFB[None, None, 0, tma_stage].iterator.toint() >> 4 + ) + sfbu_desc = sdesc_sf | ( + sSFB[None, None, 1, tma_stage].iterator.toint() >> 4 + ) + + cute.arch.mbarrier_wait( + tma_full_mbar + tma_stage, tma_full_parity + ) + _tcgen05.fence_after_thread_sync() + + _tcgen05.cp(sfa_tmem, sfa_desc, "32x128b", "warpx4", 2) + _tcgen05.cp(sfbg_tmem, sfbg_desc, "32x128b", "warpx4", 2) + _tcgen05.cp(sfbu_tmem, sfbu_desc, "32x128b", "warpx4", 2) + + for k in cutlass.range_constexpr(BK // 32): + enable_input_d = iter_k > 0 or k > 0 + # select this k-block's SF byte inside the staged + # 4-col tmem atoms (idesc SF-id fields) + idesc_k = idesc + ((k << 4) | (k << 29)) + _tcgen05.mma_mxfp8( + acc_base, + a_desc, + b_desc, + idesc_k, + sfa_tmem, + sfbg_tmem, + enable_input_d, + 2, + ) + a_desc += 32 >> 4 + b_desc += 32 >> 4 + _tcgen05.commit(tma_empty_mbar + tma_stage, multicast_mask, 2) + + tma_stage = (tma_stage + 1) % num_stages + if tma_stage == 0: + tma_full_parity ^= 1 + + _tcgen05.commit(tmem_full_mbar + tmem_stage, multicast_mask, 2) + tmem_stage ^= 1 + if tmem_stage == 0: + tmem_parity ^= 1 + + else: + # epilogue warps (one warpgroup; tid < 128 indexes the tmem lane) + if warp_id == 0: + _tcgen05.alloc(taddr, cta_group=2) + cute.arch.barrier(barrier_id=BAR_TMEM_ALLOC, number_of_threads=2 * 32) + + exp_scale = -1.4426950216293334961 * alpha + + # ((32,4), (M, N/BN)) + Q_ = cute.zipped_divide(Q_tensor, (1, cute.make_layout((32, 4)))) + Q_ = Q_[(0, None), None] + + f8x32_atom = cute.make_copy_atom( + cute.nvgpu.CopyUniversalOp(), + Float8E4M3FN, + num_bits_per_copy=256, + l1c_evict_priority=cute.nvgpu.CacheEvictionPriority.NO_ALLOCATE, + ) + + partial_ = to_cta0_smem(tmem_partial_mbar) + empty_ = to_cta0_smem(tmem_empty_mbar) + + tmem_stage = 0 + tmem_parity = 0 + for work_id in range(raw_bid, total_tiles, num_bids): + bid_m, bid_n = compute_bid(work_id, GROUP_M, grid_m, grid_n) + m = bid_m * BM + tid + acc_base = 224 * tmem_stage + + if warp_id == 0: + cute.arch.mbarrier_wait(tmem_full_mbar + tmem_stage, tmem_parity) + cute.arch.barrier(barrier_id=BAR_EPI, number_of_threads=4 * 32) + _tcgen05.fence_after_thread_sync() + + rGate = cute.make_rmem_tensor(32, Float32) + rUp = cute.make_rmem_tensor(32, Float32) + + # cc=0 is the overlap chunk: cols [224,256) (up[96:128] on + # even tiles, gate[0:32] on odd) plus the matching 32 cols of + # the other operand. cc=1..3: the remaining chunk-pairs in + # order. Each chunk: load -> act+quant -> store. + for cc in cutlass.range_constexpr(4): + if cutlass.const_expr(cc == 0): + c = 3 - 3 * tmem_stage # even tiles: 3; odd: 0 + gate_col = 96 + 128 * tmem_stage + up_col = 224 + 128 * tmem_stage + else: + c = cc - 1 + tmem_stage # even: 0,1,2; odd: 1,2,3 + gate_col = acc_base + c * 32 + up_col = acc_base + 128 + c * 32 + rGate.store(_tcgen05.ld(tid // 32 * 32, gate_col, "32x32b", 32)) + rUp.store(_tcgen05.ld(tid // 32 * 32, up_col, "32x32b", 32)) + _tcgen05.wait_ld() + if cutlass.const_expr(cc == 0): + _tcgen05.fence_before_thread_sync() + mbarrier.arrive(partial_, "cluster") + if cutlass.const_expr(cc == 3): + _tcgen05.fence_before_thread_sync() + mbarrier.arrive(empty_ + tmem_stage, "cluster") + + q_rmem = cute.make_rmem_tensor(32, Float8E4M3FN) + q_i32 = cute.recast_tensor(q_rmem, Uint32) + + # activation + for j in cutlass.range_constexpr(32): + rGate[j] = cute.arch.fmin(rGate[j], limit) + rUp[j] = cute.arch.fmin(cute.arch.fmax(rUp[j], -limit), limit) + + af = cute.make_rmem_tensor(32, Float32) + for j in cutlass.range(32, vectorize=True): + e = cute.math.exp2(rGate[j] * exp_scale, fastmath=True) + gate = rGate[j] * cute.arch.rcp_approx(1.0 + e) + af[j] = gate * (rUp[j] + beta) + + # quantization + amax0 = cute.math.abs(af[0]) + amax1 = cute.math.abs(af[1]) + for j in cutlass.range_constexpr(15): + amax0 = cute.arch.fmax(amax0, cute.math.abs(af[j * 2 + 2])) + amax1 = cute.arch.fmax(amax1, cute.math.abs(af[j * 2 + 3])) + amax = cute.arch.fmax(amax0, amax1) + + # Scale byte via exact integer math: + # ceil(log2(amax/448)) = E - 8 + (amax > 1.75 * 2^E), + # E = exponent(amax); amax=0 (all-zero block) clamps to 0. + bits = amax.bitcast(Int32) + exp_bits = bits & 0x7F800000 + thr = (exp_bits | 0x600000).bitcast(Float32) # 1.75 * 2^E + sb = (exp_bits >> 23) - 8 + Int32(amax > thr) + sb = cutlass.min(cutlass.max(sb, Int32(0)), Int32(254)) + + inv = ((Int32(254) - sb) << 23).bitcast(Float32) + for j in cutlass.range(32, vectorize=True): + af[j] *= inv + + for j in cutlass.range_constexpr(8): + q_i32[j] = fp32x4_to_fp8x4(*[af[4 * j + t] for t in range(4)]) + + kb = bid_n * (BN // 32) + c + sf_off = ( + (bid_m * NUM_KT + kb // 4) * 512 + + (m % 32) * 16 + + ((m // 32) % 4) * 4 + + kb % 4 + ) + if m < M: + cute.copy(f8x32_atom, q_rmem, Q_[(None, c), (m, bid_n)]) + SFQ_tensor[sf_off] = Uint8(sb) + + tmem_stage ^= 1 + if tmem_stage == 0: + tmem_parity ^= 1 + + cute.arch.cluster_arrive_relaxed() + cute.arch.cluster_wait() + if warp_id == 0: + _tcgen05.dealloc(cta_group=2) + + @cache + @staticmethod + def compile(GROUP_M: int, use_pdl: bool = True): + M = cute.sym_int() + K = cute.sym_int() + N2 = cute.sym_int() + + A = make_fake_tensor( + Float8E4M3FN, + (M, K), + (cute.sym_int64(divisibility=16), 1), + assumed_align=16, + ) + B = make_fake_tensor( + Float8E4M3FN, + (N2, K), + (cute.sym_int64(divisibility=16), 1), + assumed_align=16, + ) + SFA = make_fake_tensor( + Float8E8M0FNU, (cute.sym_int(divisibility=512),), (1,), assumed_align=16 + ) + SFB = make_fake_tensor( + Float8E8M0FNU, (cute.sym_int(divisibility=512),), (1,), assumed_align=16 + ) + Q = make_fake_tensor( + Float8E4M3FN, + (M, cute.sym_int(divisibility=256)), + (cute.sym_int64(divisibility=256), 1), + assumed_align=32, + ) + SFQ = make_fake_tensor( + Uint8, (cute.sym_int(divisibility=512),), (1,), assumed_align=16 + ) + + stream = make_fake_stream(use_tvm_ffi_env_stream=True) + kernel = Sm100DenseGemm1Mxfp8(GROUP_M, use_pdl) + return cute.compile( + kernel, + A, + B, + SFA, + SFB, + Q, + SFQ, + Float32(7.0), + Float32(1.702), + Float32(1.0), + 148, + stream, + options="--enable-tvm-ffi", + ) + + +# Below this the unfused GEMM -> act -> quant chain is as fast (TP4 shared +# expert, I=768: break-even at ~1024 tokens). +MIN_TOKENS = 1024 + + +def _linear_kernel(linear): + method = getattr(linear, "scheme", getattr(linear, "quant_method", None)) + return getattr(method, "kernel", None) + + +def can_fuse_gemm1(gate_up_proj, down_proj, act_fn) -> bool: + """Whether fused_gemm1 can replace gate_up_proj + act_fn for down_proj. + + Called at init, before weight loading: kernels are selected at + create_weights time, so the decision does not depend on the weights. + """ + from vllm.model_executor.kernels.linear.mxfp8.flashinfer import ( + FlashInferCutedslMxfp8LinearKernel, + FlashInferCutlassMxfp8LinearKernel, + ) + from vllm.model_executor.layers.activation import SiluAndMulWithClamp + + if not ( + current_platform.is_cuda() and current_platform.is_device_capability_family(100) + ): + return False + if not isinstance(act_fn, SiluAndMulWithClamp): + return False + # The kernel reads gate_up's fp8 weight and F8_128x4-swizzled weight + # scale directly, so it depends on these kernels' weight layout. + if not isinstance( + _linear_kernel(gate_up_proj), + (FlashInferCutedslMxfp8LinearKernel, FlashInferCutlassMxfp8LinearKernel), + ): + return False + down_kernel = _linear_kernel(down_proj) + if down_kernel is None or down_kernel.input_quant_key() != kMxfp8Dynamic: + return False + # I % 256 == 0 (output row stride), K % 128 == 0 (BK). + n = gate_up_proj.output_size_per_partition // 2 + k = gate_up_proj.input_size_per_partition + return n % 256 == 0 and k % 128 == 0 + + +def fused_gemm1(x: torch.Tensor, gate_up_proj, act_fn) -> QuantizedActivation: + """act_fn(gate_up_proj(x)), MXFP8-quantized for an MXFP8 down_proj. + + Requires can_fuse_gemm1(gate_up_proj, down_proj, act_fn). + """ + from vllm.model_executor.kernels.linear.mxfp8.flashinfer import ( + FlashInferCutedslMxfp8LinearKernel, + ) + + assert x.ndim == 2 and x.dtype == torch.bfloat16 + weight = gate_up_proj.weight + # FlashInferCutedsl stores the weight as a column-major [K, 2I] view. + if isinstance(_linear_kernel(gate_up_proj), FlashInferCutedslMxfp8LinearKernel): + weight = weight.t() + + M = x.shape[0] + N = weight.shape[0] // 2 + q = torch.empty((M, N), dtype=torch.float8_e4m3fn, device=x.device) + sf = torch.empty( + ((M + 127) // 128) * 128 * (N // 32), dtype=torch.uint8, device=x.device + ) + + xq, xsf = mxfp8_e4m3_quantize(x, is_sf_swizzled_layout=True) + run( + xq, + weight, + xsf.view(-1).view(torch.float8_e8m0fnu), + gate_up_proj.weight_scale.view(torch.float8_e8m0fnu), + q, + sf, + act_fn.swiglu_limit, + act_fn.alpha, + act_fn.beta, + ) + return QuantizedActivation( + data=q, + scale=sf, + orig_dtype=x.dtype, + orig_shape=x.shape[:-1] + (N,), + quant_key=kMxfp8Dynamic, + ) + + +def run( + xq: torch.Tensor, + weight: torch.Tensor, + x_scale: torch.Tensor, + weight_scale: torch.Tensor, + q: torch.Tensor, + sf: torch.Tensor, + limit: float, + alpha: float, + beta: float, + grid: int | None = None, +) -> None: + """Functional interface to the fused kernel (hides compile + grid sizing). + + xq: [M, K] fp8e4m3; weight: [2N, K] fp8e4m3 row-major; x_scale/weight_scale: + F8_128x4-swizzled E8M0 (flat, any uint8-viewable dtype); q: [M, N] fp8e4m3; + sf: flat uint8 scale buffer (round_up(M,128) * N/32 bytes; rows >= M are + not written). + """ + M, K = xq.shape + _, N = q.shape + if grid is None: + grid_m2 = ((M + 127) // 128 + 1) // 2 * 2 + num_sms = torch.cuda.get_device_properties(xq.device).multi_processor_count + grid = min(num_sms, grid_m2 * (N // 128)) + + # Grouped (m-fastest) rasterization only pays when B (n2*k fp8 bytes) + # exceeds half of L2; below that the flat order is faster (no div/mod + # overhead in compute_bid) + GROUP_M = 32 if N * 2 * K > (63 << 20) else 0 + kernel = Sm100DenseGemm1Mxfp8.compile(GROUP_M) + kernel(xq, weight, x_scale, weight_scale, q, sf, limit, alpha, beta, grid) diff --git a/vllm/models/minimax_m3/nvidia/ops/finalize_allreduce_norm.py b/vllm/models/minimax_m3/nvidia/ops/finalize_allreduce_norm.py new file mode 100644 index 000000000000..9c75e71e3249 --- /dev/null +++ b/vllm/models/minimax_m3/nvidia/ops/finalize_allreduce_norm.py @@ -0,0 +1,781 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +# The consumer is adapted from FlashInfer's low-latency MNNVL CuTe DSL +# all-reduce (flashinfer/comm/mnnvl_cutedsl/kernel_ll, +# _LamportResidualRMSNormDeviceKernel), as DSV4.1's AllReduceMHC is. + +"""MoE top-k finalize + TP all-reduce + Gemma RMSNorm + MXFP8 quantization. + +FlashInfer's Lamport all-reduce: the finalize publish kernel sums each token's +routed expert rows and its shared-expert row, then multicasts that TP-partial +row into a three-generation mailbox; a PDL-chained consumer spins until every +rank's fragment lands, reduces them, adds the residual and applies the Gemma +RMSNorm. Instead of a BF16 row, the consumer writes the normalized row as MXFP8 +(E4M3 values and UE8M0 scales of 32-element blocks in the 128x4 swizzled +layout), so the MXFP8 linear that follows skips its own input quantization. +""" + +import math + +import cuda.bindings.driver as cuda +import cutlass +import cutlass.cute as cute +import torch +import torch.distributed as dist +import torch.distributed._symmetric_memory as symm_mem +from cutlass import BFloat16, Float32, Int32, Int64, Uint8, Uint32 +from cutlass._mlir.dialects import llvm +from cutlass.cute.runtime import make_fake_compact_tensor +from cutlass.cutlass_dsl import T, dsl_user_op + +from vllm.config import VllmConfig +from vllm.distributed import get_tensor_model_parallel_world_size, get_tp_group +from vllm.model_executor.layers.fused_moe.moe_output import ( + MoEOutput, + UnfinalizedMoEOutput, +) +from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation +from vllm.model_executor.layers.quantization.utils.quant_utils import kMxfp8Dynamic +from vllm.models.common.ops.moe_tail_fusion.primitives import ( + ACTIVE_STAGE, + LAMPORT_GENERATIONS, + NEXT_STAGE, + VEC_BF16, + WARP_SIZE, + bf16x8_to_packed_u32x4, + current_cu_stream, + fragment_has_negative_zero, + group_leader_block_sum, + load_global_u32x4, + load_volatile_u32, + make_fake_dynamic_compact_tensor, + map_shared_to_peer, + packed_u32x4_to_bf16x8, + store_global_u32, + store_global_u32x4, + store_lamport_sentinel_u32x4, + store_shared_cluster_f32, + to_cute, + to_cute_dynamic, +) +from vllm.models.deepseek_v41.nvidia.ops.cute_dsl.all_reduce_mhc import ( + _QuadFinalizePublishDeviceKernel, +) +from vllm.platforms import current_platform + +MXFP8_BLOCK = 32 +# Fragments (of VEC_BF16 values) per MXFP8 block, held by adjacent lanes. +_FRAGMENTS_PER_BLOCK = MXFP8_BLOCK // VEC_BF16 +# The swizzled scale layout tiles 128 rows by 4 block columns. +_SCALE_ROW_TILE = 128 +_SCALE_COL_TILE = 4 + + +@dsl_user_op +def _ue8m0_ceil(value: Float32, *, loc=None, ip=None) -> Uint32: + """FlashInfer's float_to_ue8m0_fast: the biased exponent rounded up, 0 for + non-positive input, as its MXFP8 quantization kernels compute it.""" + return Uint32( + llvm.inline_asm( + T.i32(), + [Float32(value).ir_value(loc=loc, ip=ip)], + "{\n\t" + ".reg .pred p_zero, p_has_mant, p_exp_zero, p_tiny_sub, p_ovf;\n\t" + ".reg .u32 bits, exp_biased, mantissa, bump, result;\n\t" + "setp.le.f32 p_zero, $1, 0f00000000;\n\t" + "mov.b32 bits, $1;\n\t" + "shr.b32 exp_biased, bits, 23;\n\t" + "and.b32 exp_biased, exp_biased, 255;\n\t" + "and.b32 mantissa, bits, 0x7FFFFF;\n\t" + "setp.ne.u32 p_has_mant, mantissa, 0;\n\t" + "selp.u32 bump, 1, 0, p_has_mant;\n\t" + "setp.eq.u32 p_exp_zero, exp_biased, 0;\n\t" + "setp.le.u32 p_tiny_sub, mantissa, 0x400000;\n\t" + "and.pred p_tiny_sub, p_exp_zero, p_tiny_sub;\n\t" + "@p_tiny_sub mov.u32 bump, 0;\n\t" + "add.u32 result, exp_biased, bump;\n\t" + "setp.gt.u32 p_ovf, result, 254;\n\t" + "selp.u32 result, 254, result, p_ovf;\n\t" + "selp.u32 $0, 0, result, p_zero;\n\t" + "}", + "=r,f", + has_side_effects=False, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def _ue8m0_inverse(exponent: Uint32, *, loc=None, ip=None) -> Float32: + """2^(127 - exponent), or 0 for exponent 0.""" + return Float32( + llvm.inline_asm( + T.f32(), + [Uint32(exponent).ir_value(loc=loc, ip=ip)], + "{\n\t" + ".reg .s32 new_exp;\n\t" + ".reg .pred p_zero;\n\t" + "setp.eq.u32 p_zero, $1, 0;\n\t" + "sub.s32 new_exp, 254, $1;\n\t" + "max.s32 new_exp, new_exp, 0;\n\t" + "shl.b32 $0, new_exp, 23;\n\t" + "@p_zero mov.b32 $0, 0;\n\t" + "}", + "=f,r", + has_side_effects=False, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def _f32x4_to_e4m3x4( + a: Float32, b: Float32, c: Float32, d: Float32, *, loc=None, ip=None +) -> Uint32: + """Four values to E4M3, ``a`` in the low byte, clamped to +-448 first so + that inf saturates like FlashInfer's MXFP8 kernels and torch.""" + return Uint32( + llvm.inline_asm( + T.i32(), + [Float32(v).ir_value(loc=loc, ip=ip) for v in (a, b, c, d)], + "{\n\t" + ".reg .f32 f0, f1, f2, f3;\n\t" + ".reg .b16 lo, hi;\n\t" + "min.f32 f0, $1, 0f43E00000;\n\t" + "max.f32 f0, f0, 0fC3E00000;\n\t" + "min.f32 f1, $2, 0f43E00000;\n\t" + "max.f32 f1, f1, 0fC3E00000;\n\t" + "min.f32 f2, $3, 0f43E00000;\n\t" + "max.f32 f2, f2, 0fC3E00000;\n\t" + "min.f32 f3, $4, 0f43E00000;\n\t" + "max.f32 f3, f3, 0fC3E00000;\n\t" + "cvt.rn.satfinite.e4m3x2.f32 lo, f1, f0;\n\t" + "cvt.rn.satfinite.e4m3x2.f32 hi, f3, f2;\n\t" + "mov.b32 $0, {lo, hi};\n\t" + "}", + "=r,f,f,f,f", + has_side_effects=False, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def _store_global_u32x2( + address: Int64, low: Uint32, high: Uint32, *, loc=None, ip=None +) -> None: + llvm.inline_asm( + None, + [ + address.ir_value(loc=loc, ip=ip), + low.ir_value(loc=loc, ip=ip), + high.ir_value(loc=loc, ip=ip), + ], + "st.global.v2.u32 [$0], {$1, $2};", + "l,r,r", + has_side_effects=True, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + + +@cute.jit +def _swizzled_scale_offset(row: Int32, col: Int32, padded_cols: Int32) -> Int32: + """Byte offset of block ``col`` of ``row`` in the 128x4 swizzled layout.""" + return ( + col % Int32(4) + + (col // Int32(4)) * Int32(512) + + (row % Int32(32)) * Int32(16) + + ((row % Int32(128)) // Int32(32)) * Int32(4) + + (row // Int32(128)) * Int32(128) * padded_cols + ) + + +class _LamportGemmaRMSNormMxfp8Kernel: + """FlashInfer's ``_LamportResidualRMSNormDeviceKernel`` (residual add and + copy, one rank lane) with a Gemma RMSNorm whose BF16 result is quantized to + MXFP8 instead of stored. + + A 32-element scale block is four consecutive fragments, which adjacent lanes + hold, so two shuffles reduce its amax. The scales of the padding rows below + the next multiple of 128 are zeroed, as FlashInfer's quantization does. + """ + + def __init__( + self, + *, + hidden: int, + tp: int, + capacity_m: int, + cluster_size: int, + threads: int, + enable_pdl: bool, + ) -> None: + if hidden <= 0 or hidden % (MXFP8_BLOCK * _SCALE_COL_TILE): + raise ValueError("hidden must be a positive multiple of 128") + if threads <= 0 or threads % WARP_SIZE: + raise ValueError("threads must be a positive multiple of the warp size") + self.hidden = hidden + self.tp = tp + self.capacity_m = capacity_m + self.cluster_size = cluster_size + self.threads = threads + self.enable_pdl = enable_pdl + self.fragments = hidden // VEC_BF16 + self.fragment_stride = cluster_size * threads + self.trips = math.ceil(self.fragments / self.fragment_stride) + self.warps = threads // WARP_SIZE + self.scale_cols = hidden // MXFP8_BLOCK + + def smem_size_in_bytes(self) -> int: + return (self.warps + self.cluster_size) * 4 + + @cute.jit + def __call__( + self, + contribution_mailbox: cute.Tensor, + residual_source: cute.Tensor, + gamma: cute.Tensor, + residual_output: cute.Tensor, + quant_output: cute.Tensor, + scale_output: cute.Tensor, + stage_state: cute.Tensor, + eps: Float32, + m: Int32, + stream: cuda.CUstream, + ) -> None: + self.kernel( + contribution_mailbox, + residual_source, + gamma, + residual_output, + quant_output, + scale_output, + stage_state, + eps, + m, + ).launch( + grid=(m, self.cluster_size, 1), + block=(self.threads, 1, 1), + cluster=(1, self.cluster_size, 1), + smem=self.smem_size_in_bytes(), + stream=stream, + use_pdl=self.enable_pdl, + ) + + @cute.kernel + def kernel( + self, + contribution_mailbox: cute.Tensor, + residual_source: cute.Tensor, + gamma: cute.Tensor, + residual_output: cute.Tensor, + quant_output: cute.Tensor, + scale_output: cute.Tensor, + stage_state: cute.Tensor, + eps: Float32, + m: Int32, + ) -> None: + tidx, _, _ = cute.arch.thread_idx() + token, _, _ = cute.arch.block_idx() + cluster_rank = cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) + base_fragment = cluster_rank * self.threads + tidx + + prenorm_fragments = cute.make_rmem_tensor( + cute.make_layout((self.trips, VEC_BF16), stride=(VEC_BF16, 1)), + BFloat16, + ) + prenorm_fragments.fill(BFloat16(0.0)) + gamma_fragments = cute.make_rmem_tensor( + cute.make_layout((self.trips, VEC_BF16), stride=(VEC_BF16, 1)), + BFloat16, + ) + gamma_fragments.fill(BFloat16(0.0)) + residual_fragments = cute.make_rmem_tensor( + cute.make_layout((self.trips, VEC_BF16), stride=(VEC_BF16, 1)), + BFloat16, + ) + residual_fragments.fill(BFloat16(0.0)) + + for trip in cutlass.range_constexpr(self.trips): + fragment = base_fragment + trip * self.fragment_stride + if fragment < self.fragments: + gamma_element = Int64(fragment) * VEC_BF16 + gamma_pointer = cute.make_ptr( + BFloat16, + (gamma.iterator + gamma_element).llvm_ptr, + cute.AddressSpace.gmem, + assumed_align=16, + ) + gamma_fragments[trip, None].store( + packed_u32x4_to_bf16x8(load_global_u32x4(gamma_pointer)) + ) + residual_element = Int64(token) * self.hidden + gamma_element + residual_pointer = cute.make_ptr( + BFloat16, + (residual_source.iterator + residual_element).llvm_ptr, + cute.AddressSpace.gmem, + assumed_align=16, + ) + residual_fragments[trip, None].store( + packed_u32x4_to_bf16x8(load_global_u32x4(residual_pointer)) + ) + + if cutlass.const_expr(self.enable_pdl): + cute.arch.griddepcontrol_wait() + + active_stage = load_volatile_u32(stage_state.iterator + ACTIVE_STAGE) + for trip in cutlass.range_constexpr(self.trips): + fragment = base_fragment + trip * self.fragment_stride + lane_packed = cute.make_rmem_tensor(cute.make_layout((self.tp, 4)), Uint32) + lane_packed.fill(Uint32(0)) + dirty = fragment < self.fragments + while dirty: + dirty = False + for source_rank in cutlass.range_constexpr(self.tp): + if fragment < self.fragments: + source_element = ( + (Int64(active_stage) * self.tp + Int64(source_rank)) + * self.capacity_m + + Int64(token) + ) * self.hidden + Int64(fragment) * VEC_BF16 + source_pointer = cute.make_ptr( + BFloat16, + (contribution_mailbox.iterator + source_element).llvm_ptr, + cute.AddressSpace.gmem, + assumed_align=16, + ) + packed = load_global_u32x4(source_pointer, volatile=True) + dirty = dirty | fragment_has_negative_zero(packed) + for word in cutlass.range_constexpr(4): + lane_packed[source_rank, word] = packed[word] + + if fragment < self.fragments: + prenorm = cute.make_rmem_tensor(cute.make_layout((VEC_BF16,)), Float32) + prenorm.fill(Float32(0.0)) + for source_rank in cutlass.range_constexpr(self.tp): + packed = cute.make_rmem_tensor(cute.make_layout((4,)), Uint32) + for word in cutlass.range_constexpr(4): + packed[word] = lane_packed[source_rank, word] + prenorm.store( + prenorm.load() + + packed_u32x4_to_bf16x8(packed.load()).to(Float32) + ) + prenorm_bf16 = ( + prenorm.load() + residual_fragments[trip, None].load().to(Float32) + ).to(BFloat16) + prenorm_fragments[trip, None].store(prenorm_bf16) + output_element = Int64(token) * self.hidden + Int64(fragment) * VEC_BF16 + store_global_u32x4( + Int64((residual_output.iterator + output_element).toint()), + bf16x8_to_packed_u32x4(prenorm_bf16), + ) + + if token == 0 and cluster_rank == 0 and tidx == 0: + store_global_u32( + (stage_state.iterator + NEXT_STAGE).toint(), + (active_stage + Uint32(1)) % Uint32(LAMPORT_GENERATIONS), + ) + if cutlass.const_expr(self.enable_pdl): + cute.arch.griddepcontrol_launch_dependents() + + for trip in cutlass.range_constexpr(self.trips): + fragment = base_fragment + trip * self.fragment_stride + for source_rank in cutlass.range_constexpr(self.tp): + if fragment < self.fragments: + source_element = ( + (Int64(active_stage) * self.tp + Int64(source_rank)) + * self.capacity_m + + Int64(token) + ) * self.hidden + Int64(fragment) * VEC_BF16 + store_lamport_sentinel_u32x4( + Int64((contribution_mailbox.iterator + source_element).toint()) + ) + + thread_sum = Float32(0.0) + for trip in cutlass.range_constexpr(self.trips): + fragment = base_fragment + trip * self.fragment_stride + if fragment < self.fragments: + values = prenorm_fragments[trip, None].load().to(Float32) + thread_sum = thread_sum + (values * values).reduce( + cute.ReductionOp.ADD, + init_val=Float32(0.0), + reduction_profile=0, + ) + + smem = cutlass.utils.SmemAllocator() + warp_sums = smem.allocate_array(Float32, self.warps) + cluster_sums = smem.allocate_array(Float32, self.cluster_size) + cta_sum = group_leader_block_sum(thread_sum, warp_sums, self.warps, 1) + if tidx < self.cluster_size: + local_slot = cluster_sums + cluster_rank + remote_slot = map_shared_to_peer(local_slot, Int32(tidx)) + store_shared_cluster_f32(remote_slot, cta_sum) + cute.arch.cluster_arrive() + cute.arch.cluster_wait() + + full_sum = Float32(0.0) + for peer in cutlass.range_constexpr(self.cluster_size): + full_sum = full_sum + cute.arch.load( + (cluster_sums + peer).llvm_ptr, + Float32, + ) + inv_rms = cute.math.rsqrt( + full_sum / Float32(self.hidden) + eps, + fastmath=True, + ) + padded_cols = Int32(self.scale_cols) + for trip in cutlass.range_constexpr(self.trips): + fragment = base_fragment + trip * self.fragment_stride + # Gemma RMSNorm scales by (1 + weight); the unfused norm returns BF16. + normed = ( + ( + prenorm_fragments[trip, None].load().to(Float32) + * inv_rms + * (gamma_fragments[trip, None].load().to(Float32) + Float32(1.0)) + ) + .to(BFloat16) + .to(Float32) + ) + values = cute.make_rmem_tensor(cute.make_layout((VEC_BF16,)), Float32) + values.store(normed) + amax = Float32(0.0) + for element in cutlass.range_constexpr(VEC_BF16): + amax = cute.arch.fmax( + amax, cute.arch.fmax(values[element], -values[element]) + ) + # Out-of-range fragments are zero; every lane joins the shuffles. + for offset in cutlass.range_constexpr(1, _FRAGMENTS_PER_BLOCK): + if cutlass.const_expr((offset & (offset - 1)) == 0): + amax = cute.arch.fmax( + amax, + cute.arch.shuffle_sync_bfly( + amax, offset=offset, mask=-1, mask_and_clamp=31 + ), + ) + exponent = _ue8m0_ceil(amax * Float32(1.0 / 448.0)) + inverse = _ue8m0_inverse(exponent) + if fragment < self.fragments: + low = _f32x4_to_e4m3x4( + values[0] * inverse, + values[1] * inverse, + values[2] * inverse, + values[3] * inverse, + ) + high = _f32x4_to_e4m3x4( + values[4] * inverse, + values[5] * inverse, + values[6] * inverse, + values[7] * inverse, + ) + quant_element = Int64(token) * self.hidden + Int64(fragment) * VEC_BF16 + _store_global_u32x2( + Int64((quant_output.iterator + quant_element).toint()), low, high + ) + if fragment % _FRAGMENTS_PER_BLOCK == 0: + col = fragment // _FRAGMENTS_PER_BLOCK + scale_output[_swizzled_scale_offset(token, col, padded_cols)] = ( + exponent.to(Uint8) + ) + + # Zero the scales of the last row tile's padding rows. A 4-byte word of + # a 512-byte block holds the 4 blocks of one row, so every thread of + # the grid clears whole words. + tile_words = Int32(self.scale_cols * _SCALE_ROW_TILE // 4) + last_tile = (m - Int32(1)) // Int32(_SCALE_ROW_TILE) + word = (token * Int32(self.cluster_size) + cluster_rank) * Int32( + self.threads + ) + tidx + while word < tile_words: + block_word = word % Int32(128) + row = ( + last_tile * Int32(_SCALE_ROW_TILE) + + block_word // Int32(4) + + block_word % Int32(4) * Int32(32) + ) + if row >= m: + byte = (Int64(last_tile) * Int64(tile_words) + Int64(word)) * 4 + store_global_u32( + cute.make_ptr( + Uint32, + (scale_output.iterator + byte).llvm_ptr, + cute.AddressSpace.gmem, + assumed_align=4, + ).toint(), + Uint32(0), + ) + word = word + m * Int32(self.cluster_size * self.threads) + + +def mxfp8_scale_numel(num_tokens: int, hidden_size: int) -> int: + """Bytes of the 128x4 swizzled UE8M0 scales of ``num_tokens`` rows.""" + rows = math.ceil(num_tokens / _SCALE_ROW_TILE) * _SCALE_ROW_TILE + cols = math.ceil(hidden_size // MXFP8_BLOCK / _SCALE_COL_TILE) * _SCALE_COL_TILE + return rows * cols + + +class FinalizeAllReduceGemmaRMSNormMxfp8: + """MoE top-k finalize, TP all-reduce, residual add, Gemma RMSNorm and MXFP8 + quantization in two PDL-chained launches. + + ``__call__`` takes an unfinalized MoE output plus its TP-partial shared-expert + output and returns the MXFP8 normalized rows with the new residual. Each + instance owns a Lamport mailbox for ``max_num_tokens`` rows that all layers + share; construction is collective over the TP group. + """ + + def __init__( + self, + *, + hidden_size: int, + max_num_tokens: int, + top_k: int, + fp32_weights: bool, + device: torch.device, + ) -> None: + group = get_tp_group().device_group + self.hidden_size = hidden = hidden_size + self.capacity = capacity = max_num_tokens + self.top_k = top_k + self.fp32_weights = fp32_weights + tp = dist.get_world_size(group) + rank = dist.get_rank(group) + device = torch.device(device) + + # A cluster of 128-thread CTAs covers a token's fragments in one trip + # (six for hidden 6144); the finalize stages all top_k routes at once. + cluster_size = math.ceil(hidden // VEC_BF16 / 128) + with torch.accelerator.device_index(device.index): + self._publish = cute.compile( + _QuadFinalizePublishDeviceKernel( + hidden=hidden, + top_k=top_k, + tp=tp, + rank=rank, + capacity_m=capacity, + threads=128, + # The routing weights already carry routed_scaling_factor. + routed_scaling_factor=1.0, + include_shared_expert=True, + load_shared_expert_before_pdl=False, + enable_pdl=True, + prefetch_group=top_k, + fp32_weights=fp32_weights, + ), + make_fake_dynamic_compact_tensor( + BFloat16, alignment=16, divisibility=hidden + ), + make_fake_dynamic_compact_tensor( + Float32 if fp32_weights else BFloat16, + alignment=4 if fp32_weights else 2, + divisibility=top_k, + ), + make_fake_dynamic_compact_tensor( + Int32, alignment=4, divisibility=top_k + ), + make_fake_dynamic_compact_tensor( + BFloat16, alignment=16, divisibility=hidden + ), + make_fake_compact_tensor(Int32, (2,), assumed_align=4), + Int64(0), + Int32(capacity), + current_cu_stream(), + ) + self._collective = cute.compile( + _LamportGemmaRMSNormMxfp8Kernel( + hidden=hidden, + tp=tp, + capacity_m=capacity, + cluster_size=cluster_size, + threads=128, + enable_pdl=True, + ), + make_fake_compact_tensor( + BFloat16, + (LAMPORT_GENERATIONS * tp * capacity * hidden,), + assumed_align=16, + ), + make_fake_dynamic_compact_tensor( + BFloat16, alignment=16, divisibility=hidden + ), + make_fake_compact_tensor(BFloat16, (hidden,), assumed_align=16), + make_fake_dynamic_compact_tensor( + BFloat16, alignment=16, divisibility=hidden + ), + make_fake_dynamic_compact_tensor( + Uint8, alignment=16, divisibility=hidden + ), + make_fake_dynamic_compact_tensor( + Uint8, alignment=16, divisibility=_SCALE_ROW_TILE + ), + make_fake_compact_tensor(Int32, (2,), assumed_align=4), + Float32(0.0), + Int32(capacity), + current_cu_stream(), + ) + + self._mailbox = symm_mem.empty( + (LAMPORT_GENERATIONS, tp, capacity, hidden), + dtype=torch.bfloat16, + device=device, + ) + self._mailbox_handle = symm_mem.rendezvous(self._mailbox, group) + multicast = int(self._mailbox_handle.multicast_ptr or 0) + if not multicast or multicast % 16: + raise RuntimeError("NVLink multicast mapping is unavailable") + self._multicast = multicast + # Every slot starts as the Lamport sentinel, BF16 negative zero. + self._mailbox.view(torch.int16).fill_(-32768) + self._stage_state = torch.zeros(2, dtype=torch.int32, device=device) + torch.accelerator.synchronize() + dist.barrier(group=group) + + def __call__( + self, + moe_output: MoEOutput, + residual: torch.Tensor, + norm_weight: torch.Tensor, + norm_eps: float, + ) -> tuple[QuantizedActivation, torch.Tensor]: + """Return (MXFP8 normalized rows, new residual). + + Args: + moe_output: Unfinalized TP-partial routed output and the TP-partial + shared-expert output, with routed_scaling_factor in the weights. + residual: [M, hidden] BF16 residual stream. + norm_weight: [hidden] BF16 Gemma RMSNorm weight (scale is 1 + w). + norm_eps: RMSNorm epsilon. + + """ + routed = moe_output.routed + shared_output = moe_output.shared_output + assert isinstance(routed, UnfinalizedMoEOutput) + assert shared_output is not None + assert moe_output.routed_scaling_factor == 1.0 + hidden, top_k = self.hidden_size, self.top_k + m = residual.shape[0] + if not 1 <= m <= self.capacity: + raise ValueError(f"M={m} is outside [1, {self.capacity}]") + if residual.shape != (m, hidden) or shared_output.shape != (m, hidden): + raise ValueError("residual and shared_output must be [M, hidden]") + weights_dtype = torch.float32 if self.fp32_weights else torch.bfloat16 + if ( + routed.expert_weights.dtype != weights_dtype + or routed.expert_weights.numel() != m * top_k + ): + raise ValueError(f"expert_weights must be {weights_dtype} [M, top_k]") + self._publish( + to_cute_dynamic(routed.gemm2_permuted.flatten(), 16, divisibility=hidden), + to_cute_dynamic( + routed.expert_weights.flatten(), + 4 if self.fp32_weights else 2, + divisibility=top_k, + ), + to_cute_dynamic( + routed.expanded_idx_to_permuted_idx.flatten(), 4, divisibility=top_k + ), + to_cute_dynamic(shared_output.flatten(), 16, divisibility=hidden), + to_cute(self._stage_state, 4), + Int64(self._multicast), + Int32(m), + current_cu_stream(), + ) + residual_output = torch.empty_like(residual) + quantized = torch.empty( + (m, hidden), dtype=torch.float8_e4m3fn, device=residual.device + ) + scales = torch.empty( + mxfp8_scale_numel(m, hidden), dtype=torch.uint8, device=residual.device + ) + self._collective( + to_cute(self._mailbox.flatten(), 16), + to_cute_dynamic(residual.flatten(), 16, divisibility=hidden), + to_cute(norm_weight, 16), + to_cute_dynamic(residual_output.flatten(), 16, divisibility=hidden), + to_cute_dynamic( + quantized.view(torch.uint8).flatten(), 16, divisibility=hidden + ), + to_cute_dynamic(scales, 16, divisibility=_SCALE_ROW_TILE), + to_cute(self._stage_state, 4), + Float32(norm_eps), + Int32(m), + current_cu_stream(), + ) + return ( + QuantizedActivation( + quantized, scales, residual.dtype, quantized.shape, kMxfp8Dynamic + ), + residual_output, + ) + + +_fused_moe_finalize: FinalizeAllReduceGemmaRMSNormMxfp8 | None = None + + +def supports_fused_moe_finalize(vllm_config: VllmConfig) -> bool: + """Whether to build the fused MoE finalize kernel: tensor parallel without + expert parallel, a BF16 model on SM100-family GPUs, and NVLink multicast on + every TP rank. Every TP rank calls it; the multicast check is collective. + """ + from vllm.distributed.device_communicators.custom_all_reduce import ( + _all_ranks_true, + _has_local_multicast_support, + ) + + if ( + get_tensor_model_parallel_world_size() <= 1 + or vllm_config.parallel_config.enable_expert_parallel + or not current_platform.is_cuda() + or not current_platform.is_device_capability_family(100) + or vllm_config.model_config.dtype != torch.bfloat16 + ): + return False + device = torch.device( + current_platform.device_type, torch.accelerator.current_device_index() + ) + return _all_ranks_true( + get_tp_group().cpu_group, _has_local_multicast_support(device) + ) + + +def init_fused_moe_finalize( + *, hidden_size: int, max_num_tokens: int, top_k: int, fp32_weights: bool +) -> None: + """Build the kernel every deferred MoE output is finalized with. + + Collective over the TP group, so every rank calls it, and only when + ``supports_fused_moe_finalize`` holds. + """ + global _fused_moe_finalize + _fused_moe_finalize = FinalizeAllReduceGemmaRMSNormMxfp8( + hidden_size=hidden_size, + max_num_tokens=max_num_tokens, + top_k=top_k, + fp32_weights=fp32_weights, + device=torch.device( + current_platform.device_type, torch.accelerator.current_device_index() + ), + ) + + +def finalize_allreduce_gemma_rms_norm_mxfp8( + moe_output: MoEOutput, + residual: torch.Tensor, + norm_weight: torch.Tensor, + norm_eps: float, +) -> tuple[QuantizedActivation, torch.Tensor]: + """Finalize a deferred MoE output into the next layer's MXFP8 input and + new residual.""" + assert _fused_moe_finalize is not None, "init_fused_moe_finalize was not called" + return _fused_moe_finalize(moe_output, residual, norm_weight, norm_eps) diff --git a/vllm/models/minimax_m3/nvidia/ops/gather_nvfp4_index_k.py b/vllm/models/minimax_m3/nvidia/ops/gather_nvfp4_index_k.py new file mode 100644 index 000000000000..0c9f477180ff --- /dev/null +++ b/vllm/models/minimax_m3/nvidia/ops/gather_nvfp4_index_k.py @@ -0,0 +1,174 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Gather NVFP4 index-K pages into compact FP8 pages for the Q8KV8 prefill indexer. + +A packed NVFP4 page ``[128, 72]`` holds the E2M1 codes of all 128 tokens (64 B +per token, low nibble first) followed by their E4M3 16-element block scales +(``token * 8 + group``), with no global scale. Each element dequantizes to +``e4m3_rn_satfinite(e2m1 * scale)``, the value the Q8KV4 decode indexer scores, +so prefill and decode rank pages from identical keys. + +Where Triton can emit it, each four elements are one QMUL4 +(``mul.rn.satfinite.e4m3x4.e2m1x4.e4m3x4``), the instruction the decode kernel +dequantizes with; otherwise the product is formed exactly in fp32 and rounded +once, which gives the same bytes. +""" + +import functools + +import torch + +from vllm.platforms import current_platform +from vllm.triton_utils import tl, triton + +PAGE_SIZE = 128 +HEAD_DIM = 128 +E4M3_MAX = 448.0 +# QMUL4 needs PTX ISA 9.4 (ptxas 13.4) and an sm_100a/sm_103a target. +QMUL4_MIN_PTX_VERSION = 94 + + +@functools.cache +def _qmul4_supported(device_index: int) -> bool: + """Whether Triton emits PTX that can use QMUL4 on this device. + + Triton takes the PTX ISA version from its Blackwell ptxas: the bundled one + unless ``TRITON_PTXAS_BLACKWELL_PATH`` points at a CUDA 13.4+ ptxas. + """ + capability = current_platform.get_device_capability(device_index) + if capability is None or capability.to_int() not in (100, 103): + return False + try: + from triton.backends.nvidia.compiler import get_ptxas, ptx_get_version + + ptxas_version = get_ptxas(capability.to_int()).version + return ptx_get_version(ptxas_version) >= QMUL4_MIN_PTX_VERSION + except Exception: + # Triton-internal helpers; without them keep the portable path. + return False + + +@triton.jit +def _e2m1_to_f32(code): + # |code| 0..7 -> 0, 0.5, 1, 1.5, 2, 3, 4, 6; bit 3 is the sign. + exponent = (code >> 1) & 3 + mantissa = (code & 1).to(tl.float32) + normal = (2.0 + mantissa) * (1 << exponent).to(tl.float32) * 0.25 + value = tl.where(exponent == 0, 0.5 * mantissa, normal) + # Multiply (not negate) so that code 8 stays -0, as in the decode kernel. + return value * tl.where((code & 8) != 0, -1.0, 1.0) + + +@triton.jit +def _gather_nvfp4_index_k_fp8_kernel( + kv_cache, + block_table, + num_pages, + page_offsets, + out, + kv_page_stride, + block_table_stride, + PAGE_SIZE: tl.constexpr, + HEAD_DIM: tl.constexpr, + E4M3_MAX: tl.constexpr, + USE_QMUL4: tl.constexpr, +): + req = tl.program_id(0) + col = tl.program_id(1) + if col >= tl.load(num_pages + req): + return + page = tl.load(block_table + req * block_table_stride + col).to(tl.int64) + dst_page = (tl.load(page_offsets + req) + col).to(tl.int64) + + src = kv_cache + page * kv_page_stride + dst = out + dst_page * (PAGE_SIZE * HEAD_DIM) + tokens = tl.arange(0, PAGE_SIZE)[:, None] + scales = src + PAGE_SIZE * (HEAD_DIM // 2) + tokens * (HEAD_DIM // 16) + if USE_QMUL4: + # A 16-bit word holds four elements of one group; multiply it by the + # group's scale byte broadcast to E4M3x4. + words = tl.arange(0, HEAD_DIM // 4)[None, :] + packed4 = tl.load( + src.to(tl.pointer_type(tl.uint16)) + tokens * (HEAD_DIM // 4) + words + ) + scale4 = tl.load(scales + words // 4).to(tl.uint32) * 0x01010101 + values4 = tl.inline_asm_elementwise( + "{ .reg .b16 v; cvt.u16.u32 v, $1; " + "mul.rn.satfinite.e4m3x4.e2m1x4.e4m3x4 $0, v, $2; }", + "=r,r,r", + [packed4.to(tl.uint32), scale4], + dtype=tl.uint32, + is_pure=True, + pack=1, + ) + tl.store( + dst.to(tl.pointer_type(tl.uint32)) + tokens * (HEAD_DIM // 4) + words, + values4, + ) + return + + packed_cols = tl.arange(0, HEAD_DIM // 2)[None, :] + packed = tl.load(src + tokens * (HEAD_DIM // 2) + packed_cols) + # Packed byte b holds elements 2b and 2b+1, both in group b // 8. + scale = tl.load(scales + packed_cols // 8) + scale = scale.to(tl.float8e4nv, bitcast=True).to(tl.float32) + # e2m1 * e4m3 is exact in fp32; clamp, then round once to e4m3. + low = _e2m1_to_f32(packed & 0xF) * scale + high = _e2m1_to_f32(packed >> 4) * scale + values = tl.interleave(low, high) + values = tl.minimum(tl.maximum(values, -E4M3_MAX), E4M3_MAX) + tl.store( + dst + tokens * HEAD_DIM + tl.arange(0, HEAD_DIM)[None, :], + values.to(tl.float8e4nv), + ) + + +def minimax_m3_gather_nvfp4_index_k_fp8( + kv_cache: torch.Tensor, + block_table: torch.Tensor, + num_pages: torch.Tensor, + page_offsets: torch.Tensor, + max_num_pages: int, + out: torch.Tensor, +) -> torch.Tensor: + """Dequantize each request's leading NVFP4 pages into contiguous FP8 pages. + + Args: + kv_cache: ``[num_blocks, 128, 72]`` uint8 packed NVFP4 pages. + block_table: ``[num_reqs, max_blocks]`` int32 physical page ids. + num_pages: ``[num_reqs]`` int32 pages to gather per request (its first + ``num_pages[r]`` logical pages). + page_offsets: ``[num_reqs]`` int32 first output page of each request. + max_num_pages: Host upper bound of ``num_pages``. + out: ``[>= sum(num_pages), 128, 128]`` contiguous float8_e4m3fn. + + Returns: + ``out``. + + """ + assert kv_cache.dtype == torch.uint8 and kv_cache.shape[1:] == ( + PAGE_SIZE, + HEAD_DIM // 2 + HEAD_DIM // 16, + ) + assert kv_cache.stride(1) == kv_cache.shape[2] and kv_cache.stride(2) == 1 + assert out.dtype == torch.float8_e4m3fn and out.is_contiguous() + assert out.shape[1:] == (PAGE_SIZE, HEAD_DIM) + assert block_table.stride(1) == 1 + num_reqs = block_table.shape[0] + if num_reqs == 0 or max_num_pages == 0: + return out + _gather_nvfp4_index_k_fp8_kernel[(num_reqs, max_num_pages)]( + kv_cache, + block_table, + num_pages, + page_offsets, + out, + kv_cache.stride(0), + block_table.stride(0), + PAGE_SIZE=PAGE_SIZE, + HEAD_DIM=HEAD_DIM, + E4M3_MAX=E4M3_MAX, + USE_QMUL4=_qmul4_supported(kv_cache.device.index or 0), + num_warps=4, + ) + return out diff --git a/vllm/models/minimax_m3/nvidia/ops/qkv_index_fused_epilogue.py b/vllm/models/minimax_m3/nvidia/ops/qkv_index_fused_epilogue.py new file mode 100644 index 000000000000..e531f4f9e792 --- /dev/null +++ b/vllm/models/minimax_m3/nvidia/ops/qkv_index_fused_epilogue.py @@ -0,0 +1,1101 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MXFP8 QKV+indexer GEMM with a fused QK-norm/RoPE + KV-insert epilogue. + +Replaces mm_mxfp8 + fused_minimax_m3_qknorm_rope_kv_insert for the MiniMax-M3 +qkv_proj with one persistent SM100 kernel. Per 128-col head tile, the +epilogue applies Gemma RMSNorm + partial NeoX RoPE to the f32 accumulator +(no bf16 round trip) and writes q (bf16, optionally fp8) and index_q (fp8), +or NVFP4-quantizes k / v / index_k into the paged caches. The qkv projection +is never materialized. +""" + +from dataclasses import dataclass +from functools import cache + +import cutlass +import torch +from cuda.bindings.driver import CUstream +from cutlass import ( + BFloat16, + Float8E4M3FN, + Float8E8M0FNU, + Float32, + Int32, + Int64, + Uint8, + Uint16, + Uint32, + Uint64, + cute, +) +from cutlass.cute.nvgpu import cpasync, tcgen05 +from cutlass.cute.runtime import make_fake_tensor + +from vllm.cute_utils import _tcgen05, mbarrier, simple_tma_copy, to_cta0_smem +from vllm.cute_utils.cvt import ( + bf16x2_to_fp32x2, + fp32x8_to_fp4x8, +) +from vllm.model_executor.warmup.jit_warmup_cutedsl_helper import VllmCuTeDSLJitKernel + +HEAD_DIM = 128 # one 128-col N-tile per head +# epilogue outputs are consumed by other kernels: stores bypass L1 +_NO_L1_ALLOC = dict(level1_eviction_priority="evict_no_allocate") + + +@cute.jit +def _rms_norm(acc, sW, eps): + """Gemma RMS-norm the 128-col head row in acc in place; sW is the head + type's bf16 weight as (8, 16) tiles.""" + acc1 = cute.make_tensor(acc.iterator, cute.make_layout(HEAD_DIM)) + # 4 independent fma chains; starting from 0 makes every step + # fma(x, x, ss) (x0 * x0 + x1 * x1 would let ptxas fuse either product) + ss = cute.full(4, 0.0, Float32) + for j in cutlass.range_constexpr(HEAD_DIM // 4): + x = cute.local_tile(acc1, (4,), (j,)).load() + ss = ss + x * x + t = (ss[0] + ss[1] + ss[2] + ss[3]) * Float32(1.0 / HEAD_DIM) + eps + # t >= eps, so rsqrt.approx needs no subnormal handling + rms = cute.math.rsqrt(t, approx=True) + + # load 8 norm weights at a time -> 16-byte loads + for j in cutlass.range_constexpr(HEAD_DIM // 8): + w_f32 = bf16x2_to_fp32x2(sW[None, j].load()) + x = cute.local_tile(acc1, (8,), (j,)) + n = x.load() * rms + x.store(n + n * w_f32) + + +def _rope64(acc, CS, pos): + """NeoX-rope cols [0, 64) of acc in place, rotating chunk 0 (x) with + chunk 1 (y); CS is the bf16 cos | sin cache as [32, (pos, 2)].""" + cos = bf16x2_to_fp32x2(CS[None, (pos, 0)].load()) + sin = bf16x2_to_fp32x2(CS[None, (pos, 1)].load()) + x = acc[None, 0].load() + y = acc[None, 1].load() + acc[None, 0].store(x * cos - y * sin) + acc[None, 1].store(y * cos + x * sin) + + +def _nvfp4_cache_views(C, bs, nslots): + """Views of the [num_pages, page_bytes] NVFP4 cache C. A page holds nslots + slots of bs tokens' E2M1 data (64B each), then their E4M3 scales (8B + each). Returns the data as u32 words [8, half, token, slot, page], the + linear scales as [8, token, slot, page], and the V-swizzled scales as + [(2, 4), token, slot, page]: byte h of token t at + (t // 4 * 4 + h // 2) * 8 + h % 2 * 4 + t % 4.""" + slot_bytes = bs * (HEAD_DIM // 2 + HEAD_DIM // 16) + sf_off = bs * HEAD_DIM // 2 + nb, page = C.shape[0], C.stride[0] + data = cute.make_tensor( + C.iterator, + cute.make_layout((32, 2, bs, nslots, nb), stride=(1, 32, 64, slot_bytes, page)), + ) + sf = cute.make_tensor( + C.iterator + sf_off, + cute.make_layout((8, bs, nslots, nb), stride=(1, 8, slot_bytes, page)), + ) + vsf = cute.make_tensor( + C.iterator + sf_off, + cute.make_layout( + ((2, 4), (4, bs // 4), nslots, nb), + stride=((4, 8), (1, 32), slot_bytes, page), + ), + ) + return cute.recast_tensor(data, Uint32), sf, vsf + + +def _nvfp4_quant32(vals, words, sf, sf_scale): + """NVFP4-quantize 32 f32 (two 16-value groups) into 4 data words and the + 2 scale bytes `sf`, following + fused_minimax_m3_qknorm_rope_kv_insert's quantizer. sf_scale is + 1 / (global dequant scale), or None for unit scale.""" + # E4M3(amax / 6) floored at 2^-9 (satfinite caps it at 448); the unfused + # op's 1e-12 amax floor lies below that and is omitted. Both groups' + # scales share one e4m3x2 cvt. + amax_6 = cute.make_rmem_tensor(2, Float32) + for g in range(2): + gmax = Float32(0.0) + for i in range(16 * g, 16 * g + 16): + gmax = cute.arch.fmax(gmax, cute.math.abs(vals[i])) + a = gmax * Float32(1.0 / 6.0) + if sf_scale is not None: + a = a * sf_scale + amax_6[g] = cute.arch.fmax(a, Float32(2.0**-9)) + + sf8 = amax_6.load().to(Float8E4M3FN) + sf.store(sf8.bitcast(Uint8)) + sf_f32 = sf8.to(Float32) + + q = cute.make_rmem_tensor(32, Float32) + for g in range(2): + # rcp.approx.ftz is exact on every positive E4M3 value + r = cute.arch.rcp_approx(sf_f32[g]) + if sf_scale is not None: + r = r * sf_scale + # rz: r >= 1 / sf, so a rounded product could step past an exact E2M1 + # midpoint and round away from even; truncation lands back on it (raw + # v accumulators do hit exact midpoints, rarely) + for i in range(16 * g, 16 * g + 16, 2): + q[i], q[i + 1] = cute.arch.mul_packed_f32x2( + (vals[i], vals[i + 1]), (r, r), rnd="rz" + ) + + # clear the sign of zero-magnitude nibbles (+7 carries into bit 3 exactly + # when the 3-bit magnitude is nonzero) + m = Uint32(0x77777777) + for j in range(4): + w = fp32x8_to_fp4x8(q, 8 * j) + words[j] = w & (((w & m) + m) | m) + + +def _nvfp4_quant64(vals, sf_scale=None): + """NVFP4-quantize 64 f32 (a 64-col half, one 32-col chunk at a time); + returns the 8 data words and the 4 scale bytes.""" + words = cute.make_rmem_tensor(8, Uint32) + sf = cute.make_rmem_tensor(4, Uint8) + for c in range(2): + _nvfp4_quant32( + cute.local_tile(vals, (32,), (c,)), + cute.local_tile(words, (4,), (c,)), + cute.local_tile(sf, (2,), (c,)), + sf_scale, + ) + return words.load(), sf.load() + + +class QkvIndexFusedEpilogueKernel: + """Persistent MXFP8 GEMM with a BM x BN = 128 x (128 * cta_group) output + tile per CTA (one head per epilogue warpgroup). 2-SM (cta_group=2): a CTA + pair runs one m256n256 MMA per k-step over two adjacent M-tiles, each CTA + loading half of the BN rows of B. 1-SM (cta_group=1): one m128n128 MMA per + CTA (finer tiles for small M). Warps: 4 * cta_group epilogue, then MMA and + TMA; cta_group=2 adds 2 padding warps so setmaxnreg can move registers to + the epilogue (at cta_group=1, 6 warps already fit 255 regs each). + """ + + def __init__( + self, + nkv: int, + block_size: int, + cta_group: int = 2, + group_m: int = 1, + use_pdl: bool = True, + ) -> None: + assert nkv in (1, 2, 4) + assert block_size % 4 == 0 # V scales swizzle over 4-token quads + assert cta_group in (1, 2) + self.cta_group = cta_group + self.group_m = group_m + self.num_warps = 12 if cta_group == 2 else 6 + self.tma_group = ( + tcgen05.CtaGroup.TWO if cta_group == 2 else tcgen05.CtaGroup.ONE + ) + self.use_pdl = use_pdl + self.nkv = nkv + self.block_size = block_size + + # The N dim is a list of 128-col heads, [q x 16nkv | k x nkv | + # v x nkv | index_q x nkv | index_k x 1]; first head of each role + # (q starts at 0). An odd head count leaves a phantom head in the + # last tile at cta_group=2 (TMA zero-fill, never stored). + self.k_start = 16 * nkv + self.v_start = self.k_start + nkv + self.iq_start = self.v_start + nkv + self.ik_start = self.iq_start + nkv + + BM, BN, BK = 128, cta_group * HEAD_DIM, 128 + self.cta_tile = (BM, BN, BK) + # per CTA and stage: A + this CTA's share of B (cta_group=2 splits B + # across the pair) + SFA + full SFB (each CTA multicasts its half) + self.stage_size = (BM + BN // cta_group) * BK + (BM + BN) * (BK // 32) + self.num_stages = ( + cutlass.memory.SmemAllocator.capacity_in_bytes() // self.stage_size + ) + + @cute.jit + def prepare_AB(self, A: cute.Tensor, BM: int, BK: int) -> cpasync.TmaInfo: + tma_op = cpasync.CopyBulkTensorTileG2SOp(cta_group=self.tma_group) + swizzle_128B = cute.make_swizzle(3, 4, 3) + s_layout = cute.make_layout((BM, BK, self.num_stages), stride=(BK, 1, BM * BK)) + s_layout = cute.make_composed_layout(swizzle_128B, 0, s_layout) + return cpasync.make_tiled_tma_atom(tma_op, A, s_layout, (BM, BK)) + + @cute.jit + def prepare_SF( + self, + SF: cute.Tensor, + R: Int32, + Ksf: Int32, + tma_op: cpasync.CopyG2STileBaseOp, + ) -> cpasync.TmaInfo: + # SF grid [R, Ksf] padded to R % 128 == 0 and permuted as + # [R/128, Ksf/4, 32, 4, 4]; the [32, 4, 4] atom is tcgen05's opaque + # 512B block, so treat it as bytes. One box = one atom (128 rows x + # BK / 32 = 4 K-groups) = 64 Int64 x 1 row-block. + g_layout = cute.make_layout((Ksf * 128, cute.ceil_div(R, 128))) + SF_i64 = cute.recast_tensor(cute.make_tensor(SF.iterator, g_layout), Int64) + s_layout = cute.make_layout((64, 1, self.num_stages)) + return cpasync.make_tiled_tma_atom(tma_op, SF_i64, s_layout, (64, 1)) + + @cute.jit + def __call__( + self, + A: cute.Tensor, + B: cute.Tensor, + SFA: cute.Tensor, + SFB: cute.Tensor, + Q: cute.Tensor | None, + WQ: cute.Tensor, + WK: cute.Tensor, + WIQ: cute.Tensor, + WIK: cute.Tensor, + COS_SIN: cute.Tensor, + POS: cute.Tensor, + KVC: cute.Tensor, + IDXC: cute.Tensor, + SLOT: cute.Tensor, + IDX_SLOT: cute.Tensor, + IQFP8: cute.Tensor, + QFP8: cute.Tensor | None, + eps: Float32, + q_fp8_scale: Float32, + k_scale: Float32, + v_scale: Float32, + grid_size: Int32, + stream: CUstream, + ) -> None: + M, K = A.shape + N, _ = B.shape + BM, BN, BK = self.cta_tile + + A_tma = self.prepare_AB(A, BM, BK) + B_tma = self.prepare_AB(B, BN // self.cta_group, BK) + SFA_tma = self.prepare_SF( + SFA, M, K // 32, cpasync.CopyBulkTensorTileG2SOp(self.tma_group) + ) + sfb_op = ( + cpasync.CopyBulkTensorTileG2SMulticastOp(self.tma_group) + if self.cta_group == 2 + else cpasync.CopyBulkTensorTileG2SOp(self.tma_group) + ) + SFB_tma = self.prepare_SF(SFB, N, K // 32, sfb_op) + + self.kernel( + A_tma, + B_tma, + SFA_tma, + SFB_tma, + Q, + WQ, + WK, + WIQ, + WIK, + COS_SIN, + POS, + KVC, + IDXC, + SLOT, + IDX_SLOT, + IQFP8, + QFP8, + eps, + q_fp8_scale, + k_scale, + v_scale, + ).launch( + grid=(grid_size, 1, 1), + block=(self.num_warps * 32, 1, 1), + cluster=(self.cta_group, 1, 1), + min_blocks_per_mp=1, + stream=stream, + use_pdl=self.use_pdl, + ) + + @cute.kernel + def kernel( + self, + A_tma: cpasync.TmaInfo, + B_tma: cpasync.TmaInfo, + SFA_tma: cpasync.TmaInfo, + SFB_tma: cpasync.TmaInfo, + Q_tensor: cute.Tensor | None, + WQ_tensor: cute.Tensor, + WK_tensor: cute.Tensor, + WIQ_tensor: cute.Tensor, + WIK_tensor: cute.Tensor, + COS_SIN_tensor: cute.Tensor, + POS_tensor: cute.Tensor, + KVC_tensor: cute.Tensor, + IDXC_tensor: cute.Tensor, + SLOT_tensor: cute.Tensor, + IDX_SLOT_tensor: cute.Tensor, + IQFP8_tensor: cute.Tensor, + QFP8_tensor: cute.Tensor | None, + eps: Float32, + q_fp8_scale: Float32, + k_scale: Float32, + v_scale: Float32, + ) -> None: + tid, _, _ = cute.arch.thread_idx() + raw_bid, _, _ = cute.arch.block_idx() + num_bids, _, _ = cute.arch.grid_dim() + warp_id = cute.arch.make_warp_uniform(tid // 32) + cg = self.cta_group + cta_rank = raw_bid % cg + + BM, BN, BK = self.cta_tile + num_stages = self.num_stages + + # tmem (512 cols): double-buffered accumulators, then SFA/SFB0/SFB1. + # At cta_group=2, 2 x 256 + SF cols don't fit, so they overlap by 32 + # cols (even tiles at [0, 256), odd at [224, 480)). + acc_odd = BN - 32 if cg == 2 else BN + sfa_tmem = 496 + sfb0_tmem = sfa_tmem + 4 + sfb1_tmem = sfb0_tmem + 4 + # q / k / index_q / index_k norm weight index in sW + W_Q, W_K, W_IQ, W_IK = range(4) + bs = self.block_size + + BAR_EPI = 1 + BAR_TMEM_ALLOC = 2 + cta_pair = Uint16(3) if cg == 2 else None # multicast / commit mask + + smem = cutlass.memory.SmemAllocator() + sA = smem.allocate_tensor( + Float8E4M3FN, + A_tma.smem_layout.outer, + byte_alignment=128, + swizzle=A_tma.smem_layout.inner, + ) + sB = smem.allocate_tensor( + Float8E4M3FN, + B_tma.smem_layout.outer, + byte_alignment=128, + swizzle=B_tma.smem_layout.inner, + ) + sSFA = smem.allocate_tensor(Int64, SFA_tma.smem_layout, byte_alignment=128) + # SFB slots: CTA r's multicast copy (head tile 2 * bid_n + r) fills slot + # r of both CTAs; each slot matches the atom's (64, 1):(1, 64) tile + sSFB = smem.allocate_tensor( + Int64, + cute.make_layout((64, 1, cg, num_stages), stride=(1, 64, 64, 64 * cg)), + byte_alignment=128, + ) + # norm weights as (8, 16) tiles per head type + sW = smem.allocate_tensor( + BFloat16, cute.make_layout((8, 16, 4)), byte_alignment=16 + ) + + tma_full_mbar = smem.allocate_array(Int64, num_stages) + tma_empty_mbar = smem.allocate_array(Int64, num_stages) + tmem_full_mbar = smem.allocate_array(Int64, 2) + tmem_partial_mbar = smem.allocate_array(Int64, 1) + tmem_empty_mbar = smem.allocate_array(Int64, 2) + taddr = smem.allocate(Int32, 4) + + M, K = A_tma.tma_tensor.shape + N, _ = B_tma.tma_tensor.shape + + def num_tiles(M, N, cg): + # per-CTA M-tiles (a multiple of cg) x BN-wide N-tiles. Each role + # recomputes these after setmaxnreg: a value kept live across it + # is spilled. + grid_n = cute.ceil_div(N, 128 * cg) + grid_mp = cute.ceil_div(M, 128 * cg) + return grid_mp, grid_n, grid_mp * cg * grid_n + + def tile_coords(bid, grid_mp, grid_n, cg, G): + # CTA group p = bid // cg covers M-tiles cg * m + rank (one per + # CTA) and N-tile n. Rasterized in groups of G M-tile groups, m + # fastest within each N-tile of a group (G = 1: n fastest). + p = bid // cg + if cutlass.const_expr(G == 1): + return (p // grid_n) * cg + bid % cg, p % grid_n + group = p // (G * grid_n) + first = group * G + size = cutlass.min(grid_mp - first, G) + local = p - group * (G * grid_n) + return (first + local % size) * cg + bid % cg, local // size + + if warp_id == 0: + # counts: tma_full cg CTAs; tmem_empty cg CTAs x 128 * cg epilogue + # threads; tmem_partial 2 CTAs x 128 (the overlap warpgroup) + with cute.arch.elect_one(): + for i in cutlass.range_constexpr(num_stages): + cute.arch.mbarrier_init(tma_full_mbar + i, cg) + cute.arch.mbarrier_init(tma_empty_mbar + i, 1) + for i in cutlass.range_constexpr(2): + cute.arch.mbarrier_init(tmem_full_mbar + i, 1) + cute.arch.mbarrier_init(tmem_empty_mbar + i, 128 * cg * cg) + cute.arch.mbarrier_init(tmem_partial_mbar, 256) + cute.arch.mbarrier_init_fence() + elif warp_id == 1: + cpasync.prefetch_descriptor(A_tma.atom) + cpasync.prefetch_descriptor(B_tma.atom) + cpasync.prefetch_descriptor(SFA_tma.atom) + cpasync.prefetch_descriptor(SFB_tma.atom) + elif warp_id < 4: + # norm weights (static, so before the PDL wait): 4 x 256B, one 16B + # cp.async per thread of warps 2-3 + t = tid - 64 + cp_atom = cute.make_copy_atom( + cpasync.CopyG2SOp(), BFloat16, num_bits_per_copy=128 + ) + for i, Wt in enumerate((WQ_tensor, WK_tensor, WIQ_tensor, WIK_tensor)): + if t // 16 == i: + cute.copy( + cp_atom, + cute.zipped_divide(Wt, (8,))[None, t % 16], + sW[None, t % 16, i], + ) + cute.arch.cp_async_commit_group() + cute.arch.cp_async_wait_group(0) + cute.arch.sync_threads() # sW visible (cluster_arrive is relaxed) + cute.arch.cluster_arrive_relaxed() + cute.arch.cluster_wait() + + if cutlass.const_expr(self.use_pdl): + cute.arch.griddepcontrol_wait() + + # warps: 4 * cg epilogue (one warpgroup per head), then MMA, TMA (and 2 + # padding warps at cg=2, completing the producer warpgroup) + MMA_WARP = 4 * cg + TMA_WARP = MMA_WARP + 1 + # setmaxnreg (cg=2): the producer warpgroup drops to 40 regs, the + # epilogue rises to 232 (2*128*232 + 128*40 <= 64K) + REG_DEC = 40 + REG_INC = 232 + + if warp_id > TMA_WARP: + # padding warps + if cutlass.const_expr(cg == 2): + cute.arch.setmaxregister_decrease(REG_DEC) + + elif warp_id == TMA_WARP: + # TMA warp; both CTAs load, copies arrive on CTA0's mbarrier. + # SFB is multicast: the pair's MMA needs all 256 rows in each CTA. + if cutlass.const_expr(cg == 2): + cute.arch.setmaxregister_decrease(REG_DEC) + grid_mp, grid_n, total_tiles = num_tiles(M, N, cg) + tma_stage = 0 + tma_empty_parity = 1 + tma_full_mbar_ = to_cta0_smem(tma_full_mbar) + + gA_tiles = cute.zipped_divide(A_tma.tma_tensor, (BM, BK)) + gB_tiles = cute.zipped_divide(B_tma.tma_tensor, (BN // cg, BK)) + # SF boxes: one [32, 4, 4] atom = (64, 1) Int64 (see prepare_SF) + gSFA_tiles = cute.zipped_divide(SFA_tma.tma_tensor, (64, 1)) + gSFB_tiles = cute.zipped_divide(SFB_tma.tma_tensor, (64, 1)) + + for bid in range(raw_bid, total_tiles, num_bids): + bid_m, bid_n = tile_coords(bid, grid_mp, grid_n, cg, self.group_m) + + for iter_k in cutlass.range(cute.ceil_div(K, BK), unroll=1): + mbar = tma_full_mbar_ + tma_stage + cute.arch.mbarrier_wait( + tma_empty_mbar + tma_stage, tma_empty_parity + ) + with cute.arch.elect_one(): + mbarrier.arrive_expect_tx(mbar, self.stage_size, "cluster") + simple_tma_copy( + A_tma.atom, + gA_tiles[None, (bid_m, iter_k)], + sA[None, None, tma_stage], + mbar, + ) + simple_tma_copy( + B_tma.atom, + gB_tiles[None, (cg * bid_n + cta_rank, iter_k)], + sB[None, None, tma_stage], + mbar, + ) + simple_tma_copy( + SFA_tma.atom, + gSFA_tiles[None, (iter_k, bid_m)], + sSFA[None, None, tma_stage], + mbar, + ) + simple_tma_copy( + SFB_tma.atom, + gSFB_tiles[None, (iter_k, cg * bid_n + cta_rank)], + sSFB[None, None, cta_rank, tma_stage], + mbar, + mcast_mask=cta_pair, + ) + + tma_stage = (tma_stage + 1) % num_stages + if tma_stage == 0: + tma_empty_parity ^= 1 + + if cutlass.const_expr(self.use_pdl): + cute.arch.griddepcontrol_launch_dependents() + + elif warp_id == MMA_WARP: + # MMA warp (2-SM collective; only cta_rank 0 issues). tmem is + # allocated by epilogue warp 0. + if cutlass.const_expr(cg == 2): + cute.arch.setmaxregister_decrease(REG_DEC) + cute.arch.barrier(barrier_id=BAR_TMEM_ALLOC, number_of_threads=2 * 32) + + grid_mp, grid_n, total_tiles = num_tiles(M, N, cg) + tma_stage = 0 + tma_full_parity = 0 + + sdesc = _tcgen05.make_sdesc_128B_swizzle(0) + # SF smem descriptor: no swizzle, SBO = 8 * 16 bytes + sdesc_sf = Uint64((8 << 32) | (1 << 46)) + idesc = _tcgen05.make_mxfp8_idesc(cg * BM, BN) + + if cta_rank == 0: + tmem_stage = 0 + tmem_parity = 1 + for _ in range(raw_bid, total_tiles, num_bids): + acc_base = acc_odd * tmem_stage + cute.arch.mbarrier_wait(tmem_empty_mbar + tmem_stage, tmem_parity) + # the previous tile's overlap-region read (cols [224, 256)); + # the single partial barrier phases once per tile + if cutlass.const_expr(cg == 2): + cute.arch.mbarrier_wait(tmem_partial_mbar, tmem_stage ^ 1) + _tcgen05.fence_after_thread_sync() + + for iter_k in cutlass.range(cute.ceil_div(K, BK), unroll=1): + a_desc = sdesc | ( + sA[None, None, tma_stage].iterator.toint() >> 4 + ) + b_desc = sdesc | ( + sB[None, None, tma_stage].iterator.toint() >> 4 + ) + sfa_desc = sdesc_sf | ( + sSFA[None, None, tma_stage].iterator.toint() >> 4 + ) + sfb0_desc = sdesc_sf | ( + sSFB[None, None, 0, tma_stage].iterator.toint() >> 4 + ) + + cute.arch.mbarrier_wait( + tma_full_mbar + tma_stage, tma_full_parity + ) + _tcgen05.fence_after_thread_sync() + + _tcgen05.cp(sfa_tmem, sfa_desc, "32x128b", "warpx4", cg) + _tcgen05.cp(sfb0_tmem, sfb0_desc, "32x128b", "warpx4", cg) + if cutlass.const_expr(cg == 2): + sfb1_desc = sdesc_sf | ( + sSFB[None, None, 1, tma_stage].iterator.toint() >> 4 + ) + _tcgen05.cp(sfb1_tmem, sfb1_desc, "32x128b", "warpx4", 2) + + for k in cutlass.range_constexpr(BK // 32): + enable_input_d = iter_k > 0 or k > 0 + # select this k-block's SF byte inside the staged + # 4-col tmem atoms (idesc SF-id fields) + idesc_k = idesc + ((k << 4) | (k << 29)) + _tcgen05.mma_mxfp8( + acc_base, + a_desc, + b_desc, + idesc_k, + sfa_tmem, + sfb0_tmem, + enable_input_d, + cg, + ) + a_desc += 32 >> 4 + b_desc += 32 >> 4 + _tcgen05.commit(tma_empty_mbar + tma_stage, cta_pair, cg) + + tma_stage = (tma_stage + 1) % num_stages + if tma_stage == 0: + tma_full_parity ^= 1 + + _tcgen05.commit(tmem_full_mbar + tmem_stage, cta_pair, cg) + tmem_stage ^= 1 + if tmem_stage == 0: + tmem_parity ^= 1 + + else: + # epilogue warps + if cutlass.const_expr(cg == 2): + cute.arch.setmaxregister_increase(REG_INC) + if warp_id == 0: + _tcgen05.alloc(taddr, cta_group=cg) + cute.arch.barrier(barrier_id=BAR_TMEM_ALLOC, number_of_threads=2 * 32) + + # warp w reads tmem rows (w % 4) * 32 of head cg * bid_n + w // 4; + # thread t owns row t % 128. Padding rows (m >= M) compute garbage + # from clamped metadata and skip only the stores. + warp_e = warp_id % 4 + wg_id = warp_id // 4 + tid_ = tid % 128 + + # Q / QFP8 are each optional (None -> compiled out) + has_q = cutlass.const_expr(Q_tensor is not None) + has_qfp8 = cutlass.const_expr(QFP8_tensor is not None) + # [32, (pos, cos | sin)] + CS_CHUNKS = cute.zipped_divide(COS_SIN_tensor, (1, 32))[(0, None), None] + # KV head h's K / V go to slots 2h / 2h + 1; index_k has one slot + KV_DATA, KV_SF, KV_VSF = _nvfp4_cache_views(KVC_tensor, bs, 2 * self.nkv) + IDX_DATA, IDX_SF, _ = _nvfp4_cache_views(IDXC_tensor, bs, 1) + + partial_ = to_cta0_smem(tmem_partial_mbar) + empty_ = to_cta0_smem(tmem_empty_mbar) + + grid_mp, grid_n, total_tiles = num_tiles(M, N, cg) + tmem_stage = 0 + tmem_parity = 0 + for bid in range(raw_bid, total_tiles, num_bids): + bid_m, bid_n = tile_coords(bid, grid_mp, grid_n, cg, self.group_m) + acc_base = acc_odd * tmem_stage + + if warp_id == 0: + cute.arch.mbarrier_wait(tmem_full_mbar + tmem_stage, tmem_parity) + cute.arch.barrier(barrier_id=BAR_EPI, number_of_threads=cg * 128) + _tcgen05.fence_after_thread_sync() + + head = cg * bid_n + wg_id # this warpgroup's head + m = bid_m * BM + tid_ + + # Drain this warp's 32 rows of its head into registers + row = warp_e * 32 + base = acc_base + wg_id * HEAD_DIM + acc = cute.make_rmem_tensor((32, 4), Float32) # 4 x 32 cols + owns_overlap = False + if cutlass.const_expr(cg == 2): + owns_overlap = wg_id == 1 - tmem_stage + if owns_overlap: + # This warpgroup holds cols [224, 256), which the next + # tile's MMA reuses: load and release them first. They are + # chunk 0 of the head on odd tiles, chunk 3 on even. + if tmem_stage == 1: + acc[None, 0].store(_tcgen05.ld(row, base, "32x32b", 32)) + _tcgen05.wait_ld() + mbarrier.arrive(partial_, "cluster") + for c in cutlass.range_constexpr(1, 4): + col = base + 32 * c + acc[None, c].store(_tcgen05.ld(row, col, "32x32b", 32)) + else: + acc[None, 3].store(_tcgen05.ld(row, base + 96, "32x32b", 32)) + _tcgen05.wait_ld() + mbarrier.arrive(partial_, "cluster") + for c in cutlass.range_constexpr(3): + col = base + 32 * c + acc[None, c].store(_tcgen05.ld(row, col, "32x32b", 32)) + else: + acc.store(_tcgen05.ld(row, base, "32x32b", HEAD_DIM)) + _tcgen05.wait_ld() + _tcgen05.fence_before_thread_sync() + mbarrier.arrive(empty_ + tmem_stage, "cluster") + + # rope dim is 64: store the unrotated half (cols 64-127) first + # to free its registers before rope. Only the stores are + # predicated on the row / slot. + halves = cute.make_tensor(acc.iterator, cute.make_layout((64, 2))) + m_safe = cutlass.min(m, M - 1) + + if head < self.k_start: + # q: bf16 and / or scaled e4m3 + _rms_norm(acc, sW[None, None, W_Q], eps) + if cutlass.const_expr(has_qfp8): + qfp8_inv = cute.math.rcp(q_fp8_scale) + + for h in (1, 0): # NoPE, then RoPE + if cutlass.const_expr(h == 0): + _rope64(acc, CS_CHUNKS, POS_tensor[m_safe].to(Int32)) + + x = halves[None, h].load() + col = HEAD_DIM * head + 64 * h + if cutlass.const_expr(has_q): + assert Q_tensor is not None + q = x.to(BFloat16) + if m < M: + dst = Q_tensor[m, None].iterator + col + cute.arch.store(dst, q, **_NO_L1_ALLOC) + # fp8 is stored as u32 words: fp8 vectors don't lower + # in cute.arch.store (NVIDIA/cutlass#3712) + if cutlass.const_expr(has_qfp8): + assert QFP8_tensor is not None + q = (x * qfp8_inv).to(Float8E4M3FN).bitcast(Uint32) + if m < M: + dst = QFP8_tensor[m, None].iterator + col + dst = cute.recast_ptr(dst, dtype=Uint32) + cute.arch.store(dst, q, **_NO_L1_ALLOC) + + elif head < self.v_start: + # k: NVFP4 into its KV head's K slot, linear scale bytes + _rms_norm(acc, sW[None, None, W_K], eps) + kv_slot = 2 * (head - self.k_start) + slot = SLOT_tensor[m_safe] + page, token = slot // bs, slot % bs + k_sf = cute.math.rcp(k_scale) + sf = cute.make_rmem_tensor(8, Uint8) + + for h in (1, 0): # NoPE, then RoPE + if cutlass.const_expr(h == 0): + _rope64(acc, CS_CHUNKS, POS_tensor[m_safe].to(Int32)) + + words, sf_h = _nvfp4_quant64(halves[None, h], k_sf) + cute.local_tile(sf, (4,), (h,)).store(sf_h) + if m < M and slot >= 0: + dst = KV_DATA[None, h, token, kv_slot, page].iterator + cute.arch.store(dst, words, **_NO_L1_ALLOC) + + if m < M and slot >= 0: + dst = KV_SF[None, token, kv_slot, page].iterator + cute.arch.store(dst, sf.load(), **_NO_L1_ALLOC) + + elif head < self.iq_start: + # v: raw accumulator, NVFP4 into its KV head's V slot, + # swizzled scale bytes + kv_slot = 2 * (head - self.v_start) + 1 + slot = SLOT_tensor[m_safe] + page, token = slot // bs, slot % bs + v_sf = cute.math.rcp(v_scale) + + for h in (0, 1): + words, sf = _nvfp4_quant64(halves[None, h], v_sf) + if m < M and slot >= 0: + dst = KV_DATA[None, h, token, kv_slot, page].iterator + cute.arch.store(dst, words, **_NO_L1_ALLOC) + vsf = KV_VSF[None, token, kv_slot, page] + cute.local_tile(vsf, (4,), (h,)).store(sf) + + elif head < self.ik_start: + # index_q: e4m3 + _rms_norm(acc, sW[None, None, W_IQ], eps) + iq_col = HEAD_DIM * (head - self.iq_start) + + for h in (1, 0): # NoPE, then RoPE + if cutlass.const_expr(h == 0): + _rope64(acc, CS_CHUNKS, POS_tensor[m_safe].to(Int32)) + + # u32 words: see the q branch + q = halves[None, h].load().to(Float8E4M3FN).bitcast(Uint32) + if m < M: + dst = IQFP8_tensor[m, None].iterator + iq_col + 64 * h + dst = cute.recast_ptr(dst, dtype=Uint32) + cute.arch.store(dst, q, **_NO_L1_ALLOC) + + elif head == self.ik_start: + # index_k: NVFP4 into the index cache (one slot per page, + # linear scale bytes) + _rms_norm(acc, sW[None, None, W_IK], eps) + slot = IDX_SLOT_tensor[m_safe] + page, token = slot // bs, slot % bs + sf = cute.make_rmem_tensor(8, Uint8) + + for h in (1, 0): # NoPE, then RoPE + if cutlass.const_expr(h == 0): + _rope64(acc, CS_CHUNKS, POS_tensor[m_safe].to(Int32)) + + words, sf_h = _nvfp4_quant64(halves[None, h]) + cute.local_tile(sf, (4,), (h,)).store(sf_h) + if m < M and slot >= 0: + dst = IDX_DATA[None, h, token, 0, page].iterator + cute.arch.store(dst, words, **_NO_L1_ALLOC) + + if m < M and slot >= 0: + dst = IDX_SF[None, token, 0, page].iterator + cute.arch.store(dst, sf.load(), **_NO_L1_ALLOC) + + # else: phantom head (odd head count), nothing to store + + tmem_stage ^= 1 + if tmem_stage == 0: + tmem_parity ^= 1 + + cute.arch.cluster_arrive_relaxed() + cute.arch.cluster_wait() + if warp_id == 0: + _tcgen05.dealloc(cta_group=cg) + + +class _QkvIndexFusedEpilogueJit( + VllmCuTeDSLJitKernel["_QkvIndexFusedEpilogueJit.CompileKey"] +): + """Compile keys, warmup (fake) inputs and the compiled executors of + QkvIndexFusedEpilogueKernel.""" + + @dataclass(frozen=True) + class CompileKey: + has_q: bool + has_qfp8: bool + nkv: int + block_size: int + group_m: int + cta_group: int + use_pdl: bool = True + + @staticmethod + def kernel(key: CompileKey) -> QkvIndexFusedEpilogueKernel: + return QkvIndexFusedEpilogueKernel( + key.nkv, key.block_size, key.cta_group, key.group_m, key.use_pdl + ) + + def get_warmup_keys(self, **fields) -> list[CompileKey]: + # a layer's keys differ only in the tile config, picked per batch size + return [self.CompileKey(cta_group=cg, **fields) for cg in (1, 2)] + + def warmup_inputs(self, key: CompileKey) -> tuple: + M = cute.sym_int() + N = cute.sym_int() + K = cute.sym_int() + P = cute.sym_int() + slot_bytes = key.block_size * (HEAD_DIM // 2 + HEAD_DIM // 16) + + A = make_fake_tensor( + Float8E4M3FN, (M, K), (cute.sym_int64(divisibility=16), 1), assumed_align=16 + ) + B = make_fake_tensor( + Float8E4M3FN, (N, K), (cute.sym_int64(divisibility=16), 1), assumed_align=16 + ) + SFA = make_fake_tensor( + Float8E8M0FNU, (cute.sym_int(divisibility=512),), (1,), assumed_align=16 + ) + SFB = make_fake_tensor( + Float8E8M0FNU, (cute.sym_int(divisibility=512),), (1,), assumed_align=16 + ) + q_cols = 16 * key.nkv * HEAD_DIM + Q = ( + make_fake_tensor(BFloat16, (M, q_cols), (q_cols, 1), assumed_align=32) + if key.has_q + else None + ) + WQ, WK, WIQ, WIK = ( + make_fake_tensor(BFloat16, (HEAD_DIM,), (1,), assumed_align=16) + for _ in range(4) + ) + COS_SIN = make_fake_tensor(BFloat16, (P, 64), (64, 1), assumed_align=16) + POS = make_fake_tensor(Int64, (M,), (1,), assumed_align=16) + # caches as [nb, page_bytes] with a dynamic page stride: no dynamic dim + # may exceed int32, and cross-layer layouts space pages wider than a page + KVC = make_fake_tensor( + Uint8, + (cute.sym_int(), 2 * key.nkv * slot_bytes), + (cute.sym_int64(divisibility=32), 1), + assumed_align=32, + ) + IDXC = make_fake_tensor( + Uint8, + (cute.sym_int(), slot_bytes), + (cute.sym_int64(divisibility=32), 1), + assumed_align=32, + ) + SLOT = make_fake_tensor(Int64, (M,), (1,), assumed_align=16) + IDX_SLOT = make_fake_tensor(Int64, (M,), (1,), assumed_align=16) + IQFP8 = make_fake_tensor( + Float8E4M3FN, + (M, key.nkv * HEAD_DIM), + (key.nkv * HEAD_DIM, 1), + assumed_align=32, + ) + QFP8 = ( + make_fake_tensor(Float8E4M3FN, (M, q_cols), (q_cols, 1), assumed_align=32) + if key.has_qfp8 + else None + ) + + return ( + A, + B, + SFA, + SFB, + Q, + WQ, + WK, + WIQ, + WIK, + COS_SIN, + POS, + KVC, + IDXC, + SLOT, + IDX_SLOT, + IQFP8, + QFP8, + # runtime scalars (eps, q/k/v scales, grid): placeholder values + Float32(1e-6), + Float32(1.0), + Float32(1.0), + Float32(1.0), + 148, + ) + + +_JIT = _QkvIndexFusedEpilogueJit() + + +@cache +def _device_info(device: int) -> tuple[int, int]: + """(SM count, L2 bytes) of a CUDA device.""" + props = torch.cuda.get_device_properties(device) + return props.multi_processor_count, props.L2_cache_size + + +def _group_m(weight_bytes: int, l2_bytes: int) -> int: + # Group M-tiles 16 at a time when the weight is a large fraction of L2, so + # a wave reads a few N-panels instead of all of B (GB300: helps TP1's 60MB + # weight by 1.5-5%; slows TP2 / TP4, whose weights stay L2-resident anyway) + return 16 if weight_bytes >= l2_bytes // 4 else 1 + + +def register_qkv_index_fused_epilogue_warmup( + *, has_q: bool, has_qfp8: bool, nkv: int, block_size: int, weight_bytes: int +) -> None: + """Compile this layer's kernels (both tile configs) during JIT warmup.""" + _, l2_bytes = _device_info(torch.accelerator.current_device_index()) + _JIT.register_warmup( + has_q=has_q, + has_qfp8=has_qfp8, + nkv=nkv, + block_size=block_size, + group_m=_group_m(weight_bytes, l2_bytes), + ) + + +def minimax_m3_qkv_index_fused_epilogue( + xq: torch.Tensor, + xsf: torch.Tensor, + wq: torch.Tensor, + wsf: torch.Tensor, + positions: torch.Tensor, + cos_sin_cache: torch.Tensor, + q_norm_weight: torch.Tensor, + k_norm_weight: torch.Tensor, + index_q_norm_weight: torch.Tensor, + index_k_norm_weight: torch.Tensor, + eps: float, + *, + slot_mapping: torch.Tensor, + index_slot_mapping: torch.Tensor, + kv_cache: torch.Tensor, + index_cache: torch.Tensor, + index_q_out: torch.Tensor, + q_out: torch.Tensor | None = None, + q_fp8_out: torch.Tensor | None = None, + q_fp8_scale: float = 1.0, + k_scale: float = 1.0, + v_scale: float = 1.0, + cta_group: int | None = None, + use_pdl: bool = True, + grid: int | None = None, +) -> None: + """QKV+indexer projection with fused epilogue: writes q (bf16 and / or + fp8; at least one) and index_q, and NVFP4-inserts k / v / index_k into the + paged caches. + nkv in {1, 2, 4} KV heads per rank is inferred from N = (19 * nkv + 1) * 128. + + Args: + xq: MXFP8 activation [M, K]. + xsf: xq's F8_128x4-swizzled E8M0 scales. + wq: K-major MXFP8 weight [N, K]: [q | k | v | index_q | index_k]. + wsf: wq's F8_128x4-swizzled E8M0 scales. + positions: [M] int64 token positions. + cos_sin_cache: [max_pos, 64] bf16 RoPE cache (cos | sin). + q_norm_weight: [128] bf16 Gemma RMSNorm weight; likewise the next three. + k_norm_weight: see q_norm_weight. + index_q_norm_weight: see q_norm_weight. + index_k_norm_weight: see q_norm_weight. + eps: RMSNorm epsilon. + slot_mapping: [M] int64 KV-cache slots (-1 = skip). + index_slot_mapping: [M] int64 index-cache slots (-1 = skip). + kv_cache: NVFP4 [nb, 2 * nkv, block_size, 72] uint8; packed pages at + any page stride. block_size % 4 == 0. + index_cache: NVFP4 [nb, block_size, 72] uint8; packed pages at any + page stride. + index_q_out: [M, nkv * 128] e4m3 normed + roped index_q. + q_out: optional [M, 16 * nkv * 128] bf16 normed + roped q. + q_fp8_out: optional [M, 16 * nkv * 128] e4m3 normed + roped q. + q_fp8_scale: dequantization scale of q_fp8_out. + k_scale: dequantization (global) scale of the NVFP4 k entries. + v_scale: dequantization (global) scale of the NVFP4 v entries. + cta_group: 2 (2-SM: CTA pairs, 128 x 256 tiles), 1 (1-SM: 128 x 128 + tiles) or None (pick by wave count). + use_pdl: launch with programmatic dependent launch. + grid: persistent grid size override (testing). + + """ + M, K = xq.shape + N = wq.shape[0] + nkv = (N // HEAD_DIM - 1) // 19 + assert nkv in (1, 2, 4) and (19 * nkv + 1) * HEAD_DIM == N, N + assert K % 128 == 0 and wq.shape[1] == K and wq.stride() == (K, 1) + assert index_q_out.shape == (M, nkv * HEAD_DIM) + assert index_q_out.dtype == torch.float8_e4m3fn and index_q_out.is_contiguous() + assert q_out is not None or q_fp8_out is not None, "no q output" + for t in (positions, slot_mapping, index_slot_mapping): + assert t.shape == (M,) and t.dtype == torch.int64 + assert cos_sin_cache.dtype == torch.bfloat16 and cos_sin_cache.is_contiguous() + assert cos_sin_cache.dim() == 2 and cos_sin_cache.shape[1] == 64 + for w in (q_norm_weight, k_norm_weight, index_q_norm_weight, index_k_norm_weight): + assert w.shape == (HEAD_DIM,) and w.dtype == torch.bfloat16 + for q, dtype in ((q_out, torch.bfloat16), (q_fp8_out, torch.float8_e4m3fn)): + if q is not None: + assert q.shape == (M, 16 * nkv * HEAD_DIM) + assert q.dtype == dtype and q.is_contiguous() + assert kv_cache.dtype == torch.uint8 and index_cache.dtype == torch.uint8 + block_size, token_bytes = kv_cache.shape[2:] + assert token_bytes == HEAD_DIM // 2 + HEAD_DIM // 16 + assert kv_cache.shape[1] == 2 * nkv + assert kv_cache.stride()[1:] == (block_size * token_bytes, token_bytes, 1) + assert index_cache.shape[1:] == (block_size, token_bytes) + assert index_cache.stride()[1:] == (token_bytes, 1) + for c in (kv_cache, index_cache): # 32B NVFP4 data stores + assert c.data_ptr() % 32 == 0 and c.stride(0) % 32 == 0 + num_sms, l2_bytes = _device_info(xq.device.index) + + def num_tiles(cg): + tile = 128 * cg # M rows per CTA group, N cols per tile + return -(-M // tile) * cg * -(-N // tile) + + if cta_group is None: + # a 128 x 128 tile costs ~2/3 of a 128 x 256 one (GB300): take 1-SM + # when that wins after wave quantization (odd M-tile counts, few tiles) + waves1, waves2 = (-(-num_tiles(cg) // num_sms) for cg in (1, 2)) + cta_group = 1 if 2 * waves1 < 3 * waves2 else 2 + if grid is None: + grid = min(num_sms, num_tiles(cta_group)) + # caches as [nb, page_bytes], keeping the page stride (a flat 1-D view + # exceeds the DSL's int32 shapes at production sizes) + slot_bytes = block_size * token_bytes + kvc = kv_cache.as_strided( + (kv_cache.size(0), 2 * nkv * slot_bytes), (kv_cache.stride(0), 1) + ) + idxc = index_cache.as_strided( + (index_cache.size(0), slot_bytes), (index_cache.stride(0), 1) + ) + key = _JIT.CompileKey( + has_q=q_out is not None, + has_qfp8=q_fp8_out is not None, + nkv=nkv, + block_size=block_size, + group_m=_group_m(wq.numel(), l2_bytes), + cta_group=cta_group, + use_pdl=use_pdl, + ) + _JIT._get_or_compile(key)( + xq, + wq, + xsf.view(-1).view(torch.float8_e8m0fnu), + wsf.view(-1).view(torch.float8_e8m0fnu), + q_out, + q_norm_weight, + k_norm_weight, + index_q_norm_weight, + index_k_norm_weight, + cos_sin_cache, + positions, + kvc, + idxc, + slot_mapping, + index_slot_mapping, + index_q_out, + q_fp8_out, + eps, + q_fp8_scale, + k_scale, + v_scale, + grid, + ) diff --git a/vllm/models/minimax_m3/nvidia/sparse_attention_msa.py b/vllm/models/minimax_m3/nvidia/sparse_attention_msa.py index a5598c719bfa..0b87b26596ec 100644 --- a/vllm/models/minimax_m3/nvidia/sparse_attention_msa.py +++ b/vllm/models/minimax_m3/nvidia/sparse_attention_msa.py @@ -1,16 +1,21 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""MSA (SM100/Blackwell) block-sparse attention for MiniMax M3. +"""MSA (SM100 family) block-sparse attention for MiniMax M3. -Prefill attends with ``fmha_sm100`` (``build_k2q_csr`` + ``sparse_atten_func``). -Decode uses Triton split-K by default, with an opt-in CUTLASS ``fmha_sm100`` -path for regular decode and speculative verification. NVFP4 KV caches read the -vLLM packed pages directly in both prefill and CUTLASS decode. +``MiniMaxM3SparseMSAImpl`` serves BF16 and FP8 KV caches: prefill attends with +``fmha_sm100`` (``build_k2q_csr`` + ``sparse_atten_func``), and decode uses the +CUTLASS ``fmha_sm100`` path by default for regular decode and speculative +verification, with Triton split-K as the fallback. + +``MiniMaxM3SparseMSANvfp4Impl`` serves NVFP4 KV caches, reading vLLM's packed +pages directly with only the E4M3 query: decode and prefill both run the CUTLASS +Q8KV4 kernels. """ +import functools import os -from dataclasses import dataclass, replace -from typing import ClassVar +from dataclasses import dataclass, fields, replace +from typing import TYPE_CHECKING, ClassVar import torch @@ -29,8 +34,10 @@ MiniMaxM3SparseImpl, MiniMaxM3SparseMetadata, MiniMaxM3SparseMetadataBuilder, + MiniMaxM3SparsePrefillMetadata, ) from vllm.models.minimax_m3.nvidia.msa_cutlass_sparse_decode import ( + NVFP4_BLOCK_SCALE_SHIFT, MSACutlassDecodeMetadata, MSACutlassDecodePlanCache, is_nvfp4_kv_cache, @@ -39,7 +46,9 @@ prepare_decode_metadata, should_prepare_decode_metadata, supports_cutlass_sparse_decode, + uses_q8kv4_decode, ) +from vllm.platforms import current_platform from vllm.utils.torch_utils import get_dtype_size, nvfp4_kv_cache_full_dim from vllm.v1.attention.backend import ( AttentionLayer, @@ -47,19 +56,40 @@ ) from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout +if TYPE_CHECKING: + from vllm.third_party.fmha_sm100.prefill_q8kv4 import PrefillWorkspace + logger = init_logger(__name__) +@functools.cache +def _q8kv4_prefill_blocker( + num_q_heads: int, num_kv_heads: int, page_size: int, topk_blocks: int +) -> str | None: + """Why the Q8KV4 kernel cannot prefill this layout on this device, or None.""" + from vllm.third_party.fmha_sm100.q8kv4_prefill_adapter import _plan_blocker + + return _plan_blocker( + num_qo_heads=num_q_heads, + num_kv_heads=num_kv_heads, + page_size=page_size, + kv_block_num=topk_blocks, + causal=True, + output_maxscore=False, + device=None, + ) + + def _get_msa_cutlass_min_batch_size() -> int | None: value = os.getenv("VLLM_MINIMAX_M3_MSA_CUTLASS_MIN_BATCH") return int(value) if value is not None else None def _dequantize_query( - query_fp8: torch.Tensor, q_scale: float, out: torch.Tensor + query_fp8: torch.Tensor, q_scale: float, dtype: torch.dtype ) -> torch.Tensor: - """Write ``query_fp8 * q_scale`` into ``out`` (E4M3 is exact in BF16).""" - out.copy_(query_fp8) + """``query_fp8 * q_scale`` in ``dtype`` (E4M3 is exact in BF16).""" + out = query_fp8.to(dtype) if q_scale != 1.0: out.mul_(q_scale) return out @@ -89,6 +119,7 @@ def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec: num_head_slots=2 * spec.num_kv_heads, state_content_bytes=nvfp4_kv_cache_full_dim(spec.head_size) * get_dtype_size(spec.dtype), + kv_head_major_slots=True, ) @classmethod @@ -118,6 +149,12 @@ class MiniMaxM3SparseMSADecodeMetadata(MiniMaxM3SparseDecodeMetadata): msa_cutlass: MSACutlassDecodeMetadata | None = None +@dataclass +class MiniMaxM3SparseMSAPrefillMetadata(MiniMaxM3SparsePrefillMetadata): + # The builder's Q8KV4 prefill split workspace; None off Rubin. + workspace: "PrefillWorkspace | None" = None + + class MiniMaxM3SparseMSAMetadataBuilder(MiniMaxM3SparseMetadataBuilder): """Prepare MSA plans only for decode shapes supported by ``fmha_sm100``.""" @@ -138,8 +175,29 @@ def __init__( # format to distinguish E4M3 (supported) from E5M2 before planning. self.kv_cache_dtype = vllm_config.cache_config.cache_dtype self.decode_backend = vllm_config.attention_config.minimax_m3_msa_decode_backend + self.q8kv4_decode = uses_q8kv4_decode( + kv_cache_dtype=self.kv_cache_dtype, + num_q_heads=self.num_q_heads, + num_kv_heads=self.num_kv_heads, + ) self.msa_cutlass_plan_cache = MSACutlassDecodePlanCache() self.msa_cutlass_min_batch_size = _get_msa_cutlass_min_batch_size() + # Rubin only: Q8KV4 prefill split partials striped over the memory + # locality domains, reserved for the largest batch. + self.prefill_workspace: "PrefillWorkspace | None" = None # noqa: UP037 + if is_nvfp4_kv_cache( + self.kv_cache_dtype + ) and current_platform.is_device_capability(107): + from vllm.third_party.fmha_sm100.prefill_q8kv4 import PrefillWorkspace + + self.prefill_workspace = PrefillWorkspace( + device, block_scale_shift=NVFP4_BLOCK_SCALE_SHIFT + ) + self.prefill_workspace.split_buffers( + self.topk_blocks, + vllm_config.scheduler_config.max_num_batched_tokens, + self.num_q_heads, + ) def build( self, @@ -152,6 +210,12 @@ def build( common_attn_metadata, fast_build, ) + prefill = metadata.prefill + if prefill is not None and self.prefill_workspace is not None: + metadata.prefill = MiniMaxM3SparseMSAPrefillMetadata( + **{f.name: getattr(prefill, f.name) for f in fields(prefill)}, + workspace=self.prefill_workspace, + ) decode = metadata.decode if decode is None: return metadata @@ -179,6 +243,7 @@ def build( num_kv_heads=self.num_kv_heads, page_size=SPARSE_BLOCK_SIZE, topk_blocks=self.topk_blocks, + q8kv4=self.q8kv4_decode, plan_cache=self.msa_cutlass_plan_cache, ) metadata.decode = MiniMaxM3SparseMSADecodeMetadata( @@ -190,8 +255,58 @@ def build( return metadata -class MiniMaxM3SparseMSAImpl(MiniMaxM3SparseImpl): - """MSA block-sparse attention with guarded CUTLASS sparse decode.""" +class MiniMaxM3SparseMSABaseImpl(MiniMaxM3SparseImpl): + """What the MSA impls share: CUTLASS decode plans and the prefill CSR.""" + + use_cutlass_decode: bool + # The prefill kernels ``fmha_sm100.warmup`` prebuilds for this impl. + prefill_backend: str + + def should_use_msa_decode(self, layer_name: str) -> bool: + if not self.use_cutlass_decode: + return False + attn_metadata = get_forward_context().attn_metadata + if not isinstance(attn_metadata, dict): + return False + main_md = attn_metadata[layer_name] + if not isinstance(main_md, MiniMaxM3SparseMetadata): + return False + decode = main_md.decode + return ( + isinstance(decode, MiniMaxM3SparseMSADecodeMetadata) + and decode.msa_cutlass is not None + ) + + def _build_prefill_csr( + self, + topk: torch.Tensor, + nd: int, + num_tokens: int, + p: MiniMaxM3SparsePrefillMetadata, + ): + from vllm.third_party.fmha_sm100.sparse import build_k2q_csr + + # [H, prefill, MK] transposed view; build_k2q_csr consumes the strided + # view directly (topK stays innermost-contiguous). + return build_k2q_csr( + topk[nd:num_tokens].transpose(0, 1), + p.cu_seqlens_q, + p.cu_seqlens_k, + SPARSE_BLOCK_SIZE, + total_k=0, + max_seqlen_k=p.max_seq_len, + max_seqlen_q=p.max_query_len, + total_rows=p.total_kv_blocks, + qhead_per_kv=self.num_heads // self.num_kv_heads, + return_schedule=True, + ) + + +class MiniMaxM3SparseMSAImpl(MiniMaxM3SparseMSABaseImpl): + """MSA block-sparse attention over a BF16 or FP8 KV cache, with guarded + CUTLASS sparse decode.""" + + prefill_backend = "cute_dsl" def __init__( self, @@ -203,7 +318,7 @@ def __init__( *, topk_blocks: int, sparse_block_size: int, - msa_decode_backend: MiniMaxM3MSADecodeBackend = "triton", + msa_decode_backend: MiniMaxM3MSADecodeBackend = "cutlass", ) -> None: super().__init__( num_heads, @@ -214,7 +329,6 @@ def __init__( topk_blocks=topk_blocks, sparse_block_size=sparse_block_size, ) - self.use_nvfp4_kv = is_nvfp4_kv_cache(kv_cache_dtype) self.use_cutlass_decode = supports_cutlass_sparse_decode( decode_backend=msa_decode_backend, num_q_heads=self.num_heads, @@ -223,31 +337,18 @@ def __init__( page_size=self.block_size, topk_blocks=self.topk_blocks, ) - if self.use_nvfp4_kv and not self.use_cutlass_decode: - raise ValueError( - "MiniMax M3 NVFP4 KV cache requires CUTLASS MSA sparse decode " - f"(num_heads={self.num_heads}, num_kv_heads={self.num_kv_heads}, " - f"block_size={self.block_size}, topk_blocks={self.topk_blocks})" - ) logger.info_once( "MiniMax M3 MSA sparse decode selected %s", "CUTLASS" if self.use_cutlass_decode else "Triton", ) - def should_use_msa_decode(self, layer_name: str) -> bool: + def _bf16_query( + self, q: torch.Tensor, q_scale: float, dtype: torch.dtype + ) -> torch.Tensor: + # With CUTLASS decode the query is E4M3; the other kernels read BF16. if not self.use_cutlass_decode: - return False - attn_metadata = get_forward_context().attn_metadata - if not isinstance(attn_metadata, dict): - return False - main_md = attn_metadata[layer_name] - if not isinstance(main_md, MiniMaxM3SparseMetadata): - return False - decode = main_md.decode - return ( - isinstance(decode, MiniMaxM3SparseMSADecodeMetadata) - and decode.msa_cutlass is not None - ) + return q + return _dequantize_query(q, q_scale, dtype) def forward( self, @@ -255,8 +356,6 @@ def forward( query: torch.Tensor, kv_cache: torch.Tensor, output: torch.Tensor, - *, - query_fp8: torch.Tensor | None = None, ) -> torch.Tensor: attn_metadata = get_forward_context().attn_metadata if not isinstance(attn_metadata, dict): @@ -273,16 +372,8 @@ def forward( hd = self.head_size q = query[:num_tokens].view(-1, self.num_heads, hd) out = output[:num_tokens].view(-1, self.num_heads, hd) - # Given query_fp8, it is the only q the fused insert wrote: CUTLASS - # decode and prefill read it directly, and Triton decode reads it - # dequantized into ``query``. - q_fp8 = ( - None - if query_fp8 is None - else query_fp8[:num_tokens].view(-1, self.num_heads, hd) - ) q_scale_float = getattr(layer, "_q_scale_float", 1.0) - if self.use_fp8_kv and not self.use_nvfp4_kv: + if self.use_fp8_kv: kv_cache = kv_cache.view(self.kv_cache_fp8_dtype) k_scale = getattr(layer, "_k_scale", None) if self.use_fp8_kv else None v_scale = getattr(layer, "_v_scale", None) if self.use_fp8_kv else None @@ -290,16 +381,11 @@ def forward( # Decode [:nd]: CUTLASS for planned shapes, otherwise Triton. if main_md.num_decodes > 0: d = main_md.decode - assert d is not None - msa_metadata = ( - d.msa_cutlass - if isinstance(d, MiniMaxM3SparseMSADecodeMetadata) - else None - ) + assert isinstance(d, MiniMaxM3SparseMSADecodeMetadata) + msa_metadata = d.msa_cutlass if self.use_cutlass_decode and msa_metadata is not None: - assert q_fp8 is not None msa_cutlass_sparse_decode( - q_fp8[:nd], + q[:nd], kv_cache, topk[:nd], out[:nd], @@ -308,20 +394,10 @@ def forward( q_scale_float=q_scale_float, k_scale_float=getattr(layer, "_k_scale_float", 1.0), v_scale_float=getattr(layer, "_v_scale_float", 1.0), - k_scale=k_scale if self.use_nvfp4_kv else None, - v_scale=v_scale if self.use_nvfp4_kv else None, - ) - elif self.use_nvfp4_kv: - raise RuntimeError( - "MiniMax M3 NVFP4 KV cache has no Triton decode fallback; " - f"CUTLASS decode was not planned for {main_md.num_decodes} " - f"requests with query length {d.decode_query_len}" ) else: minimax_m3_sparse_attn_decode( - q[:nd] - if q_fp8 is None - else _dequantize_query(q_fp8[:nd], q_scale_float, q[:nd]), + self._bf16_query(q[:nd], q_scale_float, output.dtype), kv_cache, topk[:nd].transpose(0, 1), d.block_table, @@ -336,61 +412,18 @@ def forward( # Prefill [nd:]: MSA sparse FMHA over the selected blocks. if main_md.num_prefills > 0: - from vllm.third_party.fmha_sm100.sparse import ( - build_k2q_csr, - sparse_atten_func, - sparse_atten_nvfp4_kv_func, - ) + from vllm.third_party.fmha_sm100.sparse import sparse_atten_func p = main_md.prefill assert p is not None - # [H, prefill, MK] transposed view; build_k2q_csr consumes the - # strided view directly (topK stays innermost-contiguous). - prefill_topk = topk[nd:num_tokens].transpose(0, 1) + k2q_row_ptr, k2q_q_indices, schedule = self._build_prefill_csr( + topk, nd, num_tokens, p + ) # An E4M3 query attends as is, its scale folded into softmax_scale. - if q_fp8 is None: - qp, softmax_scale = q[nd:], self.scale - else: - qp, softmax_scale = q_fp8[nd:], self.scale * q_scale_float - k2q_row_ptr, k2q_q_indices, schedule = build_k2q_csr( - prefill_topk, - p.cu_seqlens_q, - p.cu_seqlens_k, - SPARSE_BLOCK_SIZE, - total_k=0, - max_seqlen_k=p.max_seq_len, - max_seqlen_q=p.max_query_len, - total_rows=p.total_kv_blocks, - qhead_per_kv=qp.shape[1] // self.num_kv_heads, - return_schedule=True, + qp = q[nd:] + softmax_scale = ( + self.scale * q_scale_float if self.use_cutlass_decode else self.scale ) - if self.use_nvfp4_kv: - k_data, k_sf, v_data, v_sf = nvfp4_kv_cache_views(kv_cache) - sparse_atten_nvfp4_kv_func( - qp, - k_data, - v_data, - k_sf, - v_sf, - k_scale, - v_scale, - k2q_row_ptr, - k2q_q_indices, - self.topk_blocks, - cu_seqlens_q=p.cu_seqlens_q, - cu_seqlens_k=p.cu_seqlens_k, - max_seqlen_q=p.max_query_len, - max_seqlen_k=p.max_seq_len, - blk_kv=SPARSE_BLOCK_SIZE, - causal=True, - softmax_scale=softmax_scale, - page_table=p.block_table, - seqused_k=p.seq_lens, - schedule=schedule, - out=out[nd:], - kv_layout="vllm", - ) - return output k_cache, v_cache = kv_cache.split(self.head_size, dim=-1) sparse_atten_func( qp, @@ -412,3 +445,158 @@ def forward( out=out[nd:], ) return output + + +class MiniMaxM3SparseMSANvfp4Impl(MiniMaxM3SparseMSABaseImpl): + """MSA block-sparse attention over an NVFP4 KV cache, SM100 family only. + + Decode and prefill run the CUTLASS Q8KV4 kernels, which read the E4M3 + query; there is no BF16-query kernel and no Triton fallback. + """ + + use_cutlass_decode = True + prefill_backend = "q8kv4" + + def __init__( + self, + num_heads: int, + head_size: int, + scale: float, + num_kv_heads: int | None = None, + kv_cache_dtype: str = "nvfp4", + *, + topk_blocks: int, + sparse_block_size: int, + msa_decode_backend: MiniMaxM3MSADecodeBackend = "cutlass", + ) -> None: + super().__init__( + num_heads, + head_size, + scale, + num_kv_heads, + kv_cache_dtype, + topk_blocks=topk_blocks, + sparse_block_size=sparse_block_size, + ) + if not ( + current_platform.is_cuda() + and current_platform.is_device_capability_family(100) + ): + raise ValueError("MiniMax M3 NVFP4 KV cache requires an SM100-family GPU") + # NVFP4 decodes only on CUTLASS, whatever msa_decode_backend says. + if not supports_cutlass_sparse_decode( + decode_backend="cutlass", + num_q_heads=self.num_heads, + num_kv_heads=self.num_kv_heads, + kv_cache_dtype=self.kv_cache_dtype, + page_size=self.block_size, + topk_blocks=self.topk_blocks, + ): + raise ValueError( + "MiniMax M3 NVFP4 KV cache requires CUTLASS MSA sparse decode " + f"(num_heads={self.num_heads}, num_kv_heads={self.num_kv_heads}, " + f"block_size={self.block_size}, topk_blocks={self.topk_blocks})" + ) + blocker = _q8kv4_prefill_blocker( + self.num_heads, self.num_kv_heads, self.block_size, self.topk_blocks + ) + if blocker is not None: + raise ValueError( + "MiniMax M3 NVFP4 KV cache requires the CUTLASS Q8KV4 prefill, " + f"which cannot serve this layout or device: {blocker}" + ) + logger.info_once("MiniMax M3 NVFP4 MSA: CUTLASS Q8KV4 decode and prefill") + # NVFP4_BLOCK_SCALE_SHIFT assumes unit global scales; checked on the + # first forward, once the checkpoint's KV scales are loaded. + self._check_global_scales = True + + def forward( + self, + layer: AttentionLayer, + query: torch.Tensor, + kv_cache: torch.Tensor, + output: torch.Tensor, + ) -> torch.Tensor: + assert query.dtype == torch.float8_e4m3fn + attn_metadata = get_forward_context().attn_metadata + if not isinstance(attn_metadata, dict): + return output # profiling run; caches unbound + main_md = attn_metadata[layer.layer_name] # type: ignore[attr-defined] + assert isinstance(main_md, MiniMaxM3SparseMetadata) + + nd = main_md.num_decode_tokens + num_tokens = main_md.num_actual_tokens + topk = layer.topk_indices_buffer # type: ignore[attr-defined] + assert topk is not None + hd = self.head_size + q_fp8 = query[:num_tokens].view(-1, self.num_heads, hd) + out = output[:num_tokens].view(-1, self.num_heads, hd) + q_scale_float = getattr(layer, "_q_scale_float", 1.0) + k_scale = getattr(layer, "_k_scale", None) + v_scale = getattr(layer, "_v_scale", None) + if self._check_global_scales: + k_global = getattr(layer, "_k_scale_float", 1.0) + v_global = getattr(layer, "_v_scale_float", 1.0) + if k_global != 1.0 or v_global != 1.0: + raise ValueError( + "MiniMax M3 reads its NVFP4 KV cache on the Q8KV4 kernels with " + f"block_scale_shift={NVFP4_BLOCK_SCALE_SHIFT}, which needs unit " + f"global scales; got k_scale={k_global}, v_scale={v_global}" + ) + self._check_global_scales = False + + if main_md.num_decodes > 0: + d = main_md.decode + assert isinstance(d, MiniMaxM3SparseMSADecodeMetadata) + msa_metadata = d.msa_cutlass + if msa_metadata is None: + raise RuntimeError( + "MiniMax M3 NVFP4 KV cache has no Triton decode fallback; " + f"CUTLASS decode was not planned for {main_md.num_decodes} " + f"requests with query length {d.decode_query_len}" + ) + msa_cutlass_sparse_decode( + q_fp8[:nd], + kv_cache, + topk[:nd], + out[:nd], + msa_metadata, + scale=self.scale, + q_scale_float=q_scale_float, + k_scale_float=getattr(layer, "_k_scale_float", 1.0), + v_scale_float=getattr(layer, "_v_scale_float", 1.0), + k_scale=k_scale, + v_scale=v_scale, + ) + + if main_md.num_prefills > 0: + from vllm.third_party.fmha_sm100.prefill_q8kv4 import run_prefill + + p = main_md.prefill + assert p is not None + k2q_row_ptr, _, schedule = self._build_prefill_csr(topk, nd, num_tokens, p) + k_data, k_sf, v_data, v_sf = nvfp4_kv_cache_views(kv_cache) + run_prefill( + q_fp8[nd:], + (k_data, v_data), + (k_sf, v_sf), + kv_indices=p.block_table, + kv_indptr=None, + cu_seqlens_q=p.cu_seqlens_q, + cu_seqlens_k=p.cu_seqlens_k, + k2q_row_ptr=k2q_row_ptr, + schedule=schedule, + sm_scale=self.scale * q_scale_float, + topk=self.topk_blocks, + seqused_k=p.seq_lens, + k_global_scale=k_scale, + v_global_scale=v_scale, + block_scale_shift=NVFP4_BLOCK_SCALE_SHIFT, + out=out[nd:], + workspace=( + p.workspace + if isinstance(p, MiniMaxM3SparseMSAPrefillMetadata) + else None + ), + ) + return output diff --git a/vllm/transformers_utils/processors/minimax_m3.py b/vllm/transformers_utils/processors/minimax_m3.py index 9d922f8e4c64..8d4212cee395 100644 --- a/vllm/transformers_utils/processors/minimax_m3.py +++ b/vllm/transformers_utils/processors/minimax_m3.py @@ -1,16 +1,17 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""MiniMax M3 VL HuggingFace-compatible Processor / ImageProcessor / +"""MiniMax M3.1 VL HuggingFace-compatible Processor / ImageProcessor / VideoProcessor, vendored into vLLM so the model loads without ``--trust-remote-code`` (the released checkpoint only ships these classes as remote code via ``auto_map``). -Adapted verbatim from the ``MiniMaxAI/Minimax-M3-preview`` repository files -``image_processor.py``, ``video_processor.py`` and ``processing_minimax.py`` -(revision ``db01c0fe``). Both image and video processors use Qwen-style -``smart_resize`` (bound by total pixels). The original async frame-sampling -helpers are intentionally omitted: vLLM performs its own frame loading and -feeds decoded frames to the processor. +Both image and video processors use the MiniMax M3.1 aligned-size resize +(``compute_aligned_size``): tiny inputs are upscaled to a minimum area / +short side, then both dims are ceil-aligned to the patch factor and capped +at a per-modality long side (selectable via the OpenAI-style ``detail`` +kwarg or an explicit ``max_long_side_pixel``). The original async +frame-sampling helpers are intentionally omitted: vLLM performs its own +frame loading and feeds decoded frames to the processor. """ import math @@ -35,125 +36,158 @@ from transformers.video_processing_utils import BaseVideoProcessor from transformers.video_utils import group_videos_by_shape, reorder_videos -# Maximum allowed aspect ratio before smart_resize rejects the input. +# Maximum allowed aspect ratio before compute_aligned_size rejects the input. MAX_RATIO = 200 -# Fixed (non-configurable) bounds for the long-side resize logic, per the -# MiniMax-M3 size spec. ``min_short_side_pixel`` is the floor the short edge is -# enlarged to; ``*_MAX_TOTAL_PIXELS`` is the hard area cap that, once exceeded, -# aborts processing instead of downscaling. -MIN_SHORT_SIDE_PIXEL = 112 -IMAGE_MAX_TOTAL_PIXELS = 12_845_056 # 3584 ** 2 (width * height) -VIDEO_MAX_TOTAL_PIXELS = 301_056_000 # width * height * frames +# Fixed (non-configurable) bounds of the aligned-size resize, per the +# MiniMax M3.1 size spec. ``MIN_SHORT_SIDE_PIXEL`` is the floor the short +# edge is enlarged to; ``VIDEO_MAX_TOTAL_PIXELS`` is the hard volumetric cap +# (width * height * frames) that, once exceeded, aborts video processing. +MIN_SHORT_SIDE_PIXEL = 168 +MIN_PIXELS = MIN_SHORT_SIDE_PIXEL**2 +VIDEO_MAX_TOTAL_PIXELS = 301_056_000 +# OpenAI-style ``detail`` -> long-side pixel cap, per modality. +IMAGE_DETAIL_MAX_LONG_SIDE_PIXEL = {"low": 672, "auto": 2016, "high": 3584} +VIDEO_DETAIL_MAX_LONG_SIDE_PIXEL = {"low": 504, "auto": 672, "high": 2188} -def round_by_factor(number: int | float, factor: int) -> int: - return round(number / factor) * factor - -def ceil_by_factor(number: int | float, factor: int) -> int: - return math.ceil(number / factor) * factor - - -def floor_by_factor(number: int | float, factor: int) -> int: - return math.floor(number / factor) * factor - - -def _smart_resize_by_long_side( +def compute_aligned_size( height: int, width: int, factor: int, + *, + min_pixels: int = MIN_PIXELS, max_long_side_pixel: int, - min_short_side_pixel: int, - max_total_pixels: int | None, + min_short_side: int = MIN_SHORT_SIDE_PIXEL, ) -> tuple[int, int]: - """Long-side based resize (MiniMax-M3 size spec). - - (a) if the long side exceeds ``max_long_side_pixel`` → shrink so the long - side equals ``max_long_side_pixel``; - (b) else if the short side is below ``min_short_side_pixel`` → enlarge so the - short side equals ``min_short_side_pixel``; - (c) if the resulting area still exceeds ``max_total_pixels`` → raise. - - (a) and (b) are mutually exclusive (they branch on the *original* long side). - Both sides are then rounded to a multiple of ``factor``. For videos the - ``max_total_pixels`` cap is volumetric (width * height * frames) and is - enforced by the caller, so pass ``max_total_pixels=None`` here. - """ - long_side = max(height, width) - short_side = min(height, width) - - scaled_height: float = height - scaled_width: float = width - if long_side > max_long_side_pixel: - beta = max_long_side_pixel / long_side - scaled_height = height * beta - scaled_width = width * beta - elif short_side < min_short_side_pixel: - beta = min_short_side_pixel / short_side - scaled_height = height * beta - scaled_width = width * beta - - h_bar = max(factor, round_by_factor(scaled_height, factor)) - w_bar = max(factor, round_by_factor(scaled_width, factor)) - - if max_total_pixels is not None and h_bar * w_bar > max_total_pixels: - raise ValueError( - f"image area {h_bar * w_bar} exceeds max_total_pixels " - f"{max_total_pixels} after resizing" - ) - return h_bar, w_bar + """Compute the resize target ``(resized_height, resized_width)``. + Three layers (mirrors sglang's M3.1 ``compute_aligned_size``): -def smart_resize( - height: int, - width: int, - factor: int = 28, - min_pixels: int = 4 * 28 * 28, - max_pixels: int = 451584, - max_long_side_pixel: int | None = None, - min_short_side_pixel: int = MIN_SHORT_SIDE_PIXEL, - max_total_pixels: int | None = None, -) -> tuple[int, int]: - """Rescale (height, width) so each side is a multiple of ``factor``. + 1. Aspect-ratio guard: reject inputs whose ratio exceeds ``MAX_RATIO``. + 2. Floor layers: upscale proportionally when the area is below + ``min_pixels``, or the short side is below ``min_short_side``. + 3. Alignment layer: ``_align_to_factor`` ceil-aligns both dims to + ``factor`` and caps them at ``max_long_side_pixel``. + + Args: + height: Original height in pixels, must be > 0. + width: Original width in pixels, must be > 0. + factor: Alignment factor, usually ``patch_size * merge_size``. + min_pixels: Area floor; smaller inputs are upscaled to at least + this area before alignment. + max_long_side_pixel: Per-dim cap applied by the alignment layer + (used for both dims). + min_short_side: Short-side pixel floor. + + Returns: + ``(resized_height, resized_width)``, both multiples of ``factor`` + and at most ``max_long_side_pixel``. + + Raises: + ValueError: If the aspect ratio exceeds ``MAX_RATIO``. - When ``max_long_side_pixel`` is set, use the MiniMax-M3 long-side resize - spec (see :func:`_smart_resize_by_long_side`). Otherwise fall back to the - Qwen-VL area bound, keeping the total area within ``[min_pixels, max_pixels]``. """ if max(height, width) / min(height, width) > MAX_RATIO: raise ValueError( f"absolute aspect ratio must be smaller than {MAX_RATIO}, " f"got {max(height, width) / min(height, width)}" ) - if max_long_side_pixel is not None: - return _smart_resize_by_long_side( - height, - width, - factor=factor, - max_long_side_pixel=max_long_side_pixel, - min_short_side_pixel=min_short_side_pixel, - max_total_pixels=max_total_pixels, - ) - h_bar = max(factor, round_by_factor(height, factor)) - w_bar = max(factor, round_by_factor(width, factor)) - if h_bar * w_bar > max_pixels: - beta = math.sqrt((height * width) / max_pixels) - h_bar = floor_by_factor(height / beta, factor) - w_bar = floor_by_factor(width / beta, factor) - elif h_bar * w_bar < min_pixels: + if height * width < min_pixels: beta = math.sqrt(min_pixels / (height * width)) - h_bar = ceil_by_factor(height * beta, factor) - w_bar = ceil_by_factor(width * beta, factor) - return h_bar, w_bar + height = math.ceil(height * beta) + width = math.ceil(width * beta) + if min(height, width) < min_short_side: + beta = min_short_side / min(height, width) + height = math.ceil(height * beta) + width = math.ceil(width * beta) + return _align_to_factor( + height, width, factor, (max_long_side_pixel, max_long_side_pixel) + ) + + +def _align_to_factor( + height: int, + width: int, + factor: int, + max_size: tuple[int, int], +) -> tuple[int, int]: + """Ceil-align both dims to ``factor``, then cap at per-dim ``max_size``. + + When either aligned dim exceeds its cap, scale both dims back down + proportionally (integer arithmetic, preserving the aspect ratio) and + ceil-align again. + + Returns: + ``(height, width)`` with both dims multiples of ``factor`` and at + most the corresponding ``max_size`` dim. + + """ + max_w, max_h = max_size + # Round the caps down to factor multiples so alignment never exceeds them. + max_w = max_w - (max_w % factor) + max_h = max_h - (max_h % factor) + new_w = width if width % factor == 0 else width + (factor - width % factor) + new_h = height if height % factor == 0 else height + (factor - height % factor) + if new_w > max_w or new_h > max_h: + new_w_ = min((new_w * max_w) // new_w, (new_w * max_h) // new_h) + new_h_ = min((new_h * max_w) // new_w, (new_h * max_h) // new_h) + new_w = new_w_ + new_h = new_h_ + new_w = new_w if new_w % factor == 0 else new_w + (factor - new_w % factor) + new_h = new_h if new_h % factor == 0 else new_h + (factor - new_h % factor) + assert new_w <= max_w and new_h <= max_h, ( + f"_align_to_factor: result (h={new_h}, w={new_w}) exceeds max_size " + f"{max_size}; input (h={height}, w={width}, factor={factor})" + ) + return new_h, new_w + + +def resolve_max_long_side_pixel( + detail: "str | None", + max_long_side_pixel: "int | None", + *, + modality: str, +) -> int: + """Resolve the long-side pixel cap from ``detail`` / explicit override. + + ``detail`` (default ``"auto"``) maps to a per-modality cap. An explicit + ``max_long_side_pixel`` takes priority over a non-auto ``detail``; the + ``"auto"`` tier value itself is treated as "unset" so the processor class + defaults (2016 for images, 672 for videos) do not shadow ``detail``. + + Raises: + ValueError: If ``detail`` or ``modality`` is not a known value. + + """ + if modality == "image": + detail_map = IMAGE_DETAIL_MAX_LONG_SIDE_PIXEL + elif modality == "video": + detail_map = VIDEO_DETAIL_MAX_LONG_SIDE_PIXEL + else: + raise ValueError(f"unknown modality {modality!r}") + detail = detail or "auto" + if detail not in detail_map: + raise ValueError( + f"invalid detail {detail!r} for {modality}; " + f"expected one of {sorted(detail_map)}" + ) + if max_long_side_pixel is not None and max_long_side_pixel != detail_map["auto"]: + return max_long_side_pixel + return detail_map[detail] class MiniMaxM3VLImageProcessorKwargs(ImagesKwargs, total=False): # type: ignore[call-arg] patch_size: int temporal_patch_size: int merge_size: int + detail: "str | None" + max_long_side_pixel: "int | None" + # Legacy keys from released preprocessor_config.json files; accepted for + # backward compatibility but ignored by the aligned-size resize. + min_pixels: int max_pixels: int - max_long_side_pixel: int class MiniMaxM3VLImageProcessor(TorchvisionBackend): @@ -171,12 +205,11 @@ class MiniMaxM3VLImageProcessor(TorchvisionBackend): patch_size = 14 temporal_patch_size = 2 merge_size = 2 - max_pixels = 451584 # 672 * 672 - # Long-side resize spec (opt-in via ``max_long_side_pixel``). The latter two - # are fixed per the spec and are not exposed as configurable kwargs. - max_long_side_pixel = None + # Aligned-size resize bounds (M3.1). ``detail`` selects the long-side cap + # ("low"/"auto"/"high"); an explicit ``max_long_side_pixel`` wins. + detail = "auto" + max_long_side_pixel = 2016 min_short_side_pixel = MIN_SHORT_SIDE_PIXEL - max_total_pixels = IMAGE_MAX_TOTAL_PIXELS valid_kwargs = MiniMaxM3VLImageProcessorKwargs model_input_names = ["pixel_values", "image_grid_thw"] @@ -202,7 +235,7 @@ def _preprocess( patch_size: int, temporal_patch_size: int, merge_size: int, - max_pixels: int, + detail: str, max_long_side_pixel: "int | None", disable_grouping: "bool | None", return_tensors: "str | TensorType | None", @@ -213,17 +246,18 @@ def _preprocess( ) resized_images_grouped = {} factor = patch_size * merge_size + max_long_side = resolve_max_long_side_pixel( + detail, max_long_side_pixel, modality="image" + ) for shape, stacked_images in grouped_images.items(): height, width = stacked_images.shape[-2:] if do_resize: - resized_height, resized_width = smart_resize( + resized_height, resized_width = compute_aligned_size( height, width, factor=factor, - max_pixels=max_pixels, - max_long_side_pixel=max_long_side_pixel, - min_short_side_pixel=self.min_short_side_pixel, - max_total_pixels=self.max_total_pixels, + max_long_side_pixel=max_long_side, + min_short_side=self.min_short_side_pixel, ) stacked_images = self.resize( stacked_images, @@ -308,19 +342,19 @@ def get_number_of_image_patches(self, height: int, width: int, images_kwargs=Non images_kwargs = images_kwargs or {} patch_size = images_kwargs.get("patch_size", self.patch_size) merge_size = images_kwargs.get("merge_size", self.merge_size) - max_pixels = images_kwargs.get("max_pixels", self.max_pixels) + detail = images_kwargs.get("detail", self.detail) max_long_side_pixel = images_kwargs.get( "max_long_side_pixel", self.max_long_side_pixel ) - - resized_height, resized_width = smart_resize( + max_long_side = resolve_max_long_side_pixel( + detail, max_long_side_pixel, modality="image" + ) + resized_height, resized_width = compute_aligned_size( height, width, factor=patch_size * merge_size, - max_pixels=max_pixels, - max_long_side_pixel=max_long_side_pixel, - min_short_side_pixel=self.min_short_side_pixel, - max_total_pixels=self.max_total_pixels, + max_long_side_pixel=max_long_side, + min_short_side=self.min_short_side_pixel, ) grid_h, grid_w = resized_height // patch_size, resized_width // patch_size return grid_h * grid_w @@ -330,13 +364,16 @@ class MiniMaxM3VLVideoProcessorKwargs(VideosKwargs, total=False): # type: ignor patch_size: int temporal_patch_size: int merge_size: int - min_pixels: int - max_pixels: int - max_long_side_pixel: int - total_pixels: int + detail: "str | None" + max_long_side_pixel: "int | None" min_frames: int max_frames: int fps: "float | int" + # Legacy keys from released preprocessor_config.json files; accepted for + # backward compatibility but ignored by the aligned-size resize. + min_pixels: int + max_pixels: int + total_pixels: int class MiniMaxM3VLVideoProcessor(BaseVideoProcessor): @@ -354,13 +391,12 @@ class MiniMaxM3VLVideoProcessor(BaseVideoProcessor): patch_size = 14 temporal_patch_size = 2 merge_size = 2 - min_pixels = 4 * 28 * 28 - max_pixels = 768 * 28 * 28 # 602,112 - total_pixels = int(64000 * 28 * 28 * 0.9) # ~45M, ~64k tokens budget - # Long-side resize spec (opt-in via ``max_long_side_pixel``). The video + # Aligned-size resize bounds (M3.1). ``detail`` selects the long-side cap + # ("low"/"auto"/"high"); an explicit ``max_long_side_pixel`` wins. The # ``max_total_pixels`` cap is volumetric (width * height * frames) and is # enforced in ``_preprocess`` once the frame count is known. - max_long_side_pixel = None + detail = "auto" + max_long_side_pixel = 672 min_short_side_pixel = MIN_SHORT_SIDE_PIXEL max_total_pixels = VIDEO_MAX_TOTAL_PIXELS fps = 1.0 @@ -386,8 +422,7 @@ def _preprocess( patch_size: int, temporal_patch_size: int, merge_size: int, - min_pixels: int, - max_pixels: int, + detail: str = "auto", max_long_side_pixel: "int | None" = None, return_tensors: "str | TensorType | None" = None, **kwargs, @@ -395,27 +430,21 @@ def _preprocess( grouped_videos, grouped_videos_index = group_videos_by_shape(videos) resized_videos_grouped = {} factor = patch_size * merge_size + max_long_side = resolve_max_long_side_pixel( + detail, max_long_side_pixel, modality="video" + ) for shape, stacked_videos in grouped_videos.items(): batch_size, num_frames, channels, height, width = stacked_videos.shape resized_height, resized_width = height, width if do_resize: - resized_height, resized_width = smart_resize( + resized_height, resized_width = compute_aligned_size( height, width, factor=factor, - min_pixels=min_pixels, - max_pixels=max_pixels, - max_long_side_pixel=max_long_side_pixel, - min_short_side_pixel=self.min_short_side_pixel, - # Per-frame raise disabled; the video cap is volumetric and - # is enforced below once num_frames is known. - max_total_pixels=None, + max_long_side_pixel=max_long_side, + min_short_side=self.min_short_side_pixel, ) - if ( - max_long_side_pixel is not None - and resized_height * resized_width * num_frames - > self.max_total_pixels - ): + if resized_height * resized_width * num_frames > self.max_total_pixels: raise ValueError( f"video area {resized_height * resized_width * num_frames} " f"(width * height * frames) exceeds max_total_pixels " @@ -424,8 +453,10 @@ def _preprocess( stacked_videos = stacked_videos.view( batch_size * num_frames, channels, height, width ) + # Resize in float32, matching the training/SFT pipeline (and + # sglang): uint8 resize rounds intermediates and shifts pixels. stacked_videos = self.resize( - stacked_videos, + stacked_videos.float(), size=SizeDict(height=resized_height, width=resized_width), resample=resample, ) diff --git a/vllm/transformers_utils/repo_utils.py b/vllm/transformers_utils/repo_utils.py index 43ef07676e3a..8f4573780395 100644 --- a/vllm/transformers_utils/repo_utils.py +++ b/vllm/transformers_utils/repo_utils.py @@ -304,6 +304,30 @@ def get_model_path(model: str | Path, revision: str | None = None): ) +def get_subfolder_path( + model: str, + subfolder: str, + revision: str | None = None, + cache_dir: str | None = None, +) -> str: + """Return the local path of `subfolder` in a local or Hub checkpoint, + downloading only that subfolder from the Hub.""" + if os.path.isdir(model): + return os.path.join(model, subfolder) + # Avoid circular import + from vllm.model_executor.model_loader.weight_utils import get_lock + + with get_lock(model, cache_dir): + snapshot = hf_api().snapshot_download( + repo_id=model, + revision=revision, + cache_dir=cache_dir, + allow_patterns=f"{subfolder}/*", + local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE, + ) + return os.path.join(snapshot, subfolder) + + _WEIGHT_FILE_PATTERNS = [ "*.safetensors", "*.bin", diff --git a/vllm/utils/flashinfer.py b/vllm/utils/flashinfer.py index 725e2f8039a6..88f7e99891b7 100644 --- a/vllm/utils/flashinfer.py +++ b/vllm/utils/flashinfer.py @@ -29,6 +29,13 @@ logger = init_logger(__name__) +def is_flashinfer_autotuning() -> bool: + """Whether a FlashInfer autotune(True) context is active.""" + from flashinfer.autotuner import AutoTuner + + return AutoTuner.get().is_tuning_mode + + def flashinfer_bf16_mm( a: torch.Tensor, b: torch.Tensor, @@ -1310,6 +1317,7 @@ def is_flashinfer_cudnn_fp8_prefill_attn_supported() -> bool: __all__ = [ "has_flashinfer", "flashinfer_bf16_mm", + "is_flashinfer_autotuning", "has_flashinfer_bf16_gemm", "has_flashinfer_concat_mla_kv_quant_fp8", "is_flashinfer_bf16_gemm_supported", diff --git a/vllm/v1/attention/backends/flash_attn.py b/vllm/v1/attention/backends/flash_attn.py index c33def11a8ea..88fe210b9390 100755 --- a/vllm/v1/attention/backends/flash_attn.py +++ b/vllm/v1/attention/backends/flash_attn.py @@ -1179,6 +1179,25 @@ def __init__( vllm_config.scheduler_config.max_num_batched_tokens ) + def _descale( + self, scale: torch.Tensor, scale_float: float, shape: tuple[int, int] + ) -> torch.Tensor | None: + # FA4 reads a missing descale as 1.0, and it copies every expanded view + # into a contiguous tensor: three copy kernels per layer and step. The + # scales are fixed once weights are loaded, so a per-tensor scale of 1.0 + # (FP8 KV cache without calibrated scales) needs none. Per-head scales + # keep their tensor: their float mirror holds only the maximum. + if ( + self.vllm_flash_attn_version == 4 + and scale.numel() == 1 + and scale_float == 1.0 + ): + return None + # A (1, 1) expanded view (one sequence, one KV head per rank) counts + # as contiguous, so FA4 skips its copy and its CuTe layout check then + # rejects the zero stride. + return canonicalize_singleton_dim_strides(scale.expand(shape)) + def forward( self, layer: torch.nn.Module, @@ -1286,14 +1305,13 @@ def forward( scheduler_metadata = attn_metadata.scheduler_metadata descale_shape = (cu_seqlens_q.shape[0] - 1, self.num_kv_heads) - q_descale = ( - layer._q_scale.expand(descale_shape) + self._descale(layer._q_scale, layer._q_scale_float, descale_shape) if self.supports_quant_query_input else None ) - k_descale = layer._k_scale.expand(descale_shape) - v_descale = layer._v_scale.expand(descale_shape) + k_descale = self._descale(layer._k_scale, layer._k_scale_float, descale_shape) + v_descale = self._descale(layer._v_scale, layer._v_scale_float, descale_shape) if self.dcp_world_size > 1: self._forward_with_dcp( diff --git a/vllm/v1/attention/backends/flashinfer_ts.py b/vllm/v1/attention/backends/flashinfer_ts.py new file mode 100644 index 000000000000..248eb7f65013 --- /dev/null +++ b/vllm/v1/attention/backends/flashinfer_ts.py @@ -0,0 +1,512 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""FlashInfer task-scheduled (``prims_ts``) paged decode. + +Wraps ``flashinfer.attention.prims_ts.BatchDecodePagedTSWrapper`` for uniform +query-block decode: every request contributes exactly ``max_query_len`` query +tokens over a paged KV cache. That is the DFlash/DSpark drafter shape, and the +reason this backend exists is that ``mask_type="dense"`` expresses a +*non-causal* draft block directly -- the trtllm-gen paged decode kernel is +bottom-right causal and silently ignores a supplied mask. + +Layout. No KV cache change: K and V are the two halves of vLLM's ordinary +``[pages, Hkv, page_size, 2 * D]`` page, so their token stride is ``2 * D``. +The kernel builds its TMA descriptors from the tensors' own strides +(``_validate_native_hnd_tma_strides``), so the only requirement is a +contiguous head_dim. Verified numerically equal to the same data repacked +into compact planes. + +Sliding window. ``prims_ts`` rejects ``window_left >= 0`` unless the mask is +causal, so a non-causal windowed layer cannot be expressed directly. The query +block always sits at the end of the sequence, so the symmetric window reduces +to a suffix, and we hand the kernel a block table restricted to the window's +pages (see :func:`_restrict_to_window`). Because the restriction is page +aligned, each query token sees up to ``page_size - 1`` extra tokens at the old +edge, and all query tokens share one window start rather than each having its +own (``max_query_len - 1`` tokens of drift). +""" + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, ClassVar + +import torch + +from vllm.config import VllmConfig +from vllm.logger import init_logger +from vllm.platforms import current_platform +from vllm.utils.math_utils import cdiv +from vllm.v1.attention.backend import ( + AttentionBackend, + AttentionCGSupport, + AttentionImpl, + AttentionLayer, + AttentionMetadata, + AttentionMetadataBuilder, + AttentionType, + CommonAttentionMetadata, + MultipleOf, + max_decode_query_len, +) +from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheSpec + +if TYPE_CHECKING: + from vllm.config.cache import CacheDType + from vllm.platforms.interface import DeviceCapability + +logger = init_logger(__name__) + +# flashinfer/attention/prims_ts/decode.py: _SUPPORTED_PAGE_SIZES, +# _SUPPORTED_HEAD_DIMS, _SUPPORTED_COMPUTE_CAPABILITIES. (10, 7) is SM107a / +# Rubin, which the kernel additionally gates on a CuTe DSL that can emit for +# the sm_100f family (>= 4.8, else CUTE_DSL_ARCH=sm_100f in the environment). +_TS_PAGE_SIZES = (16, 32, 64, 128) +_TS_HEAD_DIMS = (64, 128, 256) +_TS_CAPABILITIES = ((10, 0), (10, 3), (10, 7)) +_TS_MAX_HEAD_RATIO = 128 + + +def _require_prims_ts(): + """Import the prims_ts wrapper, or explain which flashinfer is needed. + + 0.7.0.post1 ships prims_ts but calls ``Task._run_task_body_impl`` with a + ``context`` kwarg that cutlass-dsl 4.8.0 removed, so it raises TypeError + deep inside kernel codegen. + """ + try: + from flashinfer.attention.prims_ts import BatchDecodePagedTSWrapper + except ImportError as exc: + raise RuntimeError( + "FLASHINFER_TS needs flashinfer-python>=0.7.1 " + "(flashinfer.attention.prims_ts is missing)." + ) from exc + import flashinfer + + if tuple(int(p) for p in flashinfer.__version__.split(".")[:3]) < (0, 7, 1): + raise RuntimeError( + f"FLASHINFER_TS needs flashinfer-python>=0.7.1, found " + f"{flashinfer.__version__}: earlier builds of prims_ts are " + "incompatible with cutlass-dsl>=4.8." + ) + return BatchDecodePagedTSWrapper + + +def _ts_output_dtype(q_dtype: torch.dtype, model_dtype: torch.dtype) -> torch.dtype: + """The output dtype the kernel can write for this query dtype. + + An FP8 query only yields FP16 or FP8 out, so a bf16 model stages through + FP16 and converts; every other combination writes the model dtype directly. + """ + if q_dtype is torch.float8_e4m3fn and model_dtype is not torch.float16: + return torch.float16 + return model_dtype + + +def _kv_kernel_dtype(spec: AttentionSpec) -> torch.dtype: + """An FP8 cache is stored as uint8 and viewed as e4m3 at use.""" + if spec.dtype is torch.uint8: + return current_platform.fp8_dtype() + return spec.dtype + + +@dataclass +class FlashInferTSMetadata(AttentionMetadata): + # Per-request K/V lengths the kernel reads, already restricted to the + # window when one applies. + seq_lens: torch.Tensor + # [B, C] int32 page ids, likewise restricted. + block_table: torch.Tensor + num_reqs: int + num_actual_tokens: int + query_len: int + # Plan bound at build time; the same object must be replayed by a captured + # graph, which is why plans are keyed only on (batch size, query length). + wrapper: Any + + +class FlashInferTSMetadataBuilder(AttentionMetadataBuilder[FlashInferTSMetadata]): + _cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH + + def __init__( + self, + kv_cache_spec: KVCacheSpec, + layer_names: list[str], + vllm_config: VllmConfig, + device: torch.device, + ): + super().__init__(kv_cache_spec, layer_names, vllm_config, device) + assert isinstance(kv_cache_spec, AttentionSpec) + self.page_size = kv_cache_spec.block_size + self.num_kv_heads = kv_cache_spec.num_kv_heads + self.head_size = kv_cache_spec.head_size + # Q and K/V dtypes are kept matched: FP8 query against the FP8 cache, + # or model-dtype against an unquantized one. The FP8 query is produced + # upstream (MiniMax-M3's fused QK-norm/RoPE kernel writes it through + # q_fp8_out), so the attention layer does not quantize it again. + self.kv_dtype = _kv_kernel_dtype(kv_cache_spec) + self.q_dtype = self.kv_dtype + self.out_dtype = vllm_config.model_config.dtype + self.num_qo_heads = vllm_config.model_config.get_num_attention_heads( + vllm_config.parallel_config + ) + # FullAttentionSpec records the window when the hybrid KV cache manager + # is disabled; SlidingWindowSpec carries it directly. + self.sliding_window: int | None = getattr(kv_cache_spec, "sliding_window", None) + self.query_len = max_decode_query_len(vllm_config) + self._plans: dict[tuple[int, int, bool], Any] = {} + self._init_reorder_batch_threshold(1, supports_spec_as_decode=True) + + # CUDA-graph-safe metadata. This builder advertises UNIFORM_BATCH, so + # the drafter's attention is captured and replayed; the kernel records + # the ADDRESS of seq_lens and the page table at capture time. Building + # fresh tensors per step would leave a replayed graph reading freed + # memory, so every build writes into these buffers in place. + max_reqs = max( + vllm_config.scheduler_config.max_num_seqs, + vllm_config.scheduler_config.max_num_batched_tokens + // max(self.query_len, 1), + ) + self._buf_seq_lens = torch.zeros(max_reqs, dtype=torch.int32, device=device) + self._buf_block_table = torch.zeros( + (max_reqs, self._window_pages(self.query_len)), + dtype=torch.int32, + device=device, + ) + + def _window_pages(self, query_len: int) -> int: + """Page-table width a restricted (windowed) batch needs.""" + if self.sliding_window is None: + return cdiv(self.vllm_config.model_config.max_model_len, self.page_size) + return cdiv(self.sliding_window + query_len - 1, self.page_size) + 1 + + def _max_kv_len(self) -> int: + """Constant K/V capacity every plan compiles for. + + Keeping it constant is what makes one plan per (batch size, query + length) safe to replay from a CUDA graph: ``build()`` can never pick a + differently-compiled plan for a batch the graph already captured. + """ + if self.sliding_window is not None: + # _restrict_to_window leaves at most one partial page in front of + # the window plus the query block itself. + return self.sliding_window + self.query_len + self.page_size + return self.vllm_config.model_config.max_model_len + + def _get_plan(self, num_reqs: int, query_len: int, causal: bool) -> Any: + key = (num_reqs, query_len, causal) + plan = self._plans.get(key) + if plan is not None: + return plan + + BatchDecodePagedTSWrapper = _require_prims_ts() + + window = self.sliding_window + wrapper = BatchDecodePagedTSWrapper(kv_layout="HND") + wrapper.plan( + device=self.device, + batch_size=num_reqs, + num_qo_heads=self.num_qo_heads, + num_kv_heads=self.num_kv_heads, + head_dim=self.head_size, + page_size=self.page_size, + max_kv_len=self._max_kv_len(), + max_seq_len_q=query_len, + packed_query=False, + q_data_type=self.q_dtype, + kv_data_type=self.kv_dtype, + o_data_type=_ts_output_dtype(self.q_dtype, self.out_dtype), + # A dense plan is what makes a non-causal draft block expressible; + # it cannot carry a window, which _restrict_to_window applies to + # the page table instead. + mask_type="causal" if causal else "dense", + window_left=window - 1 if (causal and window is not None) else -1, + ) + self._plans[key] = wrapper + return wrapper + + def _restrict_to_window( + self, seq_lens: torch.Tensor, block_table: torch.Tensor, query_len: int + ) -> tuple[torch.Tensor, torch.Tensor]: + """Cut the page table down to the pages the window can reach. + + The query block ends the sequence, so a symmetric window around it is + the suffix ``[L - w - query_len + 1, L)``. Round that start down to a + page so the slice is expressible as a page table, then renumber the + lengths relative to the new first page. + """ + assert self.sliding_window is not None + span = self.sliding_window + query_len - 1 + num_pages = self._buf_block_table.shape[1] + num_reqs = seq_lens.shape[0] + + start_page = torch.clamp_min( + (seq_lens - span).div(self.page_size, rounding_mode="floor"), 0 + ) + cols = torch.arange(num_pages, device=block_table.device, dtype=torch.int32) + idx = start_page.unsqueeze(1).to(torch.int64) + cols.unsqueeze(0) + idx = idx.clamp_max(block_table.shape[1] - 1) + + assert num_reqs <= self._buf_seq_lens.shape[0], ( + f"FLASHINFER_TS metadata buffer holds {self._buf_seq_lens.shape[0]} " + f"requests, got {num_reqs}" + ) + out_lens = self._buf_seq_lens[:num_reqs] + out_table = self._buf_block_table[:num_reqs] + out_lens.copy_(seq_lens - start_page.to(seq_lens.dtype) * self.page_size) + out_table.copy_(block_table.gather(1, idx)) + return out_lens, out_table + + def build( + self, + common_prefix_len: int, + common_attn_metadata: CommonAttentionMetadata, + fast_build: bool = False, + ) -> FlashInferTSMetadata: + num_reqs = common_attn_metadata.num_reqs + num_tokens = common_attn_metadata.num_actual_tokens + causal = common_attn_metadata.causal + if isinstance(causal, torch.Tensor): + raise NotImplementedError( + "FLASHINFER_TS has no per-sequence causality; it plans one " + "mask for the whole batch." + ) + # The drafter contributes the same number of query tokens per request, + # so the block length is the quotient; max_query_len is only an upper + # bound. Startup profiling also builds ragged batches that no real + # draft step produces (e.g. 5 tokens over 2 requests). Rounding down + # covers a whole number of blocks and leaves the remainder untouched, + # which keeps those builds in bounds instead of failing the engine. + query_len = num_tokens // num_reqs if num_reqs else 0 + num_tokens = num_reqs * query_len + # The model runner builds metadata for every KV cache group on every + # batch, so this is also called with the target's prefill shapes for + # the drafter's own group -- metadata the speculator never uses, since + # it builds its own. A drafter block is never longer than + # max_decode_query_len, so anything wider is not a batch this backend + # runs; planning it would compile a prefill-shaped plan and fail + # validation (seq_len_q > max_kv_len). + if query_len > self.query_len: + query_len = 0 + + seq_lens = common_attn_metadata.seq_lens[:num_reqs] + block_table = common_attn_metadata.block_table_tensor[:num_reqs] + if self.sliding_window is not None and not causal: + seq_lens, block_table = self._restrict_to_window( + seq_lens, block_table, query_len + ) + else: + num_pages = min(block_table.shape[1], self._buf_block_table.shape[1]) + out_lens = self._buf_seq_lens[:num_reqs] + out_table = self._buf_block_table[:num_reqs, :num_pages] + out_lens.copy_(seq_lens) + out_table.copy_(block_table[:, :num_pages]) + seq_lens, block_table = out_lens, out_table + + if query_len == 0: + return FlashInferTSMetadata( + seq_lens=common_attn_metadata.seq_lens[:num_reqs], + block_table=common_attn_metadata.block_table_tensor[:num_reqs], + num_reqs=num_reqs, + num_actual_tokens=0, + query_len=0, + wrapper=None, + ) + + return FlashInferTSMetadata( + seq_lens=seq_lens, + block_table=block_table, + num_reqs=num_reqs, + num_actual_tokens=num_tokens, + query_len=query_len, + wrapper=self._get_plan(num_reqs, query_len, causal), + ) + + +class FlashInferTSImpl(AttentionImpl[FlashInferTSMetadata]): + forward_includes_kv_cache_update: bool = False + + def __init__( + self, + num_heads: int, + head_size: int, + scale: float, + num_kv_heads: int | None = None, + alibi_slopes: list[float] | None = None, + sliding_window: int | None = None, + kv_cache_dtype: str = "auto", + logits_soft_cap: float | None = None, + attn_type: str = AttentionType.DECODER, + kv_sharing_target_layer_name: str | None = None, + sinks: torch.Tensor | None = None, + ) -> None: + if sinks is not None: + raise NotImplementedError("FLASHINFER_TS does not support attention sinks.") + if alibi_slopes is not None: + raise NotImplementedError("FLASHINFER_TS does not support alibi.") + if logits_soft_cap: + raise NotImplementedError("FLASHINFER_TS does not support softcap.") + if kv_sharing_target_layer_name is not None: + raise NotImplementedError("FLASHINFER_TS does not support KV sharing.") + if attn_type != AttentionType.DECODER: + raise NotImplementedError( + f"FLASHINFER_TS does not support attention type {attn_type}." + ) + self.num_heads = num_heads + self.head_size = head_size + self.scale = float(scale) + self.num_kv_heads = num_kv_heads or num_heads + self.sliding_window = sliding_window + self.kv_cache_dtype = kv_cache_dtype + # The kernel wants the query in the cache's dtype. For FP8 the caller + # supplies it already quantized (query_pre_quantized on the layer), so + # advertise support rather than making the layer quantize a second time. + self.supports_quant_query_input = kv_cache_dtype.startswith("fp8") + + def _kv_views(self, kv_cache: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """HND K/V views of vLLM's ``[pages, Hkv, page, 2 * D]`` page. + + Their token stride is ``2 * D`` rather than ``D``; the kernel builds its + TMA descriptors from the tensor's own strides, so no repacking and no + layout change are needed. + """ + if self.kv_cache_dtype.startswith("fp8"): + kv_cache = kv_cache.view(current_platform.fp8_dtype()) + return kv_cache[..., : self.head_size], kv_cache[..., self.head_size :] + + def do_kv_cache_update( + self, + layer: AttentionLayer, + key: torch.Tensor, + value: torch.Tensor, + kv_cache: torch.Tensor, + slot_mapping: torch.Tensor, + ) -> None: + from vllm._custom_ops import reshape_and_cache_flash + + key_cache, value_cache = kv_cache.transpose(1, 2).split(self.head_size, dim=-1) + reshape_and_cache_flash( + key, + value, + key_cache, + value_cache, + slot_mapping, + self.kv_cache_dtype, + layer._k_scale, + layer._v_scale, + ) + + def forward( + self, + layer: AttentionLayer, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + kv_cache: torch.Tensor, + attn_metadata: FlashInferTSMetadata, + output: torch.Tensor, + output_scale: torch.Tensor | None = None, + output_block_scale: torch.Tensor | None = None, + ) -> torch.Tensor: + if attn_metadata is None: + # Profiling run: the KV cache is not bound yet. + return output + if output_scale is not None or output_block_scale is not None: + raise NotImplementedError( + "FLASHINFER_TS does not support fused output quantization." + ) + + n = attn_metadata.num_actual_tokens + if n == 0: + return output + b, sq = attn_metadata.num_reqs, attn_metadata.query_len + k_cache, v_cache = self._kv_views(kv_cache) + q = query[:n].view(b, sq, self.num_heads, self.head_size) + + out = output[:n].view(b, sq, self.num_heads, self.head_size) + kernel_dtype = _ts_output_dtype(q.dtype, out.dtype) + needs_cast = kernel_dtype is not out.dtype + kernel_out = torch.empty_like(out, dtype=kernel_dtype) if needs_cast else out + + attn_metadata.wrapper.run( + q=q, + paged_kv_cache=(k_cache, v_cache), + seq_lens=attn_metadata.seq_lens, + block_tables=attn_metadata.block_table, + bmm1_scale=self.scale * layer._q_scale_float * layer._k_scale_float, + bmm2_scale=layer._v_scale_float, + out=kernel_out, + validate=False, + ) + if needs_cast: + out.copy_(kernel_out) + return output + + +class FlashInferTSBackend(AttentionBackend): + supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16] + supported_kv_cache_dtypes: ClassVar[list["CacheDType"]] = [ + "auto", + "float16", + "bfloat16", + "fp8", + "fp8_e4m3", + ] + forward_includes_kv_cache_update: bool = False + + @staticmethod + def get_name() -> str: + return "FLASHINFER_TS" + + @staticmethod + def get_impl_cls() -> type[FlashInferTSImpl]: + return FlashInferTSImpl + + @staticmethod + def get_builder_cls() -> type[FlashInferTSMetadataBuilder]: + return FlashInferTSMetadataBuilder + + @classmethod + def get_supported_head_sizes(cls) -> list[int]: + return list(_TS_HEAD_DIMS) + + @staticmethod + def get_supported_kernel_block_sizes( + kv_cache_spec=None, + ) -> list[int | MultipleOf]: + return list(_TS_PAGE_SIZES) + + @classmethod + def supports_sliding_window(cls) -> bool: + # Causal layers use the kernel's own window_left; non-causal ones get a + # page-restricted block table (see the module docstring). + return True + + @classmethod + def supports_non_causal(cls) -> bool: + return True + + @classmethod + def supports_attn_type(cls, attn_type: str) -> bool: + return attn_type == AttentionType.DECODER + + @classmethod + def supports_compute_capability(cls, capability: "DeviceCapability") -> bool: + return (capability.major, capability.minor) in _TS_CAPABILITIES + + @classmethod + def supports_combination( + cls, + head_size: int, + dtype: torch.dtype, + kv_cache_dtype: "CacheDType | None", + block_size: int | None, + use_mla: bool, + has_sink: bool, + use_sparse: bool, + use_mm_prefix: bool, + device_capability: "DeviceCapability", + ) -> str | None: + if use_mla or use_sparse or use_mm_prefix: + return "FLASHINFER_TS supports dense non-MLA attention only" + if has_sink: + return "FLASHINFER_TS does not support attention sinks" + return None diff --git a/vllm/v1/attention/backends/registry.py b/vllm/v1/attention/backends/registry.py index 1e40298c7d69..eca068d40b34 100644 --- a/vllm/v1/attention/backends/registry.py +++ b/vllm/v1/attention/backends/registry.py @@ -69,6 +69,7 @@ class AttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta): XPU_MLA_SPARSE = "vllm.v1.attention.backends.mla.xpu_mla_sparse.XPUMLASparseBackend" TORCH_SDPA = "" # this tag is only used for ViT FLASHINFER = "vllm.v1.attention.backends.flashinfer.FlashInferBackend" + FLASHINFER_TS = "vllm.v1.attention.backends.flashinfer_ts.FlashInferTSBackend" TRITON_FLASHINFER = ( "vllm.v1.attention.backends.triton_flashinfer.TritonFlashInferBackend" ) diff --git a/vllm/v1/core/kv_cache_utils.py b/vllm/v1/core/kv_cache_utils.py index d24674e48318..58c709bc333b 100644 --- a/vllm/v1/core/kv_cache_utils.py +++ b/vllm/v1/core/kv_cache_utils.py @@ -1107,6 +1107,9 @@ def generate_scheduler_kv_cache_config( # All workers have the same kv_cache_config except layer names, so use # an arbitrary one to initialize the scheduler. cfg = copy.deepcopy(kv_cache_configs[0]) + # Resolve before reducing the groups below: one layer spec per group would + # hide mixed precision, and with it KV cache zeroing, from the scheduler. + cfg.mixed_precision_kv_cache = cfg.has_mixed_precision_kv_cache for group in cfg.kv_cache_groups: if isinstance(group.kv_cache_spec, UniformTypeKVCacheSpecs): # All layers in the UniformTypeKVCacheSpecs have the same type, diff --git a/vllm/v1/core/sched/scheduler.py b/vllm/v1/core/sched/scheduler.py index 7bc557d97330..07e19e3ca14b 100644 --- a/vllm/v1/core/sched/scheduler.py +++ b/vllm/v1/core/sched/scheduler.py @@ -289,6 +289,22 @@ def __init__( self.use_eagle_block_drop = False self.num_spec_tokens = vllm_config.num_speculative_tokens self.num_lookahead_tokens = vllm_config.num_lookahead_tokens + self.draft_slots = ( + speculative_config.max_num_new_slots_for_drafting + if speculative_config is not None + else 0 + ) + # Model Runner V2's DFlash/DSpark query pass has its own + # max_num_batched_tokens-row buffers: no charge once every request's + # 1 + num_spec_tokens queries fit them. + if ( + speculative_config is not None + and speculative_config.method in ("dflash", "dspark") + and vllm_config.use_v2_model_runner + and self.scheduler_config.max_num_seqs * (1 + self.num_spec_tokens) + <= self.scheduler_config.max_num_batched_tokens + ): + self.draft_slots = 0 # DSV41 SWA bounded replay: groups that declare a replay window are rebuilt # after a prefix hit by recomputing its trailing tokens. One window # for all such groups, so the rewind matches every group's allocation. @@ -706,8 +722,7 @@ def schedule(self, throttle_prefills: bool = False) -> SchedulerOutput: req_to_new_blocks: dict[str, KVCacheBlocks] = {} num_scheduled_tokens: dict[str, int] = {} token_budget = self.max_num_scheduled_tokens - spec = self.vllm_config.speculative_config - draft_slots = spec.max_num_new_slots_for_drafting if spec is not None else 0 + draft_slots = self.draft_slots input_budget = self.scheduler_config.max_num_batched_tokens if self._pause_state == PauseState.PAUSED_ALL: # Do not schedule any requests when paused. diff --git a/vllm/v1/kv_cache_interface.py b/vllm/v1/kv_cache_interface.py index 7a6650ce5025..a943594addc2 100644 --- a/vllm/v1/kv_cache_interface.py +++ b/vllm/v1/kv_cache_interface.py @@ -566,6 +566,10 @@ class AttentionSpec(KVCacheSpec): """ state_content_bytes: int | None = None """C in bytes when packed; None means dense K/V content.""" + kv_head_major_slots: bool = False + """Whether ``num_head_slots`` slots are grouped by KV head (``H2ND``: head + ``h``'s K and V slots are adjacent), so every KV head is one contiguous run + of the page and the page re-shards across TP by byte offset.""" tokens_per_state: int | Fraction = 1 """Tokens covered by one stored state. Ints > 1 compress multiple tokens into one state (DSv4 sparse MLA); fractions < 1 store multiple states per @@ -692,6 +696,7 @@ def merge(cls, specs: list[Self]) -> Self: page_size_padded=specs[0].page_size_padded, num_head_slots=specs[0].num_head_slots, state_content_bytes=specs[0].state_content_bytes, + kv_head_major_slots=specs[0].kv_head_major_slots, tokens_per_state=specs[0].tokens_per_state, sliding_window=cls.merge_window_sizes(sliding_window), attention_chunk_size=cls.merge_window_sizes(attention_chunk_size), @@ -783,6 +788,7 @@ def merge(cls, specs: list[Self]) -> Self: page_size_padded=specs[0].page_size_padded, num_head_slots=specs[0].num_head_slots, state_content_bytes=specs[0].state_content_bytes, + kv_head_major_slots=specs[0].kv_head_major_slots, cache_dtype_str=cache_dtype_str_set.pop(), topk_buffer_width=topk_buffer_width_set.pop(), tokens_per_state=tokens_per_state_set.pop(), @@ -849,6 +855,7 @@ def merge(cls, specs: list[RSWASpec]) -> RSWASpec: page_size_padded=base.page_size_padded, num_head_slots=base.num_head_slots, state_content_bytes=base.state_content_bytes, + kv_head_major_slots=base.kv_head_major_slots, tokens_per_state=base.tokens_per_state, sliding_window=base.sliding_window, attention_chunk_size=base.attention_chunk_size, @@ -1071,6 +1078,7 @@ def merge(cls, specs: list[Self]) -> Self: page_size_padded=specs[0].page_size_padded, num_head_slots=specs[0].num_head_slots, state_content_bytes=specs[0].state_content_bytes, + kv_head_major_slots=specs[0].kv_head_major_slots, sliding_window=sliding_window_set.pop(), extra_retained_tokens=extra_retained_set.pop(), cache_dtype_str=cache_dtype_str_set.pop(), @@ -1266,6 +1274,7 @@ def merge(cls, specs: list[Self]) -> Self: page_size_padded=specs[0].page_size_padded, num_head_slots=specs[0].num_head_slots, state_content_bytes=specs[0].state_content_bytes, + kv_head_major_slots=specs[0].kv_head_major_slots, sliding_window=cls.merge_window_sizes(sliding_window), attention_chunk_size=cls.merge_window_sizes(attention_chunk_size), non_causal=any(spec.non_causal for spec in specs), @@ -1558,6 +1567,10 @@ class KVCacheConfig: kv_tp_replicas: int = 1 """Consecutive TP ranks holding identical KV for every layer (1: none).""" + mixed_precision_kv_cache: bool | None = field(default=None, compare=False) + """Precomputed `has_mixed_precision_kv_cache`, set on the scheduler config + before its UniformTypeKVCacheSpecs groups are reduced to one layer spec.""" + @cached_property def transfer_group_ids(self) -> tuple[int, ...]: """IDs of cache groups that participate in external KV transfer.""" @@ -1637,6 +1650,8 @@ def has_mamba_layers(self) -> bool: @property def has_mixed_precision_kv_cache(self) -> bool: """Whether device attention caches use more than one precision.""" + if self.mixed_precision_kv_cache is not None: + return self.mixed_precision_kv_cache kv_cache_precisions: set[tuple[torch.dtype, KVQuantMode]] = set() for group in self.kv_cache_groups: if group.host_resident: diff --git a/vllm/v1/sample/ops/topk_topp_sampler.py b/vllm/v1/sample/ops/topk_topp_sampler.py index 14ee9b7064f4..e9157dcd82d9 100644 --- a/vllm/v1/sample/ops/topk_topp_sampler.py +++ b/vllm/v1/sample/ops/topk_topp_sampler.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from subprocess import CalledProcessError +from typing import Any import torch import torch.nn as nn @@ -26,14 +27,14 @@ logger = init_logger(__name__) -def register_top_k_top_p_warmups() -> None: +def register_top_k_top_p_warmups(**warmup_kwargs: Any) -> None: """Register every native accelerator sampling kernel used at runtime.""" if HAS_TRITON and not current_platform.is_cpu(): - _topk_topp.register_warmup() + _topk_topp.register_warmup(**warmup_kwargs) if current_platform.is_cuda_alike(): - _topp_split_stats.register_warmup() - _topp_split_step.register_warmup() - _topp_split_mask.register_warmup() + _topp_split_stats.register_warmup(**warmup_kwargs) + _topp_split_step.register_warmup(**warmup_kwargs) + _topp_split_mask.register_warmup(**warmup_kwargs) def _aiter_temp_gumbel_sample( diff --git a/vllm/v1/sample/ops/topk_topp_triton.py b/vllm/v1/sample/ops/topk_topp_triton.py index 870aba02bf3e..db6a23857eee 100755 --- a/vllm/v1/sample/ops/topk_topp_triton.py +++ b/vllm/v1/sample/ops/topk_topp_triton.py @@ -855,6 +855,21 @@ def _topk_topp_kernel( if not (final_pivot < max_logit): final_pivot = -float("inf") elif final_pivot != -float("inf"): + # A top-p below the fp32 resolution of the kept mass (e.g. 1e-9) can + # drop every duplicate; if nothing else survives, keep the max token(s). + if num_keep == 0 and num_duplicate_logit > 0: + num_survivors = tl.zeros((), dtype=tl.uint32) + for i in range(0, NUM_TILES): + offs_s = i * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + mask_s = offs_s < VOCAB_SIZE + logits_s = tl.load( + LOGITS_ROW + offs_s, mask=mask_s, other=-float("inf") + ) + survive = (logits_s > final_pivot) & mask_s + survive = survive & (tl.abs(logits_s - duplicate_logit) >= 1e-9) + num_survivors += tl.sum(survive) + if num_survivors == 0: + num_keep = num_duplicate_logit for i in range(0, NUM_TILES): offs_n = i * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) mask_n = offs_n < VOCAB_SIZE @@ -884,11 +899,13 @@ def _max_sampler_batch_size(vllm_config: Any) -> int: ) -def _topk_topp_warmup_inputs(vllm_config: Any) -> dict[str, Any]: +def _topk_topp_warmup_inputs( + vllm_config: Any, logits_strides: tuple[int, ...] = (16, 2) +) -> dict[str, Any]: vocab_size = vllm_config.model_config.get_vocab_size() split_enabled = current_platform.is_cuda_alike() mode: Any = WarmupChoices((True, False), (True, True), (False, True)) - logits_stride: Any = WarmupChoices(16, 2) + logits_stride: Any = WarmupChoices(*logits_strides) batch_size: Any = WarmupIntRange(1, _max_sampler_batch_size(vllm_config) + 1) topk_enabled = mode[0] topp_enabled = mode[1] @@ -1051,10 +1068,12 @@ def _topp_sb_stats_kernel( tl.store(STATS + base + 3, cnt) -def _topp_split_stats_warmup_inputs(vllm_config: Any) -> dict[str, Any]: +def _topp_split_stats_warmup_inputs( + vllm_config: Any, logits_strides: tuple[int, ...] = (16, 2) +) -> dict[str, Any]: vocab_size = vllm_config.model_config.get_vocab_size() num_sm = num_compute_units() - logits_stride: Any = WarmupChoices(16, 2) + logits_stride: Any = WarmupChoices(*logits_strides) batch_size: Any = WarmupIntRange( 1, min(_max_sampler_batch_size(vllm_config), _SPLIT_MAX_BATCH) + 1 ) @@ -1340,10 +1359,12 @@ def _topp_sb_step_kernel( tl.store(pbase + fidx * 3 + 2, nmin) -def _topp_split_step_warmup_inputs(vllm_config: Any) -> dict[str, Any]: +def _topp_split_step_warmup_inputs( + vllm_config: Any, logits_strides: tuple[int, ...] = (16, 2) +) -> dict[str, Any]: vocab_size = vllm_config.model_config.get_vocab_size() num_sm = num_compute_units() - logits_stride: Any = WarmupChoices(16, 2) + logits_stride: Any = WarmupChoices(*logits_strides) batch_size: Any = WarmupIntRange( 1, min(_max_sampler_batch_size(vllm_config), _SPLIT_MAX_BATCH) + 1 ) @@ -1518,10 +1539,12 @@ def _topp_sb_mask_kernel( tl.store(ROW + i + offs, tl.where(keep, x, MASK_VALUE), mask=mask_n) -def _topp_split_mask_warmup_inputs(vllm_config: Any) -> dict[str, Any]: +def _topp_split_mask_warmup_inputs( + vllm_config: Any, logits_strides: tuple[int, ...] = (16, 2) +) -> dict[str, Any]: vocab_size = vllm_config.model_config.get_vocab_size() num_sm = num_compute_units() - logits_stride: Any = WarmupChoices(16, 2) + logits_stride: Any = WarmupChoices(*logits_strides) batch_size: Any = WarmupIntRange( 1, min(_max_sampler_batch_size(vllm_config), _SPLIT_MAX_BATCH) + 1 ) diff --git a/vllm/v1/simple_kv_offload/cuda_mem_ops.py b/vllm/v1/simple_kv_offload/cuda_mem_ops.py index 1f3044155eaa..af9c48418ef4 100644 --- a/vllm/v1/simple_kv_offload/cuda_mem_ops.py +++ b/vllm/v1/simple_kv_offload/cuda_mem_ops.py @@ -62,6 +62,13 @@ class _CUmemcpyAttributes(ctypes.Structure): # Resolved lazily on first use: (entry point, numAttrs to pass). _batch_memcpy: tuple[Any, int] | None = None +# hipMemcpyAttributes.flags for the batch copies, resolved with _batch_memcpy. +_batch_copy_flags = 0 + +# hipMemcpyFlagExtPreferCE: run host <-> device batches on the SDMA engines +# rather than as a blit kernel on the CUs (HIP 7.16+). +_HIP_MEMCPY_FLAG_EXT_PREFER_CE = 0x100 + # Max copy descriptors per batch call, resolved lazily on first use. _max_batch_descriptors: int | None = None @@ -118,7 +125,10 @@ def _resolve_batch_memcpy() -> tuple[Any, int]: ctypes.c_void_p, # failIdx ctypes.c_void_p, # stream ] - return fn, _rocm_num_attrs(lib) + global _batch_copy_flags + version = _hip_runtime_version(lib) + _batch_copy_flags = _copy_flags_for_hip_version(version) + return fn, _num_attrs_for_hip_version(version) from cuda.bindings import driver as drv @@ -146,15 +156,26 @@ def _load_hip_runtime() -> ctypes.CDLL: raise OSError("could not load the HIP runtime: " + "; ".join(errors)) -def _rocm_num_attrs(lib: ctypes.CDLL) -> int: - """``numAttrs`` for ``hipMemcpyBatchAsync`` on the running HIP runtime.""" +def _hip_runtime_version(lib: ctypes.CDLL) -> int: + """``hipRuntimeGetVersion`` of the running HIP runtime, 0 if unknown.""" ver = ctypes.c_int(0) try: if lib.hipRuntimeGetVersion(ctypes.byref(ver)) != 0: ver.value = 0 except (OSError, AttributeError): ver.value = 0 - return _num_attrs_for_hip_version(ver.value) + return ver.value + + +def _copy_flags_for_hip_version(version: int) -> int: + """``hipMemcpyAttributes.flags`` for the batch copies on HIP ``version``. + + Without ``hipMemcpyFlagExtPreferCE``, HIP 7.16 runs the batch as a blit + kernel (``__amd_rocclr_copyBufferBatch``) that slows concurrent decode like + the Triton copier; with it the copies stay on SDMA at the same bandwidth. + """ + major, minor = version // 10_000_000, (version // 100_000) % 100 + return _HIP_MEMCPY_FLAG_EXT_PREFER_CE if (major, minor) >= (7, 16) else 0 def _num_attrs_for_hip_version(version: int) -> int: @@ -209,7 +230,9 @@ def build_params( dst_bases.append(d.data_ptr()) bpb.append(s_bpb) - attrs = _CUmemcpyAttributes(srcAccessOrder=src_access_order) + attrs = _CUmemcpyAttributes( + srcAccessOrder=src_access_order, flags=_batch_copy_flags + ) return BatchMemcpyParams( src_bases=np.array(src_bases, dtype=np.uint64), diff --git a/vllm/v1/simple_kv_offload/host_buffer.py b/vllm/v1/simple_kv_offload/host_buffer.py new file mode 100644 index 000000000000..c3098aaedd38 --- /dev/null +++ b/vllm/v1/simple_kv_offload/host_buffer.py @@ -0,0 +1,109 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""One host mapping backing all of a rank's CPU KV caches. + +Ordinary pages by default, or explicit 2 MiB / 1 GiB HugeTLB pages, which +never fall back to ordinary memory: a short pool or hugetlb cgroup limit +fails at startup. +""" + +import ctypes +import mmap +import os +import platform + +import torch + +from vllm.logger import init_logger + +logger = init_logger(__name__) + +HUGEPAGE_SIZES = {"2MB": 2 << 20, "1GB": 1 << 30} + +_MAP_HUGETLB = 0x40000 +_MAP_HUGE_SHIFT = 26 +_MADV_DONTFORK = getattr(mmap, "MADV_DONTFORK", 10) +_MADV_POPULATE_WRITE = getattr(mmap, "MADV_POPULATE_WRITE", 23) +_MPOL_PREFERRED = 1 +_SYS_MBIND = {"x86_64": 237, "aarch64": 235} # glibc does not export mbind + + +def parse_hugepage_size(value: object) -> int | None: + """Parse ``cpu_hugepage_block_size``; ``None``/``""``/``"none"`` disable it.""" + key = str(value or "none").strip().upper().replace("IB", "B") + key = {"2M": "2MB", "1G": "1GB"}.get(key, key) + if key == "NONE": + return None + if key not in HUGEPAGE_SIZES: + raise ValueError( + f"Unsupported cpu_hugepage_block_size {value!r}; " + f"expected one of {sorted(HUGEPAGE_SIZES)} or none" + ) + return HUGEPAGE_SIZES[key] + + +class HostBuffer: + """One anonymous mapping, viewed as an int8 CPU tensor. + + Keep this object alive as long as any tensor views the mapping. + """ + + def __init__( + self, + nbytes: int, + hugepage_size: int | None = None, + numa_node: int | None = None, + ): + self.page_size = hugepage_size or mmap.PAGESIZE + self.nbytes = max(1, -(-nbytes // self.page_size)) * self.page_size + kind = f"{self.page_size >> 20} MiB HugeTLB" if hugepage_size else "ordinary" + flags = mmap.MAP_PRIVATE | mmap.MAP_ANONYMOUS + if hugepage_size: + flags |= _MAP_HUGETLB | (hugepage_size.bit_length() - 1) << _MAP_HUGE_SHIFT + try: + # HugeTLB reserves every page from the host pool here. + self._mmap = mmap.mmap(-1, self.nbytes, flags=flags) + except OSError as e: + raise RuntimeError( + f"Cannot map {self.nbytes / 2**30:.2f} GiB of {kind} pages: {e}. " + "Reserve the pages on the host and request them for the container." + ) from e + # Children never need the buffer, so fork() neither copies nor + # copy-on-write shares the pinned pages. + self._mmap.madvise(_MADV_DONTFORK) + self.tensor = torch.frombuffer(memoryview(self._mmap), dtype=torch.int8) + if numa_node is not None: + self._prefer_node(numa_node) + try: + # Fault every page now: a cgroup or pool shortfall becomes an + # error here instead of SIGBUS or an OOM kill while serving. + self._mmap.madvise(_MADV_POPULATE_WRITE) + except OSError as e: + if e.errno == 22 and not hugepage_size: # kernel < 5.14 + self.tensor[:: self.page_size].zero_() + return + raise RuntimeError( + f"Cannot populate {self.nbytes / 2**30:.2f} GiB of {kind} pages: " + f"{e}. The container's memory or hugetlb limit is too small." + ) from e + + def _prefer_node(self, node: int) -> None: + nr = _SYS_MBIND.get(platform.machine()) + if nr is None: + return + mask = (ctypes.c_ulong * (node // 64 + 1))() + mask[node // 64] = 1 << (node % 64) + libc = ctypes.CDLL(None, use_errno=True) + libc.syscall.restype = ctypes.c_long + ret = libc.syscall( + ctypes.c_long(nr), + ctypes.c_void_p(self.tensor.data_ptr()), + ctypes.c_ulong(self.nbytes), + ctypes.c_int(_MPOL_PREFERRED), + mask, + ctypes.c_ulong(len(mask) * 64 + 1), + ctypes.c_uint(0), + ) + if ret != 0: + err = ctypes.get_errno() + logger.warning("mbind to NUMA node %d failed: %s", node, os.strerror(err)) diff --git a/vllm/v1/simple_kv_offload/worker.py b/vllm/v1/simple_kv_offload/worker.py index 6a43c67ed133..10455791613c 100644 --- a/vllm/v1/simple_kv_offload/worker.py +++ b/vllm/v1/simple_kv_offload/worker.py @@ -2,16 +2,19 @@ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Worker-side handler for SimpleCPUOffloadConnector.""" +import time from typing import TYPE_CHECKING import torch from vllm.config import VllmConfig from vllm.logger import init_logger +from vllm.platforms import current_platform from vllm.utils.torch_utils import PIN_MEMORY from vllm.v1.simple_kv_offload.copy_backend import DmaCopyBackend from vllm.v1.simple_kv_offload.cuda_mem_ops import pin_tensor from vllm.v1.simple_kv_offload.disk_backend import DiskBackend +from vllm.v1.simple_kv_offload.host_buffer import HostBuffer from vllm.v1.simple_kv_offload.metadata import ( SimpleCPUOffloadMetadata, SimpleCPUOffloadWorkerMetadata, @@ -38,6 +41,7 @@ def __init__( disk_buffer_slots: int = 2, use_page_cache: bool = False, num_cpu_blocks: int | None = None, + cpu_hugepage_size: int | None = None, ): self.vllm_config = vllm_config self.kv_cache_config = kv_cache_config @@ -48,6 +52,8 @@ def __init__( self.disk_buffer_slots = disk_buffer_slots self.use_page_cache = use_page_cache self.disk_mode = kv_offload_backend == "disk" + self.cpu_hugepage_size = cpu_hugepage_size + self._host_buffer: HostBuffer | None = None self.gpu_kv_caches: dict[str, torch.Tensor] | None = None self.cpu_kv_caches: dict[str, torch.Tensor] | None = None @@ -238,16 +244,9 @@ def _init_cpu_mode( "Pinned memory not available. CPU offload performance may be degraded." ) - self.cpu_kv_caches = {} - for name, gpu_tensor in unique_gpu_caches.items(): - cpu_shape = (self.num_cpu_blocks,) + gpu_tensor.shape[1:] - # Allocate non-pinned first, then pin via cudaHostRegister to - # bypass PyTorch's CUDACachingHostAllocator which rounds up to - # the next power of 2 (e.g. 100 GB -> 128 GB). - tensor = torch.zeros(cpu_shape, dtype=gpu_tensor.dtype, device="cpu") - if pin_memory: - pin_tensor(tensor) - self.cpu_kv_caches[name] = tensor + self.cpu_kv_caches = self._alloc_cpu_caches( + unique_gpu_caches, device, pin_memory + ) self._backend = DmaCopyBackend() self._backend.init( @@ -258,6 +257,59 @@ def _init_cpu_mode( self.store_stream, ) + def _alloc_cpu_caches( + self, + unique_gpu_caches: dict[str, torch.Tensor], + device: torch.device, + pin_memory: bool, + ) -> dict[str, torch.Tensor]: + """Carve every per-layer CPU cache out of one host mapping, pinned once. + + The mapping is sized from the user's per-rank capacity, so a rank uses + ceil(capacity / page size) pages. On CUDA a single registration of + >= 512 GiB fails (vllm-project/vllm#51081). + """ + layer_bytes = [ + self.num_cpu_blocks * t[0].nbytes for t in unique_gpu_caches.values() + ] + + numa_node = None + get_numa_nodes = getattr(current_platform, "get_all_device_numa_nodes", None) + numa_nodes = get_numa_nodes() if get_numa_nodes is not None else None + if numa_nodes is not None and device.index is not None: + numa_node = numa_nodes[device.index] + + start = time.perf_counter() + buf = HostBuffer( + max(self.cpu_capacity_bytes, sum(layer_bytes)), + self.cpu_hugepage_size, + numa_node, + ) + populated = time.perf_counter() + self._host_buffer = buf + + cpu_kv_caches = {} + offset = 0 + for size, (name, gpu_tensor) in zip(layer_bytes, unique_gpu_caches.items()): + cpu_shape = (self.num_cpu_blocks,) + gpu_tensor.shape[1:] + view = buf.tensor[offset : offset + size].view(gpu_tensor.dtype) + cpu_kv_caches[name] = view.view(cpu_shape) + offset += size + if pin_memory: + pin_tensor(buf.tensor) + pinned = time.perf_counter() + logger.info( + "SimpleCPUOffloadWorker [CPU]: %.2f GiB on %d KiB pages for %s, " + "NUMA node %s; populate %.2fs, pin %.2fs", + buf.nbytes / (1024**3), + buf.page_size >> 10, + device, + numa_node, + populated - start, + pinned - populated, + ) + return cpu_kv_caches + def bind_connector_metadata(self, metadata: SimpleCPUOffloadMetadata) -> None: self._connector_metadata = metadata if metadata.load_event >= 0: diff --git a/vllm/v1/worker/gpu/dp_utils.py b/vllm/v1/worker/gpu/dp_utils.py index fb9f4c02d3e4..7ffd9db5c5e8 100644 --- a/vllm/v1/worker/gpu/dp_utils.py +++ b/vllm/v1/worker/gpu/dp_utils.py @@ -290,6 +290,23 @@ def dispatch_cg_and_sync_dp( ) if dp_size == 1: + # One DP rank: the split is a local decision; a split step runs eager. + if ( + allow_ubatching + and dp_sync_state is None + and parallel_config is not None + and num_tokens >= get_num_ubatches(parallel_config) + and check_ubatch_thresholds( + parallel_config, num_tokens, uniform_decode=uniform_decode + ) + ): + batch_desc = BatchExecutionDescriptor( + cg_mode=CUDAGraphMode.NONE, + num_tokens=num_tokens, + num_reqs=num_reqs, + num_active_loras=num_active_loras, + num_ubatches=get_num_ubatches(parallel_config), + ) return batch_desc, None if dp_sync_state is not None: diff --git a/vllm/v1/worker/gpu/input_batch.py b/vllm/v1/worker/gpu/input_batch.py index 6d9732b67ab1..aa12203558f2 100644 --- a/vllm/v1/worker/gpu/input_batch.py +++ b/vllm/v1/worker/gpu/input_batch.py @@ -360,8 +360,12 @@ def _prepare_pos_seq_lens_kernel( idx_mapping_ptr, query_start_loc_ptr, num_computed_tokens_ptr, + is_padding_ptr, + num_tokens_padded, + pad_start, max_num_reqs, BLOCK_SIZE: tl.constexpr, + WRITE_IS_PADDING: tl.constexpr, ): req_id = tl.program_id(0) num_reqs = tl.num_programs(0) - 1 @@ -371,6 +375,25 @@ def _prepare_pos_seq_lens_kernel( block = i + tl.arange(0, BLOCK_SIZE) mask = block < max_num_reqs tl.store(seq_lens_ptr + block, 0, mask=mask) + if WRITE_IS_PADDING: + # Compaction can leave real scheduler rows outside the query ranges. + num_tokens = tl.load(query_start_loc_ptr + num_reqs) + for i in tl.range(num_tokens, pad_start, BLOCK_SIZE): + block = i + tl.arange(0, BLOCK_SIZE) + mask = block < pad_start + tl.store( + is_padding_ptr + block, + tl.zeros([BLOCK_SIZE], tl.int1), + mask=mask, + ) + for i in tl.range(pad_start, num_tokens_padded, BLOCK_SIZE): + block = i + tl.arange(0, BLOCK_SIZE) + mask = block < num_tokens_padded + tl.store( + is_padding_ptr + block, + tl.full([BLOCK_SIZE], 1, tl.int1), + mask=mask, + ) return req_state_idx = tl.load(idx_mapping_ptr + req_id) @@ -388,6 +411,12 @@ def _prepare_pos_seq_lens_kernel( mask = block < query_len pos = num_computed_tokens + block tl.store(pos_ptr + start + block, pos, mask=mask) + if WRITE_IS_PADDING: + tl.store( + is_padding_ptr + start + block, + tl.zeros([BLOCK_SIZE], tl.int1), + mask=mask, + ) def prepare_pos_seq_lens( @@ -396,6 +425,9 @@ def prepare_pos_seq_lens( num_computed_tokens: torch.Tensor, pos: torch.Tensor, seq_lens: torch.Tensor, + is_padding: torch.Tensor | None = None, + num_tokens_padded: int = 0, + pad_start: int = 0, ) -> None: num_reqs = idx_mapping.shape[0] # NOTE(woosuk): We do +1 because the last thread block is used @@ -406,8 +438,12 @@ def prepare_pos_seq_lens( idx_mapping, query_start_loc, num_computed_tokens, + pos if is_padding is None else is_padding, + num_tokens_padded, + pad_start, seq_lens.shape[0], BLOCK_SIZE=1024, + WRITE_IS_PADDING=is_padding is not None, ) diff --git a/vllm/v1/worker/gpu/model_runner.py b/vllm/v1/worker/gpu/model_runner.py index c1622ba8cda2..319baac914f1 100644 --- a/vllm/v1/worker/gpu/model_runner.py +++ b/vllm/v1/worker/gpu/model_runner.py @@ -458,6 +458,8 @@ def load_model( ), ) logger.info("Batch-sharded sampling enabled.") + if isinstance(self.speculator, DraftModelSpeculator): + self.speculator.enable_batch_sharded_sampling() else: logger.warning_once( "Disabling batch-sharded sampling: %s does not implement " @@ -481,7 +483,14 @@ def load_model( ) with self.jit_warmup_registry.activate(): - register_top_k_top_p_warmups() + if current_platform.is_cuda(): + # V2's native logits processors use contiguous FP32 rows. + register_top_k_top_p_warmups( + vllm_config=self.vllm_config, + logits_strides=(self.vocab_size,), + ) + else: + register_top_k_top_p_warmups() sampler_kwargs: dict[str, Any] = { "vllm_config": self.vllm_config, @@ -1415,9 +1424,6 @@ def prepare_inputs( num_tokens_after_padding = max(num_tokens, batch_desc.num_tokens) assert num_tokens > 0 is_padding = self.input_buffers.is_padding[:num_tokens_after_padding] - if envs.VLLM_MOE_SKIP_PADDING: - is_padding[:num_tokens].fill_(False) - is_padding[num_tokens:].fill_(True) req_ids = batch_req_state.req_ids num_scheduled_tokens_np = batch_req_state.num_scheduled_tokens @@ -1521,6 +1527,9 @@ def prepare_inputs( self.req_states.num_computed_tokens.gpu, self.input_buffers.positions, self.input_buffers.seq_lens, + is_padding=(is_padding if envs.VLLM_MOE_SKIP_PADDING else None), + num_tokens_padded=num_tokens_after_padding, + pad_start=num_tokens, # Scheduler total before adaptive compaction. ) seq_lens = self.input_buffers.seq_lens[:num_reqs_padded] diff --git a/vllm/v1/worker/gpu/sample/batch_shard.py b/vllm/v1/worker/gpu/sample/batch_shard.py index daaf8806ff89..4a9c16778fc4 100644 --- a/vllm/v1/worker/gpu/sample/batch_shard.py +++ b/vllm/v1/worker/gpu/sample/batch_shard.py @@ -346,22 +346,196 @@ def all_to_all_logits( logits_shard: torch.Tensor, metadata: BatchShardMetadata, ) -> torch.Tensor: - recv = logits_shard.new_empty( - metadata.tp_size * metadata.num_local_logits, logits_shard.shape[-1] + return all_to_all_rows( + logits_shard, metadata.num_logits_per_rank, metadata.num_local_logits ) + + +def all_to_all_rows( + rows_shard: torch.Tensor, + num_rows_per_rank: list[int], + num_local_rows: int, +) -> torch.Tensor: + """Send owner-sorted vocab-shard rows to their owners; return this rank's + rows with the full vocab, shards in rank order (the all-gather layout).""" + tp_size = len(num_rows_per_rank) + recv = rows_shard.new_empty(tp_size * num_local_rows, rows_shard.shape[-1]) torch.distributed.all_to_all_single( recv, - logits_shard.contiguous(), - output_split_sizes=[metadata.num_local_logits] * metadata.tp_size, - input_split_sizes=metadata.num_logits_per_rank, + rows_shard.contiguous(), + output_split_sizes=[num_local_rows] * tp_size, + input_split_sizes=num_rows_per_rank, group=get_tp_group().device_group, ) shard_width = recv.shape[-1] return ( - recv.view(metadata.tp_size, metadata.num_local_logits, shard_width) + recv.view(tp_size, num_local_rows, shard_width) .permute(1, 0, 2) - .reshape(metadata.num_local_logits, metadata.tp_size * shard_width) + .reshape(num_local_rows, tp_size * shard_width) + ) + + +@triton.jit(do_not_specialize=["num_reqs"]) +def _build_draft_shard_plan_kernel( + sample_idx_mapping_ptr, + sample_pos_ptr, + send_rows_ptr, + gathered_src_ptr, + local_rows_ptr, + # [NUM_STEPS, local_stride]: step-major, so each step's slice is contiguous + local_idx_mapping_ptr, + local_sample_pos_ptr, + local_stride, + num_reqs, + NUM_STEPS: tl.constexpr, + PADDED_NUM_STEPS: tl.constexpr, + TP_SIZE: tl.constexpr, + TP_RANK: tl.constexpr, + PADDED_NUM_REQS: tl.constexpr, +): + req_idx = tl.program_id(0) + req_state_idx = tl.load(sample_idx_mapping_ptr + req_idx * NUM_STEPS) + is_valid = req_state_idx >= 0 + owner = req_state_idx % TP_SIZE + + req_block = tl.arange(0, PADDED_NUM_REQS) + req_mask = req_block < num_reqs + slots = tl.load( + sample_idx_mapping_ptr + req_block * NUM_STEPS, mask=req_mask, other=-1 + ) + valid = slots >= 0 + owners = slots % TP_SIZE + before = req_block < req_idx + local_idx = tl.sum((valid & (owners == owner) & before).to(tl.int32)) + owner_start = tl.sum((valid & (owners < owner)).to(tl.int32)) + # Padding rows (slot -1) go after every owner's rows, so the whole send + # permutation is rewritten each step. + pad_start = tl.sum(valid.to(tl.int32)) + tl.sum( + (req_mask & (slots < 0) & before).to(tl.int32) + ) + send_idx = tl.where(is_valid, owner_start + local_idx, pad_start) + + steps = tl.arange(0, PADDED_NUM_STEPS) + step_mask = steps < NUM_STEPS + rows = req_idx * NUM_STEPS + steps + tl.store( + send_rows_ptr + send_idx * NUM_STEPS + steps, rows.to(tl.int64), mask=step_mask ) + if is_valid: + tl.store( + gathered_src_ptr + req_idx, (owner * num_reqs + local_idx).to(tl.int64) + ) + if owner == TP_RANK: + tl.store(local_rows_ptr + local_idx, req_idx.to(tl.int64)) + local = steps * local_stride + local_idx + tl.store( + local_idx_mapping_ptr + local, + tl.load(sample_idx_mapping_ptr + rows, mask=step_mask), + mask=step_mask, + ) + tl.store( + local_sample_pos_ptr + local, + tl.load(sample_pos_ptr + rows, mask=step_mask), + mask=step_mask, + ) + + +class DraftBatchSharder: + """Routes a drafter's per-position logits rows to their owner ranks. + + Ownership is BatchSharder's (request slot % TP size), so a request's draft + logits land on the rank that verifies it in the next step. `stage` runs + inside the drafter's CUDA graph; `all_to_all` and `gather_draft_ids` run + after it, since their split sizes change every step. + """ + + def __init__( + self, + max_num_reqs: int, + num_steps: int, + shard_width: int, + dtype: torch.dtype, + device: torch.device, + ): + tp_group = get_tp_group() + self.tp_rank = tp_group.rank_in_group + self.tp_size = tp_group.world_size + self.num_steps = num_steps + max_rows = max_num_reqs * num_steps + # Owner-sorted vocab-shard rows, read by the all-to-all after the graph. + self.send = torch.empty(max_rows, shard_width, dtype=dtype, device=device) + self.send_rows = torch.zeros(max_rows, dtype=torch.int64, device=device) + self.gathered_src = torch.zeros(max_num_reqs, dtype=torch.int64, device=device) + self.local_rows = torch.zeros(max_num_reqs, dtype=torch.int64, device=device) + # [num_steps, max_num_reqs]: the owned requests' slots and positions. + self.local_idx_mapping = torch.full( + (num_steps, max_num_reqs), -1, dtype=torch.int32, device=device + ) + self.local_sample_pos = torch.zeros( + num_steps, max_num_reqs, dtype=torch.int64, device=device + ) + self.local_draft_ids = torch.zeros( + max_num_reqs, num_steps, dtype=torch.int64, device=device + ) + self._padded_num_reqs = triton.next_power_of_2(max_num_reqs) + self._padded_num_steps = triton.next_power_of_2(num_steps) + + def stage( + self, + local_logits: torch.Tensor, + sample_idx_mapping: torch.Tensor, + sample_pos: torch.Tensor, + num_reqs: int, + ) -> None: + """Owner-sort this rank's vocab shard of the (req, step) rows. + + `sample_idx_mapping` holds -1 for padded requests; everything is + derived on device, so a captured graph replays any batch. + """ + num_rows = num_reqs * self.num_steps + _build_draft_shard_plan_kernel[(num_reqs,)]( + sample_idx_mapping, + sample_pos, + self.send_rows, + self.gathered_src, + self.local_rows, + self.local_idx_mapping, + self.local_sample_pos, + self.local_idx_mapping.stride(0), + num_reqs, + NUM_STEPS=self.num_steps, + PADDED_NUM_STEPS=self._padded_num_steps, + TP_SIZE=self.tp_size, + TP_RANK=self.tp_rank, + PADDED_NUM_REQS=self._padded_num_reqs, + ) + torch.index_select( + local_logits, 0, self.send_rows[:num_rows], out=self.send[:num_rows] + ) + + def all_to_all(self, idx_mapping_np: np.ndarray) -> tuple[torch.Tensor, int]: + """This rank's (req, step) rows with the full vocab, and its number of + requests. `idx_mapping_np` is the unpadded batch staged last.""" + num_reqs_per_rank = np.bincount( + idx_mapping_np % self.tp_size, minlength=self.tp_size + ) + num_local_reqs = int(num_reqs_per_rank[self.tp_rank]) + num_rows = idx_mapping_np.shape[0] * self.num_steps + logits = all_to_all_rows( + self.send[:num_rows], + (num_reqs_per_rank * self.num_steps).tolist(), + num_local_reqs * self.num_steps, + ) + return logits, num_local_reqs + + def gather_draft_ids(self, num_reqs_padded: int, out: torch.Tensor) -> torch.Tensor: + """All-gather the owners' `local_draft_ids` into `out` in batch order.""" + gathered = tensor_model_parallel_all_gather( + self.local_draft_ids[:num_reqs_padded], dim=0 + ) + return torch.index_select( + gathered, 0, self.gathered_src[: out.shape[0]], out=out + ) def _shard_grammar_output( diff --git a/vllm/v1/worker/gpu/sample/gumbel.py b/vllm/v1/worker/gpu/sample/gumbel.py index 0c6503cbd6da..5de87a2aa7e4 100644 --- a/vllm/v1/worker/gpu/sample/gumbel.py +++ b/vllm/v1/worker/gpu/sample/gumbel.py @@ -186,7 +186,7 @@ def gumbel_noised_argmax( appears; `pos` and `seed` place the draw in the request's stream, which is what lets a draft and its verification agree. """ - if temp != 0.0 and APPLY_TEMPERATURE: + if APPLY_TEMPERATURE and temp != 0.0 and temp != 1.0: # Match the behavior of _temperature_kernel: if that kernel uses # tl.div_rn, this must too. logits = logits / temp @@ -236,6 +236,8 @@ def gumbel_block_argmax( PER_TOKEN_COL: tl.constexpr = False, CACHE_NUM_SHARDS: tl.constexpr = 1, CACHE_SHARD_IDX: tl.constexpr = 0, + # Cache `logits` itself (e.g. after an in-kernel bias add), not the source. + CACHE_LOGITS: tl.constexpr = False, ): req_state_idx = tl.load(expanded_idx_mapping_ptr + token_idx).to(tl.int64) is_valid_req = req_state_idx >= 0 @@ -251,10 +253,15 @@ def gumbel_block_argmax( col = tl.load(logits_cache_col_ptr + token_idx) else: col = tl.load(logits_cache_col_ptr) - cached_logits = tl.load( - logits_cache_source_ptr + token_idx * logits_cache_source_stride + block, - mask=mask, - ) + if CACHE_LOGITS: + cached_logits = logits + else: + cached_logits = tl.load( + logits_cache_source_ptr + + token_idx * logits_cache_source_stride + + block, + mask=mask, + ) tl.store( logits_cache_ptr + shard_row(req_state_idx, CACHE_NUM_SHARDS) * logits_cache_stride_0 @@ -299,6 +306,10 @@ def _gumbel_sample_kernel( logits_cache_source_stride, logits_ptr, logits_stride, + # [num_bias_rows, vocab_size]; row bias_rows[token_idx] is added + bias_ptr, + bias_stride, + bias_rows_ptr, expanded_idx_mapping_ptr, seeds_ptr, pos_ptr, @@ -311,6 +322,7 @@ def _gumbel_sample_kernel( PER_TOKEN_COL: tl.constexpr, CACHE_NUM_SHARDS: tl.constexpr, CACHE_SHARD_IDX: tl.constexpr, + HAS_BIAS: tl.constexpr, ): token_idx = tl.program_id(0).to(tl.int64) block_idx = tl.program_id(1) @@ -321,6 +333,11 @@ def _gumbel_sample_kernel( mask=mask, other=float("-inf"), ) + if HAS_BIAS: + # Rounded to the logits dtype, as `logits + bias` would be. + bias_row = tl.load(bias_rows_ptr + token_idx) + bias = tl.load(bias_ptr + bias_row * bias_stride + block, mask=mask, other=0.0) + logits = (logits.to(tl.float32) + bias.to(tl.float32)).to(logits.dtype) logits = logits.to(tl.float32) value, idx = gumbel_block_argmax( @@ -345,12 +362,44 @@ def _gumbel_sample_kernel( PER_TOKEN_COL=PER_TOKEN_COL, CACHE_NUM_SHARDS=CACHE_NUM_SHARDS, CACHE_SHARD_IDX=CACHE_SHARD_IDX, + CACHE_LOGITS=HAS_BIAS, ) token_id = block_idx * BLOCK_SIZE + idx tl.store(local_argmax_ptr + token_idx * local_argmax_stride + block_idx, token_id) tl.store(local_max_ptr + token_idx * local_max_stride + block_idx, value) +@triton.jit +def _gumbel_combine_kernel( + local_argmax_ptr, + local_argmax_stride, + local_max_ptr, + local_max_stride, + sampled_ptr, + num_blocks, + PADDED_NUM_BLOCKS: tl.constexpr, +): + row = tl.program_id(0).to(tl.int64) + block = tl.arange(0, PADDED_NUM_BLOCKS) + mask = block < num_blocks + values = tl.load( + local_max_ptr + row * local_max_stride + block, + mask=mask, + other=float("-inf"), + ) + # Match torch.argmax: the first NaN wins, otherwise the first maximum. + nan_block = tl.min(tl.where(values != values, block, PADDED_NUM_BLOCKS), axis=0) + if nan_block < PADDED_NUM_BLOCKS: + winner = nan_block + else: + maximum = tl.max(values, axis=0) + winner = tl.min( + tl.where(mask & (values == maximum), block, PADDED_NUM_BLOCKS), axis=0 + ) + sampled = tl.load(local_argmax_ptr + row * local_argmax_stride + winner) + tl.store(sampled_ptr + row, sampled) + + def gumbel_sample( logits: torch.Tensor, # [num_tokens, vocab_size] expanded_idx_mapping: torch.Tensor, # [num_tokens] @@ -365,6 +414,8 @@ def gumbel_sample( logits_cache_source: torch.Tensor | None = None, logits_cache_num_shards: int = 1, logits_cache_shard_idx: int = 0, + bias: torch.Tensor | None = None, # [num_bias_rows, vocab_size] + bias_rows: torch.Tensor | None = None, # [num_tokens] ) -> torch.Tensor: # Enforce contiguity on non-strided input tensors expanded_idx_mapping = expanded_idx_mapping.contiguous() @@ -372,6 +423,8 @@ def gumbel_sample( if logits_cache_col is not None: logits_cache_col = logits_cache_col.contiguous() num_tokens, vocab_size = logits.shape + # With a bias, the kernel caches the biased logits it samples from. + assert bias is None or logits_cache_source is None if logits_cache is not None: if logits_cache_source is None: logits_cache_source = logits @@ -399,6 +452,10 @@ def gumbel_sample( local_max_dtype = torch.float64 if use_fp64 else torch.float32 local_max = logits.new_empty(num_tokens, num_blocks, dtype=local_max_dtype) per_token_col = logits_cache_col is not None and logits_cache_col.dim() > 0 + if bias is not None: + # The sum is rounded to the logits dtype: same dtype only. + assert bias.dtype == logits.dtype and bias.stride(-1) == 1 + assert bias_rows is not None and bias.shape[-1] == vocab_size _gumbel_sample_kernel[(num_tokens, num_blocks)]( local_argmax, local_argmax.stride(0), @@ -412,6 +469,9 @@ def gumbel_sample( logits_cache_source.stride(0) if logits_cache_source is not None else 0, logits, logits.stride(0), + bias, + bias.stride(0) if bias is not None else 0, + bias_rows, expanded_idx_mapping, seed, pos, @@ -424,8 +484,16 @@ def gumbel_sample( PER_TOKEN_COL=per_token_col, CACHE_NUM_SHARDS=logits_cache_num_shards, CACHE_SHARD_IDX=logits_cache_shard_idx, + HAS_BIAS=bias is not None, + ) + sampled = logits.new_empty(num_tokens, dtype=torch.int64) + _gumbel_combine_kernel[(num_tokens,)]( + local_argmax, + local_argmax.stride(0), + local_max, + local_max.stride(0), + sampled, + num_blocks, + PADDED_NUM_BLOCKS=triton.next_power_of_2(num_blocks), ) - # NOTE(woosuk): Use int64 for later indexing. - max_block_idx = local_max.argmax(dim=-1, keepdim=True) - sampled = local_argmax.gather(dim=-1, index=max_block_idx).view(-1) return sampled diff --git a/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py b/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py index c694d99a4335..b232019a677f 100644 --- a/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py +++ b/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py @@ -133,9 +133,9 @@ def __init__(self, vllm_config: VllmConfig, device: torch.device): @property def attn_vllm_config(self) -> VllmConfig: # The draft's attention differs from the target's in causality. - config = copy.copy(super().attn_vllm_config) + config = super().attn_vllm_config config.attention_config = replace( - self.vllm_config.attention_config, + config.attention_config, use_non_causal=self.requires_non_causal, ) return config @@ -621,6 +621,7 @@ def propose( if is_full_cudagraph: assert self.query_cudagraph_manager is not None self.query_cudagraph_manager.run_fullgraph(batch_desc) + num_sample_reqs = batch_desc.num_reqs or num_reqs else: draft_slot_mappings_by_layer = build_slot_mappings_by_layer( self.block_tables.slot_mappings[:, :num_tokens_padded], @@ -634,9 +635,15 @@ def propose( num_tokens_across_dp=num_tokens_across_dp, cudagraph_runtime_mode=batch_desc.cg_mode, ) + num_sample_reqs = num_reqs + self._sample_after_forward(input_batch, num_sample_reqs) return self.draft_tokens[:num_reqs] + def _sample_after_forward(self, input_batch: InputBatch, num_reqs: int) -> None: + """Sampling left out of `_generate_draft`; `num_reqs` is the (padded) + request count it ran with. Nothing by default.""" + @triton.jit def _prepare_dflash_inputs_kernel( @@ -682,6 +689,7 @@ def _prepare_dflash_inputs_kernel( CP_SIZE: tl.constexpr, CP_INTERLEAVE: tl.constexpr, BLOCK_SIZE: tl.constexpr, + PAD_BLOCK: tl.constexpr, ): req_idx = tl.program_id(0) block_idx = tl.program_id(1) @@ -810,12 +818,12 @@ def _prepare_dflash_inputs_kernel( if req_idx == num_reqs - 1: # Pad per-request buffers to max_num_reqs for CUDA graph safety. last_query_end = num_reqs * num_query_per_req - for i in range(num_reqs, max_num_reqs + 1, BLOCK_SIZE): - block = i + tl.arange(0, BLOCK_SIZE) + for i in range(num_reqs, max_num_reqs + 1, PAD_BLOCK): + block = i + tl.arange(0, PAD_BLOCK) mask = block < max_num_reqs + 1 tl.store(out_query_start_loc_ptr + block, last_query_end, mask=mask) - for i in range(num_reqs, max_num_reqs, BLOCK_SIZE): - block = i + tl.arange(0, BLOCK_SIZE) + for i in range(num_reqs, max_num_reqs, PAD_BLOCK): + block = i + tl.arange(0, PAD_BLOCK) mask = block < max_num_reqs tl.store(out_seq_lens_ptr + block, 0, mask=mask) # Padded sample slots point at query index 0 (a valid row in @@ -824,8 +832,8 @@ def _prepare_dflash_inputs_kernel( # sampling to prevent writing stale values to draft logits. pad_start = num_reqs * num_speculative_steps pad_end = max_num_reqs * num_speculative_steps - for i in range(pad_start, pad_end, BLOCK_SIZE): - block = i + tl.arange(0, BLOCK_SIZE) + for i in range(pad_start, pad_end, PAD_BLOCK): + block = i + tl.arange(0, PAD_BLOCK) mask = block < pad_end tl.store(out_sample_indices_ptr + block, 0, mask=mask) tl.store(out_sample_pos_ptr + block, 0, mask=mask) @@ -834,8 +842,8 @@ def _prepare_dflash_inputs_kernel( # captured CG sees PAD slots (no K/V write) for replay sizes # larger than the current request count. q_pad_start = num_reqs * num_query_per_req - for i in range(q_pad_start, max_num_tokens, BLOCK_SIZE): - block = i + tl.arange(0, BLOCK_SIZE) + for i in range(q_pad_start, max_num_tokens, PAD_BLOCK): + block = i + tl.arange(0, PAD_BLOCK) mask = block < max_num_tokens tl.store(out_input_ids_ptr + block, 0, mask=mask) tl.store(out_query_positions_ptr + block, 0, mask=mask) @@ -928,4 +936,7 @@ def prepare_dflash_inputs( CP_SIZE=cp_size, CP_INTERLEAVE=cp_interleave, BLOCK_SIZE=BLOCK_SIZE, + # Pad in wide blocks: at BLOCK_SIZE (8 in a decode step) the padding up + # to max_num_tokens takes thousands of serial iterations (~20 us). + PAD_BLOCK=1024, ) diff --git a/vllm/v1/worker/gpu/spec_decode/dspark/speculator.py b/vllm/v1/worker/gpu/spec_decode/dspark/speculator.py index d2425ad95a87..3b7938f7f13f 100644 --- a/vllm/v1/worker/gpu/spec_decode/dspark/speculator.py +++ b/vllm/v1/worker/gpu/spec_decode/dspark/speculator.py @@ -20,7 +20,9 @@ previously sampled token at each step. CUDA graphs (FULL, mirroring DFlash) cover the whole draft step: the parallel -backbone forward AND the sequential Markov sampling. +backbone forward AND the sequential Markov sampling. With batch-sharded +sampling the graph ends at the owner-sorted LM-head shard; each rank then +samples its own requests after it (the all-to-all splits change every step). """ from typing import Any @@ -29,7 +31,10 @@ from vllm.config import VllmConfig from vllm.config.compilation import CUDAGraphMode +from vllm.distributed.parallel_state import get_tp_group from vllm.logger import init_logger +from vllm.v1.worker.gpu.input_batch import InputBatch +from vllm.v1.worker.gpu.sample.batch_shard import DraftBatchSharder from vllm.v1.worker.gpu.sample.gumbel import gumbel_sample from vllm.v1.worker.gpu.spec_decode.dflash.speculator import DFlashSpeculator from vllm.v1.worker.gpu.spec_decode.dspark.utils import load_dspark_model @@ -71,6 +76,10 @@ def __init__(self, vllm_config: VllmConfig, device: torch.device): torch.arange(self.max_num_reqs, dtype=torch.int64, device=device) * self.num_query_per_req ) + # The replicated Markov loop samples every row of its bias. + self._req_rows = torch.arange( + self.max_num_reqs, dtype=torch.int64, device=device + ) # Reduced-vocab probabilistic drafting only; set in load_draft_model. self._d2t_scatter_index: torch.Tensor | None = None @@ -80,6 +89,8 @@ def __init__(self, vllm_config: VllmConfig, device: torch.device): ) self.use_confidence_head: bool = False + # Set by enable_batch_sharded_sampling(). + self._draft_sharder: DraftBatchSharder | None = None def load_draft_model( self, @@ -117,6 +128,37 @@ def supports_batch_sharded_draft_logits(self) -> bool: # A model's own sample_sequential kernels write the full-size cache. return not hasattr(self.model, "sample_sequential") + def enable_batch_sharded_sampling(self) -> None: + # The target verifies each request on its owner rank, so each rank + # samples only its own requests' drafts and keeps their logits. + tp_group = get_tp_group() + lm_head = getattr(self.model, "lm_head", None) + reason = None + if not hasattr(self.model, "compute_draft_logits_local"): + reason = "the draft model has no compute_draft_logits_local" + elif tp_group.world_size == 1 or ( + getattr(lm_head, "tp_size", 1) != tp_group.world_size + ): + reason = "the draft LM head is not vocab-parallel over the TP group" + elif self._draft_topk is not None: + reason = "top-k drafting is not supported" + elif self.draft_watermarker is not None: + reason = "draft watermarking is not supported" + elif self.acceptance_estimator is not None or self.use_confidence_head: + reason = "adaptive verification is not supported" + if reason is not None: + logger.info("DSpark draft sampling stays replicated: %s.", reason) + return + assert lm_head is not None + self._draft_sharder = DraftBatchSharder( + max_num_reqs=self.max_num_reqs, + num_steps=self.num_speculative_steps, + shard_width=lm_head.num_embeddings_per_partition, + dtype=self.model.logits_processor.head_dtype or self.dtype, + device=self.device, + ) + logger.info("DSpark draft sampling is batch-sharded.") + def _sample_logits( self, logits: torch.Tensor, @@ -167,6 +209,49 @@ def _sample_logits( logits_cache_shard_idx=self.draft_logits_shard_idx, ) + def _sample_markov_step( + self, + step: int, + logits: torch.Tensor, + bias: torch.Tensor, + bias_rows: torch.Tensor, + idx_map: torch.Tensor, + draw_pos: torch.Tensor, + ) -> torch.Tensor: + """Draft ids of step `step`, sampled from `logits + bias[bias_rows]`.""" + # Greedy drafting, a reduced draft vocab, watermarking, the acceptance + # estimator and an output logit transform need the biased logits; + # otherwise the Gumbel kernel adds the bias itself. + transform = getattr(self.model, "apply_output_logit_transform", None) + if ( + self.draft_logits is None + or self._d2t_scatter_index is not None + or self.draft_watermarker is not None + or self.acceptance_estimator is not None + or transform is not None + ): + logits = logits + bias[bias_rows] + if transform is not None: + logits = transform(logits) + # _sample_logits takes the predicted position P. + return self._sample_logits(logits, idx_map, draw_pos + 1, step) + return gumbel_sample( + logits, + idx_map, + self.temperature, + self.seeds, + draw_pos, + apply_temperature=True, + is_drafting=True, + logits_cache=self.draft_logits, + logits_cache_col=self._step_cols[step], + use_fp64=self.use_fp64_gumbel, + logits_cache_num_shards=self.draft_logits_num_shards, + logits_cache_shard_idx=self.draft_logits_shard_idx, + bias=bias, + bias_rows=bias_rows, + ) + def _sample_sequential(self, num_reqs: int, head_hidden: torch.Tensor) -> None: if self._draft_topk is not None: self._sample_sequential_topk(num_reqs, head_hidden) @@ -192,7 +277,13 @@ def _sample_sequential(self, num_reqs: int, head_hidden: torch.Tensor) -> None: idx_map = self.sample_idx_mapping[:num_sample].view(num_reqs, n_spec) sample_pos = self.sample_pos[:num_sample].view(num_reqs, n_spec) + # Step-major, so every step reads contiguous rows. Draws are keyed by + # the position before the sampled token, P-1. + idx_map_steps = idx_map.t().contiguous() + draw_pos_steps = (sample_pos.t() - 1).contiguous() + bias_rows = self._req_rows[:num_reqs] confidence_markov_embeds = [] + draft_ids = [] # Anchor (bonus) token per request = the input id at query offset 0, # read via the precomputed persistent index (fixed buffer for capture). @@ -204,14 +295,16 @@ def _sample_sequential(self, num_reqs: int, head_hidden: torch.Tensor) -> None: if self.use_confidence_head: confidence_markov_embeds.append(markov_embed) bias = self.model.markov_bias(markov_embed) - logits_i = base_logits[:, i] + bias - if hasattr(self.model, "apply_output_logit_transform"): - logits_i = self.model.apply_output_logit_transform(logits_i) - draft_sampled_i = self._sample_logits( - logits_i, idx_map[:, i], sample_pos[:, i], i + prev = self._sample_markov_step( + i, + base_logits[:, i], + bias, + bias_rows, + idx_map_steps[i], + draw_pos_steps[i], ) - self.draft_tokens[:num_reqs, i] = draft_sampled_i - prev = draft_sampled_i + draft_ids.append(prev) + torch.stack(draft_ids, dim=1, out=self.draft_tokens[:num_reqs]) if self.use_confidence_head: confidence = self.model.compute_confidence( @@ -289,4 +382,54 @@ def _generate_draft( num_tokens_across_dp, cudagraph_runtime_mode, ) + if self._draft_sharder is not None: + # Sampled after the graph, in _sample_after_forward. + num_sample = num_reqs * self.num_speculative_steps + sample_hidden = head_hidden[self.sample_indices[:num_sample]] + self._draft_sharder.stage( + self.model.compute_draft_logits_local(sample_hidden), + self.sample_idx_mapping, + self.sample_pos, + num_reqs, + ) + return self._sample_sequential(num_reqs, head_hidden) + + def _sample_after_forward(self, input_batch: InputBatch, num_reqs: int) -> None: + sharder = self._draft_sharder + if sharder is None: + return + logits, num_local_reqs = sharder.all_to_all(input_batch.idx_mapping_np) + if num_local_reqs > 0: + self._sample_sequential_local(logits, num_local_reqs, num_reqs) + sharder.gather_draft_ids(num_reqs, self.draft_tokens[: input_batch.num_reqs]) + + def _sample_sequential_local( + self, logits: torch.Tensor, num_local_reqs: int, num_reqs: int + ) -> None: + """_sample_sequential over this rank's requests (`logits` holds their + full-vocab rows); `num_reqs` is the staged, padded batch size.""" + sharder = self._draft_sharder + assert sharder is not None + n_spec = self.num_speculative_steps + vocab_size = self.model.logits_processor.org_vocab_size + base_logits = logits[:, :vocab_size].view(num_local_reqs, n_spec, vocab_size) + local_rows = sharder.local_rows[:num_local_reqs] + idx_map = sharder.local_idx_mapping[:, :num_local_reqs] + sample_pos = sharder.local_sample_pos[:, :num_local_reqs] + # sample_pos is the predicted position; draws are keyed by P-1. + draw_pos = sample_pos - 1 + + # The Markov bias keeps all num_reqs rows, so it runs the GEMM (and + # gets the bits) of the replicated path; other ranks' rows are unused. + prev = self.input_buffers.input_ids[self._anchor_idx[:num_reqs]].long() + draft_ids = [] + for i in range(n_spec): + bias = self.model.markov_bias(self.model.markov_embed(prev)) + draft_sampled_i = self._sample_markov_step( + i, base_logits[:, i], bias, local_rows, idx_map[i], draw_pos[i] + ) + draft_ids.append(draft_sampled_i) + if i + 1 < n_spec: + prev.index_copy_(0, local_rows, draft_sampled_i) + torch.stack(draft_ids, dim=1, out=sharder.local_draft_ids[:num_local_reqs]) diff --git a/vllm/v1/worker/gpu/spec_decode/speculator.py b/vllm/v1/worker/gpu/spec_decode/speculator.py index 261c83a94727..216d441fc89a 100644 --- a/vllm/v1/worker/gpu/spec_decode/speculator.py +++ b/vllm/v1/worker/gpu/spec_decode/speculator.py @@ -1,5 +1,6 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project +import copy from abc import ABC, abstractmethod from collections.abc import Mapping from dataclasses import replace @@ -11,6 +12,7 @@ from vllm.config import VllmConfig, get_layers_from_vllm_config from vllm.config.compilation import CUDAGraphMode +from vllm.config.speculative import _DRAFT_VLLM_CONFIG_OVERRIDES from vllm.distributed.eplb.eplb_state import EplbState from vllm.distributed.parallel_state import get_tp_group from vllm.logger import init_logger @@ -101,7 +103,7 @@ def propose( mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None, is_profile: bool = False, num_speculative_tokens: int | None = None, - ) -> torch.Tensor: + ) -> torch.Tensor | None: pass @@ -313,7 +315,16 @@ def _prepare_eplb_forward(self, num_unpadded_tokens: int) -> None: def attn_vllm_config(self) -> VllmConfig: """Config for the draft's attention metadata builders. Overridden by speculators whose attention mode differs from the target's.""" - return self.vllm_config + # Shallow copies instead of apply_draft_overrides: its replace() + # rebuilds each sub-config and drops engine-resolved init=False state + # such as cache_config.kv_cache_layout. + config = copy.copy(self.vllm_config) + for src, config_name, dst in _DRAFT_VLLM_CONFIG_OVERRIDES: + if (value := getattr(self.speculative_config, src)) is not None: + sub_config = copy.copy(getattr(config, config_name)) + setattr(sub_config, dst, value) + setattr(config, config_name, sub_config) + return config def set_attn( self, @@ -436,6 +447,10 @@ def _build_attn_metadata( ) return attn_metadata + def enable_batch_sharded_sampling(self) -> None: + """Called when the target samples batch-sharded: each request is + verified on its owner rank, which alone reads its draft logits.""" + def draft_logits_spec(self, vllm_config: VllmConfig) -> tuple[torch.dtype, float]: """Dtype and fill for the cached proposal distribution. diff --git a/vllm/v1/worker/gpu/ubatch_utils.py b/vllm/v1/worker/gpu/ubatch_utils.py index 608231a3ed42..2e9ff4a736e6 100644 --- a/vllm/v1/worker/gpu/ubatch_utils.py +++ b/vllm/v1/worker/gpu/ubatch_utils.py @@ -20,6 +20,7 @@ override_forward_context, ) from vllm.logger import init_logger +from vllm.platforms import current_platform from vllm.sequence import IntermediateTensors from vllm.utils.torch_utils import current_stream from vllm.v1.kv_cache_interface import KVCacheConfig @@ -33,7 +34,11 @@ create_sm_control_context, maybe_create_ubatch_slices, ) -from vllm.v1.worker.ubatching import make_ubatch_contexts +from vllm.v1.worker.ubatching import ( + dbo_comm_stream_priority, + init_dbo_tp_comms, + make_ubatch_contexts, +) from vllm.v1.worker.utils import AttentionGroup logger = init_logger(__name__) @@ -264,7 +269,8 @@ def merge_ubatch_outputs(outputs: list[Any]) -> Any: """Reassemble the full-batch model output from the per-microbatch ones. Models return hidden states, a tuple of those plus auxiliary hidden states - (EAGLE3), or IntermediateTensors on non-final pipeline ranks. + (EAGLE3; a list of them for DSpark), or IntermediateTensors on non-final + pipeline ranks. """ first = outputs[0] if isinstance(first, IntermediateTensors): @@ -274,8 +280,10 @@ def merge_ubatch_outputs(outputs: list[Any]) -> Any: for key in first.tensors } ) - if isinstance(first, tuple): - return tuple(torch.cat(parts, dim=0) for parts in zip(*outputs)) + if isinstance(first, (tuple, list)): + return type(first)(merge_ubatch_outputs(list(parts)) for parts in zip(*outputs)) + if first is None: + return None return torch.cat(outputs, dim=0) @@ -324,13 +332,41 @@ def __init__( else None for _ in range(self.num_ubatches) ] - self.comm_stream = torch.cuda.Stream(device=device) + self.comm_stream = torch.cuda.Stream( + device=device, priority=dbo_comm_stream_priority() + ) # Threads and graph capture must use the same compute stream. self.capture_stream = torch.cuda.Stream(device=device) # The microbatch threads plus the thread that starts them. self.ready_barrier = threading.Barrier(self.num_ubatches + 1) + init_dbo_tp_comms(self.parallel_config) self._pending_finish: Callable[[], Any] | None = None self.sm_control = create_sm_control_context(self.parallel_config) + if current_platform.is_rocm(): + self._warm_blas_lt_handles() + + def _warm_blas_lt_handles(self) -> None: + """Fill torch's hipBLASLt handle pool for the microbatch threads. + + hipblasLtCreate clears a new handle's Stream-K flags with a null-stream + hipMemset that can land after a GEMM on the comm stream has started, and + the GEMM then never finishes. Microbatch threads are new every step and + take their per-stream handles from the pool.""" + a = torch.zeros((64, 64), dtype=torch.bfloat16, device=self.device) + streams = (current_stream(), self.capture_stream, self.comm_stream) + + def touch() -> None: + torch.accelerator.set_device_index(self.device.index) + for stream in streams: + with torch.cuda.stream(stream): + torch.mm(a, a, out_dtype=torch.float32) + + threads = [threading.Thread(target=touch) for _ in range(self.num_ubatches)] + for t in threads: + t.start() + for t in threads: + t.join() + torch.cuda.synchronize(self.device) def prepare( self, @@ -418,8 +454,12 @@ def _make_forward_contexts( self.vllm_config, dp_metadata=DPMetadata.make( self.parallel_config, num_tokens, num_tokens_across_dp - ), + ) + if dp_size > 1 + else None, cudagraph_runtime_mode=CUDAGraphMode.NONE, + # A model picking a path per step sees the whole split. + ubatch_slices=ubatch_slices, slot_mapping=slot_mappings_by_layer[i], is_padding=is_padding[i], ) @@ -489,6 +529,8 @@ def run_ubatch(ubatch_context, inputs: dict[str, Any]) -> None: # changing the shared handoff protocol in ubatching.py, which # is deliberately out of scope here. errors[ubatch_context.id] = e + # The sibling may wait on a hand-off forever: log before the join. + logger.exception("Microbatch %d failed", ubatch_context.id) # Threads own the forward context; keep it cleared and SMs reserved # until finish joins them. @@ -556,7 +598,9 @@ def maybe_build_ubatch_runner( available with more than one DP rank (as in the V1 runner). """ parallel_config = vllm_config.parallel_config - if not parallel_config.use_ubatching or parallel_config.data_parallel_size <= 1: + if not parallel_config.use_ubatching: + return None + if parallel_config.data_parallel_size <= 1 and not parallel_config.dbo_tp_only: return None logger.info_once("Dual batch overlap is enabled.") diff --git a/vllm/v1/worker/gpu_model_runner.py b/vllm/v1/worker/gpu_model_runner.py index ac3ff3b65865..71c4f1a92e14 100644 --- a/vllm/v1/worker/gpu_model_runner.py +++ b/vllm/v1/worker/gpu_model_runner.py @@ -213,6 +213,7 @@ from vllm.v1.worker.ubatch_utils import ( UBatchSlices, check_ubatch_thresholds, + is_last_ubatch_empty, maybe_create_ubatch_slices, split_attn_metadata, ) @@ -3767,6 +3768,17 @@ def dispatch_cudagraph(num_tokens, disable_full=False, valid_modes=None): # Assert to make sure the agreed upon token count is correct otherwise # num_tokens_across_dp will no-longer be valid assert batch_descriptor.num_tokens == num_tokens_padded + elif self.parallel_config.dbo_tp_only and allow_microbatching: + # One DP rank: decide the split locally; only eager steps split. + should_ubatch = ( + cudagraph_mode == CUDAGraphMode.NONE + and check_ubatch_thresholds( + self.parallel_config, num_tokens, uniform_decode=uniform_decode + ) + and not is_last_ubatch_empty( + num_tokens, num_tokens_padded, self.parallel_config.num_ubatches + ) + ) cudagraph_stats = None if self.vllm_config.observability_config.cudagraph_metrics: @@ -6128,6 +6140,16 @@ def profile_run(self, randomize_inputs: bool = False) -> None: for i, output in enumerate(dummy_encoder_outputs): self.encoder_cache[f"tmp_{i}"] = output + if ( + self.parallel_config.use_ubatching + and not self.parallel_config.enable_expert_parallel + ): + # The profile step below is split; size the workspaces for the + # unsplit step first. + unsplit_hidden, unsplit_last = self._dummy_run( + self.max_num_tokens, is_profile=True, allow_microbatching=False + ) + del unsplit_hidden, unsplit_last # Add `is_profile` here to pre-allocate communication buffers hidden_states, last_hidden_states = self._dummy_run( self.max_num_tokens, is_profile=True, randomize_inputs=randomize_inputs diff --git a/vllm/v1/worker/gpu_ubatch_wrapper.py b/vllm/v1/worker/gpu_ubatch_wrapper.py index 816df537762b..6e5865903246 100644 --- a/vllm/v1/worker/gpu_ubatch_wrapper.py +++ b/vllm/v1/worker/gpu_ubatch_wrapper.py @@ -9,6 +9,10 @@ import torch +from vllm.compilation.breakable_cudagraph import ( + BreakableCUDAGraphWrapper, + is_breakable_cudagraph_enabled, +) from vllm.compilation.cuda_graph import CUDAGraphWrapper from vllm.config import CUDAGraphMode, VllmConfig from vllm.distributed.device_communicators.pynccl_allocator import set_graph_pool_id @@ -23,7 +27,12 @@ from vllm.platforms import current_platform from vllm.sequence import IntermediateTensors from vllm.v1.worker.ubatch_utils import create_sm_control_context -from vllm.v1.worker.ubatching import UBatchContext, make_ubatch_contexts +from vllm.v1.worker.ubatching import ( + UBatchContext, + dbo_comm_stream_priority, + init_dbo_tp_comms, + make_ubatch_contexts, +) logger = init_logger(__name__) @@ -41,7 +50,9 @@ def _cat_ubatch_outputs( produced for a single ubatch (#40769). """ if sorted_results and isinstance(sorted_results[0], tuple): - return tuple(torch.cat(parts, dim=0) for parts in zip(*sorted_results)) + return tuple(_cat_ubatch_outputs(list(parts)) for parts in zip(*sorted_results)) + if sorted_results and isinstance(sorted_results[0], list): + return [torch.cat(parts, dim=0) for parts in zip(*sorted_results)] return torch.cat(sorted_results, dim=0) @@ -73,7 +84,9 @@ def __init__( self.runnable = runnable self.vllm_config = vllm_config self.compilation_config = vllm_config.compilation_config - self.comm_stream = torch.cuda.Stream(device=device) + self.comm_stream = torch.cuda.Stream( + device=device, priority=dbo_comm_stream_priority() + ) # Ubatch threads plus the main thread self.ready_barrier = threading.Barrier( self.vllm_config.parallel_config.num_ubatches + 1 @@ -86,6 +99,14 @@ def __init__( self.cudagraph_wrapper = CUDAGraphWrapper( runnable, vllm_config, runtime_mode=runtime_mode ) + # Unsplit steps keep their breakable piecewise graphs. + self.piecewise_wrapper = None + if ( + is_breakable_cudagraph_enabled() + and self.compilation_config.cudagraph_mode != CUDAGraphMode.NONE + ): + self.piecewise_wrapper = BreakableCUDAGraphWrapper(runnable, vllm_config) + init_dbo_tp_comms(self.vllm_config.parallel_config) self.sm_control = create_sm_control_context(vllm_config.parallel_config) self.device = device @@ -373,6 +394,11 @@ def __call__(self, *args, **kwargs): if batch_descriptor.num_tokens in self.cudagraphs: cudagraph_runtime_mode = CUDAGraphMode.NONE + if ( + cudagraph_runtime_mode is CUDAGraphMode.PIECEWISE + and self.piecewise_wrapper is not None + ): + return self.piecewise_wrapper(*args, **kwargs) if cudagraph_runtime_mode in (CUDAGraphMode.NONE, CUDAGraphMode.PIECEWISE): return self.runnable(*args, **kwargs) else: @@ -391,10 +417,11 @@ def __call__(self, *args, **kwargs): dp_metadata = forward_context.dp_metadata - # We shouldn't be here unless we are running with multiple DP ranks - assert dp_metadata is not None - ubatch_dp_metadata = [] + ubatch_dp_metadata: list = [] for ubatch_slice in ubatch_slices: + if dp_metadata is None: + ubatch_dp_metadata.append(None) + continue dp_size = self.vllm_config.parallel_config.data_parallel_size ubatch_num_tokens_across_dp = torch.tensor( [ubatch_slice.num_tokens] * dp_size, device="cpu", dtype=torch.int32 diff --git a/vllm/v1/worker/gpu_worker.py b/vllm/v1/worker/gpu_worker.py index 537a262dd42b..cb37316cdcf5 100644 --- a/vllm/v1/worker/gpu_worker.py +++ b/vllm/v1/worker/gpu_worker.py @@ -562,6 +562,10 @@ def _init_workspace_and_model_runner(self) -> None: """Set up the workspace manager, build the model runner, report usage.""" # DSpark target and draft CUDA graphs retain workspace views concurrently. num_ubatches = 2 if self.vllm_config.parallel_config.enable_dbo else 1 + pc = self.vllm_config.parallel_config + if self.use_v2_model_runner and pc.dbo_tp_only: + # Both microbatches compute on one stream: one workspace set. + num_ubatches = 1 init_workspace_manager( self.device, num_ubatches, diff --git a/vllm/v1/worker/ubatch_utils.py b/vllm/v1/worker/ubatch_utils.py index 85e83489c94b..08398ca664da 100644 --- a/vllm/v1/worker/ubatch_utils.py +++ b/vllm/v1/worker/ubatch_utils.py @@ -320,6 +320,14 @@ def _make_metadata_with_slice( block_table_tensor = attn_metadata.block_table_tensor[request_slice] slot_mapping = attn_metadata.slot_mapping[token_slice] + causal = attn_metadata.causal + if isinstance(causal, torch.Tensor): + causal = causal[request_slice] + is_prefilling = ( + attn_metadata.is_prefilling[request_slice] + if attn_metadata.is_prefilling is not None + else None + ) positions = attn_metadata.positions if positions is not None: @@ -335,7 +343,9 @@ def _make_metadata_with_slice( max_seq_len=max_seq_len, block_table_tensor=block_table_tensor, slot_mapping=slot_mapping, + causal=causal, positions=positions, + is_prefilling=is_prefilling, seq_lens_cpu_upper_bound=seq_lens_cpu_upper_bound, ) diff --git a/vllm/v1/worker/ubatching.py b/vllm/v1/worker/ubatching.py index a39f85d388f2..9a1b79d4f6a8 100644 --- a/vllm/v1/worker/ubatching.py +++ b/vllm/v1/worker/ubatching.py @@ -5,6 +5,7 @@ import torch from vllm import forward_context +from vllm.distributed import parallel_state from vllm.forward_context import ForwardContext from vllm.logger import init_logger from vllm.utils.torch_utils import current_stream @@ -252,3 +253,77 @@ def make_ubatch_contexts( ctxs.append(ctx) return ctxs + + +# DBO under pure TP: each TP all-reduce is a hand-off point and runs on the comm +# stream, on a per-microbatch communicator, while the other microbatch computes. +_TP_UBATCH_COMMS: list | None = None + + +def init_dbo_tp_comms(parallel_config) -> None: + """Build the per-microbatch TP communicators and install the all-reduce hook + (DBO under pure TP only). Collective: every rank calls it in the same order.""" + global _TP_UBATCH_COMMS + if not parallel_config.dbo_tp_only or _TP_UBATCH_COMMS is not None: + return + from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator + + tp = parallel_state.get_tp_group() + comms = [ + PyNcclCommunicator(group=tp.cpu_group, device=tp.device) + for _ in range(parallel_config.num_ubatches) + ] + if any(c.disabled for c in comms): + logger.warning( + "DBO: the NCCL library is unavailable, the TP all-reduces of a " + "microbatch stay on the compute stream (no overlap)" + ) + return + _TP_UBATCH_COMMS = comms + parallel_state.set_dbo_tp_all_reduce_hook(_dbo_tp_all_reduce) + logger.info( + "DBO: %d per-microbatch TP communicators for the comm-stream all-reduce", + len(comms), + ) + + +def dbo_comm_stream_priority() -> int: + """High on ROCm: at the default priority comm and compute can share one + hardware queue and serialize.""" + from vllm.platforms import current_platform + + return -1 if current_platform.is_rocm() else 0 + + +def dbo_tp_collective(issue) -> bool: + """Run ``issue(comm, stream)`` as a microbatch hand-off on its comm stream; + False outside a microbatch.""" + if len(_THREAD_ID_TO_CONTEXT) == 0 or _TP_UBATCH_COMMS is None: + return False + ctx_idx = _THREAD_ID_TO_CONTEXT.get(threading.get_ident()) + if ctx_idx is None: + return False + ctx = _CURRENT_CONTEXTS[ctx_idx] + ctx.yield_and_switch_from_compute_to_comm() + issue(_TP_UBATCH_COMMS[ctx_idx], ctx.comm_stream) + ctx.switch_to_compute_sync() + return True + + +def _dbo_tp_all_reduce(group, input_: torch.Tensor) -> torch.Tensor | None: + """The TP all-reduce of a microbatch, on the comm stream.""" + if len(_THREAD_ID_TO_CONTEXT) == 0: + return None + ctx_idx = _THREAD_ID_TO_CONTEXT.get(threading.get_ident()) + if ctx_idx is None or group is not parallel_state._TP: + return None + assert _TP_UBATCH_COMMS is not None + ctx = _CURRENT_CONTEXTS[ctx_idx] + logger.info_once("DBO: TP all-reduces of a microbatch go to the comm stream") + # No record_stream: the stream waits already order the buffers, and it would + # pin every block until the GPU catches up (out of memory at a 32k step). + out = torch.empty_like(input_) + ctx.yield_and_switch_from_compute_to_comm() + _TP_UBATCH_COMMS[ctx_idx].all_reduce(input_, out_tensor=out, stream=ctx.comm_stream) + ctx.switch_to_compute_sync() + return out diff --git a/vllm/v1/worker/workspace.py b/vllm/v1/worker/workspace.py index a05534281c11..48ebdc2609d1 100644 --- a/vllm/v1/worker/workspace.py +++ b/vllm/v1/worker/workspace.py @@ -127,7 +127,10 @@ def _get_workspace_id(self) -> int: f"Workspace lane {lane} is not configured; manager has " f"{self._num_lanes} lane(s)." ) - return dbo_current_ubatch_id() * self._num_lanes + lane + # One set of workspaces shared by every microbatch (TP-only DBO) or one + # per microbatch. + ubatch = dbo_current_ubatch_id() if self._num_ubatches > 1 else 0 + return ubatch * self._num_lanes + lane def get_persistent_resource(self, key: Hashable, factory: Callable[[], T]) -> T: """Return the resource cached for ``key`` in the current ubatch and lane. From 0282ef0a507e3c4f95336d9da53ba2744532f445 Mon Sep 17 00:00:00 2001 From: Taoyu Zhu Date: Mon, 26 Oct 2026 12:59:05 +0800 Subject: [PATCH 2/7] [ROCm][MiniMax-M3.1] Move DBO under pure TP and SP prefill to their own PRs (#63490) Signed-off-by: Taoyu Zhu Co-authored-by: Claude Opus 5.5 --- .../moe/test_minimax_m3_moe_mxfp4_prefill.py | 206 --- .../moe/test_minimax_m3_moe_prefill.py | 155 --- tests/kernels/test_minimax_m3_sp_coll.py | 193 --- .../test_minimax_m3_sp_prefill_kernels.py | 97 -- tests/v1/worker/test_dbo_pure_tp.py | 186 --- vllm/config/parallel.py | 10 - vllm/config/vllm.py | 8 +- vllm/distributed/parallel_state.py | 15 - vllm/envs.py | 6 - .../kernels/linear/mxfp8/rocm_native.py | 40 +- .../layers/fused_allreduce_gemma_rms_norm.py | 6 +- .../fused_moe/prepare_finalize/no_dp_ep.py | 4 - vllm/models/minimax_m3/amd/model.py | 46 +- .../amd/ops/moe_flydsl_common/__init__.py | 3 - .../amd/ops/moe_flydsl_common/epilogue.py | 72 - .../amd/ops/moe_flydsl_common/launch.py | 32 - .../amd/ops/moe_flydsl_common/loaders.py | 397 ------ .../amd/ops/moe_flydsl_common/reduce_bf16.py | 98 -- .../amd/ops/moe_flydsl_common/sort.py | 223 --- .../amd/ops/moe_flydsl_common/tile_map.py | 91 -- .../amd/ops/moe_flydsl_common/utils.py | 34 - .../minimax_m3/amd/ops/moe_mxfp4/__init__.py | 3 - .../amd/ops/moe_mxfp4/gemm1_prefill.py | 1192 ----------------- .../amd/ops/moe_mxfp4/gemm2_prefill.py | 1088 --------------- .../minimax_m3/amd/ops/moe_mxfp4/prefill.py | 217 --- .../minimax_m3/amd/ops/moe_mxfp8/__init__.py | 3 - .../amd/ops/moe_mxfp8/gemm1_prefill.py | 822 ------------ .../amd/ops/moe_mxfp8/gemm2_prefill.py | 682 ---------- .../amd/ops/moe_mxfp8/gemm2_prefill_bm256.py | 697 ---------- .../minimax_m3/amd/ops/moe_mxfp8/prefill.py | 228 ---- .../minimax_m3/amd/ops/sp_coll/__init__.py | 7 - .../models/minimax_m3/amd/ops/sp_coll/host.py | 321 ----- .../minimax_m3/amd/ops/sp_coll/kernel.py | 438 ------ .../minimax_m3/amd/ops/sp_norm_quant.py | 113 -- vllm/models/minimax_m3/amd/ops/sp_pack.py | 114 -- vllm/models/minimax_m3/amd/sp_prefill.py | 737 ---------- vllm/v1/worker/gpu/dp_utils.py | 17 - vllm/v1/worker/gpu/ubatch_utils.py | 58 +- vllm/v1/worker/gpu_model_runner.py | 22 - vllm/v1/worker/gpu_ubatch_wrapper.py | 39 +- vllm/v1/worker/gpu_worker.py | 4 - vllm/v1/worker/ubatch_utils.py | 10 - vllm/v1/worker/ubatching.py | 75 -- vllm/v1/worker/workspace.py | 5 +- 44 files changed, 38 insertions(+), 8776 deletions(-) delete mode 100644 tests/kernels/moe/test_minimax_m3_moe_mxfp4_prefill.py delete mode 100644 tests/kernels/moe/test_minimax_m3_moe_prefill.py delete mode 100644 tests/kernels/test_minimax_m3_sp_coll.py delete mode 100644 tests/kernels/test_minimax_m3_sp_prefill_kernels.py delete mode 100644 tests/v1/worker/test_dbo_pure_tp.py delete mode 100644 vllm/models/minimax_m3/amd/ops/moe_flydsl_common/__init__.py delete mode 100644 vllm/models/minimax_m3/amd/ops/moe_flydsl_common/epilogue.py delete mode 100644 vllm/models/minimax_m3/amd/ops/moe_flydsl_common/launch.py delete mode 100644 vllm/models/minimax_m3/amd/ops/moe_flydsl_common/loaders.py delete mode 100644 vllm/models/minimax_m3/amd/ops/moe_flydsl_common/reduce_bf16.py delete mode 100644 vllm/models/minimax_m3/amd/ops/moe_flydsl_common/sort.py delete mode 100644 vllm/models/minimax_m3/amd/ops/moe_flydsl_common/tile_map.py delete mode 100644 vllm/models/minimax_m3/amd/ops/moe_flydsl_common/utils.py delete mode 100644 vllm/models/minimax_m3/amd/ops/moe_mxfp4/__init__.py delete mode 100644 vllm/models/minimax_m3/amd/ops/moe_mxfp4/gemm1_prefill.py delete mode 100644 vllm/models/minimax_m3/amd/ops/moe_mxfp4/gemm2_prefill.py delete mode 100644 vllm/models/minimax_m3/amd/ops/moe_mxfp4/prefill.py delete mode 100644 vllm/models/minimax_m3/amd/ops/moe_mxfp8/__init__.py delete mode 100644 vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm1_prefill.py delete mode 100644 vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm2_prefill.py delete mode 100644 vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm2_prefill_bm256.py delete mode 100644 vllm/models/minimax_m3/amd/ops/moe_mxfp8/prefill.py delete mode 100644 vllm/models/minimax_m3/amd/ops/sp_coll/__init__.py delete mode 100644 vllm/models/minimax_m3/amd/ops/sp_coll/host.py delete mode 100644 vllm/models/minimax_m3/amd/ops/sp_coll/kernel.py delete mode 100644 vllm/models/minimax_m3/amd/ops/sp_norm_quant.py delete mode 100644 vllm/models/minimax_m3/amd/ops/sp_pack.py delete mode 100644 vllm/models/minimax_m3/amd/sp_prefill.py diff --git a/tests/kernels/moe/test_minimax_m3_moe_mxfp4_prefill.py b/tests/kernels/moe/test_minimax_m3_moe_mxfp4_prefill.py deleted file mode 100644 index 84f66bea5716..000000000000 --- a/tests/kernels/moe/test_minimax_m3_moe_mxfp4_prefill.py +++ /dev/null @@ -1,206 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""MiniMax-M3 FlyDSL W4A4 MoE prefill chain at TP4 vs aiter's ``fused_moe`` (the -``AITER_MXFP4_MXFP4`` backend's call) and a float reference, routed only and with -aiter's fused shared expert (expert 129, every token, weight 1).""" - -import pytest -import torch - -from vllm.platforms import current_platform -from vllm.platforms.rocm import on_gfx950 - -pytestmark = [ - pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm only"), - pytest.mark.skipif(not on_gfx950(), reason="gfx950 only"), -] - -HIDDEN, INTER, NUM_ROUTED, TOPK = 6144, 768, 128, 4 -SWIGLU_ALPHA, SWIGLU_LIMIT = 1.702, 7.0 -CHECK_TOKENS = 64 - - -def _quantize_like_backend(w13: torch.Tensor, w2: torch.Tensor): - """Per-1x32 MXFP4 + the shuffles oracle/mxfp4.py applies for - AITER_MXFP4_MXFP4.""" - from aiter import dtypes - from aiter.ops.quant import per_1x32_f4_quant - from aiter.utility.fp4_utils import e8m0_shuffle - - from vllm._aiter_ops import rocm_aiter_ops - - e = w13.shape[0] - fp4 = torch.float4_e2m1fn_x2 - w13_q, w13_s = per_1x32_f4_quant(w13, quant_dtype=dtypes.fp4x2) - w2_q, w2_s = per_1x32_f4_quant(w2, quant_dtype=dtypes.fp4x2) - w13_q = w13_q.view(e, w13.shape[1], w13.shape[2] // 2) - w2_q = w2_q.view(e, w2.shape[1], w2.shape[2] // 2) - w13_s = w13_s.view(torch.uint8).view(e, w13.shape[1], w13.shape[2] // 32) - w2_s = w2_s.view(torch.uint8).view(e, w2.shape[1], w2.shape[2] // 32) - raw = (w13_q, w13_s, w2_q, w2_s) - w13_k, w2_k = rocm_aiter_ops.shuffle_weights(w13_q.view(fp4), w2_q.view(fp4)) - w13_sk = e8m0_shuffle(w13_s.view(e * w13.shape[1], -1)).view(e, w13.shape[1], -1) - w2_sk = e8m0_shuffle(w2_s.view(e * w2.shape[1], -1)).view(e, w2.shape[1], -1) - shuffled = (w13_k.contiguous(), w13_sk.contiguous()) - return raw, shuffled + (w2_k.contiguous(), w2_sk.contiguous()) - - -def _routing(m: int, shared: bool, device): - routed = torch.stack( - [torch.randperm(NUM_ROUTED, device=device)[:TOPK] for _ in range(m)] - ) - w = torch.rand((m, TOPK), device=device) - w = w / w.sum(dim=1, keepdim=True) - if shared: - routed = torch.cat([routed, torch.full((m, 1), NUM_ROUTED, device=device)], 1) - w = torch.cat([w, torch.ones((m, 1), device=device)], dim=1) - return routed.to(torch.int32), w.to(torch.float32) - - -def _dequant(q: torch.Tensor, s: torch.Tensor, n_cols: int) -> torch.Tensor: - from aiter.utility import fp4_utils - - v = fp4_utils.mxfp4_to_f32(q.view(torch.uint8)).view(q.shape[0], -1) - sc = fp4_utils.e8m0_to_f32(s.view(torch.uint8)).view(q.shape[0], -1) - return (v.view(q.shape[0], -1, 32) * sc.unsqueeze(-1)).view(q.shape[0], n_cols) - - -_FP4_GRID = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0) - - -def _fp4_quant_dequant(h: torch.Tensor) -> torch.Tensor: - """Per-32 MXFP4 of fp32 rows: e8m0 scale ceil_pow2(amax / 6) (aiter's RoundUp, - computed on the f32 bits like the kernels), round-to-nearest-even onto e2m1.""" - g = h.view(*h.shape[:-1], -1, 32) - amax = g.abs().amax(-1, keepdim=True) - bits = (amax * torch.tensor(1.0 / 6.0, dtype=torch.float32)).view(torch.int32) - e = (bits >> 23) & 0xFF - e = e + (((bits & 0x7FFFFF) != 0) & (e < 255)).to(torch.int32) - scale = (e << 23).view(torch.float32) - v = (g / torch.where(scale > 0, scale, 1.0)).abs() - mids = torch.tensor([0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0], device=h.device) - idx = torch.bucketize(v, mids) # a tie goes to the lower code ... - idx = idx + ((v == 0.75) | (v == 1.75) | (v == 3.5)).to(idx.dtype) # ... or even - q = torch.tensor(_FP4_GRID, device=h.device)[idx] * g.sign() - return (q * scale).view_as(h) - - -def _float_reference(x, raw, topk_ids, topk_weights, tokens, same_operands): - """fp32 MoE on the dequantized experts. ``same_operands``: the kernel's x (the - per-token MXFP4 codes) and its intermediate rounding (bf16, then MXFP4); - otherwise bf16 x and no intermediate quant (the W4A4 error, cos ~0.98).""" - from vllm.models.minimax_m3.amd.ops.moe_mxfp4.prefill import mxfp4_quant - - w13_q, w13_s, w2_q, w2_s = raw - xs = x[tokens] - if same_operands: - xs = _dequant(*mxfp4_quant(xs, None, None), HIDDEN) - xs = xs.float() - deq = {} - out = torch.zeros((len(tokens), HIDDEN), dtype=torch.float32, device=x.device) - for i, t in enumerate(tokens): - for j in range(topk_ids.shape[1]): - e = int(topk_ids[t, j]) - if e not in deq: - deq[e] = ( - _dequant(w13_q[e], w13_s[e], HIDDEN), - _dequant(w2_q[e], w2_s[e], INTER), - ) - w13e, w2e = deq[e] - h = xs[i] @ w13e.T - g = h[:INTER].clamp(max=SWIGLU_LIMIT) - u = h[INTER:].clamp(-SWIGLU_LIMIT, SWIGLU_LIMIT) - a = g * torch.sigmoid(SWIGLU_ALPHA * g) * (u + 1.0) - if same_operands: - a = _fp4_quant_dequant(a.bfloat16().float()) - out[i] += float(topk_weights[t, j]) * (a @ w2e.T) - return out - - -def _cos(a: torch.Tensor, b: torch.Tensor) -> float: - a, b = a.float().flatten(), b.float().flatten() - return float((a @ b) / (a.norm() * b.norm() + 1e-12)) - - -@pytest.fixture(scope="module", params=[False, True], ids=["routed", "fused_shared"]) -def weights(request): - torch.manual_seed(0) - num_experts = NUM_ROUTED + int(request.param) - w13 = torch.randn( - (num_experts, 2 * INTER, HIDDEN), dtype=torch.bfloat16, device="cuda" - ) - w2 = torch.randn((num_experts, HIDDEN, INTER), dtype=torch.bfloat16, device="cuda") - raw, shuffled = _quantize_like_backend(w13 * 0.02, w2 * 0.02) - return request.param, raw, shuffled - - -def _run(shuffled, x, topk_ids, topk_weights): - from vllm.models.minimax_m3.amd.ops.moe_mxfp4.prefill import ( - a4w4_prefill_moe, - mxfp4_quant, - ) - - w13, w13_s, w2, w2_s = shuffled - return a4w4_prefill_moe( - mxfp4_quant(x, None, None), - w13, - w13_s, - w2, - w2_s, - topk_weights, - topk_ids, - hidden_size=HIDDEN, - intermediate_size=INTER, - num_experts=w13.shape[0], - ) - - -def _run_aiter(shuffled, x, topk_ids, topk_weights): - from aiter import ActivationType, QuantType - from aiter.fused_moe import fused_moe - from aiter.ops.flydsl.moe_common import GateMode - - w13, w13_s, w2, w2_s = shuffled - return fused_moe( - x, - w13, - w2, - topk_weights, - topk_ids, - quant_type=QuantType.per_1x32, - activation=ActivationType.Swiglu, - w1_scale=w13_s, - w2_scale=w2_s, - swiglu_limit=SWIGLU_LIMIT, - gate_mode=GateMode.SEPARATED.value, - ) - - -@pytest.mark.parametrize("m", [4096, 16384, 32768]) -def test_moe_mxfp4_prefill(weights, m): - """4096: 128-row sort blocks; 16384 and 32768: 256-row blocks.""" - from vllm.models.minimax_m3.amd.ops.moe_mxfp4.prefill import supports_shapes - - assert supports_shapes(HIDDEN, INTER) - shared, raw, shuffled = weights - torch.manual_seed(m) - x = torch.randn((m, HIDDEN), dtype=torch.bfloat16, device="cuda") - topk_ids, topk_weights = _routing(m, shared, x.device) - out = _run(shuffled, x, topk_ids, topk_weights) - out2 = _run(shuffled, x, topk_ids, topk_weights) - ref_aiter = _run_aiter(shuffled, x, topk_ids, topk_weights) - torch.cuda.synchronize() - assert out.shape == (m, HIDDEN) and out.dtype == torch.bfloat16 - assert torch.equal(out, out2) # no atomics: the same bits every call - tokens = torch.randperm(m, device=x.device)[:CHECK_TOKENS].tolist() - ref = _float_reference(x, raw, topk_ids, topk_weights, tokens, True) - ref_hp = _float_reference(x, raw, topk_ids, topk_weights, tokens, False) - cos, cos_hp = _cos(out[tokens], ref), _cos(out[tokens], ref_hp) - aiter_hp = _cos(ref_aiter[tokens], ref_hp) - print( - f"\nRESULT m={m} shared={shared}: cos vs same-operand ref {cos:.6f}, vs " - f"high-precision ref {cos_hp:.6f} (aiter {aiter_hp:.6f})" - ) - # the kernel computes what it should; W4A4 loses no more than aiter's path - assert cos > 0.9999 - assert cos_hp >= aiter_hp - 1e-3 diff --git a/tests/kernels/moe/test_minimax_m3_moe_prefill.py b/tests/kernels/moe/test_minimax_m3_moe_prefill.py deleted file mode 100644 index 7ed7207fa113..000000000000 --- a/tests/kernels/moe/test_minimax_m3_moe_prefill.py +++ /dev/null @@ -1,155 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""MiniMax-M3 FlyDSL MXFP8 MoE prefill chain vs aiter and a float reference, routed -only and with aiter's fused shared expert (expert 129, every token, weight 1).""" - -from types import SimpleNamespace - -import pytest -import torch - -from vllm.platforms import current_platform -from vllm.platforms.rocm import on_gfx950 - -pytestmark = [ - pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm only"), - pytest.mark.skipif(not on_gfx950(), reason="gfx950 only"), -] - -HIDDEN, INTER, NUM_ROUTED, TOPK = 6144, 768, 128, 4 -SWIGLU_ALPHA, SWIGLU_LIMIT = 1.702, 7.0 -CHECK_TOKENS = 64 - - -def _quantize(x: torch.Tensor): - """Aiter's per-1x32 MX quant.""" - from aiter import dtypes - from aiter.ops.quant import per_1x32_mx_quant_hip - - *lead, k = x.shape - q, s = per_1x32_mx_quant_hip( - x.reshape(-1, k), quant_dtype=dtypes.fp8, scale_type=dtypes.fp8_e8m0 - ) - return q.view(*lead, k), s.view(torch.uint8).view(*lead, k // 32) - - -def _dequant(q: torch.Tensor, s: torch.Tensor) -> torch.Tensor: - n, k = q.shape - sc = torch.ldexp(torch.ones_like(s, dtype=torch.float32), s.to(torch.int32) - 127) - return (q.float().view(n, k // 32, 32) * sc.unsqueeze(-1)).view(n, k) - - -@pytest.fixture( - scope="module", params=[NUM_ROUTED, NUM_ROUTED + 1], ids=["routed", "fse"] -) -def m3_weights(request): - from vllm.model_executor.layers.fused_moe.oracle.fp8 import ( - Fp8MoeBackend, - convert_to_fp8_moe_kernel_format, - ) - - torch.manual_seed(0) - device = torch.device("cuda") - e = request.param - w13 = torch.randn((e, 2 * INTER, HIDDEN), device=device) * 0.02 - w2 = torch.randn((e, HIDDEN, INTER), device=device) * 0.02 - raw = (*_quantize(w13.bfloat16()), *_quantize(w2.bfloat16())) - shuffled = convert_to_fp8_moe_kernel_format( - fp8_backend=Fp8MoeBackend.AITER_MXFP8, - layer=SimpleNamespace(weight_block_size=[1, 32]), - w13=raw[0], - w2=raw[2], - w13_scale=raw[1], - w2_scale=raw[3], - w13_input_scale=None, - w2_input_scale=None, - ) - return raw, shuffled - - -def _routing(m: int, device, shared: bool): - ids = torch.stack( - [torch.randperm(NUM_ROUTED, device=device)[:TOPK] for _ in range(m)] - ) - w = torch.rand((m, TOPK), device=device) - w = w / w.sum(dim=1, keepdim=True) * 2.0 - if shared: - ids = torch.cat([ids, torch.full((m, 1), NUM_ROUTED, device=device)], 1) - w = torch.cat([w, torch.ones((m, 1), device=device)], dim=1) - return ids.to(torch.int32).contiguous(), w.to(torch.float32).contiguous() - - -def _float_reference(x, raw, topk_ids, topk_weights, tokens): - w13_q, w13_s, w2_q, w2_s = raw - out = torch.zeros((len(tokens), HIDDEN), dtype=torch.float32, device=x.device) - for i, t in enumerate(tokens): - for j in range(topk_ids.shape[1]): - e = int(topk_ids[t, j]) - h = x[t].float() @ _dequant(w13_q[e], w13_s[e]).T - g = h[:INTER].clamp(max=SWIGLU_LIMIT) - u = h[INTER:].clamp(-SWIGLU_LIMIT, SWIGLU_LIMIT) - a = g * torch.sigmoid(SWIGLU_ALPHA * g) * (u + 1.0) - out[i] += float(topk_weights[t, j]) * (a @ _dequant(w2_q[e], w2_s[e]).T) - return out - - -def _cos(a: torch.Tensor, b: torch.Tensor) -> float: - a, b = a.float().flatten(), b.float().flatten() - return float((a @ b) / (a.norm() * b.norm() + 1e-12)) - - -@pytest.mark.parametrize("m", [4096, 16384, 32768]) -def test_prefill_matches_aiter(m3_weights, m): - """4096: 128-row gemm2 tiles; 16384: 256-row tiles; 32768: the large n-split.""" - from aiter import ActivationType, QuantType - from aiter.fused_moe import fused_moe - from aiter.ops.flydsl.moe_common import GateMode - - from vllm.models.minimax_m3.amd.ops.moe_mxfp8 import prefill - - raw, (w13, w2, w13_s, w2_s) = m3_weights - torch.manual_seed(m) - device = w13.device - num_experts = w13.shape[0] - x = torch.randn((m, HIDDEN), dtype=torch.bfloat16, device=device) - topk_ids, topk_weights = _routing(m, device, num_experts > NUM_ROUTED) - - def ours(): - return prefill.a8w8_prefill_moe( - _quantize(x), - w13, - w13_s, - w2, - w2_s, - topk_weights, - topk_ids, - hidden_size=HIDDEN, - intermediate_size=INTER, - num_experts=num_experts, - ) - - out, out2 = ours(), ours() - ref_aiter = fused_moe( - x, - w13, - w2, - topk_weights, - topk_ids, - activation=ActivationType.Swiglu, - quant_type=QuantType.per_1x32, - w1_scale=w13_s, - w2_scale=w2_s, - gate_mode=GateMode.INTERLEAVE.value, - swiglu_limit=SWIGLU_LIMIT, - ) - torch.accelerator.synchronize() - assert out.shape == (m, HIDDEN) and out.dtype == torch.bfloat16 - assert torch.equal(out, out2) # no atomics: the same bits every call - tokens = torch.randperm(m, device=device)[:CHECK_TOKENS].tolist() - ref = _float_reference(x, raw, topk_ids, topk_weights, tokens) - ours_t, theirs = out[tokens].float(), ref_aiter[tokens].float() - assert _cos(ours_t, ref) > 0.997 - assert _cos(ours_t, ref) >= _cos(theirs, ref) - 1e-3 - err_ours = (ours_t - ref).abs().max().item() - err_theirs = (theirs - ref).abs().max().item() - assert err_ours <= err_theirs * 1.1 + 1e-3, (err_ours, err_theirs) diff --git a/tests/kernels/test_minimax_m3_sp_coll.py b/tests/kernels/test_minimax_m3_sp_coll.py deleted file mode 100644 index bfa5919fd7d0..000000000000 --- a/tests/kernels/test_minimax_m3_sp_coll.py +++ /dev/null @@ -1,193 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""ops.sp_coll on four GPUs vs CPU references: gathers bitwise, reduce-scatter = -the fp32 rank-order sum; slot reuse, in-place inputs and the RCCL fallback.""" - -import pytest -import torch -import torch.distributed as dist -import torch.multiprocessing as mp - -from vllm.platforms import current_platform - -WORLD = 4 -HIDDEN = 1024 -ROWS = 256 # rows per rank - -pytestmark = pytest.mark.skipif( - not current_platform.is_rocm(), reason="FlyDSL kernel is ROCm-only" -) - - -class _NoRccl: - """Records the calls that fell back to RCCL.""" - - def __init__(self): - self.calls = [] - - def all_gather(self, outs, ins): - self.calls.append("all_gather") - for o, i in zip(outs, ins): - gathered = [torch.empty_like(i.cpu()) for _ in range(WORLD)] - dist.all_gather(gathered, i.cpu()) - exp = torch.cat(gathered) - o.view(exp.shape).copy_(exp.to(o.device)) - - def reduce_scatter(self, out, x): - raise AssertionError("unexpected fallback") - - def all_to_all(self, out, x): - raise AssertionError("unexpected fallback") - - -def _gather_cpu(x: torch.Tensor) -> list[torch.Tensor]: - xs = [torch.empty_like(x.cpu()) for _ in range(WORLD)] - dist.all_gather(xs, x.cpu().contiguous()) - return xs - - -def _worker(rank: int, init_file: str, errors): - try: - _run(rank, init_file) - except Exception as e: # noqa: BLE001 - errors.put(f"rank {rank}: {type(e).__name__}: {e}") - raise - - -def _run(rank: int, init_file: str): - torch.cuda.set_device(rank) - dev = torch.device("cuda", rank) - dist.init_process_group( - "gloo", init_method=f"file://{init_file}", rank=rank, world_size=WORLD - ) - from vllm.models.minimax_m3.amd.ops import sp_coll - - padded = ROWS * WORLD - q = 512 - # the largest phase: bf16 partials + two bf16 gathers (as sp_prefill sizes it) - slot = padded * HIDDEN * 2 + 2 * ROWS * HIDDEN * 2 + 4096 - pools = sp_coll.Pools(rank, WORLD, dist.group.WORLD, dev, slot, sets=3) - stream = torch.cuda.current_stream() - gen = torch.Generator().manual_seed(100 + rank) - - def rnd_u8(*shape): - return torch.randint(0, 256, shape, generator=gen, dtype=torch.uint8).to(dev) - - for phase in range(6): - set_id = phase % 3 # three slot sets - rccl = _NoRccl() - coll = sp_coll.Collectives(pools, set_id).bind(stream, rccl) - # attention phase: all-to-all, then gathers - send = rnd_u8(WORLD * ROWS, q + q // 32) - recv = torch.empty_like(send) - coll.all_to_all(recv, send) - codes = rnd_u8(ROWS, HIDDEN).view(torch.float8_e4m3fn) - scales = rnd_u8(ROWS, HIDDEN // 32) - routing = torch.randint( - -(2**31), 2**31 - 1, (ROWS, 18), generator=gen, dtype=torch.int32 - ).to(dev) - g_codes = torch.empty((padded, HIDDEN), dtype=codes.dtype, device=dev) - g_scales = torch.empty((padded, HIDDEN // 32), dtype=torch.uint8, device=dev) - g_routing = torch.empty((padded, 18), dtype=torch.int32, device=dev) - coll.all_gather([g_codes, g_scales, g_routing], [codes, scales, routing]) - torch.cuda.synchronize() - sends = _gather_cpu(send) - for p in range(WORLD): - exp = sends[p][rank * ROWS : (rank + 1) * ROWS] - assert torch.equal(recv[p * ROWS : (p + 1) * ROWS].cpu(), exp), (phase, p) - for g, x in ((g_codes, codes), (g_scales, scales), (g_routing, routing)): - if x.dtype != torch.int32: - g, x = g.view(torch.uint8), x.view(torch.uint8) - assert torch.equal(g.cpu(), torch.cat(_gather_cpu(x))), (phase, x.dtype) - assert rccl.calls == [] - # MoE phase: reduce-scatter, then gathers - coll = sp_coll.Collectives(pools, set_id).bind(stream, rccl) - part = torch.randn((padded, HIDDEN), generator=gen) * (1 + rank) - part = part.bfloat16().to(dev) - h = torch.empty((ROWS, HIDDEN), dtype=torch.bfloat16, device=dev) - coll.reduce_scatter(h, part) - aux = (torch.randn((ROWS, HIDDEN), generator=gen)).bfloat16().to(dev) - ctx = (torch.randn((ROWS, HIDDEN), generator=gen)).bfloat16().to(dev) - g_aux = torch.empty((padded, HIDDEN), dtype=torch.bfloat16, device=dev) - g_ctx = torch.empty((padded, HIDDEN), dtype=torch.bfloat16, device=dev) - coll.all_gather([g_aux, g_ctx], [aux, ctx]) - torch.cuda.synchronize() - parts = _gather_cpu(part) - acc = torch.zeros((ROWS, HIDDEN), dtype=torch.float32) - for p in range(WORLD): - acc += parts[p][rank * ROWS : (rank + 1) * ROWS].float() - assert torch.equal(h.cpu(), acc.bfloat16()), phase - assert torch.equal(g_aux.cpu(), torch.cat(_gather_cpu(aux))), phase - assert torch.equal(g_ctx.cpu(), torch.cat(_gather_cpu(ctx))), phase - assert rccl.calls == [] - # slot views from alloc are read in place - rccl = _NoRccl() - coll = sp_coll.Collectives(pools, 1) - send = coll.alloc((WORLD * ROWS, q + q // 32), torch.uint8) - send.copy_(rnd_u8(WORLD * ROWS, q + q // 32)) - recv = torch.empty((WORLD * ROWS, q + q // 32), dtype=torch.uint8, device=dev) - coll.bind(stream, rccl).all_to_all(recv, send) - coll = sp_coll.Collectives(pools, 1) - part = coll.alloc((padded, HIDDEN), torch.bfloat16) - part.copy_((torch.randn((padded, HIDDEN), generator=gen) * 3).bfloat16()) - h = torch.empty((ROWS, HIDDEN), dtype=torch.bfloat16, device=dev) - coll.bind(stream, rccl).reduce_scatter(h, part) - torch.cuda.synchronize() - sends, parts = _gather_cpu(send), _gather_cpu(part) - for p in range(WORLD): - exp = sends[p][rank * ROWS : (rank + 1) * ROWS] - assert torch.equal(recv[p * ROWS : (p + 1) * ROWS].cpu(), exp), p - acc = torch.zeros((ROWS, HIDDEN), dtype=torch.float32) - for p in range(WORLD): - acc += parts[p][rank * ROWS : (rank + 1) * ROWS].float() - assert torch.equal(h.cpu(), acc.bfloat16()) - assert rccl.calls == [] - # all_to_all_unpack = all_to_all + mxfp8_unpack - from vllm.models.minimax_m3.amd.ops.sp_pack import mxfp8_unpack - - rccl = _NoRccl() - coll = sp_coll.Collectives(pools, 0).bind(stream, rccl) - send = rnd_u8(WORLD * ROWS, q + q // 32) - recv = torch.empty_like(send) - coll.all_to_all(recv, send) - coll = sp_coll.Collectives(pools, 0).bind(stream, rccl) - codes, scales = coll.all_to_all_unpack(send, q) - torch.cuda.synchronize() - ref_codes, ref_scales = mxfp8_unpack(recv, WORLD, ROWS, q) - assert torch.equal(codes.view(torch.uint8), ref_codes.view(torch.uint8)) - assert torch.equal(scales, ref_scales) - assert rccl.calls == [] - # a phase that does not fit the slot falls back to RCCL - rccl = _NoRccl() - coll = sp_coll.Collectives(pools, 0).bind(stream, rccl) - big = rnd_u8(4 * padded, HIDDEN) - g_big = torch.empty((WORLD, 4 * padded, HIDDEN), dtype=torch.uint8, device=dev) - coll.all_gather([g_big], [big]) - torch.cuda.synchronize() - assert rccl.calls == ["all_gather"] - assert torch.equal(g_big.view(-1, HIDDEN).cpu(), torch.cat(_gather_cpu(big))) - dist.barrier() - dist.destroy_process_group() - - -def test_sp_coll_four_gpus(tmp_path): - if torch.cuda.device_count() < WORLD: - pytest.skip("needs four GPUs") - from vllm.platforms.rocm import on_gfx950 - - if not on_gfx950(): - pytest.skip("the kernels use gfx950 instructions") - ctx = mp.get_context("spawn") - errors = ctx.Queue() - init_file = str(tmp_path / "init") - procs = [ - ctx.Process(target=_worker, args=(r, init_file, errors)) for r in range(WORLD) - ] - for p in procs: - p.start() - for p in procs: - p.join(timeout=600) - msgs = [] - while not errors.empty(): - msgs.append(errors.get()) - assert all(p.exitcode == 0 for p in procs), msgs or [p.exitcode for p in procs] diff --git a/tests/kernels/test_minimax_m3_sp_prefill_kernels.py b/tests/kernels/test_minimax_m3_sp_prefill_kernels.py deleted file mode 100644 index bd1b5121dd06..000000000000 --- a/tests/kernels/test_minimax_m3_sp_prefill_kernels.py +++ /dev/null @@ -1,97 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""MiniMax-M3 sequence-parallel prefill kernels, bit for bit against the kernels -they replace.""" - -import pytest -import torch - -from vllm.platforms import current_platform - -if not current_platform.is_rocm(): - pytest.skip("ROCm sequence-parallel prefill kernels", allow_module_level=True) - -from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( # noqa: E402 - _mxfp8_e4m3_quantize_triton, -) -from vllm.models.minimax_m3.amd.ops.gemma_rmsnorm import ( # noqa: E402 - gemma_fused_add_rmsnorm, - gemma_rmsnorm, -) -from vllm.models.minimax_m3.amd.ops.sp_norm_quant import ( # noqa: E402 - MOE_MIN_SCALE_BYTE, - gemma_rmsnorm_mx, -) -from vllm.models.minimax_m3.amd.ops.sp_pack import ( # noqa: E402 - mxfp8_quant_pack, - mxfp8_unpack, -) - - -def _rows(m: int, n: int, seed: int) -> torch.Tensor: - g = torch.Generator(device="cuda").manual_seed(seed) - x = torch.randn(m, n, device="cuda", generator=g) - x = x * torch.rand(m, 1, device="cuda", generator=g) * 40 - x[1] = 0 # an all-zero row: the scale floor - x[2, :32] = 2.0**-36 # a tiny block - x[3, :64] = 3e4 # a large block - return x.to(torch.bfloat16) - - -@pytest.mark.parametrize("rows", [64, 1032]) -@pytest.mark.parametrize("world", [4]) -def test_quant_pack_unpack(rows: int, world: int): - d = 2048 - x = _rows(world * rows, d, 0) - codes, scales = _mxfp8_e4m3_quantize_triton(x) - packed = mxfp8_quant_pack(x) - assert torch.equal(packed[:, :d], codes.view(torch.uint8)) - assert torch.equal(packed[:, d:], scales) - got_codes, got_scales = mxfp8_unpack(packed, world, rows, d) - blocks = packed.view(world, rows, -1).transpose(0, 1) - assert torch.equal(got_codes.view(torch.uint8), blocks[:, :, :d].reshape(rows, -1)) - assert torch.equal(got_scales, blocks[:, :, d:].reshape(rows, -1)) - - -@pytest.mark.parametrize("rows", [7, 2048]) -@pytest.mark.parametrize("with_residual", [False, True]) -@pytest.mark.parametrize("moe", [False, True]) -def test_rmsnorm_mx(rows: int, with_residual: bool, moe: bool): - """The linear input = gemma norm + ``mxfp8_e4m3_quantize``; the MoE input = - gemma norm + aiter's ``per_1x32_mx_quant`` (the AITER MXFP8 MoE's quant).""" - hidden = 6144 - x = _rows(rows, hidden, 1) - residual = _rows(rows, hidden, 2) * 4 if with_residual else None - weight = torch.randn(hidden, device="cuda") * 0.3 - if residual is None: - norm_ref, res_ref = gemma_rmsnorm(x, weight, 1e-6), x - else: - norm_ref, res_ref = gemma_fused_add_rmsnorm(x, residual, weight, 1e-6) - if moe: - from aiter import dtypes - from aiter.ops.quant import per_1x32_mx_quant_hip - - q_ref, s_ref = per_1x32_mx_quant_hip( - norm_ref, - scale=None, - quant_dtype=dtypes.fp8, - scale_type=dtypes.fp8_e8m0, - shuffle=False, - ) - else: - q_ref, s_ref = _mxfp8_e4m3_quantize_triton(norm_ref) - norm, res, q, s = gemma_rmsnorm_mx( - x, - residual, - weight, - 1e-6, - min_scale_byte=MOE_MIN_SCALE_BYTE if moe else 0, - store_out=moe, - ) - if moe: - assert torch.equal(norm, norm_ref) - else: - assert norm is None - assert torch.equal(res, res_ref) - assert torch.equal(q.view(torch.uint8), q_ref.view(torch.uint8)) - assert torch.equal(s, s_ref.view(torch.uint8)) diff --git a/tests/v1/worker/test_dbo_pure_tp.py b/tests/v1/worker/test_dbo_pure_tp.py deleted file mode 100644 index ae3fb50d2387..000000000000 --- a/tests/v1/worker/test_dbo_pure_tp.py +++ /dev/null @@ -1,186 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""DBO under pure tensor parallelism (one DP rank, no EP), without GPUs.""" - -import threading -from types import SimpleNamespace - -import pytest -import torch - -import vllm.distributed.parallel_state as parallel_state -import vllm.v1.worker.ubatching as ubatching -import vllm.v1.worker.workspace as workspace -from vllm.config import CUDAGraphMode, ParallelConfig, VllmConfig -from vllm.sequence import IntermediateTensors -from vllm.v1.worker.gpu.dp_utils import dispatch_cg_and_sync_dp -from vllm.v1.worker.gpu.ubatch_utils import merge_ubatch_outputs - - -def test_merge_tensors_concatenates_along_tokens(): - a, b = torch.arange(6.0).view(3, 2), torch.arange(6.0, 10.0).view(2, 2) - assert torch.equal(merge_ubatch_outputs([a, b]), torch.cat([a, b])) - - -def test_merge_recurses_into_tuples_and_lists(): - # EAGLE3 returns (hidden, aux); DSpark returns (hidden, [aux, ...]). - h = [torch.full((2, 4), float(i)) for i in range(2)] - aux = [ - [torch.full((2, 3), 10.0 + i), torch.full((2, 5), 20.0 + i)] for i in range(2) - ] - merged = merge_ubatch_outputs([(h[0], aux[0]), (h[1], aux[1])]) - assert isinstance(merged, tuple) and isinstance(merged[1], list) - assert torch.equal(merged[0], torch.cat(h)) - assert torch.equal(merged[1][0], torch.cat([aux[0][0], aux[1][0]])) - assert torch.equal(merged[1][1], torch.cat([aux[0][1], aux[1][1]])) - - -def test_merge_keeps_none_and_intermediate_tensors(): - assert merge_ubatch_outputs([None, None]) is None - parts = [ - IntermediateTensors({"hidden_states": torch.ones(2, 4) * i}) for i in range(2) - ] - merged = merge_ubatch_outputs(parts) - assert merged["hidden_states"].shape == (4, 4) - - -def _parallel_config(tp=4, dp=1, ep=False): - return ParallelConfig( - tensor_parallel_size=tp, - data_parallel_size=dp, - enable_expert_parallel=ep, - enable_dbo=True, - ) - - -@pytest.mark.parametrize( - ("tp", "dp", "ep", "tp_only"), - [ - (4, 1, False, True), - (4, 2, False, False), - (4, 1, True, False), - (1, 1, False, False), - ], -) -def test_dbo_tp_only(tp, dp, ep, tp_only): - assert _parallel_config(tp, dp, ep).dbo_tp_only is tp_only - assert not ParallelConfig(tensor_parallel_size=tp).dbo_tp_only # DBO off - - -def _config(tp=4, dp=1, ep=False, spec=False, mm=False, enc_dec=False): - return SimpleNamespace( - model_config=SimpleNamespace( - is_multimodal_model=mm, is_encoder_decoder=enc_dec, is_hybrid=False - ), - parallel_config=_parallel_config(tp, dp, ep), - lora_config=None, - speculative_config=object() if spec else None, - compilation_config=SimpleNamespace(cudagraph_mode=CUDAGraphMode.FULL), - is_mm_encoder_only=False, - ) - - -@pytest.mark.parametrize( - ("kwargs", "rejected"), - [ - # pure TP: the drafter and the vision encoder run outside the split - (dict(spec=True), None), - (dict(mm=True), None), - (dict(spec=True, mm=True), None), - # anything that is not pure TP keeps the old restrictions - (dict(spec=True, dp=2), "speculative decoding"), - (dict(spec=True, ep=True), "speculative decoding"), - (dict(spec=True, tp=1), "speculative decoding"), - (dict(mm=True, dp=2), "multimodal"), - # encoder-decoder models stay out under pure TP too - (dict(enc_dec=True), "multimodal"), - ], -) -def test_dbo_unsupported_features(monkeypatch, kwargs, rejected): - monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1") - unsupported = VllmConfig._get_dbo_unsupported_features(_config(**kwargs)) - if rejected is None: - assert unsupported == [] - else: - assert any(rejected in u for u in unsupported), unsupported - - -def _parallel(threshold_prefill=8192, threshold_decode=32768): - return SimpleNamespace( - use_ubatching=True, - num_ubatches=2, - dbo_prefill_token_threshold=threshold_prefill, - dbo_decode_token_threshold=threshold_decode, - ) - - -@pytest.mark.parametrize( - ("num_tokens", "uniform_decode", "allow", "expected_ubatches"), - [ - (16384, False, True, 2), # prefill above its threshold: split - (4096, False, True, 1), # below: whole - (16384, True, True, 1), # a decode step uses the decode threshold - (16384, False, False, 1), # the caller did not allow a split - ], -) -def test_single_dp_rank_splits_on_its_own( - num_tokens, uniform_decode, allow, expected_ubatches -): - desc, sync = dispatch_cg_and_sync_dp( - None, - num_reqs=2, - num_tokens=num_tokens, - uniform_token_count=None, - dp_size=1, - dp_rank=0, - need_eager=True, - parallel_config=_parallel(), - allow_ubatching=allow, - uniform_decode=uniform_decode, - ) - assert sync is None - assert desc.num_ubatches == expected_ubatches - if expected_ubatches > 1: - # a split step runs eager - assert desc.cg_mode == CUDAGraphMode.NONE - - -@pytest.mark.parametrize(("num_ubatches", "expected"), [(1, 0), (2, 1)]) -def test_workspace_id_shared_across_microbatches(monkeypatch, num_ubatches, expected): - # TP-only DBO on the V2 runner keeps one workspace set. - monkeypatch.setattr(workspace, "dbo_current_ubatch_id", lambda: 1) - manager = workspace.WorkspaceManager( - torch.device("cpu"), num_ubatches=num_ubatches, num_lanes=1 - ) - assert manager._get_workspace_id() == expected - - -@pytest.mark.parametrize( - "kwargs", - [dict(dp=2), dict(ep=True), dict(dbo=False)], -) -def test_hook_not_installed_outside_pure_tp_dbo(monkeypatch, kwargs): - monkeypatch.setattr(parallel_state, "_dbo_tp_all_reduce_hook", None) - monkeypatch.setattr(ubatching, "_TP_UBATCH_COMMS", None) - dbo = kwargs.pop("dbo", True) - pc = _parallel_config(**kwargs) if dbo else ParallelConfig(tensor_parallel_size=4) - ubatching.init_dbo_tp_comms(pc) - assert parallel_state._dbo_tp_all_reduce_hook is None - assert ubatching._TP_UBATCH_COMMS is None - - -def test_hook_is_inert_outside_a_microbatch(monkeypatch): - # Outside a microbatch thread or for a non-TP group the hook returns None. - monkeypatch.setattr(ubatching, "_THREAD_ID_TO_CONTEXT", {}) - assert ubatching._dbo_tp_all_reduce(object(), torch.ones(2)) is None - monkeypatch.setattr(ubatching, "_THREAD_ID_TO_CONTEXT", {threading.get_ident(): 0}) - monkeypatch.setattr(parallel_state, "_TP", object()) - assert ubatching._dbo_tp_all_reduce(object(), torch.ones(2)) is None - - -@pytest.mark.parametrize(("rocm", "priority"), [(True, -1), (False, 0)]) -def test_comm_stream_priority(monkeypatch, rocm, priority): - from vllm.platforms import current_platform - - monkeypatch.setattr(current_platform, "is_rocm", lambda: rocm) - assert ubatching.dbo_comm_stream_priority() == priority diff --git a/vllm/config/parallel.py b/vllm/config/parallel.py index 7f8deb57a972..f51a35c5c4a9 100644 --- a/vllm/config/parallel.py +++ b/vllm/config/parallel.py @@ -649,16 +649,6 @@ def use_ubatching(self) -> bool: def num_ubatches(self) -> int: return 2 if self.enable_dbo else self.ubatch_size - @property - def dbo_tp_only(self) -> bool: - """DBO with one DP rank and no EP: microbatches overlap TP all-reduces.""" - return ( - self.use_ubatching - and self.data_parallel_size == 1 - and not self.enable_expert_parallel - and self.tensor_parallel_size > 1 - ) - @property def local_engines_only(self) -> bool: """Client manages local+remote EngineCores in pure internal LB case. diff --git a/vllm/config/vllm.py b/vllm/config/vllm.py index 8013ee18392b..bbeb12c20cba 100644 --- a/vllm/config/vllm.py +++ b/vllm/config/vllm.py @@ -2178,7 +2178,7 @@ def has_blocked_weights(): f"cudagraph_mode={self.compilation_config.cudagraph_mode}" ) - if self.parallel_config.use_ubatching and not self.parallel_config.dbo_tp_only: + if self.parallel_config.use_ubatching: a2a_backend = self.parallel_config.all2all_backend if current_platform.is_rocm(): supported_backends = [ @@ -3237,10 +3237,9 @@ def _get_dbo_unsupported_features(self) -> list[str]: model_config = self.model_config parallel_config = self.parallel_config - tp_only_dbo = parallel_config.dbo_tp_only if self.lora_config is not None: unsupported.append("dual batch overlap with LoRA") - if self.speculative_config is not None and not tp_only_dbo: + if self.speculative_config is not None: unsupported.append("dual batch overlap with speculative decoding") if parallel_config.pipeline_parallel_size > 1: unsupported.append("dual batch overlap with pipeline parallelism") @@ -3250,8 +3249,7 @@ def _get_dbo_unsupported_features(self) -> list[str]: ): unsupported.append("dual batch overlap with context parallelism") if model_config is not None and ( - (model_config.is_multimodal_model and not tp_only_dbo) - or model_config.is_encoder_decoder + model_config.is_multimodal_model or model_config.is_encoder_decoder ): unsupported.append("dual batch overlap with multimodal models") if model_config is not None and model_config.is_hybrid: diff --git a/vllm/distributed/parallel_state.py b/vllm/distributed/parallel_state.py index f58e5fa39516..897518247f13 100644 --- a/vllm/distributed/parallel_state.py +++ b/vllm/distributed/parallel_state.py @@ -747,11 +747,6 @@ def all_reduce(self, input_: torch.Tensor) -> torch.Tensor: return self._all_reduce_out_place(input_) def _all_reduce_out_place(self, input_: torch.Tensor) -> torch.Tensor: - # Under the vllm.all_reduce custom op, so compiled graphs reach it too. - if _dbo_tp_all_reduce_hook is not None and not torch.compiler.is_compiling(): - out = _dbo_tp_all_reduce_hook(self, input_) - if out is not None: - return out if self.device_communicator is None: raise ValueError("No device communicator found") return self.device_communicator.all_reduce(input_) @@ -1593,16 +1588,6 @@ def _replace_active_groups( return old_groups -# Set by vllm.v1.worker.ubatching.init_dbo_tp_comms. -_DboTpAllReduceHook = Callable[[GroupCoordinator, torch.Tensor], torch.Tensor | None] -_dbo_tp_all_reduce_hook: _DboTpAllReduceHook | None = None - - -def set_dbo_tp_all_reduce_hook(hook: _DboTpAllReduceHook | None) -> None: - global _dbo_tp_all_reduce_hook - _dbo_tp_all_reduce_hook = hook - - _TP: GroupCoordinator | None = None diff --git a/vllm/envs.py b/vllm/envs.py index 0cd5ea8db560..a7bde6b336fa 100755 --- a/vllm/envs.py +++ b/vllm/envs.py @@ -160,7 +160,6 @@ VLLM_ROCM_FP8_PADDING: bool = True VLLM_ROCM_MOE_PADDING: bool = True VLLM_ROCM_SHUFFLE_KV_CACHE_LAYOUT: bool = False - VLLM_ROCM_MINIMAX_M3_SP_PREFILL: bool = False VLLM_ENABLE_V1_MULTIPROCESSING: bool = True VLLM_LOG_BATCHSIZE_INTERVAL: float = -1 VLLM_DISABLE_COMPILE_CACHE: bool = False @@ -1407,11 +1406,6 @@ def _resolve_rust_cli_path() -> str | None: "VLLM_ROCM_SHUFFLE_KV_CACHE_LAYOUT": lambda: ( os.getenv("VLLM_ROCM_SHUFFLE_KV_CACHE_LAYOUT", "False").lower() in ("true", "1") ), - # MiniMax-M3 sequence-parallel prefill under pure TP (TP4, gfx950). - # By default is disabled. - "VLLM_ROCM_MINIMAX_M3_SP_PREFILL": lambda: ( - os.getenv("VLLM_ROCM_MINIMAX_M3_SP_PREFILL", "False").lower() in ("true", "1") - ), # Custom quick allreduce kernel for MI3* cards # Choice of quantization level: FP, INT8, INT6, INT4, INT3 or NONE # Recommended for large models to get allreduce diff --git a/vllm/model_executor/kernels/linear/mxfp8/rocm_native.py b/vllm/model_executor/kernels/linear/mxfp8/rocm_native.py index 7ee4944783fd..7b601c804f9f 100644 --- a/vllm/model_executor/kernels/linear/mxfp8/rocm_native.py +++ b/vllm/model_executor/kernels/linear/mxfp8/rocm_native.py @@ -87,20 +87,10 @@ def _mxfp8_dot_scaled_linear( w: torch.Tensor, # [N, K] fp8 e4m3 w_scale: torch.Tensor, # [N, K//32] uint8 (E8M0) ) -> torch.Tensor: - x_q, x_scale = mxfp8_e4m3_quantize(x) - return _mxfp8_dot_scaled_gemm(x_q, x_scale, w, w_scale, x.dtype) - - -def _mxfp8_dot_scaled_gemm( - x_q: torch.Tensor, # [M, K] fp8 e4m3 - x_scale: torch.Tensor, # [M, K//32] uint8 (E8M0) - w: torch.Tensor, - w_scale: torch.Tensor, - out_dtype: torch.dtype, -) -> torch.Tensor: - M, K = x_q.shape + M, K = x.shape N = w.shape[0] - out = torch.empty((M, N), dtype=out_dtype, device=x_q.device) + x_q, x_scale = mxfp8_e4m3_quantize(x) + out = torch.empty((M, N), dtype=x.dtype, device=x.device) BLOCK_M, BLOCK_N, BLOCK_K, num_warps, num_stages = _select_cfg(M, N, K) grid = (triton.cdiv(M, BLOCK_M), triton.cdiv(N, BLOCK_N)) _mxfp8_linear_kernel[grid]( @@ -278,30 +268,6 @@ def process_weights_after_loading(self, layer: torch.nn.Module) -> None: replace_parameter(layer, "weight", weight.contiguous()) replace_parameter(layer, "weight_scale", weight_scale) - @staticmethod - def supports_quantized_input(layer: torch.nn.Module) -> bool: - """Whether ``apply_quantized`` serves ``layer`` (fp8 weights).""" - return layer.weight.element_size() == 1 and ( - layer.weight_scale.shape[0] != layer.weight.shape[0] - or layer.weight.shape[1] % _DOT_SCALED_K_ALIGN == 0 - ) - - def apply_quantized( - self, - layer: torch.nn.Module, - x_q: torch.Tensor, - x_scale: torch.Tensor, - out_dtype: torch.dtype, - ) -> torch.Tensor: - """``apply_weights`` on ``mxfp8_e4m3_quantize``'s fp8 + e8m0 output.""" - if layer.weight_scale.shape[0] != layer.weight.shape[0]: - return rocm_mxfp8_block32_gemm( - x_q, x_scale, layer.weight, layer.weight_scale, out_dtype - ) - return _mxfp8_dot_scaled_gemm( - x_q, x_scale, layer.weight, layer.weight_scale, out_dtype - ) - def apply_weights( self, layer: torch.nn.Module, diff --git a/vllm/model_executor/layers/fused_allreduce_gemma_rms_norm.py b/vllm/model_executor/layers/fused_allreduce_gemma_rms_norm.py index 7abad9cae919..7046bfc991b9 100644 --- a/vllm/model_executor/layers/fused_allreduce_gemma_rms_norm.py +++ b/vllm/model_executor/layers/fused_allreduce_gemma_rms_norm.py @@ -24,7 +24,6 @@ ) from vllm.model_executor.layers.layernorm import GemmaRMSNorm from vllm.platforms import current_platform -from vllm.v1.worker.ubatching import dbo_enabled MiB = 1024 * 1024 @@ -154,9 +153,8 @@ def fused_allreduce_gemma_rms_norm( # No all-reduce needed; identical to the unfused path. return norm(hidden_states, residual) - # Under DBO every all-reduce must reach the microbatch hand-off hook. ok, max_token_num = _can_use_flashinfer(hidden_states, tp_size) - if ok and not dbo_enabled(): + if ok: norm_out = torch.empty_like(hidden_states) # With norm_out provided, the kernel writes the new residual # (all_reduce(hidden_states) + residual) into the hidden_states buffer @@ -176,7 +174,7 @@ def fused_allreduce_gemma_rms_norm( ) return norm_out, hidden_states - if not dbo_enabled() and _can_use_aiter_fused_ar_rms(hidden_states): + if _can_use_aiter_fused_ar_rms(hidden_states): from vllm._aiter_ops import rocm_aiter_ops return rocm_aiter_ops.get_fused_allreduce_rmsnorm_op()( diff --git a/vllm/model_executor/layers/fused_moe/prepare_finalize/no_dp_ep.py b/vllm/model_executor/layers/fused_moe/prepare_finalize/no_dp_ep.py index f63bb843d5fd..fe5d518cf337 100644 --- a/vllm/model_executor/layers/fused_moe/prepare_finalize/no_dp_ep.py +++ b/vllm/model_executor/layers/fused_moe/prepare_finalize/no_dp_ep.py @@ -39,10 +39,6 @@ def _quantize_input( class MoEPrepareAndFinalizeNoDPEPModular(mk.FusedMoEPrepareAndFinalizeModular): - def supports_dbo(self) -> bool: - # No all2all: the DBO hand-offs are the TP all-reduces. - return True - def supports_deferred_moe_finalize(self) -> bool: # finalize() here is the top-k weight-and-reduce and nothing else, # which is exactly the work a deferring consumer takes over. diff --git a/vllm/models/minimax_m3/amd/model.py b/vllm/models/minimax_m3/amd/model.py index 63c8b42ed2b0..129987c31cfc 100644 --- a/vllm/models/minimax_m3/amd/model.py +++ b/vllm/models/minimax_m3/amd/model.py @@ -88,7 +88,6 @@ spec_decode_needs_target_embed, ) from vllm.model_executor.models.vision import run_dp_sharded_mrope_vision_model -from vllm.models.minimax_m3.amd import sp_prefill from vllm.models.minimax_m3.amd.indexer_msa import ( MiniMaxM3IndexerMSAImpl, MiniMaxM3MSAIndexer, @@ -594,11 +593,6 @@ def forward( hidden_states: torch.Tensor, ) -> torch.Tensor: qkv, _ = self.qkv_proj(hidden_states) - output, _ = self.o_proj(self.attend(positions, qkv)) - return output - - def attend(self, positions: torch.Tensor, qkv: torch.Tensor) -> torch.Tensor: - """The attention of this rank's heads, before o_proj.""" if _USE_GFX942_NATIVE_QKNORM_ROPE: num_tokens = qkv.shape[0] q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1) @@ -608,7 +602,9 @@ def attend(self, positions: torch.Tensor, qkv: torch.Tensor) -> torch.Tensor: assert k is not None q = q.reshape(num_tokens, self.q_size) k = k.reshape(num_tokens, self.kv_size) - return self.attn(q, k, v) + attn_output = self.attn(q, k, v) + output, _ = self.o_proj(attn_output) + return output # Fused per-head Gemma QK-norm + partial NeoX RoPE on q/k, in place (dense # mode: no index branch, no KV-cache insert). Matches nvidia/model.py and @@ -627,7 +623,9 @@ def attend(self, positions: torch.Tensor, qkv: torch.Tensor) -> torch.Tensor: kv_cache_dtype="auto", ) q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1) - return self.attn(q, k, v) + attn_output = self.attn(q, k, v) + output, _ = self.o_proj(attn_output) + return output # Widest row pitch aiter's reshape_and_cache can carry in its `int` stride args. @@ -1141,11 +1139,7 @@ def forward( ) -> torch.Tensor: # Single fused projection emitting [q | k | v | index_q | index_k]. qkv, _ = self.qkv_proj(hidden_states) - output, _ = self.o_proj(self.attend(positions, qkv)) - return output - def attend(self, positions: torch.Tensor, qkv: torch.Tensor) -> torch.Tensor: - """The attention of this rank's heads, before o_proj.""" # Horizontally-fused per-head Gemma QK-norm + partial NeoX RoPE on the # main (q/k) and index (index_q/index_k) branches, all read straight out # of the single fused ``qkv`` tensor. Once the paged caches are bound the @@ -1165,14 +1159,16 @@ def attend(self, positions: torch.Tensor, qkv: torch.Tensor) -> torch.Tensor: or self.layer_name not in fwd_slot_mapping ): # Memory-profiling run: caches not yet bound, slot_mapping is empty. - return qkv.new_zeros((num_tokens, self.q_size)) + return qkv.new_zeros((num_tokens, self.hidden_size)) if _USE_GFX942_NATIVE_QKNORM_ROPE: q, index_q = self._native_gfx942_qknorm_rope_cache( qkv, positions, fwd_slot_mapping ) output = torch.empty_like(q) - return self._run_attention(q, index_q, output) + attn_output = self._run_attention(q, index_q, output) + output, _ = self.o_proj(attn_output) + return output main_slot_mapping = fwd_slot_mapping[self.layer_name] if self.use_nvfp4_kv: @@ -1183,9 +1179,11 @@ def attend(self, positions: torch.Tensor, qkv: torch.Tensor) -> torch.Tensor: fwd_slot_mapping[self.indexer.index_cache.prefix], ) output = torch.empty_like(q) - return self._run_attention( + attn_output = self._run_attention( q, None if self.skip_index_topk else index_q, output ) + output, _ = self.o_proj(attn_output) + return output q = qkv.new_empty((num_tokens, self.q_size)) key_cache = value_cache = page16_slot_mapping = None k_scale = v_scale = None @@ -1381,7 +1379,9 @@ def attend(self, positions: torch.Tensor, qkv: torch.Tensor) -> torch.Tensor: ) output = torch.empty_like(q) - return self._run_attention(q, index_q, output) + attn_output = self._run_attention(q, index_q, output) + output, _ = self.o_proj(attn_output) + return output @eager_break_during_capture def _run_attention( @@ -1533,9 +1533,6 @@ def __init__( self.post_attention_layernorm = MiniMAXGemmaRMSNorm( config.hidden_size, eps=config.rms_norm_eps ) - self.self_attn.o_proj_full = sp_prefill.make_o_proj_full( - self, quant_config, prefix - ) def forward( self, @@ -1752,11 +1749,6 @@ def forward( self._maybe_add_hidden_state( aux_hidden_states, self.start_layer, hidden_states, residual ) - sp = sp_prefill.plan_model(self, hidden_states) - if sp is not None: - return sp_prefill.forward( - self, positions, hidden_states, aux_hidden_states, sp - ) layers = self.layers[self.start_layer : self.end_layer] if decode is None: for idx, layer in enumerate(layers, start=self.start_layer): @@ -1916,12 +1908,6 @@ def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: param, "weight_loader", default_weight_loader ) weight_loader(param, loaded_weight) - # the sequence-parallel prefill's whole o_proj - full = name.replace(".self_attn.o_proj.", ".self_attn.o_proj_full.") - if full != name and full in params_dict: - param = params_dict[full] - param.weight_loader(param, loaded_weight) - loaded_params.add(full) loaded_params.add(name) return loaded_params diff --git a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/__init__.py b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/__init__.py deleted file mode 100644 index eebdf8490751..000000000000 --- a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""Routing, launch and memory helpers for MiniMax-M3 FlyDSL MoE kernels.""" diff --git a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/epilogue.py b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/epilogue.py deleted file mode 100644 index c10b2f0dbbb6..000000000000 --- a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/epilogue.py +++ /dev/null @@ -1,72 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""MiniMax-M3 FlyDSL MoE epilogue helpers.""" - -import flydsl.expr as fx -from flydsl._mlir import ir as _ir -from flydsl._mlir.dialects import arith as _arith -from flydsl._mlir.dialects import llvm as _llvm -from flydsl.expr.typing import T as _T -from flydsl.expr.typing import Vector as Vec - -from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.loaders import _lds_ptr_t - -_NUM_XCDS = 8 - - -def _lds_ptr(addr_i32): - return _llvm.inttoptr(_lds_ptr_t(), fx.as_ir_value(addr_i32)) - - -def _lds_load_vec(addr_i32, n): - ty = _ir.VectorType.get([n], _T.i32) - return _llvm.LoadOp(ty, _lds_ptr(addr_i32), alignment=4 * n).result - - -def _lds_store_vec(vec, addr_i32, n): - _llvm.StoreOp(vec, _lds_ptr(addr_i32), alignment=4 * n) - - -def _bf16x2(a, b): - """Two f32 -> one i32 of 2 bf16 (RNE, v_cvt_pk_bf16_f32).""" - return Vec.from_elements([a, b], fx.Float32).to(fx.BFloat16).bitcast(fx.Int32)[0] - - -def _cvt_pk_fp8(old, a, b, scale_f32, hi: bool): - """(a, b) / scale -> 2 x e4m3 into the low or high (``hi``) 16 bits of ``old``.""" - v2i16 = _ir.VectorType.get([2], _ir.IntegerType.get_signless(16)) - old_v = _llvm.bitcast(v2i16, fx.as_ir_value(old)) - res = _llvm.call_intrinsic( - v2i16, - "llvm.amdgcn.cvt.scalef32.pk.fp8.f32", - [ - old_v, - fx.as_ir_value(a), - fx.as_ir_value(b), - fx.as_ir_value(scale_f32), - fx.Boolean(hi).ir_value(), - ], - [], - [], - ) - return fx.Int32(_llvm.bitcast(_T.i32, res)) - - -def _maxf_nn(a, b): - """Max with nnan: else LLVM canonicalizes both inputs first (2 extra VALU).""" - fm = _ir.Attribute.parse("#arith.fastmath") - return fx.Float32( - _arith.MaxNumFOp(fx.as_ir_value(a), fx.as_ir_value(b), fastmath=fm).result - ) - - -def _undef_i32(): - """Cvt destination whose other half is overwritten: saves a v_mov 0.""" - return _llvm.mlir_undef(_T.i32) - - -def _v2i32(a, b): - return Vec.from_elements([a, b], fx.Int32).ir_value() - - -_STORE_CPOL = 0x2 diff --git a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/launch.py b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/launch.py deleted file mode 100644 index 6ec18cefe02f..000000000000 --- a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/launch.py +++ /dev/null @@ -1,32 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""MiniMax-M3 FlyDSL MoE launch helpers.""" - -import functools - -import torch - -from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.reduce_bf16 import ( - compile_moe_reduce_bf16, -) -from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.sort import compile_moe_sort -from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.tile_map import compile_tile_map - - -def _u8_flat(t: torch.Tensor) -> torch.Tensor: - return t.view(torch.uint8).view(-1) - - -@functools.cache -def _get_sort(num_experts: int, topk: int, block_m: int): - return compile_moe_sort(E=num_experts, topk=topk, block_m=block_m) - - -@functools.cache -def _get_tile_map(intermediate_size: int, block_m: int): - return compile_tile_map(I=intermediate_size, BM=block_m) - - -@functools.cache -def _get_reduce_bf16(hidden_size: int, topk: int): - return compile_moe_reduce_bf16(H=hidden_size, topk=topk) diff --git a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/loaders.py b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/loaders.py deleted file mode 100644 index 12f683495455..000000000000 --- a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/loaders.py +++ /dev/null @@ -1,397 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""MiniMax-M3 FlyDSL MoE loaders helpers.""" - -import flydsl.expr as fx -from aiter.ops.flydsl.kernels import buffer_ops -from flydsl._mlir import ir as _ir -from flydsl._mlir.dialects import llvm as _llvm -from flydsl.expr import const_expr, range_constexpr -from flydsl.expr import rocdl as _rocdl -from flydsl.expr.typing import T as _T -from flydsl.expr.typing import Vector as Vec - -_N_WAVES = 4 - - -def divmod(a, b): - """Divmod for DSL values (the builtin rejects them).""" - return (a // b, a % b) - - -def swizzle_128(row, col): - """The dense kernel's 128-B-row XOR swizzle: (row, col) -> (row', col').""" - offset = row * 128 + col - swizzle = ((offset % (16 * 128)) >> 8) << 4 - swizzled_offset = offset ^ swizzle - return swizzled_offset // 128, swizzled_offset % 128 - - -SWIGLU_ALPHA = 1.702 - - -SWIGLU_LIMIT = 7.0 - - -class _Buf: - def __init__(self, base_ptr, byte_off): - self.base_ptr = base_ptr - self.byte_off = byte_off - - @property - def ptr(self): - return fx.add_offset(self.base_ptr, self.byte_off) - - -_gep = buffer_ops.get_element_ptr - - -def _lds_ptr_t(): - return _ir.Type.parse("!llvm.ptr<3>") - - -def _asm_void(operands, asm_string, constraints, clobbers=""): - """Side-effecting void inline asm (LLVM sees no memory op -> no waitcnt added).""" - if clobbers: - constraints = f"{constraints},{clobbers}" - _llvm.inline_asm(None, operands, asm_string, constraints, has_side_effects=True) - - -def wait_barrier(count): - """``s_waitcnt vmcnt(count) lgkmcnt(0)`` + ``s_barrier``""" - _rocdl.s_waitcnt(vmcnt=count, lgkmcnt=0) - _rocdl.s_barrier() - - -def _uniform_i32(value): - """i32 in a wave-uniform SGPR, for scalar inline-asm operands.""" - raw = fx.as_ir_value(value) if not isinstance(value, _ir.Value) else value - if raw.type != _T.i32: - raw = fx.as_ir_value(fx.Int32(raw)) - return _rocdl.readfirstlane(_T.i32, raw) - - -def _swizzled_col(row, col): - """The swizzled 128-B-row byte column ``swizzle_128`` lands (row, col) on.""" - r, c = swizzle_128(row, col) - return c - - -class G2SLoaderAsm: - """global -> LDS, 16 B per lane per step: per-lane offsets in VGPRs, the K-step - in soffset. With ``step_bytes`` all steps share ``gl_offsets[0]`` (one VGPR) and - advance soffset by that stride; ``soff_bytes`` is added to every soffset.""" - - def __init__( - self, rsrc, gl_offsets, n_load_steps, wave_id, step_bytes=None, soff_bytes=0 - ): - self.rsrc = fx.as_ir_value(rsrc) - self.gl_offsets = gl_offsets - self.n_load_steps = n_load_steps - self.wave_id = wave_id - self.step_bytes = step_bytes - self.soff_bytes = soff_bytes - - @property - def _step_stride(self): - # m0 (LDS byte) advance per step: 4 waves x 64 lanes x 16 B. - return _N_WAVES * 1024 - - def set_wave_base(self, base_ptr): - # the wave-uniform LDS base, in an SGPR once - wb = fx.Int32(fx.ptrtoint(base_ptr)) + fx.Int32(self.wave_id * 1024) - self._wave_base_s = _rocdl.readfirstlane(_T.i32, fx.as_ir_value(wb)) - - def _lds_base_sgpr(self, lds_dst): - m0 = fx.Int32(self._wave_base_s) + fx.Int32(lds_dst.byte_off) - return fx.as_ir_value(m0) - - def _voffset(self, step): - if self.step_bytes is not None: - return fx.as_ir_value(fx.Int32(self.gl_offsets[0])) - return fx.as_ir_value(fx.Int32(self.gl_offsets[step])) - - def _emit(self, lds_dst, k_offset, step): - # set m0 at step 0, then s_add it for the rest - voff = self._voffset(step) - extra = self.soff_bytes + (step * self.step_bytes if self.step_bytes else 0) - if extra: - k_offset = fx.Int32(k_offset) + fx.Int32(extra) - soff = _uniform_i32(k_offset) - stride = self._step_stride - # s_add_u32 writes SCC: without ~{scc} a live SCC (loop exit) gets clobbered - if step == 0: - m0 = self._lds_base_sgpr(lds_dst) - asm = "s_mov_b32 m0, $0\nbuffer_load_dwordx4 $1, $2, $3 offen lds" - _asm_void([m0, voff, self.rsrc, soff], asm, "s,v,s,s", "~{scc}") - else: - asm = ( - f"s_add_u32 m0, {stride}, m0\nbuffer_load_dwordx4 $0, $1, $2 offen lds" - ) - _asm_void([voff, self.rsrc, soff], asm, "v,s,s", "~{scc}") - - def load(self, lds_dst, k_offset): - for step in range_constexpr(self.n_load_steps): - self._emit(lds_dst, k_offset, step) - - def load_one(self, lds_dst, k_offset, step): - self._emit(lds_dst, k_offset, step) - - -class S2RLoader128B: - """LDS -> registers: two 16-byte halves of a swizzled 128-byte row.""" - - def __init__(self, wave_idx, n_tiles): - self.lane_id = fx.thread_idx.x % 64 - self.wave_idx = wave_idx - self.n_tiles = n_tiles - - def _vec_load_16xf8(self, lds_src, dyn_offset, const_offset): - total_off = lds_src.byte_off + const_offset - window_base = (total_off // 0x10000) * 0x10000 - imm = total_off - window_base - assert 0 <= imm <= 0xFFFF - vaddr = fx.Int32(fx.ptrtoint(lds_src.base_ptr)) + fx.Int32( - window_base + dyn_offset - ) - lds_ptr = _llvm.inttoptr(_lds_ptr_t(), fx.as_ir_value(vaddr)) - if imm != 0: - lds_ptr = _gep(lds_ptr, static_byte_offset=imm) - vec_i32 = _ir.VectorType.get([4], fx.Int32.ir_type) - return Vec(_llvm.LoadOp(vec_i32, lds_ptr, alignment=16).result) - - def _offset(self, unit, preshuffled): - row = self.wave_idx * (self.n_tiles * 16) + self.lane_id % 16 - if const_expr(preshuffled): - return (row // 8) * 1024 + (row % 8) * 16 + unit * 128 - row_swz, col_swz = swizzle_128(row, unit * 16) - return row_swz * 128 + col_swz - - def _dyn_offset(self, step, preshuffled): - return self._offset(self.lane_id // 16 + step * 4, preshuffled) - - def load(self, lds_src, preshuffled=False): - frag = [] - for i in range_constexpr(self.n_tiles): - halves = [] - for step in range_constexpr(2): - dyn = self._dyn_offset(step, preshuffled) - v = self._vec_load_16xf8(lds_src, dyn, i * 2048) - halves.append(v.bitcast(fx.Int32)) - frag.append(halves) - return frag - - def load_one(self, lds_src, i, ksub, preshuffled=False): - dyn = self._dyn_offset(ksub, preshuffled) - return self._vec_load_16xf8(lds_src, dyn, i * 2048).bitcast(fx.Int32) - - -def _flat_frag(frag): - return [fx.as_ir_value(x) for t in frag for x in t] - - -def _unflat_frag(flat, n_tiles, arity=2): - return [list(flat[arity * i : arity * i + arity]) for i in range(n_tiles)] - - -def _g2s_thunks(g2s, dst, gl_off, n_steps): - return [lambda s=s: g2s.load_one(dst, gl_off, s) for s in range(n_steps)] - - -def _riffle(glb, lds): - """Interleave global and LDS thunks proportionally.""" - if not glb or not lds: - return list(glb) + list(lds) - out = [] - step = len(lds) / len(glb) - li = 0 - for gi, t in enumerate(glb): - out.append(t) - upto = int(round((gi + 1) * step)) - out += lds[li:upto] - li = upto - return out + lds[li:] - - -def _s2r_thunks(s2r, src, holder, n, pre): - ts = [] - for i in range(n): - for ks in range(_FP4_PACK): - - def f(i=i, ks=ks): - if holder[i] is None: - holder[i] = [None, None] - holder[i][ks] = s2r.load_one(src, i, ks, preshuffled=pre) - - ts.append(f) - return ts - - -def _min(a, b): - return (a < b).select(a, b) - - -def _divmod_nonneg(a, b): - if const_expr(isinstance(b, int) and b > 0 and (b & (b - 1)) == 0): - sh = b.bit_length() - 1 - return (a >> sh, a & (b - 1)) if const_expr(sh > 0) else (a, 0) - return divmod(a, b) - - -_FP4_PACK = 2 # pack_M = pack_N = pack_K = 2 -_SCALE_QUARTER_BYTES = 1024 # one gather = 4 blocks = one wave's share of one operand -_SCALE_REGION_BYTES = 2 * _SCALE_QUARTER_BYTES # all of A (or all of B) for one K-step -_SCALE_SLOT_BYTES = _N_WAVES * _SCALE_QUARTER_BYTES -_SCALE_SLOTS = 4 -_SCALE_LDS_BYTES = _SCALE_SLOTS * _SCALE_SLOT_BYTES -_SCALE_A_REGION = 0 -_SCALE_B_REGION = _SCALE_REGION_BYTES - - -class ScaleGatherMoE: - """One ``buffer_load_dwordx4 ... lds`` per wave per K-step: waves 0/1 fetch A - scales, waves 2/3 B scales (the expert's gate + up slabs). A 256 B block = 32 - rows x 8 K-blocks; lane blocks ``lane // 16`` 0/1 go to LDS half 0 (R0 / gate), - 2/3 to half 1 (R1 / up).""" - - def __init__( - self, - a_scale, - b_scale, - K, - lane_id, - wave_id, - lds_base_ptr, - a_scale_bytes, - b_scale_bytes, - a_wave_groups, - a_half_groups, - b_wave_groups, - b_half_groups, - ): - self.row_i32 = (K // 256) * 64 # i32 per 32-row group (32 rows x K/32 bytes) - self.wave_id = wave_id - self.a_rsrc = fx.as_ir_value( - buffer_ops.create_buffer_resource( - a_scale, max_size=False, num_records_bytes=a_scale_bytes - ) - ) - self.b_rsrc = fx.as_ir_value( - buffer_ops.create_buffer_resource( - b_scale, max_size=False, num_records_bytes=b_scale_bytes - ) - ) - self._blk = lane_id // 16 - self._in16 = lane_id % 16 - self._lds_base = fx.Int32(fx.ptrtoint(lds_base_ptr)) - self._a_wave_groups = a_wave_groups - self._a_half_groups = a_half_groups - self._b_wave_groups = b_wave_groups - self._b_half_groups = b_half_groups - - def set_wave_base(self, a_base_row, b_base_row): - """``a_base_row``: first sorted row of the m-tile; ``b_base_row``: first - W13 row (gate) of the n-tile, both multiples of 32.""" - wid = fx.Int32(_rocdl.readfirstlane(_T.i32, fx.as_ir_value(self.wave_id))) - self._wave_base_s = fx.as_ir_value( - self._lds_base + wid * fx.Int32(_SCALE_QUARTER_BYTES) - ) - is_a = wid < fx.Int32(2) - q = wid % fx.Int32(2) - g_a = a_base_row // fx.Int32(32) + q * fx.Int32(self._a_wave_groups) - g_b = b_base_row // fx.Int32(32) + q * fx.Int32(self._b_wave_groups) - self._G = _uniform_i32(is_a.select(g_a, g_b)) - self._HS = _uniform_i32( - is_a.select(fx.Int32(self._a_half_groups), fx.Int32(self._b_half_groups)) - ) - self._rsrc = fx.arith.select(is_a, self.a_rsrc, self.b_rsrc) - self._soff0 = _uniform_i32(fx.Int32(0)) - - def gather(self, kstep, slot): - grp = ( - fx.Int32(self._G) + (self._blk // 2) * fx.Int32(self._HS) + (self._blk % 2) - ) - i32_off = ( - grp * fx.Int32(self.row_i32) - + fx.Int32(kstep) * fx.Int32(64) - + self._in16 * fx.Int32(4) - ) - voff = fx.as_ir_value(i32_off * fx.Int32(4)) # bytes - addr = fx.Int32(self._wave_base_s) + fx.Int32(slot) * fx.Int32( - _SCALE_SLOT_BYTES - ) - asm = "s_mov_b32 m0, $0\nbuffer_load_dwordx4 $1, $2, $3 offen lds" - _asm_void( - [fx.as_ir_value(addr), voff, self._rsrc, self._soff0], - asm, - "s,v,s,s", - "~{m0}", - ) - - -class ScaleLoaderLDS: - def __init__(self, n_tiles, lane_id, quarter, lds_base_ptr, region_off): - assert n_tiles % _FP4_PACK == 0 - self.n_groups = n_tiles // _FP4_PACK - self.lane_id = lane_id - self._region_base = ( - fx.Int32(fx.ptrtoint(lds_base_ptr)) - + fx.Int32(region_off) - + quarter * fx.Int32(_SCALE_QUARTER_BYTES) - ) - - def _slot_wave_byte(self, slot): - return self._region_base + fx.Int32(slot) * fx.Int32(_SCALE_SLOT_BYTES) - - def read_half(self, slot, half): - L = self.lane_id - base = self._slot_wave_byte(slot) + fx.Int32((L // 4) * 16 + (L % 4) * 4) - grp_list = [] - for gi in range_constexpr(self.n_groups): - blk = half * 2 + gi - vaddr = base + fx.Int32(blk * 256) - lds_ptr = _llvm.inttoptr(_lds_ptr_t(), fx.as_ir_value(vaddr)) - load = _llvm.LoadOp(fx.Int32.ir_type, lds_ptr, alignment=4) - grp_list.append(fx.Int32(load.result)) - return grp_list - - def read(self, slot): - return self.read_half(slot, 0), self.read_half(slot, 1) - - -def _fmax(a, b): - return (a > b).select(a, b) - - -def _fmin(a, b): - return (a < b).select(a, b) - - -def _swiglu_oai(g, u): - """SwiGLU-OAI, op for op aiter's stage-1 ``swiglu_mul_vec4``; the two separate - multiplies of ``t`` matter (folding them changes the last bit).""" - lim = fx.Float32(SWIGLU_LIMIT) - g = _fmin(g, lim) - u = _fmax(_fmin(u, lim), fx.Float32(-SWIGLU_LIMIT)) - t = (g * fx.Float32(SWIGLU_ALPHA)) * fx.Float32(-1.4426950408889634) - e = fx.Float32(_rocdl.exp2(_T.f32, t.ir_value())) - sig = fx.Float32(_rocdl.rcp(_T.f32, (fx.Float32(1.0) + e).ir_value())) - return g * sig * (u + fx.Float32(1.0)) - - -def _bits(f): - return fx.Float32(f).bitcast(fx.Int32) - - -def _as_f32(i): - return fx.Int32(i).bitcast(fx.Float32) - - -def _permlane16_swap(d_a, d_b): - pair_ty = _ir.Type.parse("!llvm.struct<(i32, i32)>") - res = _rocdl.permlane16_swap( - pair_ty, fx.as_ir_value(d_a), fx.as_ir_value(d_b), False, False - ) - return fx.Int32(_llvm.extractvalue(_T.i32, res, [0])), fx.Int32( - _llvm.extractvalue(_T.i32, res, [1]) - ) diff --git a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/reduce_bf16.py b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/reduce_bf16.py deleted file mode 100644 index c0bd2c5be45a..000000000000 --- a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/reduce_bf16.py +++ /dev/null @@ -1,98 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""Top-k sum of gemm2's routing-weighted bf16 partials ``[n_tokens * topk, H]`` -> -``[n_tokens, H]`` bf16, fp32 accumulate (aiter ``moe_reduction_kernel``'s math). -One wave per (token, 512-column chunk), non-temporal loads.""" - -import flydsl.compiler as flyc -import flydsl.expr as fx -from aiter.ops.flydsl.kernels import buffer_ops -from flydsl.expr import range_constexpr -from flydsl.expr.typing import Vector as Vec - -from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.epilogue import _bf16x2 -from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.loaders import _as_f32 -from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.utils import ( - PRELOAD_HINTS, - _tensor_addr, -) - -WAVES_PER_CTA = 1 -CHUNKS_PER_WAVE = 1 # dwordx4 per lane per row -_CHUNK = 512 # bf16 columns per (wave, dwordx4) -_NT = 2 # non-temporal cache policy - - -def compile_moe_reduce_bf16(*, H: int, topk: int): - CPW = CHUNKS_PER_WAVE - WPC = WAVES_PER_CTA - assert H % (_CHUNK * CPW) == 0 - SEGS = H // (_CHUNK * CPW) # waves per token - ROW_DW = H // 2 - CHUNK_DW = _CHUNK // 2 - LD = _NT - ST = 0 # default-policy stores - name = f"m3_reduce_bf16_h{H}_k{topk}" - - # addresses, not tensors: every argument arrives preloaded in SGPRs - @flyc.kernel(name=name, known_block_size=[64 * WPC, 1, 1]) - def kernel_reduce_bf16(n_tokens: fx.Int32, arg_out: fx.Int64, arg_y: fx.Int64): - lane = fx.thread_idx.x % 64 - gw = fx.block_idx.x * WPC + fx.thread_idx.x // 64 - tok = gw // SEGS - seg = gw % SEGS - out_rsrc = buffer_ops.create_buffer_resource_from_addr( - arg_out, num_records_bytes=n_tokens * (topk * H * 2) - ) - y_rsrc = buffer_ops.create_buffer_resource_from_addr( - arg_y, num_records_bytes=n_tokens * (H * 2) - ) - if tok < n_tokens: - col_dw = seg * (CHUNK_DW * CPW) + lane * 4 - row_dw = tok * (topk * ROW_DW) + col_dw - data = [ - [ - Vec( - buffer_ops.buffer_load( - out_rsrc, - row_dw + k * ROW_DW + j * CHUNK_DW, - vec_width=4, - dtype=fx.Int32, - cache_modifier=LD, - ) - ) - for j in range(CPW) - ] - for k in range(topk) - ] - acc = [[fx.Float32(0.0) for _ in range(8)] for _ in range(CPW)] - for k in range_constexpr(topk): - for j in range_constexpr(CPW): - for d in range_constexpr(4): - dw = fx.Int32(data[k][j][d]) - acc[j][2 * d] = acc[j][2 * d] + _as_f32(dw << 16) - acc[j][2 * d + 1] = acc[j][2 * d + 1] + _as_f32( - dw & fx.Int32(-65536) - ) - y_dw = tok * ROW_DW + col_dw - for j in range_constexpr(CPW): - packed = Vec.from_elements( - [_bf16x2(acc[j][2 * i], acc[j][2 * i + 1]) for i in range(4)], - fx.Int32, - ).ir_value() - buffer_ops.buffer_store( - packed, y_rsrc, y_dw + j * CHUNK_DW, cache_modifier=ST - ) - - @flyc.jit - def launch_reduce_bf16( - OUT: fx.Tensor, Y: fx.Tensor, n_tokens: fx.Int32, stream: fx.Stream - ): - grid = (n_tokens * SEGS + (WPC - 1)) // WPC - kernel_reduce_bf16(n_tokens, _tensor_addr(OUT), _tensor_addr(Y)).launch( - grid=(grid, 1, 1), block=(64 * WPC, 1, 1), stream=stream - ) - - launch_reduce_bf16.kernel_name = name - launch_reduce_bf16.compile_hints = PRELOAD_HINTS - return launch_reduce_bf16 diff --git a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/sort.py b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/sort.py deleted file mode 100644 index a16a338d8862..000000000000 --- a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/sort.py +++ /dev/null @@ -1,223 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""Prefill routing sort (aiter's ``moe_3stage_sort`` contract) in two launches: -``sort_count`` histograms each CTA's (token, slot) pairs, ``sort_place_pad`` scans -the padded totals, places the pairs and pads. ``sorted_ids[row] = token | slot << 24`` -(padding rows: ``n_tokens``, weight 0); the order inside an expert is not fixed.""" - -import functools -from dataclasses import dataclass - -import flydsl.compiler as flyc -import flydsl.expr as fx -import torch -from flydsl.expr import range_constexpr - -from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.utils import _lds_atomic_add_i32 - -SORT_CTAS = 128 # histogram / placement blocks -THREADS = 1024 # >= E and >= block_m - - -def max_sorted_rows(n_tokens: int, E: int, topk: int, block_m: int) -> int: - """Aiter's bound: every active expert pads by < block_m rows.""" - active = min(E, n_tokens * topk) - cumsum_max = n_tokens * topk + active * (block_m - 1) - return ((cumsum_max + block_m - 1) // block_m) * block_m - - -@dataclass -class SortBuffers: - sorted_ids: torch.Tensor - sorted_expert_ids: torch.Tensor - num_valid_ids: torch.Tensor # [2] i32: padded rows, last expert's first row - sorted_weights: torch.Tensor - block_offsets: torch.Tensor # workspace [E * SORT_CTAS]: per-CTA counts - max_sorted: int - block_m: int - - @staticmethod - def allocate(n_tokens, E, topk, block_m, device): - ms = max_sorted_rows(n_tokens, E, topk, block_m) - i32 = torch.int32 - return SortBuffers( - sorted_ids=torch.empty(ms, dtype=i32, device=device), - sorted_expert_ids=torch.empty(ms // block_m, dtype=i32, device=device), - num_valid_ids=torch.empty(2, dtype=i32, device=device), - sorted_weights=torch.empty(ms, dtype=torch.float32, device=device), - block_offsets=torch.empty(E * SORT_CTAS, dtype=i32, device=device), - max_sorted=ms, - block_m=block_m, - ) - - def launch_args(self, topk_ids, topk_weights, n_tokens): - return ( - topk_ids.contiguous().int().view(-1), - topk_weights.contiguous().float().view(-1), - self.sorted_ids, - self.sorted_expert_ids, - self.num_valid_ids, - self.sorted_weights, - self.block_offsets, - int(n_tokens), - torch.cuda.current_stream(), - ) - - -@functools.cache -def compile_moe_sort(*, E: int, topk: int, block_m: int): - assert (block_m & (block_m - 1)) == 0 and max(E, block_m) <= THREADS - experts_per_cta = (E + SORT_CTAS - 1) // SORT_CTAS - bm_shift = block_m.bit_length() - 1 - tag = f"E{E}_K{topk}_BM{block_m}" - - SCAN_W = THREADS # the padded-count scan runs on the whole block (no branch) - assert E <= SCAN_W and (SCAN_W & (SCAN_W - 1)) == 0 - PART = 4 # threads per expert summing the per-CTA counts in place_pad - assert PART * E <= THREADS and SORT_CTAS % PART == 0 and PART * E <= 2 * SCAN_W - scan_rounds = SCAN_W.bit_length() - 1 - - @fx.struct - class Shared: - count: fx.Array[fx.Int32, E] # per-CTA count / cursor - total: fx.Array[fx.Int32, E] - padded: fx.Array[fx.Int32, E] - prefix: fx.Array[fx.Int32, E] # rows placed by the earlier CTAs - starts: fx.Array[fx.Int32, E + 1] # expert start rows, [E] = padded total - scan: fx.Array[fx.Int32, 2 * SCAN_W] # ping-pong scan buffers - - def pair_range(n_tok, bx): - """This CTA's [start, end) of the n_tok * topk routing pairs""" - total = n_tok * topk - per_cta = (total + (SORT_CTAS - 1)) // SORT_CTAS - start = bx * per_cta - end = start + per_cta - return start, (end < total).select(end, total) - - @flyc.kernel(name=f"m3_sort_count_{tag}", known_block_size=[THREADS, 1, 1]) - def sort_count(topk_ids: fx.Tensor, block_offsets: fx.Tensor, n_tok: fx.Int32): - count = fx.SharedAllocator().allocate(Shared).peek().count.ptr - tx, bx = fx.thread_idx.x, fx.block_idx.x - start, end = pair_range(n_tok, bx) - if tx < E: - count[tx] = 0 - fx.gpu.barrier() - for i in range(start + tx, end, THREADS): - _lds_atomic_add_i32(count + fx.Int32(topk_ids[fx.Int32(i)]), 1) - fx.gpu.barrier() - if tx < E: - block_offsets[tx * SORT_CTAS + bx] = fx.Int32(count[tx]) - - @flyc.kernel(name=f"m3_sort_place_pad_{tag}", known_block_size=[THREADS, 1, 1]) - def sort_place_pad( - topk_ids: fx.Tensor, - topk_w: fx.Tensor, - block_offsets: fx.Tensor, - num_valid: fx.Tensor, - sorted_expert_ids: fx.Tensor, - sorted_ids: fx.Tensor, - sorted_w: fx.Tensor, - n_tok: fx.Int32, - ): - smem = fx.SharedAllocator().allocate(Shared).peek() - cursor, total_c, padded_c = smem.count.ptr, smem.total.ptr, smem.padded.ptr - prefix_c, starts = smem.prefix.ptr, smem.starts.ptr - scan = [smem.scan.ptr, smem.scan.ptr + SCAN_W] - tx, bx = fx.thread_idx.x, fx.block_idx.x - # 1. per expert: the total and the rows the earlier CTAs place - e, k = tx // PART, tx % PART - if tx < PART * E: - tot = fx.Int32(0) - pre = fx.Int32(0) - for i in range_constexpr(SORT_CTAS // PART): - c = k * (SORT_CTAS // PART) + i - v = fx.Int32(block_offsets[e * SORT_CTAS + c]) - tot = tot + v - pre = pre + (c < bx).select(v, 0) - scan[0][tx] = tot - scan[1][tx] = pre - fx.gpu.barrier() - if tx < E: - tot = fx.Int32(0) - pre = fx.Int32(0) - for i in range_constexpr(PART): - tot = tot + fx.Int32(scan[0][tx * PART + i]) - pre = pre + fx.Int32(scan[1][tx * PART + i]) - total_c[tx] = tot - padded_c[tx] = (tot + (block_m - 1)) & ~(block_m - 1) - prefix_c[tx] = pre - fx.gpu.barrier() - # 2. inclusive scan of the padded counts -> expert start rows - in_e = tx < E - scan[0][tx] = in_e.select(fx.Int32(padded_c[in_e.select(tx, 0)]), 0) - fx.gpu.barrier() - for r in range_constexpr(scan_rounds): - d, src, dst = 1 << r, r % 2, 1 - r % 2 - mine = fx.Int32(scan[src][tx]) - has = tx >= d - other = fx.Int32(scan[src][has.select(tx - d, tx)]) - scan[dst][tx] = has.select(mine + other, mine) - fx.gpu.barrier() - incl = scan[scan_rounds % 2] - if tx < E: - start = fx.Int32(incl[tx]) - fx.Int32(padded_c[tx]) - starts[tx] = start - cursor[tx] = start + fx.Int32(prefix_c[tx]) - if tx == 0: - starts[E] = fx.Int32(incl[E - 1]) - fx.gpu.barrier() - if bx == 0: - if tx == 0: - num_valid[0] = fx.Int32(starts[E]) - num_valid[1] = fx.Int32(starts[E - 1]) # the last expert's first row - if tx < E: - for b in range( - fx.Int32(starts[tx]) >> bm_shift, - fx.Int32(starts[tx + 1]) >> bm_shift, - ): - sorted_expert_ids[fx.Int32(b)] = tx - # 3. place this CTA's pairs - start, end = pair_range(n_tok, bx) - for i in range(start + tx, end, THREADS): - p = fx.Int32(i) - row = _lds_atomic_add_i32(cursor + fx.Int32(topk_ids[p]), 1) - sorted_ids[row] = ((p // topk) & 0x00FFFFFF) | ((p % topk) << 24) - sorted_w[row] = fx.Float32(topk_w[p]) - fx.gpu.barrier() - # 4. padding: < block_m rows per expert - if tx < block_m: - for ee in range_constexpr(experts_per_cta): - e = bx * experts_per_cta + ee - if e < E: - lo = fx.Int32(starts[e]) + fx.Int32(total_c[e]) + tx - for r in range(lo, fx.Int32(starts[e + 1]), THREADS): - sorted_ids[fx.Int32(r)] = n_tok # token n_tokens, slot 0 - sorted_w[fx.Int32(r)] = fx.Float32(0.0) - - @flyc.jit - def launch_sort( - topk_ids: fx.Tensor, - topk_w: fx.Tensor, - sorted_ids: fx.Tensor, - sorted_expert_ids: fx.Tensor, - num_valid: fx.Tensor, - sorted_w: fx.Tensor, - block_offsets: fx.Tensor, - n_tokens: fx.Int32, - stream: fx.Stream, - ): - sort_count(topk_ids, block_offsets, n_tokens).launch( - grid=(SORT_CTAS, 1, 1), block=(THREADS, 1, 1), stream=stream - ) - sort_place_pad( - topk_ids, - topk_w, - block_offsets, - num_valid, - sorted_expert_ids, - sorted_ids, - sorted_w, - n_tokens, - ).launch(grid=(SORT_CTAS, 1, 1), block=(THREADS, 1, 1), stream=stream) - - return launch_sort diff --git a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/tile_map.py b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/tile_map.py deleted file mode 100644 index 0753cfe80801..000000000000 --- a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/tile_map.py +++ /dev/null @@ -1,91 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project - -"""gemm1's expert-major tile order: an expert's m-blocks are the run ``[lo, hi)`` of -``sorted_expert_ids``; its (m, n) tiles are listed n-major so consecutive blocks -share the W13 slab:: - - tile_map[NB_N*lo + n*(hi - lo) + (m - lo)] = m << N_BITS | n (n < NB_N) - tile_map[valid_blocks*NB_N .. grid) = -1 (idle blocks) - tile_map[grid] = valid_blocks*NB_N -""" - -import flydsl.compiler as flyc -import flydsl.expr as fx -from flydsl.expr import range_constexpr - -from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.loaders import _min - -_THREADS = 256 -_MAX_BLOCKS = 4096 # >= max_sorted / BM (1409 at 65536 tokens, BM 256) -_SEARCH_STEPS = 13 # 2^13 > _MAX_BLOCKS - - -def compile_tile_map(*, I: int, BM: int = 128): # noqa: E741 - NB_N = I // 128 - N_BITS = (NB_N - 1).bit_length() - N_CTAS = _MAX_BLOCKS // _THREADS - TAIL_ITERS = (_MAX_BLOCKS * NB_N + 8) // (_THREADS * N_CTAS) + 1 - - @flyc.kernel - def kernel_tile_map( - sorted_expert_ids: fx.Tensor, - num_valid_ids: fx.Tensor, - tile_map: fx.Tensor, - grid_entries: fx.Int32, - ): - tid = fx.thread_idx.x - bx = fx.block_idx.x - gtid = bx * _THREADS + tid - vb = fx.Int32(num_valid_ids[0]) // BM # valid blocks (num_valid is BM-padded) - - def _eid(i): - return fx.Int32(sorted_expert_ids[i]) - - def _bound(e, upper): - """First index in [0, vb) whose expert id is > e (upper) / >= e (lower)""" - lo = fx.Int32(0) - n = vb - for _ in range_constexpr(_SEARCH_STEPS): - half = n // 2 - mid = lo + half - probe = _eid(_min(mid, vb - 1)) - go_right = (n > 0) & ((probe <= e) if upper else (probe < e)) - lo = go_right.select(mid + 1, lo) - n = go_right.select(n - half - 1, half) - return lo - - m = gtid - if m < vb: - e = _eid(m) - lo = _bound(e, False) - hi = _bound(e, True) - cnt = hi - lo - for n in range_constexpr(NB_N): - tile_map[lo * NB_N + cnt * n + m - lo] = (m << N_BITS) | n - tail0 = vb * NB_N - for it in range_constexpr(TAIL_ITERS): - i = tail0 + gtid + it * (_THREADS * N_CTAS) - if i < grid_entries: - tile_map[i] = fx.Int32(-1) - if gtid == 0: - tile_map[grid_entries] = tail0 - - @flyc.jit - def launch_tile_map( - sorted_expert_ids: fx.Tensor, - num_valid_ids: fx.Tensor, - tile_map: fx.Tensor, - grid_entries: fx.Int32, - stream: fx.Stream, - ): - kernel_tile_map( - sorted_expert_ids, num_valid_ids, tile_map, grid_entries - ).launch(grid=(N_CTAS, 1, 1), block=(_THREADS, 1, 1), stream=stream) - - return launch_tile_map - - -def tile_map_grid(num_m_blocks: int, I: int) -> int: # noqa: E741 - """gemm1 grid: every (m, n) tile of the allocation, rounded up to 8 XCDs.""" - return (num_m_blocks * (I // 128) + 7) // 8 * 8 diff --git a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/utils.py b/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/utils.py deleted file mode 100644 index 1010ba70aa3e..000000000000 --- a/vllm/models/minimax_m3/amd/ops/moe_flydsl_common/utils.py +++ /dev/null @@ -1,34 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -# Copyright (C) 2025-2026 FlyDSL Project Contributors -"""MiniMax-M3 FlyDSL MoE utils helpers.""" - -import flydsl.expr as fx -from flydsl._mlir.dialects import llvm - -# launch.compile_hints: preload kernel arguments into SGPRs (the first 56 bytes) -PRELOAD_HINTS = { - "llvm_options": { - "amdgpu-kernarg-preload": True, - "amdgpu-kernarg-preload-count": 16, - } -} - - -def _tensor_addr(t): - """Tensor as a device address: a tensor kernel argument ends the kernarg preload.""" - return fx.Int64(fx.ptrtoint(fx.get_iter(t))) - - -def _lds_atomic_add_i32(ptr, value): - """Workgroup-scope LDS i32 atomic add; returns the old value.""" - return fx.Int32( - llvm.AtomicRMWOp( - llvm.AtomicBinOp.add, - ptr.llvm_ptr, - fx.Int32(value).ir_value(), - llvm.AtomicOrdering.monotonic, - syncscope="workgroup", - alignment=4, - ).result - ) diff --git a/vllm/models/minimax_m3/amd/ops/moe_mxfp4/__init__.py b/vllm/models/minimax_m3/amd/ops/moe_mxfp4/__init__.py deleted file mode 100644 index e49d0462c3f7..000000000000 --- a/vllm/models/minimax_m3/amd/ops/moe_mxfp4/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""FlyDSL W4A4 MoE prefill chain for MiniMax-M3 on gfx950 (``sp_prefill``).""" diff --git a/vllm/models/minimax_m3/amd/ops/moe_mxfp4/gemm1_prefill.py b/vllm/models/minimax_m3/amd/ops/moe_mxfp4/gemm1_prefill.py deleted file mode 100644 index 4710b5d17986..000000000000 --- a/vllm/models/minimax_m3/amd/ops/moe_mxfp4/gemm1_prefill.py +++ /dev/null @@ -1,1192 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project - -"""MiniMax-M3 prefill MoE stage 1 (a4w4): the dense 4-wave fp4 GEMM per (m-tile of -sorted rows, n-tile of 128 intermediate columns), aiter ``moe_sorting`` layout: - - h[row, :] = swiglu_oai(x[tok] @ W_gate[e]^T, x[tok] @ W_up[e]^T) - out_q[row, :], out_scale[row, :] = mxfp4_quant(h[row, :]) (per 32 cols) - -A rows are gathered by token; padded rows (token == n_tokens) fall outside the -buffer resource and load zeros. The two LDS N-halves are the gate slab and the -matching up slab of W13, so SwiGLU is elementwise in registers. The epilogue -quantizes like aiter's FlyDSL stage 1 and writes the scales in the sorted -e8m0-shuffled layout gemm2 reads. - -Layouts (all bytes): - A [n_tokens, H/2] per-token fp4 (aiter per_1x32 quant) - A_scale [pad32(max_sorted), H/32] sorted rows, e8m0-shuffled - (aiter mxfp4_moe_sort) - W13 [E, 2I, H/2] aiter shuffle_weight(layout=(16,16)) - W13_sc [E*2I, H/32] aiter e8m0_shuffle - OUT_Q [num_m_blocks*BLOCK_M, I/2] sorted rows, fp4 - OUT_sc [pad32(num_m_blocks*BLOCK_M), I/32] sorted rows, e8m0-shuffled -""" - -import flydsl.compiler as flyc -import flydsl.expr as fx -from aiter.ops.flydsl.kernels import ( - buffer_ops, # the copy shipped in the vLLM image -) -from flydsl._mlir import ir as _ir -from flydsl._mlir.dialects import llvm as _llvm -from flydsl.expr import const_expr, range_constexpr -from flydsl.expr import rocdl as _rocdl -from flydsl.expr.typing import T as _T -from flydsl.expr.typing import Vector as Vec - -_N_WAVES = 4 - - -def divmod(a, b): - """Divmod for DSL values (the builtin rejects them).""" - return (a // b, a % b) - - -def swizzle_128(row, col): - """The dense kernel's 128-B-row XOR swizzle: (row, col) -> (row', col').""" - offset = row * 128 + col - swizzle = ((offset % (16 * 128)) >> 8) << 4 - swizzled_offset = offset ^ swizzle - return swizzled_offset // 128, swizzled_offset % 128 - - -SWIGLU_ALPHA = 1.702 -SWIGLU_LIMIT = 7.0 - - -class _Buf: - def __init__(self, base_ptr, byte_off): - self.base_ptr = base_ptr - self.byte_off = byte_off - - @property - def ptr(self): - return fx.add_offset(self.base_ptr, self.byte_off) - - -_gep = buffer_ops.get_element_ptr - - -def _lds_ptr_t(): - return _ir.Type.parse("!llvm.ptr<3>") - - -def _asm_void(operands, asm_string, constraints, clobbers=""): - """Side-effecting void inline asm (LLVM sees no memory op -> no waitcnt added).""" - if clobbers: - constraints = f"{constraints},{clobbers}" - _llvm.inline_asm(None, operands, asm_string, constraints, has_side_effects=True) - - -def wait_barrier(count): - """``s_waitcnt vmcnt(count) lgkmcnt(0)`` + ``s_barrier``""" - _rocdl.s_waitcnt(vmcnt=count, lgkmcnt=0) - _rocdl.s_barrier() - - -def _uniform_i32(value): - """Cast to i32 and force a wave-uniform SGPR value for scalar inline-asm - operands.""" - raw = fx.as_ir_value(value) if not isinstance(value, _ir.Value) else value - if raw.type != _T.i32: - raw = fx.as_ir_value(fx.Int32(raw)) - return _rocdl.readfirstlane(_T.i32, raw) - - -def _swizzled_col(row, col): - """The swizzled 128-B-row byte column ``swizzle_128`` lands (row, col) on.""" - r, c = swizzle_128(row, col) - return c - - -class G2SLoaderAsm: - """global -> LDS, 16 B per lane per step; ``gl_offsets[step]`` is the - loop-invariant per-lane byte offset, the K-step goes in soffset.""" - - def __init__(self, rsrc, gl_offsets, n_load_steps, wave_id): - self.rsrc = fx.as_ir_value(rsrc) - self.gl_offsets = gl_offsets - self.n_load_steps = n_load_steps - self.wave_id = wave_id - - @property - def _step_stride(self): - # m0 (LDS byte) advance per step: 4 waves x 64 lanes x 16 B. - return _N_WAVES * 1024 - - def set_wave_base(self, base_ptr): - # The wave-uniform LDS base, readfirstlane'd into an SGPR ONCE. - wb = fx.Int32(fx.ptrtoint(base_ptr)) + fx.Int32(self.wave_id * 1024) - self._wave_base_s = _rocdl.readfirstlane(_T.i32, fx.as_ir_value(wb)) - - def _lds_base_sgpr(self, lds_dst): - m0 = fx.Int32(self._wave_base_s) + fx.Int32(lds_dst.byte_off) - return fx.as_ir_value(m0) - - def _voffset(self, step): - return fx.as_ir_value(fx.Int32(self.gl_offsets[step])) - - def _emit(self, lds_dst, k_offset, step): - # m0 idiom (gcnasm async_copy): set m0 for step 0, then s_add for the rest. - voff = self._voffset(step) - soff = _uniform_i32(k_offset) # scalar soffset (K-step) - stride = self._step_stride - # s_add_u32 writes SCC: declare it, or the compiler may keep a live SCC - # (e.g. a loop-exit compare) across this asm and branch on garbage. - if step == 0: - m0 = self._lds_base_sgpr(lds_dst) - asm = "s_mov_b32 m0, $0\nbuffer_load_dwordx4 $1, $2, $3 offen lds" - _asm_void([m0, voff, self.rsrc, soff], asm, "s,v,s,s", "~{scc}") - else: - asm = ( - f"s_add_u32 m0, {stride}, m0\nbuffer_load_dwordx4 $0, $1, $2 offen lds" - ) - _asm_void([voff, self.rsrc, soff], asm, "v,s,s", "~{scc}") - - def load(self, lds_dst, k_offset): - for step in range_constexpr(self.n_load_steps): - self._emit(lds_dst, k_offset, step) - - def load_one(self, lds_dst, k_offset, step): - self._emit(lds_dst, k_offset, step) - - -class S2RLoaderFp4: - """LDS -> reg: per tile the two K=128 fp4 MFMA operands (i32x4 each).""" - - def __init__(self, wave_idx, n_tiles): - self.lane_id = fx.thread_idx.x % 64 - self.wave_idx = wave_idx - self.n_tiles = n_tiles - - def _vec_load_16xf8(self, lds_src, dyn_offset, const_offset): - total_off = lds_src.byte_off + const_offset - window_base = (total_off // 0x10000) * 0x10000 - imm = total_off - window_base - assert 0 <= imm <= 0xFFFF - vaddr = fx.Int32(fx.ptrtoint(lds_src.base_ptr)) + fx.Int32( - window_base + dyn_offset - ) - lds_ptr = _llvm.inttoptr(_lds_ptr_t(), fx.as_ir_value(vaddr)) - if imm != 0: - lds_ptr = _gep(lds_ptr, static_byte_offset=imm) - vec4_i32 = _ir.VectorType.get([4], fx.Int32.ir_type) - load = _llvm.LoadOp(vec4_i32, lds_ptr, alignment=16) - return Vec(load.result) - - def _dyn_offset(self, step, preshuffled): - row = self.wave_idx * (self.n_tiles * 16) + self.lane_id % 16 - col = (self.lane_id // 16) * 16 + step * 64 - if const_expr(preshuffled): - return (row // 8) * 1024 + (row % 8) * 16 + (col // 16) * 128 - row_swz, col_swz = swizzle_128(row, col) - return row_swz * 128 + col_swz - - def load(self, lds_src, preshuffled=False): - frag = [] - for i in range_constexpr(self.n_tiles): - halves = [] - for step in range_constexpr(2): - dyn = self._dyn_offset(step, preshuffled) - v = self._vec_load_16xf8(lds_src, dyn, i * 2048) - halves.append(v.bitcast(fx.Int32)) - frag.append(halves) - return frag - - def load_one(self, lds_src, i, ksub, preshuffled=False): - dyn = self._dyn_offset(ksub, preshuffled) - v = self._vec_load_16xf8(lds_src, dyn, i * 2048) - return v.bitcast(fx.Int32) - - -def _flat_frag(frag): - out = [] - for t in frag: - out.append(fx.as_ir_value(t[0])) - out.append(fx.as_ir_value(t[1])) - return out - - -def _unflat_frag(flat, n_tiles): - return [[flat[2 * i], flat[2 * i + 1]] for i in range(n_tiles)] - - -def _g2s_thunks(g2s, dst, gl_off, n_steps): - return [lambda s=s: g2s.load_one(dst, gl_off, s) for s in range(n_steps)] - - -def _riffle(glb, lds): - """Interleave the global and LDS thunk lists proportionally like aiter's asm""" - if not glb or not lds: - return list(glb) + list(lds) - out = [] - step = len(lds) / len(glb) - li = 0 - for gi, t in enumerate(glb): - out.append(t) - upto = int(round((gi + 1) * step)) - out += lds[li:upto] - li = upto - return out + lds[li:] - - -def _s2r_thunks(s2r, src, holder, n, pre): - ts = [] - for i in range(n): - for ks in range(_FP4_PACK): - - def f(i=i, ks=ks): - if holder[i] is None: - holder[i] = [None, None] - holder[i][ks] = s2r.load_one(src, i, ks, preshuffled=pre) - - ts.append(f) - return ts - - -def _min(a, b): - return (a < b).select(a, b) - - -def _divmod_nonneg(a, b): - if const_expr(isinstance(b, int) and b > 0 and (b & (b - 1)) == 0): - sh = b.bit_length() - 1 - return (a >> sh, a & (b - 1)) if const_expr(sh > 0) else (a, 0) - return divmod(a, b) - - -# ── FP4 scaled MFMA ────────────────────────────────────────────────────────── -_FP4_CBSZ = 4 -_FP4_BLGP = 4 -_FP4_PACK = 2 # pack_M = pack_N = pack_K = 2 - - -class Mfma16x16x128Fp4: - """fp4 16x16x128 scaled MFMA over an (n_tiles_a x n_tiles_b) quadrant, - accumulators pinned in AGPR (inline asm ``=a,...,0``). See the dense - kernel for the opsel / operand-swap notes.""" - - def __init__(self, n_tiles_a, n_tiles_b): - assert n_tiles_a % _FP4_PACK == 0 and n_tiles_b % _FP4_PACK == 0 - self.n_tiles_a = n_tiles_a - self.n_tiles_b = n_tiles_b - self.res_ty = Vec.make_type(4, fx.Float32) - - def idx(self, i, j): - return i * self.n_tiles_b + j - - def _order(self): - order = [] - j0s = list(range(0, self.n_tiles_b, 2)) - for n, i0 in enumerate(range(0, self.n_tiles_a, 2)): - for j0 in reversed(j0s) if n % 2 else j0s: - order += [(i0 + di, j0 + dj) for di in range(2) for dj in range(2)] - return order - - def call( - self, a, b, c, sa, sb, interleave=None, zero_acc=False, late=None, late_start=8 - ): - """``interleave``: thunks spread evenly over the MFMAs (loads, LDS reads). - ``late``: thunks spread over the MFMAs from ``late_start`` on -- for work that - reads accumulators finished by the previous call: the MFMAs are inline asm, so - the - compiler inserts no MFMA -> v_accvgpr_read hazard waits; 8 MFMAs (128+ cycles) - cover the last one's latency.""" - thunks = list(interleave) if interleave else [] - lates = list(late) if late else [] - nth = [0] - nlt = [0] - mth = [0] - order = self._order() - n_mfma = _FP4_PACK * len(order) - slots = ( - {(t * n_mfma) // len(thunks) for t in range(len(thunks))} - if thunks - else set() - ) - n_late_slots = max(n_mfma - late_start, 1) - lslots = ( - {late_start + (t * n_late_slots) // len(lates) for t in range(len(lates))} - if lates - else set() - ) - for ksub in range_constexpr(_FP4_PACK): - for i, j in order: - a_op = a[i][ksub] - sa_v = sa[i // _FP4_PACK] - ia = i % _FP4_PACK - b_op = b[j][ksub] - sb_v = sb[j // _FP4_PACK] - jb = j % _FP4_PACK - if zero_acc and ksub == 0: - c[self.idx(i, j)] = self._mfma_agpr( - a_op, b_op, None, sa_v, sb_v, ksub, ia, jb - ) - else: - c[self.idx(i, j)] = self._mfma_agpr( - a_op, b_op, c[self.idx(i, j)], sa_v, sb_v, ksub, ia, jb - ) - if nth[0] < len(thunks) and mth[0] in slots: - thunks[nth[0]]() - nth[0] += 1 - if nlt[0] < len(lates) and mth[0] in lslots: - lates[nlt[0]]() - nlt[0] += 1 - mth[0] += 1 - while nth[0] < len(thunks): - thunks[nth[0]]() - nth[0] += 1 - while nlt[0] < len(lates): - lates[nlt[0]]() - nlt[0] += 1 - return c - - def _mfma_agpr(self, a_op, b_op, acc, sa_v, sb_v, ksub, ia, jb): - # feeds (B, A) instead of (A, B): C^T = B^T A^T, so lane L ends up holding - # C[row L%16, 4 consecutive cols 4*(L//16)..]. - a_op, b_op = b_op, a_op - sa_v, sb_v = sb_v, sa_v - ia, jb = jb, ia - opsel = f"op_sel:[{ia},{jb},0]" - opsel_hi = f"op_sel_hi:[{ksub},{ksub},0]" - src2 = "$0" if acc is not None else "0" - asm = ( - f"v_mfma_scale_f32_16x16x128_f8f6f4 $0, $1, $2, {src2}, $3, $4 " - f"{opsel} {opsel_hi} cbsz:4 blgp:4" - ) - ops = [ - fx.as_ir_value(a_op), - fx.as_ir_value(b_op), - fx.as_ir_value(sa_v), - fx.as_ir_value(sb_v), - ] - cons = "=a,v,v,v,v" - if acc is not None: - ops.append(fx.as_ir_value(acc)) - cons += ",0" - return _llvm.inline_asm(self.res_ty, ops, asm, cons, has_side_effects=True) - - -# ── E8M0 scales through LDS ────────────────────────────────────────────────── -_SCALE_QUARTER_BYTES = 1024 # one gather = 4 blocks = one wave's share of one operand -_SCALE_REGION_BYTES = 2 * _SCALE_QUARTER_BYTES # all of A (or all of B) for one K-step -_SCALE_SLOT_BYTES = _N_WAVES * _SCALE_QUARTER_BYTES # 4096 -_SCALE_SLOTS = 4 -_SCALE_LDS_BYTES = _SCALE_SLOTS * _SCALE_SLOT_BYTES # 16 KB -_SCALE_A_REGION = 0 -_SCALE_B_REGION = _SCALE_REGION_BYTES - - -class ScaleGatherMoE: - """One ``buffer_load_dwordx4 ... lds`` per wave per K-step: waves 0/1 fetch - the A-scale blocks (rows of the sorted scale), waves 2/3 the B-scale blocks - (gate slab + up slab of the expert). A 256-B block = 32 rows x 8 K-blocks; - lane block ``blk = lane//16`` fetches row-group - ``G_wave + (blk//2)*half_groups + blk%2``: blocks 0/1 belong to LDS half 0 - (rows R0 / gate), blocks 2/3 to half 1 (rows R1 / up).""" - - def __init__( - self, - a_scale, - b_scale, - K, - lane_id, - wave_id, - lds_base_ptr, - a_scale_bytes, - b_scale_bytes, - a_wave_groups, - a_half_groups, - b_wave_groups, - b_half_groups, - ): - self.row_i32 = (K // 256) * 64 # i32 per 32-row group (32 rows x K/32 bytes) - self.wave_id = wave_id - # aiter's buffer_ops returns the raw ROCDL resource (!llvm.ptr<8>) directly - self.a_rsrc = fx.as_ir_value( - buffer_ops.create_buffer_resource( - a_scale, max_size=False, num_records_bytes=a_scale_bytes - ) - ) - self.b_rsrc = fx.as_ir_value( - buffer_ops.create_buffer_resource( - b_scale, max_size=False, num_records_bytes=b_scale_bytes - ) - ) - self._blk = lane_id // 16 - self._in16 = lane_id % 16 - self._lds_base = fx.Int32(fx.ptrtoint(lds_base_ptr)) - self._a_wave_groups = a_wave_groups - self._a_half_groups = a_half_groups - self._b_wave_groups = b_wave_groups - self._b_half_groups = b_half_groups - - def set_wave_base(self, a_base_row, b_base_row): - """``a_base_row``: first sorted row of the m-tile; ``b_base_row``: first - W13 row (gate) of the n-tile, both multiples of 32.""" - wid = fx.Int32(_rocdl.readfirstlane(_T.i32, fx.as_ir_value(self.wave_id))) - self._wave_base_s = fx.as_ir_value( - self._lds_base + wid * fx.Int32(_SCALE_QUARTER_BYTES) - ) - is_a = wid < fx.Int32(2) - q = wid % fx.Int32(2) - g_a = a_base_row // fx.Int32(32) + q * fx.Int32(self._a_wave_groups) - g_b = b_base_row // fx.Int32(32) + q * fx.Int32(self._b_wave_groups) - self._G = _uniform_i32(is_a.select(g_a, g_b)) - self._HS = _uniform_i32( - is_a.select(fx.Int32(self._a_half_groups), fx.Int32(self._b_half_groups)) - ) - self._rsrc = fx.arith.select(is_a, self.a_rsrc, self.b_rsrc) - self._soff0 = _uniform_i32(fx.Int32(0)) - - def gather(self, kstep, slot): - grp = ( - fx.Int32(self._G) + (self._blk // 2) * fx.Int32(self._HS) + (self._blk % 2) - ) - i32_off = ( - grp * fx.Int32(self.row_i32) - + fx.Int32(kstep) * fx.Int32(64) - + self._in16 * fx.Int32(4) - ) - voff = fx.as_ir_value(i32_off * fx.Int32(4)) # bytes - addr = fx.Int32(self._wave_base_s) + fx.Int32(slot) * fx.Int32( - _SCALE_SLOT_BYTES - ) - asm = "s_mov_b32 m0, $0\nbuffer_load_dwordx4 $1, $2, $3 offen lds" - _asm_void( - [fx.as_ir_value(addr), voff, self._rsrc, self._soff0], - asm, - "s,v,s,s", - "~{m0}", - ) - - -class ScaleLoaderLDS: - def __init__(self, n_tiles, lane_id, quarter, lds_base_ptr, region_off): - assert n_tiles % _FP4_PACK == 0 - self.n_groups = n_tiles // _FP4_PACK - self.lane_id = lane_id - self._region_base = ( - fx.Int32(fx.ptrtoint(lds_base_ptr)) - + fx.Int32(region_off) - + quarter * fx.Int32(_SCALE_QUARTER_BYTES) - ) - - def _slot_wave_byte(self, slot): - return self._region_base + fx.Int32(slot) * fx.Int32(_SCALE_SLOT_BYTES) - - def read_half(self, slot, half): - L = self.lane_id - base = self._slot_wave_byte(slot) + fx.Int32((L // 4) * 16 + (L % 4) * 4) - grp_list = [] - for gi in range_constexpr(self.n_groups): - blk = half * 2 + gi - vaddr = base + fx.Int32(blk * 256) - lds_ptr = _llvm.inttoptr(_lds_ptr_t(), fx.as_ir_value(vaddr)) - load = _llvm.LoadOp(fx.Int32.ir_type, lds_ptr, alignment=4) - grp_list.append(fx.Int32(load.result)) - return grp_list - - def read(self, slot): - return self.read_half(slot, 0), self.read_half(slot, 1) - - -# ── epilogue helpers ───────────────────────────────────────────────────────── -def _fmax(a, b): - return (a > b).select(a, b) - - -def _fmin(a, b): - return (a < b).select(a, b) - - -def _swiglu_oai(g, u): - """MiniMax-M3 activation, op for op the production stage-1 epilogue (aiter - mixed_moe_gemm_2stage ``swiglu_mul_vec4``): g clamped above, u clamped both - sides, t = (g * alpha) * (-log2 e), sigmoid = rcp(1 + exp2(t)), g * sig * (u + 1). - The two separate multiplies matter: folding the constant changes the last bit.""" - lim = fx.Float32(SWIGLU_LIMIT) - g = _fmin(g, lim) - u = _fmax(_fmin(u, lim), fx.Float32(-SWIGLU_LIMIT)) - t = (g * fx.Float32(SWIGLU_ALPHA)) * fx.Float32(-1.4426950408889634) - e = fx.Float32(_rocdl.exp2(_T.f32, t.ir_value())) - sig = fx.Float32(_rocdl.rcp(_T.f32, (fx.Float32(1.0) + e).ir_value())) - return g * sig * (u + fx.Float32(1.0)) - - -def _round_bf16x2(a, b): - """(a, b) -> the f32 values of their bf16 roundings (RNE, v_cvt_pk_bf16_f32): - production stage 1 stores bf16 and quantises from it.""" - w = Vec.from_elements([a, b], fx.Float32).to(fx.BFloat16).bitcast(fx.Int32)[0] - return _as_f32(w << 16), _as_f32(w & fx.Int32(-65536)) - - -def _quant_prep_fp4(h8): - """Production's inter-stage quant on 8 values of one 32-block: round them to - bf16 and return (rounded values, this lane's |max|).""" - hb = [] - for k in range_constexpr(0, 8, 2): - lo, hi = _round_bf16x2(h8[k], h8[k + 1]) - hb += [lo, hi] - amax = fx.math.absf(hb[0]) - for v in range_constexpr(1, 8): - amax = _fmax(amax, fx.math.absf(hb[v])) - return hb, amax - - -def _e8m0_roundup_fp4(amax): - """Aiter's default MX scale rule (kDefaultMxScaleRoundMode = RoundUp): - ceil_pow2(amax / 6) as a biased exponent (fp4 max = 6): the block's max lands in - (3, 6]. Exponent 0xFF (NaN/Inf) is not bumped.""" - u = _bits(amax * fx.Float32(1.0 / 6.0)) - e = (u >> 23) & fx.Int32(0xFF) - bump = ((u & fx.Int32(0x7FFFFF)) != fx.Int32(0)) & (e < fx.Int32(0xFF)) - return bump.select(e + fx.Int32(1), e) - - -def _bits(f): - return fx.Float32(f).bitcast(fx.Int32) - - -def _as_f32(i): - return fx.Int32(i).bitcast(fx.Float32) - - -def _cvt_pk_fp4(old, a, b, scale_f32, sel): - """v_cvt_scalef32_pk_fp4_f32: two f32 / 2^(e8m0-127) -> 2 fp4 into byte ``sel``.""" - return fx.Int32(_rocdl.cvt_scalef32_pk_fp4_f32(_T.i32, old, a, b, scale_f32, sel)) - - -def _permlane16_swap(d_a, d_b): - pair_ty = _ir.Type.parse("!llvm.struct<(i32, i32)>") - res = _rocdl.permlane16_swap( - pair_ty, fx.as_ir_value(d_a), fx.as_ir_value(d_b), False, False - ) - return fx.Int32(_llvm.extractvalue(_T.i32, res, [0])), fx.Int32( - _llvm.extractvalue(_T.i32, res, [1]) - ) - - -def compile_moe_gemm1( - *, - H: int, - I: int, # noqa: E741 - E: int, - BLOCK_M: int = 128, -): - """Grouped fp4 gemm1 for one (H, I, E, BLOCK_M). ``BLOCK_M`` must equal the - ``moe_sorting`` block size the sorted inputs were built with (128 or 256). - - Block order comes from an int32 table built on the GPU by ``tile_map.py`` - (one small kernel; ``tile_map[grid_size]`` holds the number of valid entries, - so no host sync): ``tile_map[remapped block] = m_tile << 3 | n_tile`` (-1 = - nothing to do), laid out expert by expert and n-slab-major inside an expert, - so the 32 CUs of one XCD chew through one expert with the same 768 KB - gate/up slab of W13 in L2. The hardware deals - consecutive block ids round-robin over the 8 XCDs, so block id b is first - remapped to ``(b % 8) * (grid / 8) + b // 8`` = a contiguous chunk of the - table per XCD.""" - K = H - BLOCK_K = 256 - BLOCK_K_BYTES = BLOCK_K // 2 - BLOCK_N = 256 # 128 gate cols + the matching 128 up cols - LDS_BLOCK_M = BLOCK_M // 2 - LDS_BLOCK_N = BLOCK_N // 2 - N_TILES_A = LDS_BLOCK_M // 2 // 16 # 16-row tiles per wave per LDS half - N_TILES_B = LDS_BLOCK_N // 2 // 16 # = 4 - - assert BLOCK_M in (128, 256) - assert K % BLOCK_K == 0 and I % LDS_BLOCK_N == 0 and (2 * I) % 256 == 0 - K_ITERS = K // BLOCK_K - UNROLL = 4 if (K_ITERS - 4) % 4 == 0 else 2 - assert K_ITERS >= 4 and (K_ITERS - 4) % UNROLL == 0, K_ITERS - N_ACCUMS = N_TILES_A * N_TILES_B - K_BYTES = K // 2 - - a_lds_size = LDS_BLOCK_M * BLOCK_K_BYTES # 8 KB (BM128) / 16 KB (BM256) - b_lds_size = LDS_BLOCK_N * BLOCK_K_BYTES # 16 KB - A_BUFS = 4 * a_lds_size - LDS_TILES_BYTES = A_BUFS + 4 * b_lds_size - - # scale geometry (32-row groups) - A_WAVE_GROUPS = N_TILES_A // 2 # groups per wave per LDS half - A_HALF_GROUPS = LDS_BLOCK_M // 32 - B_WAVE_GROUPS = N_TILES_B // 2 - B_HALF_GROUPS = I // 32 # gate slab -> up slab - I_BYTES = I // 2 - SCALE_COLS_OUT = I // 32 # e8m0 per output row - OUT_SC_BLOCKS_PER_ROW32 = SCALE_COLS_OUT // 8 - - @fx.struct - class SharedStorage: - all_lds: fx.Array[fx.Int8, LDS_TILES_BYTES, 16] - scale_lds: fx.Array[fx.Int8, _SCALE_LDS_BYTES, 16] - - @flyc.kernel - def kernel_gemm1( - A: fx.Tensor, - W13: fx.Tensor, - OUT_Q: fx.Tensor, - A_scale: fx.Tensor, - W13_scale: fx.Tensor, - OUT_scale: fx.Tensor, - sorted_ids: fx.Tensor, - sorted_expert_ids: fx.Tensor, - n_tokens: fx.Int32, - num_m_blocks: fx.Int32, - a_scale_bytes: fx.Int32, - tile_map_t: fx.Tensor, - grid_size: fx.Int32, - ): - lds = fx.SharedAllocator().allocate(SharedStorage).peek() - _base_ptr = lds.all_lds.ptr - - a_cur0 = _Buf(_base_ptr, 0 * a_lds_size) - a_cur1 = _Buf(_base_ptr, 1 * a_lds_size) - a_next0 = _Buf(_base_ptr, 2 * a_lds_size) - a_next1 = _Buf(_base_ptr, 3 * a_lds_size) - b_cur0 = _Buf(_base_ptr, A_BUFS + 0 * b_lds_size) - b_cur1 = _Buf(_base_ptr, A_BUFS + 1 * b_lds_size) - b_next0 = _Buf(_base_ptr, A_BUFS + 2 * b_lds_size) - b_next1 = _Buf(_base_ptr, A_BUFS + 3 * b_lds_size) - - lane_id = fx.thread_idx.x % 64 - wave_id = fx.thread_idx.x // 64 - - ids_rsrc = buffer_ops.create_buffer_resource( - sorted_ids, max_size=False, num_records_bytes=num_m_blocks * (BLOCK_M * 4) - ) - eid_rsrc = buffer_ops.create_buffer_resource( - sorted_expert_ids, max_size=False, num_records_bytes=num_m_blocks * 4 - ) - # split the valid entries [0, tile_map[grid_size]) evenly over the 8 XCDs - intra_xcd, xcd = _divmod_nonneg(fx.block_idx.x, 8) - tm_rsrc = buffer_ops.create_buffer_resource( - tile_map_t, max_size=False, num_records_bytes=(grid_size + 1) * 4 - ) - n_valid = fx.Int32( - buffer_ops.buffer_load( - tm_rsrc, grid_size, vec_width=1, dtype=fx.Int32, is_scalar=True - ) - ) - per_xcd = (n_valid + fx.Int32(7)) // fx.Int32(8) - remapped = xcd * per_xcd + intra_xcd - in_chunk = (intra_xcd < per_xcd) & (remapped < n_valid) - entry = fx.Int32( - buffer_ops.buffer_load( - tm_rsrc, - in_chunk.select(remapped, fx.Int32(0)), - vec_width=1, - dtype=fx.Int32, - ) - ) - entry = in_chunk.select(entry, fx.Int32(-1)) - tile_i = entry >> 3 - tile_j = entry & 7 - block_valid = entry >= 0 - # ---- routing: this m-tile's expert ---- - expert = fx.Int32( - buffer_ops.buffer_load(eid_rsrc, tile_i, vec_width=1, dtype=fx.Int32) - ) - m_base = tile_i * BLOCK_M - - if block_valid: - wave_i = wave_id // 2 - wave_j = wave_id % 2 - - # ---- A rows: gathered. token(sorted row) * K_BYTES + swizzled col ---- - def _a_gather_offsets(half): - offs = [] - for rnd in range_constexpr(N_TILES_A): - row = lane_id // 8 + wave_id * 8 + rnd * (_N_WAVES * 8) - col = (lane_id % 8) * 16 - sid = fx.Int32( - buffer_ops.buffer_load( - ids_rsrc, - m_base + half * LDS_BLOCK_M + row, - vec_width=1, - dtype=fx.Int32, - ) - ) - tok = sid & fx.Int32( - 0x00FFFFFF - ) # padded rows: tok == n_tokens -> OOB -> zeros - offs.append(tok * fx.Int32(K_BYTES) + _swizzled_col(row, col)) - return offs - - gl_off_a0 = _a_gather_offsets(0) - gl_off_a1 = _a_gather_offsets(1) - - # ---- B: gate slab rows [e*2I + j*128, +128), up slab +I ---- - def _b_offsets(): - offs = [] - for rnd in range_constexpr(N_TILES_B): - row = lane_id % 8 + wave_id * 8 + rnd * (_N_WAVES * 8) - col = (lane_id // 8) * 16 - offs.append( - (row // 16) * (K_BYTES * 16) - + (row % 16) * 16 - + (col // 64) * 1024 - + ((col % 64) // 16) * 256 - + (col % 16) - ) - return offs - - gl_off_b = _b_offsets() - b_row0 = expert * (2 * I) + tile_j * LDS_BLOCK_N - B0_gl_offset = b_row0 * K_BYTES - B1_gl_offset = B0_gl_offset + I * K_BYTES - A_K_STEP = BLOCK_K_BYTES - B_K_STEP = 2 * 1024 - - mfma = Mfma16x16x128Fp4(N_TILES_A, N_TILES_B) - - _scale_base_ptr = lds.scale_lds.ptr - scale_gather = ScaleGatherMoE( - A_scale, - W13_scale, - K, - lane_id, - wave_id, - _scale_base_ptr, - a_scale_bytes, - E * 2 * I * (K // 32), - A_WAVE_GROUPS, - A_HALF_GROUPS, - B_WAVE_GROUPS, - B_HALF_GROUPS, - ) - scale_gather.set_wave_base(m_base, b_row0) - a_scale_ld = ScaleLoaderLDS( - N_TILES_A, lane_id, wave_i, _scale_base_ptr, _SCALE_A_REGION - ) - b_scale_ld = ScaleLoaderLDS( - N_TILES_B, lane_id, wave_j, _scale_base_ptr, _SCALE_B_REGION - ) - - def _slot(k): - return fx.Int32(k) % fx.Int32(_SCALE_SLOTS) - - def _gather_scale_thunks(k, slot): - return [lambda: scale_gather.gather(k, slot)] - - a_rsrc = buffer_ops.create_buffer_resource( - A, max_size=False, num_records_bytes=n_tokens * K_BYTES - ) - b_rsrc = buffer_ops.create_buffer_resource( - W13, max_size=False, num_records_bytes=E * (2 * I) * K_BYTES - ) - a0_g2s = G2SLoaderAsm(a_rsrc, gl_off_a0, N_TILES_A, wave_id) - a1_g2s = G2SLoaderAsm(a_rsrc, gl_off_a1, N_TILES_A, wave_id) - b_g2s = G2SLoaderAsm(b_rsrc, gl_off_b, N_TILES_B, wave_id) - a0_g2s.set_wave_base(_base_ptr) - a1_g2s.set_wave_base(_base_ptr) - b_g2s.set_wave_base(_base_ptr) - a_s2r = S2RLoaderFp4(wave_i, N_TILES_A) - b_s2r = S2RLoaderFp4(wave_j, N_TILES_B) - - scale_gather.gather(0, _slot(0)) - scale_gather.gather(1, _slot(1)) - scale_gather.gather(2, _slot(2)) - - a0_g2s.load(a_cur0, fx.Int32(0 * A_K_STEP)) - b_g2s.load(b_cur0, B0_gl_offset + 0 * B_K_STEP) - b_g2s.load(b_cur1, B1_gl_offset + 0 * B_K_STEP) - a1_g2s.load(a_cur1, fx.Int32(0 * A_K_STEP)) - - a0_g2s.load(a_next0, fx.Int32(1 * A_K_STEP)) - b_g2s.load(b_next0, B0_gl_offset + 1 * B_K_STEP) - b_g2s.load(b_next1, B1_gl_offset + 1 * B_K_STEP) - a1_g2s.load(a_next1, fx.Int32(1 * A_K_STEP)) - - # 3 gathers + a_cur0 landed: b0/b1/a1 + the 4 next batches may fly - wait_barrier((3 * N_TILES_A) + (4 * N_TILES_B)) - a0_frag = a_s2r.load(a_cur0) - # b_cur0 AND b_cur1 landed: a1 + the 4 next batches may fly - wait_barrier((3 * N_TILES_A) + (2 * N_TILES_B)) - b0_frag = b_s2r.load(b_cur0, preshuffled=True) - b1_frag = b_s2r.load(b_cur1, preshuffled=True) - - sc0_saR0, sc0_saR1 = a_scale_ld.read(_slot(0)) - sc0_sbC0, sc0_sbC1 = b_scale_ld.read(_slot(0)) - sc0 = (sc0_saR0, sc0_saR1, sc0_sbC0, sc0_sbC1) - - # a step issues a0 (NA), b0 (NB), [SEG2], b1 (NB), gather (1), a1 (NA); - # the waits are exact: one load too many stalls on a fetch from HBM - _MAIN_VMCNT = 2 * N_TILES_A + 2 * N_TILES_B + 1 - _SEG2_VMCNT = 2 * N_TILES_A + N_TILES_B + 1 - # step 0 follows the prologue's issue order; one count looser races - _STEP0_VMCNT = 2 * N_TILES_A + 2 * N_TILES_B - _STEP0_SEG2_VMCNT = 2 * N_TILES_A + N_TILES_B - - def _read_scale_thunks(kc_idx, holder): - s = _slot(kc_idx) - - def _r(dst, ld, half, _s=s): - holder[dst] = ld.read_half(_s, half) - - return [ - lambda: _r(0, a_scale_ld, 0), - lambda: _r(1, a_scale_ld, 1), - lambda: _r(2, b_scale_ld, 0), - lambda: _r(3, b_scale_ld, 1), - ] - - def _one_step( - kc, - a0f, - b0f, - b1f_in, - sc, - accs, - bufs, - zero_acc=False, - top_vmcnt=None, - seg2_vmcnt=None, - ): - top_vmcnt = _MAIN_VMCNT if top_vmcnt is None else top_vmcnt - seg2_vmcnt = _SEG2_VMCNT if seg2_vmcnt is None else seg2_vmcnt - ac0, ac1, an0, an1, bc0, bc1, bn0, bn1 = bufs - saR0, saR1, sbC0, sbC1 = sc - c00f, c01f, c10f, c11f = accs - kc_i = fx.Int32(kc) - - _a1 = [None] * N_TILES_A - _a0n = [None] * N_TILES_A - _b0n = [None] * N_TILES_B - _b1n = [None] * N_TILES_B - ak = (kc_i + fx.Int32(2)) * fx.Int32(A_K_STEP) - bk = (kc_i + fx.Int32(2)) * fx.Int32(B_K_STEP) - a0_off = ak - a1_off = ak - b0_off = fx.Int32(B0_gl_offset) + bk - b1_off = fx.Int32(B1_gl_offset) + bk - - _scn = [None, None, None, None] - _rd_scn = _read_scale_thunks(kc_i + 1, _scn) - _gk = _min(kc_i + fx.Int32(3), fx.Int32(K_ITERS - 1)) - _sc_gather = _gather_scale_thunks(_gk, _slot(_gk)) - - wait_barrier(top_vmcnt) - il = ( - _riffle( - _g2s_thunks(a0_g2s, ac0, a0_off, N_TILES_A), - _s2r_thunks(a_s2r, ac1, _a1, N_TILES_A, False), - ) - + _rd_scn[:2] - ) - c00f = mfma.call( - a0f, b0f, c00f, saR0, sbC0, interleave=il, zero_acc=zero_acc - ) - - il = _riffle(_g2s_thunks(b_g2s, bc0, b0_off, N_TILES_B), _rd_scn[2:]) - c01f = mfma.call( - a0f, b1f_in, c01f, saR0, sbC1, interleave=il, zero_acc=zero_acc - ) - a1f = _a1 - - wait_barrier(seg2_vmcnt) - il = ( - _riffle( - _g2s_thunks(b_g2s, bc1, b1_off, N_TILES_B), - _s2r_thunks(a_s2r, an0, _a0n, N_TILES_A, False), - ) - + _sc_gather - ) - c10f = mfma.call( - a1f, b0f, c10f, saR1, sbC0, interleave=il, zero_acc=zero_acc - ) - a0nf = _a0n - - il = _riffle( - _g2s_thunks(a1_g2s, ac1, a1_off, N_TILES_A), - _s2r_thunks(b_s2r, bn0, _b0n, N_TILES_B, True) - + _s2r_thunks(b_s2r, bn1, _b1n, N_TILES_B, True), - ) - c11f = mfma.call( - a1f, b1f_in, c11f, saR1, sbC1, interleave=il, zero_acc=zero_acc - ) - b0nf = _b0n - b1nf = _b1n - - sc_next = (_scn[0], _scn[1], _scn[2], _scn[3]) - new_bufs = (an0, an1, ac0, ac1, bn0, bn1, bc0, bc1) - return a0nf, b0nf, b1nf, sc_next, (c00f, c01f, c10f, c11f), new_bufs - - bufs0 = (a_cur0, a_cur1, a_next0, a_next1, b_cur0, b_cur1, b_next0, b_next1) - - def _swap_bufs(bufs): - ac0, ac1, an0, an1, bc0, bc1, bn0, bn1 = bufs - return (an0, an1, ac0, ac1, bn0, bn1, bc0, bc1) - - n_a = 2 * N_TILES_A - n_b = 2 * N_TILES_B - n_ga = N_TILES_A // _FP4_PACK - n_gb = N_TILES_B // _FP4_PACK - n_sc = 2 * n_ga + 2 * n_gb - _R = fx.as_ir_value - - def _flat_sc(sc): - saR0, saR1, sbC0, sbC1 = sc - return ( - [_R(v) for v in saR0] - + [_R(v) for v in saR1] - + [_R(v) for v in sbC0] - + [_R(v) for v in sbC1] - ) - - def _unflat_sc(flat): - o = 0 - saR0 = list(flat[o : o + n_ga]) - o += n_ga - saR1 = list(flat[o : o + n_ga]) - o += n_ga - sbC0 = list(flat[o : o + n_gb]) - o += n_gb - sbC1 = list(flat[o : o + n_gb]) - o += n_gb - return (saR0, saR1, sbC0, sbC1) - - _accs0 = ( - [None] * N_ACCUMS, - [None] * N_ACCUMS, - [None] * N_ACCUMS, - [None] * N_ACCUMS, - ) - a0f, b0f, b1f, sc, accs, _ = _one_step( - 0, - a0_frag, - b0_frag, - b1_frag, - sc0, - _accs0, - bufs0, - zero_acc=True, - top_vmcnt=_STEP0_VMCNT, - seg2_vmcnt=_STEP0_SEG2_VMCNT, - ) - a0f, b0f, b1f, sc, accs, _ = _one_step( - 1, a0f, b0f, b1f, sc, accs, _swap_bufs(bufs0) - ) - - init_state = ( - _flat_frag(a0f) - + _flat_frag(b0f) - + _flat_frag(b1f) - + _flat_sc(sc) - + [_R(x) for x in accs[0]] - + [_R(x) for x in accs[1]] - + [_R(x) for x in accs[2]] - + [_R(x) for x in accs[3]] - ) - for kk, state in range(2, K_ITERS - 2, UNROLL, init=init_state): - off = 0 - a0f = _unflat_frag(state[off : off + n_a], N_TILES_A) - off += n_a - b0f = _unflat_frag(state[off : off + n_b], N_TILES_B) - off += n_b - b1f = _unflat_frag(state[off : off + n_b], N_TILES_B) - off += n_b - sc = _unflat_sc(state[off : off + n_sc]) - off += n_sc - c00f = list(state[off : off + N_ACCUMS]) - off += N_ACCUMS - c01f = list(state[off : off + N_ACCUMS]) - off += N_ACCUMS - c10f = list(state[off : off + N_ACCUMS]) - off += N_ACCUMS - c11f = list(state[off : off + N_ACCUMS]) - off += N_ACCUMS - accs = (c00f, c01f, c10f, c11f) - - bufs = bufs0 - for u in range_constexpr(UNROLL): - a0f, b0f, b1f, sc, accs, bufs = _one_step( - kk + u, a0f, b0f, b1f, sc, accs, bufs - ) - - new_state = ( - _flat_frag(a0f) - + _flat_frag(b0f) - + _flat_frag(b1f) - + _flat_sc(sc) - + [_R(x) for x in accs[0]] - + [_R(x) for x in accs[1]] - + [_R(x) for x in accs[2]] - + [_R(x) for x in accs[3]] - ) - state = yield new_state - - off = 0 - a0_frag = _unflat_frag(state[off : off + n_a], N_TILES_A) - off += n_a - b0_frag = _unflat_frag(state[off : off + n_b], N_TILES_B) - off += n_b - b1_frag = _unflat_frag(state[off : off + n_b], N_TILES_B) - off += n_b - sc = _unflat_sc(state[off : off + n_sc]) - off += n_sc - c00_frag = list(state[off : off + N_ACCUMS]) - off += N_ACCUMS - c01_frag = list(state[off : off + N_ACCUMS]) - off += N_ACCUMS - c10_frag = list(state[off : off + N_ACCUMS]) - off += N_ACCUMS - c11_frag = list(state[off : off + N_ACCUMS]) - off += N_ACCUMS - - # Tail step K_ITERS - 2 - saR0, saR1, sbC0, sbC1 = sc - _scn = [None, None, None, None] - _rd_scn = _read_scale_thunks(fx.Int32(K_ITERS - 1), _scn) - _a1 = [None] * N_TILES_A - wait_barrier((2 * N_TILES_A) + (2 * N_TILES_B)) - il = _s2r_thunks(a_s2r, a_cur1, _a1, N_TILES_A, False) + _rd_scn - c00_frag = mfma.call(a0_frag, b0_frag, c00_frag, saR0, sbC0, interleave=il) - a1_frag = _a1 - c01_frag = mfma.call(a0_frag, b1_frag, c01_frag, saR0, sbC1) - _a0n = [None] * N_TILES_A - _b0n = [None] * N_TILES_B - _b1n = [None] * N_TILES_B - wait_barrier(1 * N_TILES_A) - il = ( - _s2r_thunks(a_s2r, a_next0, _a0n, N_TILES_A, False) - + _s2r_thunks(b_s2r, b_next0, _b0n, N_TILES_B, True) - + _s2r_thunks(b_s2r, b_next1, _b1n, N_TILES_B, True) - ) - c10_frag = mfma.call(a1_frag, b0_frag, c10_frag, saR1, sbC0, interleave=il) - c11_frag = mfma.call(a1_frag, b1_frag, c11_frag, saR1, sbC1) - a0_frag = _a0n - b0_frag = _b0n - b1_frag = _b1n - - # Tail step K_ITERS - 1 (its A half 1 sits in a_next1; the scf.if - # rewriter must not see the outer buffer names reassigned here). - _a1 = [None] * N_TILES_A - wait_barrier(0) - saR0, saR1, sbC0, sbC1 = (_scn[0], _scn[1], _scn[2], _scn[3]) - il = _s2r_thunks(a_s2r, a_next1, _a1, N_TILES_A, False) - c00_frag = mfma.call(a0_frag, b0_frag, c00_frag, saR0, sbC0, interleave=il) - a1_frag = _a1 - c01_frag = mfma.call(a0_frag, b1_frag, c01_frag, saR0, sbC1) - c10_frag = mfma.call(a1_frag, b0_frag, c10_frag, saR1, sbC0) - c11_frag = mfma.call(a1_frag, b1_frag, c11_frag, saR1, sbC1) - - # ---- epilogue: swiglu-OAI + MXFP4 quant, sorted-row output ---- - out_rsrc = buffer_ops.create_buffer_resource( - OUT_Q, - max_size=False, - num_records_bytes=num_m_blocks * (BLOCK_M * I_BYTES), - ) - osc_rsrc = buffer_ops.create_buffer_resource( - OUT_scale, - max_size=False, - num_records_bytes=num_m_blocks * (BLOCK_M * SCALE_COLS_OUT), - ) - g = lane_id // 16 - r16 = lane_id % 16 - # gate column (in I units) this wave starts at; scale col group of it - col_base = tile_j * LDS_BLOCK_N + wave_j * (N_TILES_B * 16) - colgrp_base = col_base // 32 - - def _epilogue(c_gate, c_up, base_row): - """One quadrant pair (rows base_row + ti*16 + r16, wave's 64 gate - cols).""" - for p in range_constexpr(N_TILES_B // 2): # 32-col group p - colgrp = colgrp_base + p - sc_in_block = (colgrp % 4) * 64 + r16 * 4 + ((colgrp % 8) // 4) * 2 - e8m0_of_ti = [] - for ti in range_constexpr(N_TILES_A): - gv = Vec(c_gate[mfma.idx(ti, 2 * p)]) - gw = Vec(c_gate[mfma.idx(ti, 2 * p + 1)]) - uv = Vec(c_up[mfma.idx(ti, 2 * p)]) - uw = Vec(c_up[mfma.idx(ti, 2 * p + 1)]) - h = [ - _swiglu_oai(fx.Float32(gv[v]), fx.Float32(uv[v])) - for v in range_constexpr(4) - ] + [ - _swiglu_oai(fx.Float32(gw[v]), fx.Float32(uw[v])) - for v in range(4) - ] - h, amax = _quant_prep_fp4(h) - # the 4 lanes {L, L^16, L^32, L^48} hold the same row - amax = _fmax(amax, amax.shuffle_xor(16, 64)) - amax = _fmax(amax, amax.shuffle_xor(32, 64)) - e8m0 = _e8m0_roundup_fp4(amax) - e8m0_of_ti.append(e8m0) - scale_f = _as_f32(e8m0 << 23) - pa = _cvt_pk_fp4(fx.Int32(0), h[0], h[1], scale_f, 0) - pa = _cvt_pk_fp4(pa, h[2], h[3], scale_f, 1) - pb = _cvt_pk_fp4(fx.Int32(0), h[4], h[5], scale_f, 0) - pb = _cvt_pk_fp4(pb, h[6], h[7], scale_f, 1) - pa, pb = _permlane16_swap(pa, pb) - dword = pa | (pb << 16) - row = base_row + ti * 16 + r16 - # after the swap lane group g holds tile (2p + g%2), cols - # (g//2)*8 .. +8 - col = col_base + (2 * p + (g % 2)) * 16 + (g // 2) * 8 - buffer_ops.buffer_store( - dword, - out_rsrc, - row * I_BYTES + col // 2, - offset_is_bytes=True, - ) - # scales: rows ti (h=0) and ti+1 (h=1) of the same 32-row group -> - # i16 - for tp in range_constexpr(N_TILES_A // 2): - row32 = (base_row // 32) + tp - blk = row32 * OUT_SC_BLOCKS_PER_ROW32 + colgrp // 8 - pair = e8m0_of_ti[2 * tp] | (e8m0_of_ti[2 * tp + 1] << 8) - pair16 = fx.Int32(pair).to(fx.Int16) - buffer_ops.buffer_store( - pair16, - osc_rsrc, - blk * 256 + sc_in_block, - offset_is_bytes=True, - ) - - row_r0 = m_base + wave_i * (N_TILES_A * 16) - row_r1 = row_r0 + LDS_BLOCK_M - _epilogue(c00_frag, c01_frag, row_r0) - _epilogue(c10_frag, c11_frag, row_r1) - - @flyc.jit - def launch_gemm1( - A: fx.Tensor, - W13: fx.Tensor, - OUT_Q: fx.Tensor, - A_scale: fx.Tensor, - W13_scale: fx.Tensor, - OUT_scale: fx.Tensor, - sorted_ids: fx.Tensor, - sorted_expert_ids: fx.Tensor, - n_tokens: fx.Int32, - num_m_blocks: fx.Int32, - a_scale_bytes: fx.Int32, - tile_map_t: fx.Tensor, - grid_size: fx.Int32, - stream: fx.Stream, - ): - grid_x = grid_size - kernel_gemm1( - A, - W13, - OUT_Q, - A_scale, - W13_scale, - OUT_scale, - sorted_ids, - sorted_expert_ids, - n_tokens, - num_m_blocks, - a_scale_bytes, - tile_map_t, - grid_size, - value_attrs={ - "rocdl.waves_per_eu": 1, - "rocdl.flat_work_group_size": "256,256", - }, - ).launch(grid=(grid_x, 1, 1), block=(256, 1, 1), stream=stream) - - return launch_gemm1 diff --git a/vllm/models/minimax_m3/amd/ops/moe_mxfp4/gemm2_prefill.py b/vllm/models/minimax_m3/amd/ops/moe_mxfp4/gemm2_prefill.py deleted file mode 100644 index 7725aecd1a49..000000000000 --- a/vllm/models/minimax_m3/amd/ops/moe_mxfp4/gemm2_prefill.py +++ /dev/null @@ -1,1088 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project - -"""MiniMax-M3 prefill MoE stage 2 (a4w4, down projection), token-major output. - - y[tok, slot, :] = h[row, :] @ W2[e]^T row = sorted row of (tok, slot) - -``out_dtype`` "bf16": out[tok*topk + slot, :] = bf16(y * sorted_weights[row]), summed -by the bf16 reduce; "fp8": MXFP8 rows with the routing weights left to the reduce. - -One CTA owns an m-tile of 128 sorted rows and sweeps ``NT`` n-tiles of 256 columns: -K = I = 768 is only 3 K-steps, so the A tile stays in AGPRs for the whole sweep and -the (n-tile, k-step) sequence is one depth-3 pipeline. The epilogue runs in the MFMA -shadow and writes token-major 128-B lines; padded rows fall outside the buffer -resource. Consecutive m-tiles (same expert) go to the same XCD. - -Layouts (bytes): - A [num_m_blocks*BM, I/2] sorted rows, fp4 (gemm1 OUT_Q) - A_scale [num_m_blocks*BM, I/32] sorted rows, e8m0-shuffled (gemm1 OUT_sc) - W2 [E, H, I/2] aiter shuffle_weight(layout=(16,16)) - W2_sc [E*H, I/32] aiter e8m0_shuffle - sorted_w [num_m_blocks*BM] f32 routing weight per sorted row (bf16 mode) - OUT [n_tokens*topk, H] bf16, or fp8 e4m3 (OCP) - OUT_sc [n_tokens*topk, H/32] e8m0 (fp8 mode; any buffer in bf16 mode) -""" - -import flydsl.compiler as flyc -import flydsl.expr as fx -from aiter.ops.flydsl.kernels import buffer_ops -from flydsl._mlir import ir as _ir -from flydsl._mlir.dialects import arith as _arith -from flydsl._mlir.dialects import llvm as _llvm -from flydsl.expr import const_expr, range_constexpr -from flydsl.expr import rocdl as _rocdl -from flydsl.expr.typing import T as _T -from flydsl.expr.typing import Vector as Vec - -from .gemm1_prefill import ( - _N_WAVES, - G2SLoaderAsm, - Mfma16x16x128Fp4, - S2RLoaderFp4, - _as_f32, - _asm_void, - _bits, - _Buf, - _divmod_nonneg, - _g2s_thunks, - _lds_ptr_t, - _min, - _permlane16_swap, - _s2r_thunks, - _swizzled_col, - _uniform_i32, - wait_barrier, -) - -_NUM_XCDS = 8 - - -class _MfmaAgprAB(Mfma16x16x128Fp4): - """Same MFMA, but both matrix fragments come from AGPRs (A pinned there for the - whole n-sweep, B loaded there by ds_read) and the accumulator lives in VGPRs, so the - epilogue reads it without v_accvgpr_read copies.""" - - def _mfma_agpr(self, a_op, b_op, acc, sa_v, sb_v, ksub, ia, jb): - a_op, b_op = ( - b_op, - a_op, - ) # feeds (B, A): lane L holds C[row L%16, cols 4*(L//16)..] - sa_v, sb_v = sb_v, sa_v - ia, jb = jb, ia - opsel = f"op_sel:[{ia},{jb},0]" - opsel_hi = f"op_sel_hi:[{ksub},{ksub},0]" - src2 = "$0" if acc is not None else "0" - asm = ( - f"v_mfma_scale_f32_16x16x128_f8f6f4 $0, $1, $2, {src2}, $3, $4 " - f"{opsel} {opsel_hi} cbsz:4 blgp:4" - ) - ops = [ - fx.as_ir_value(a_op), - fx.as_ir_value(b_op), - fx.as_ir_value(sa_v), - fx.as_ir_value(sb_v), - ] - cons = "=v,a,a,v,v" - if acc is not None: - ops.append(fx.as_ir_value(acc)) - cons += ",0" - return _llvm.inline_asm(self.res_ty, ops, asm, cons, has_side_effects=True) - - -def _lds_ptr(addr_i32): - return _llvm.inttoptr(_lds_ptr_t(), fx.as_ir_value(addr_i32)) - - -def _lds_load_i32(addr_i32): - return fx.Int32( - _llvm.LoadOp(fx.Int32.ir_type, _lds_ptr(addr_i32), alignment=4).result - ) - - -def _lds_load_vec(addr_i32, n): - ty = _ir.VectorType.get([n], _T.i32) - return _llvm.LoadOp(ty, _lds_ptr(addr_i32), alignment=4 * n).result - - -def _lds_store_vec(vec, addr_i32, n): - _llvm.StoreOp(vec, _lds_ptr(addr_i32), alignment=4 * n) - - -def _bf16x2(a, b): - """Two f32 -> one i32 of 2 bf16 (RNE, v_cvt_pk_bf16_f32: the same conversion as - production's arith.truncf)""" - return Vec.from_elements([a, b], fx.Float32).to(fx.BFloat16).bitcast(fx.Int32)[0] - - -def _cvt_pk_fp8(old, a, b, scale_f32, hi: bool): - """v_cvt_scalef32_pk_fp8_f32: (a, b) / scale -> 2 x e4m3 into the low (hi=False) - or high 16 bits of ``old`` (the intrinsic works on <2 x i16>; i32 in/out here).""" - v2i16 = _ir.VectorType.get([2], _ir.IntegerType.get_signless(16)) - old_v = _llvm.bitcast(v2i16, fx.as_ir_value(old)) - res = _llvm.call_intrinsic( - v2i16, - "llvm.amdgcn.cvt.scalef32.pk.fp8.f32", - [ - old_v, - fx.as_ir_value(a), - fx.as_ir_value(b), - fx.as_ir_value(scale_f32), - fx.Boolean(hi).ir_value(), - ], - [], - [], - ) - return fx.Int32(_llvm.bitcast(_T.i32, res)) - - -def _e8m0_fp8(amax): - """floor(log2 amax) - 7, floored at 0: amax / 2^(e-127) lands in [128, 256), - inside e4m3 (max 448) with one bit of headroom, never saturates.""" - e = (_bits(amax) >> 23) - fx.Int32(7) - return (e > fx.Int32(0)).select(e, fx.Int32(0)) - - -def _fabs(v): - return fx.math.absf(v) - - -def _maxf(a, b): - """v_max_f32 (arith.maxnumf), not the select-based gemm1 helper""" - return fx.Float32(fx.arith.maxnumf(fx.as_ir_value(a), fx.as_ir_value(b))) - - -def _permlane32_swap(d_a, d_b): - pair_ty = _ir.Type.parse("!llvm.struct<(i32, i32)>") - res = _rocdl.permlane32_swap( - pair_ty, fx.as_ir_value(d_a), fx.as_ir_value(d_b), False, False - ) - return fx.Int32(_llvm.extractvalue(_T.i32, res, [0])), fx.Int32( - _llvm.extractvalue(_T.i32, res, [1]) - ) - - -def _maxf_nn(a, b): - """v_max_f32 with nnan. Without the flag LLVM canonicalizes both inputs first - (``v_max x, x, x``, maxnum must quiet sNaNs): 2 extra VALU per max in the - epilogue.""" - fm = _ir.Attribute.parse("#arith.fastmath") - return fx.Float32( - _arith.MaxNumFOp(fx.as_ir_value(a), fx.as_ir_value(b), fastmath=fm).result - ) - - -def _xlane_max4_pair(x, y): - """4-lane max (lanes L, L^16, L^32, L^48) of two values at once, both broadcast to - every lane, in 3 permlane swaps (2 x 2 done separately, plus 2 copies): - swap32(x, y) -> [x_lo|y_lo], [x_hi|y_hi]; max -> m = [X2 | Y2]; - swap16(m, m) + max -> M = [X4 X4 | Y4 Y4]; swap32(M, M) -> [X4|X4], [Y4|Y4].""" - a, b = _permlane32_swap(_bits(x), _bits(y)) - m = _bits(_maxf_nn(_as_f32(a), _as_f32(b))) - a, b = _permlane16_swap(m, m) - big = _bits(_maxf_nn(_as_f32(a), _as_f32(b))) - a, b = _permlane32_swap(big, big) - return _as_f32(a), _as_f32(b) - - -def _undef_i32(): - """Cvt destination whose other half is overwritten anyway: no v_mov 0 for it""" - return _llvm.mlir_undef(_T.i32) - - -def _lds_store_i16(v_i32, addr_i32): - h = _arith.TruncIOp(_ir.IntegerType.get_signless(16), fx.as_ir_value(v_i32)).result - _llvm.StoreOp(h, _lds_ptr(addr_i32), alignment=2) - - -def _ld_dword_asm(rsrc, voff_bytes): - """buffer_load_dword whose completion we account for ourselves: LLVM sees no load, - so it adds no vmcnt wait (which would drain the whole DMA stream). The result must - go through ``_wait_pin`` before any use; it stays live until then, so LLVM cannot - reuse the register while the load is in flight.""" - return fx.Int32( - _llvm.inline_asm( - _T.i32, - [ - fx.as_ir_value(voff_bytes), - fx.as_ir_value(rsrc), - _uniform_i32(fx.Int32(0)), - ], - "buffer_load_dword $0, $1, $2, $3 offen", - "=v,v,s,s", - has_side_effects=True, - ) - ) - - -def _wait_pin(vals, vmcnt): - """``s_waitcnt vmcnt(n)`` with every value tied through it: uses of the returned - values cannot be scheduled before the wait.""" - n = len(vals) - ty = _ir.Type.parse("!llvm.struct<(" + ", ".join(["i32"] * n) + ")>") - cons = ",".join(["=v"] * n + [str(i) for i in range(n)]) - res = _llvm.inline_asm( - ty, - [fx.as_ir_value(v) for v in vals], - f"s_waitcnt vmcnt({vmcnt})", - cons, - has_side_effects=True, - ) - return [fx.Int32(_llvm.extractvalue(_T.i32, res, [i])) for i in range(n)] - - -def _pin_vec4(v): - """Route an accumulator through a side-effecting no-op asm (tied VGPR operand): its - consumers cannot be scheduled before the asm, and the asm keeps its place among the - MFMA asms, so the reads happen 8+ MFMAs after the one that produced the value (the - compiler cannot see inline-asm MFMAs -> inserts no hazard wait states).""" - ty = Vec.make_type(4, fx.Float32) - return _llvm.inline_asm( - ty, [fx.as_ir_value(v)], "; pin $0", "=v,0", has_side_effects=True - ) - - -def _v2i32(a, b): - return Vec.from_elements([a, b], fx.Int32).ir_value() - - -class _BScaleGather: - """Per pipeline step the 8 e8m0 blocks (256 B = 32 W2 rows x 8 K-groups) of - the n-tile's 256 rows for one K-step, 2 ``buffer_load_dword ... lds`` per - wave (wave w fetches row-groups 2w, 2w+1 into slot bytes [2w*256, +512)).""" - - def __init__(self, rsrc, lane_id, wave_id, region_base_i32): - self.rsrc = fx.as_ir_value(rsrc) - self.voff = [ - fx.as_ir_value((wave_id * 2 + q) * fx.Int32(768) + lane_id * fx.Int32(4)) - for q in range(2) - ] - wave_u = fx.Int32(_rocdl.readfirstlane(_T.i32, fx.as_ir_value(wave_id))) - self.base_s = _uniform_i32(region_base_i32 + wave_u * fx.Int32(512)) - - def gather(self, slot_byte_off, soff_bytes): - m0 = fx.as_ir_value(fx.Int32(self.base_s) + slot_byte_off) - soff = _uniform_i32(soff_bytes) - asm = ( - "s_mov_b32 m0, $0\n" - "buffer_load_dword $1, $2, $3 offen lds\n" - "s_add_u32 m0, 256, m0\n" - "buffer_load_dword $4, $2, $3 offen lds" - ) - _asm_void( - [m0, self.voff[0], self.rsrc, soff, self.voff[1]], - asm, - "s,v,s,s,v", - "~{scc}", - ) - - -# non-temporal row stores (3-8% faster); the 4-B scale stores need L2 write combining -_STORE_CPOL = 0x2 -_STORE_CPOL_SC = 0 - - -def compile_moe_gemm2( - *, - H: int, - I: int, # noqa: E741 - E: int, - topk: int, - n_split: int = 2, - out_dtype: str = "bf16", - sort_block_m: int = 128, -): - """fp4 grouped down-projection with token-major output (see the module doc). - The CTA tile is always 128 sorted rows; ``sort_block_m`` (128 or 256) is the - block size of the sort that produced the rows: with 256, ``sorted_expert_ids`` - has one entry per 256 rows (index ``tile_i >> 1``) and a 128-row tile that - starts with a padding sentinel is all padding and is skipped.""" - assert out_dtype in ("bf16", "fp8"), out_dtype - FP8 = out_dtype == "fp8" - BM = 128 - assert sort_block_m in (128, 256), sort_block_m - EID_SHIFT = (sort_block_m // BM).bit_length() - 1 # 0 or 1 - BN = 256 - K = I - K_BYTES = K // 2 - BLOCK_K = 256 - BLOCK_K_BYTES = BLOCK_K // 2 - assert K % BLOCK_K == 0 - K_ITERS = K // BLOCK_K # 3 - assert K_ITERS == 3, "the flat pipeline uses LDS set = k-step (3 sets)" - N_TILES_ALL = H // BN # 24 - assert N_TILES_ALL % n_split == 0 - NT = N_TILES_ALL // n_split # n-tiles per CTA - assert NT % 2 == 0, "the n loop is unrolled by 2" - LDS_BLOCK_M = BM // 2 # 64 rows per A half - LDS_BLOCK_N = BN // 2 # 128 W2 rows per B half - N_TILES_A = LDS_BLOCK_M // 2 // 16 # 2 - N_TILES_B = LDS_BLOCK_N // 2 // 16 # 4 - N_ACCUMS = N_TILES_A * N_TILES_B - SC_COLS = K // 32 # 24 e8m0 per A row - SC_BLOCKS_PER_G = SC_COLS // 8 # 3 blocks of 256 B per 32-row group - OUT_ELEM = 1 if FP8 else 2 - OUT_ROW_BYTES = H * OUT_ELEM - OUT_SC_COLS = H // 32 - WAVE_COLS = BN // 2 # 128 output columns per wave per n-tile - - a_lds_size = LDS_BLOCK_M * BLOCK_K_BYTES # 8 KB - b_lds_size = LDS_BLOCK_N * BLOCK_K_BYTES # 16 KB - A_BYTES = K_ITERS * 2 * a_lds_size # 48 KB, whole A tile (prologue only) - B_SET_BYTES = 2 * b_lds_size # 32 KB - # set 2 lives in the A region (A is in registers before B(2) is issued) - B_SET_OFF = [A_BYTES, A_BYTES + B_SET_BYTES, 0] - LDS_TILES_BYTES = A_BYTES + 2 * B_SET_BYTES # 112 KB - A_SC_BYTES = 4096 # 12 blocks used (4 groups x 3 K-blocks), 4 waves x 1 KB DMA - B_SC_SLOT = 2048 # 8 blocks - B_SC_SLOTS = 4 - SC_LDS_BYTES = A_SC_BYTES + B_SC_SLOTS * B_SC_SLOT # 12 KB - B_SC_OFF = A_SC_BYTES - # staging: per wave 32 rows x 128 columns of the output element (+ fp8 scale bytes) - STG_ROW = WAVE_COLS * OUT_ELEM # 128 (fp8) / 256 (bf16) B per staged row - CH = STG_ROW // 16 # 16-B chunks per row: 8 / 16 - STG_DATA = 32 * STG_ROW - STG_SC = 32 * 4 if FP8 else 0 # 4 e8m0 per row per wave - STG_WAVE = (STG_DATA + STG_SC + 255) // 256 * 256 - STG_LDS_BYTES = _N_WAVES * STG_WAVE - ROWS_PER_ST = 64 // CH # rows covered by one dwordx4 wave store: 8 / 4 - N_ST = 32 // ROWS_PER_ST # data stores per flushed row half: 4 / 8 - assert LDS_TILES_BYTES + SC_LDS_BYTES + STG_LDS_BYTES <= 160 * 1024 - - NB = N_TILES_B - NG = 2 # gather loads per wave per step - P_STEP = 2 * NB + NG # loads per lane per step - ST = N_ST + (1 if FP8 else 0) # stores per lane per flush - - B_TILE_BYTES = BN * K_BYTES # W2 bytes per n-tile - B_K_STEP = 2 * 1024 # preshuffled: 128 B of K = 2 x (16 rows x 64 B) - - @fx.struct - class SharedStorage: - all_lds: fx.Array[fx.Int8, LDS_TILES_BYTES, 16] - scale_lds: fx.Array[fx.Int8, SC_LDS_BYTES, 16] - stage_lds: fx.Array[fx.Int8, STG_LDS_BYTES, 16] - - @flyc.kernel - def kernel_gemm2( - A: fx.Tensor, - W2: fx.Tensor, - OUT: fx.Tensor, - A_scale: fx.Tensor, - W2_scale: fx.Tensor, - OUT_scale: fx.Tensor, - sorted_ids: fx.Tensor, - sorted_expert_ids: fx.Tensor, - sorted_weights: fx.Tensor, - num_valid_ids: fx.Tensor, - n_tokens: fx.Int32, - num_m_blocks: fx.Int32, - grid_size: fx.Int32, - ): - lds = fx.SharedAllocator().allocate(SharedStorage).peek() - _base_ptr = lds.all_lds.ptr - _sc_ptr = lds.scale_lds.ptr - _stg_ptr = lds.stage_lds.ptr - - def a_buf(kb, half): - return _Buf(_base_ptr, (kb * 2 + half) * a_lds_size) - - def b_buf(s, half): - return _Buf(_base_ptr, B_SET_OFF[s] + half * b_lds_size) - - lane_id = fx.thread_idx.x % 64 - wave_id = fx.thread_idx.x // 64 - wave_i = wave_id // 2 - wave_j = wave_id % 2 - g4 = lane_id // 16 - r16 = lane_id % 16 - - # ---- work item: (m-tile, n-chunk); consecutive m-tiles share an XCD ---- - nv_rsrc = buffer_ops.create_buffer_resource( - num_valid_ids, max_size=False, num_records_bytes=4 - ) - num_valid = fx.Int32( - buffer_ops.buffer_load( - nv_rsrc, fx.Int32(0), vec_width=1, dtype=fx.Int32, is_scalar=True - ) - ) - n_work = (num_valid // fx.Int32(BM)) * fx.Int32(n_split) - per_xcd = (n_work + fx.Int32(_NUM_XCDS - 1)) // fx.Int32(_NUM_XCDS) - intra, xcd = _divmod_nonneg(fx.block_idx.x, _NUM_XCDS) - work = xcd * per_xcd + intra - block_valid = (intra < per_xcd) & (work < n_work) - work_safe = block_valid.select(work, fx.Int32(0)) - tile_i, chunk = _divmod_nonneg(work_safe, n_split) - m_base = tile_i * BM - eid_rsrc = buffer_ops.create_buffer_resource( - sorted_expert_ids, max_size=False, num_records_bytes=num_m_blocks * 4 - ) - expert = fx.Int32( - buffer_ops.buffer_load( - eid_rsrc, - tile_i >> EID_SHIFT, - vec_width=1, - dtype=fx.Int32, - is_scalar=True, - ) - ) - if const_expr(EID_SHIFT > 0): - # a 256-sort pads each expert to 256 rows: a 128-row tile whose first - # row is the sentinel (tok == n_tokens) holds nothing to compute - ids_pre = buffer_ops.create_buffer_resource( - sorted_ids, max_size=False, num_records_bytes=num_m_blocks * (BM * 4) - ) - first_sid = fx.Int32( - buffer_ops.buffer_load( - ids_pre, m_base, vec_width=1, dtype=fx.Int32, is_scalar=True - ) - ) - block_valid = block_valid & ((first_sid & fx.Int32(0x00FFFFFF)) < n_tokens) - chunk_n0 = chunk * NT # first n-tile (global index) of this CTA - # rotated n-tile sweep: CTA j starts at n-tile 2*j, so the tile it needs next - # was just read by CTA j+1 and sits in L2 (32768 tokens: 830 -> 669 us); only - # inside runs of >= 4 same-expert m-tiles - ROT_STRIDE, ROT_GATE = 2, 3 - _d = fx.Int32(ROT_GATE) - _lo_ok = tile_i >= _d - _hi_ok = tile_i + _d < num_m_blocks - _e_lo = fx.Int32( - buffer_ops.buffer_load( - eid_rsrc, - _lo_ok.select(tile_i - _d, fx.Int32(0)) >> EID_SHIFT, - vec_width=1, - dtype=fx.Int32, - is_scalar=True, - ) - ) - _e_hi = fx.Int32( - buffer_ops.buffer_load( - eid_rsrc, - _hi_ok.select(tile_i + _d, fx.Int32(0)) >> EID_SHIFT, - vec_width=1, - dtype=fx.Int32, - is_scalar=True, - ) - ) - rot_on = (_lo_ok & (_e_lo == expert)) | (_hi_ok & (_e_hi == expert)) - nt_rot = rot_on.select( - _divmod_nonneg(tile_i * fx.Int32(ROT_STRIDE), NT)[1], fx.Int32(0) - ) - - def _pn(nt): - """CTA-local logical n-tile (sweep order) -> physical n-tile of the chunk""" - x = nt + nt_rot - return (x >= fx.Int32(NT)).select(x - fx.Int32(NT), x) - - if block_valid: - ids_rsrc = buffer_ops.create_buffer_resource( - sorted_ids, max_size=False, num_records_bytes=num_m_blocks * (BM * 4) - ) - sw_rsrc = buffer_ops.create_buffer_resource( - sorted_weights, - max_size=False, - num_records_bytes=num_m_blocks * (BM * 4), - ) - a_rsrc = buffer_ops.create_buffer_resource( - A, max_size=False, num_records_bytes=num_m_blocks * (BM * K_BYTES) - ) - as_rsrc = buffer_ops.create_buffer_resource( - A_scale, max_size=False, num_records_bytes=num_m_blocks * (BM * SC_COLS) - ) - b_rsrc = buffer_ops.create_buffer_resource( - W2, max_size=False, num_records_bytes=E * H * K_BYTES - ) - bs_rsrc = buffer_ops.create_buffer_resource( - W2_scale, max_size=False, num_records_bytes=E * H * SC_COLS - ) - - # ---- A: contiguous sorted rows, swizzled 128-B LDS rows ---- - def _a_offsets(half): - offs = [] - for rnd in range_constexpr(N_TILES_A): - row = lane_id // 8 + wave_id * 8 + rnd * (_N_WAVES * 8) - col = (lane_id % 8) * 16 - offs.append( - (m_base + half * LDS_BLOCK_M + row) * fx.Int32(K_BYTES) - + _swizzled_col(row, col) - ) - return offs - - # B: LDS half hb, row r -> W2 row (r//64)*128 + hb*64 + r%64 of the n-tile - def _b_offsets(hb): - offs = [] - for rnd in range_constexpr(NB): - r = lane_id % 8 + wave_id * 8 + rnd * (_N_WAVES * 8) - col = (lane_id // 8) * 16 - w2row = (r // 64) * 128 + hb * 64 + (r % 64) - offs.append( - (w2row // 16) * (K_BYTES * 16) - + (w2row % 16) * 16 - + (col // 64) * 1024 - + ((col % 64) // 16) * 256 - + (col % 16) - ) - return offs - - a0_g2s = G2SLoaderAsm(a_rsrc, _a_offsets(0), N_TILES_A, wave_id) - a1_g2s = G2SLoaderAsm(a_rsrc, _a_offsets(1), N_TILES_A, wave_id) - b0_g2s = G2SLoaderAsm(b_rsrc, _b_offsets(0), NB, wave_id) - b1_g2s = G2SLoaderAsm(b_rsrc, _b_offsets(1), NB, wave_id) - for ld in (a0_g2s, a1_g2s, b0_g2s, b1_g2s): - ld.set_wave_base(_base_ptr) - # A scales: 4 x 1 KB for the 3 KB of this m-tile - as_g2s = G2SLoaderAsm( - as_rsrc, - [ - (m_base // 32) * fx.Int32(SC_BLOCKS_PER_G * 256) - + wave_id * 1024 - + lane_id * 16 - ], - 1, - wave_id, - ) - as_g2s.set_wave_base(_sc_ptr) - sc_base_i32 = fx.Int32(fx.ptrtoint(_sc_ptr)) - bsg = _BScaleGather( - bs_rsrc, lane_id, wave_id, sc_base_i32 + fx.Int32(B_SC_OFF) - ) - - a_s2r = S2RLoaderFp4(wave_i, N_TILES_A) - b_s2r = S2RLoaderFp4(wave_j, NB) - mfma = _MfmaAgprAB(N_TILES_A, NB) - - expert_rows = expert * fx.Int32(H) - b_base_bytes = expert_rows * fx.Int32(K_BYTES) - bs_base_bytes = expert_rows * fx.Int32(SC_COLS) - - def _b_soff(nt, kb): - """W2 byte offset of (n-tile nt [CTA-local], K-step kb)""" - return ( - b_base_bytes - + (chunk_n0 + _pn(nt)) * fx.Int32(B_TILE_BYTES) - + fx.Int32(kb * B_K_STEP) - ) - - def _g_soff(nt, kb): - return ( - bs_base_bytes - + (chunk_n0 + _pn(nt)) * fx.Int32(BN * SC_COLS) - + fx.Int32(kb * 256) - ) - - def _slot_off(nt, kb): - """Scale slot of flat step 3*nt + kb""" - s = (nt * fx.Int32(K_ITERS) + fx.Int32(kb)) & fx.Int32(B_SC_SLOTS - 1) - return s * fx.Int32(B_SC_SLOT) - - def _gather(nt, kb): - bsg.gather(_slot_off(nt, kb), _g_soff(nt, kb)) - - def _load_b(nt, kb): - """Both halves of B(nt, kb) into LDS set kb (issue order b0 then b1)""" - b0_g2s.load(b_buf(kb, 0), _b_soff(nt, kb)) - b1_g2s.load(b_buf(kb, 1), _b_soff(nt, kb)) - - # row ids / routing weights: issued ahead of the DMA stream - def _wave_row(h, r): - return h * LDS_BLOCK_M + wave_i * 32 + r - - _id_rows = [ - _wave_row(h, lane_id // CH + ROWS_PER_ST * k) - for h in range(2) - for k in range(N_ST) - ] + ([_wave_row(h, lane_id % 32) for h in range(2)] if FP8 else []) - _raw_ids = [ - _ld_dword_asm(ids_rsrc, (m_base + r) * fx.Int32(4)) for r in _id_rows - ] - _raw_w = ( - [ - _ld_dword_asm( - sw_rsrc, (m_base + _wave_row(h, ti * 16 + r16)) * fx.Int32(4) - ) - for h in range(2) - for ti in range(N_TILES_A) - ] - if not FP8 - else [] - ) - - # ---- prologue: A (12) + A scales (1), g(0), B(0), B(1), g(1) ---- - for kb in range_constexpr(K_ITERS): - a0_g2s.load(a_buf(kb, 0), fx.Int32(kb * BLOCK_K_BYTES)) - a1_g2s.load(a_buf(kb, 1), fx.Int32(kb * BLOCK_K_BYTES)) - as_g2s.load(_Buf(_sc_ptr, 0), fx.Int32(0)) - n0 = fx.Int32(0) - _gather(n0, 0) - _load_b(n0, 0) - _load_b(n0, 1) - _gather(n0, 1) - - # A + A scales landed (g(0), B(0), B(1), g(1) may fly) - wait_barrier(NG + 2 * NB + 2 * NB + NG) - aF = [[a_s2r.load(a_buf(kb, h)) for h in range(2)] for kb in range(K_ITERS)] - lane_sc = (lane_id // 4) * 16 + (lane_id % 4) * 4 - saA = [ - [ - _lds_load_i32( - sc_base_i32 - + ((h * 2 + wave_i) * SC_BLOCKS_PER_G + kb) * fx.Int32(256) - + lane_sc - ) - for kb in range(K_ITERS) - ] - for h in range(2) - ] - # every wave's A reads are done before B(2) overwrites the A region - wait_barrier(NG + 2 * NB + 2 * NB + NG) - _gather(n0, 2) - _load_b(n0, 2) - - def _read_bsc_thunks(nt, kb, holder): - base = sc_base_i32 + fx.Int32(B_SC_OFF) + _slot_off(nt, kb) + lane_sc - - def _rd(idx, hb, sub): - gi = wave_j * 4 + hb * 2 + sub - holder[idx] = _lds_load_i32(base + fx.Int32(gi * 256)) - - return [ - lambda: _rd(0, 0, 0), - lambda: _rd(1, 0, 1), - lambda: _rd(2, 1, 0), - lambda: _rd(3, 1, 1), - ] - - # B(0) + g(0) landed (B(1), g(1), g(2), B(2) may fly) - wait_barrier(2 * NB + NG + NG + 2 * NB) - b0f = b_s2r.load(b_buf(0, 0), preshuffled=True) - b1f = b_s2r.load(b_buf(0, 1), preshuffled=True) - _sc0 = [None] * 4 - for t in _read_bsc_thunks(n0, 0, _sc0): - t() - - # ---- output rows (token-major) of the rows this lane touches ---- - out_rsrc = buffer_ops.create_buffer_resource( - OUT, max_size=False, num_records_bytes=n_tokens * (topk * OUT_ROW_BYTES) - ) - osc_rsrc = buffer_ops.create_buffer_resource( - OUT_scale, - max_size=False, - num_records_bytes=n_tokens * (topk * OUT_SC_COLS), - ) - - _pinned = _wait_pin(_raw_ids + _raw_w, 2 * NB + NG + NG + 2 * NB) - _pid, _pw = _pinned[: len(_raw_ids)], _pinned[len(_raw_ids) :] - - def _orow(sid): - tok = sid & fx.Int32( - 0x00FFFFFF - ) # padded rows: tok == n_tokens -> OOB -> dropped - slot = (sid >> 24) & fx.Int32(0xFF) - return tok * fx.Int32(topk) + slot - - # data flush: lane L stores staged rows L//CH + ROWS_PER_ST*k, chunk L%CH - out_off = [ - [ - _orow(_pid[h * N_ST + k]) * fx.Int32(OUT_ROW_BYTES) - for k in range(N_ST) - ] - for h in range(2) - ] - # conditional expressions: the DSL rewriter drops non-IR values set in an if - sc_off = ( - [_orow(_pid[2 * N_ST + h]) * fx.Int32(OUT_SC_COLS) for h in range(2)] - if FP8 - else None - ) - # bf16: routing weight of the lane's accumulator rows (ti*16 + r16) - wA = ( - [ - [_as_f32(_pw[h * N_TILES_A + ti]) for ti in range(N_TILES_A)] - for h in range(2) - ] - if not FP8 - else None - ) - - stg_base = fx.Int32(fx.ptrtoint(_stg_ptr)) + wave_id * fx.Int32(STG_WAVE) - stg_sc_base = stg_base + fx.Int32(STG_DATA) - - def _stg_addr(row, chunk, half): - """Staged (row, 16-B chunk, 8-B half); chunks XOR-swizzled by the row so - the column-wise writes and the row-wise reads both spread over the - banks""" - return ( - stg_base - + row * fx.Int32(STG_ROW) - + ((chunk ^ (row % CH)) * 16 + half * 8) - ) - - def _stage_bf16(cq, h, hb, ti, tj): - """One 16x16 tile: 4 f32 -> bf16(v * w_row), 8 B into the staging - buffer""" - cv = Vec(_pin_vec4(cq[mfma.idx(ti, tj)])) - w = wA[h][ti] - v = [fx.Float32(cv[k]) * w for k in range_constexpr(4)] - row = ti * 16 + r16 - chunk = ( - hb * 8 + tj * 2 + g4 // 2 - ) # (hb*64 + tj*16 + g4*4) cols * 2 B / 16 - _lds_store_vec( - _v2i32(_bf16x2(v[0], v[1]), _bf16x2(v[2], v[3])), - _stg_addr(row, chunk, g4 % 2), - 2, - ) - - def _stage_fp8_pair(cq, hb, ti): - """The two 16-row x 32-col groups of (ti, hb) -- tiles (0, 1) and (2, - 3) -- - at once. The fp8 epilogue is VALU-issue bound (1 wave / SIMD; the ATT - showed ~35 sequential instructions per group between two MFMAs), so: one - amax butterfly serves both groups (3 swaps, not 4), nnan maxes (no - canonicalizing self-max), undef cvt destinations (no v_mov 0), the two - e8m0 bytes of a row go out as one 16-bit LDS write. Per group: amax over - the row's 4 lanes, e8m0, 8 fp8 per lane after a permlane16 swap.""" - v = [] - for p in range_constexpr(2): - cv = Vec(_pin_vec4(cq[mfma.idx(ti, 2 * p)])) - cw = Vec(_pin_vec4(cq[mfma.idx(ti, 2 * p + 1)])) - v.append( - [fx.Float32(cv[k]) for k in range_constexpr(4)] - + [fx.Float32(cw[k]) for k in range_constexpr(4)] - ) - am = [] - for p in range_constexpr(2): - a = _maxf_nn(_fabs(v[p][0]), _fabs(v[p][1])) - for k in range_constexpr(2, 8): - a = _maxf_nn(a, _fabs(v[p][k])) - am.append(a) - amax = _xlane_max4_pair(am[0], am[1]) - row = ti * 16 + r16 - e8s = [] - for p in range_constexpr(2): - e8 = _e8m0_fp8(amax[p]) - sf = _as_f32(e8 << 23) - da = _cvt_pk_fp8(_undef_i32(), v[p][0], v[p][1], sf, False) - da = _cvt_pk_fp8(da, v[p][2], v[p][3], sf, True) - db = _cvt_pk_fp8(_undef_i32(), v[p][4], v[p][5], sf, False) - db = _cvt_pk_fp8(db, v[p][6], v[p][7], sf, True) - da, db = _permlane16_swap(da, db) - # lane group g now holds tile (2p + g%2), cols (g//2)*8 .. +8 - chunk = hb * 4 + 2 * p + g4 % 2 - _lds_store_vec(_v2i32(da, db), _stg_addr(row, chunk, g4 // 2), 2) - e8s.append(e8) - _lds_store_i16( - e8s[0] | (e8s[1] << 8), stg_sc_base + row * fx.Int32(4) + hb * 2 - ) - - def _stage_thunks(cq, h, hb): - ts = [] - for ti in range_constexpr(N_TILES_A): - if const_expr(FP8): - ts.append(lambda ti=ti: _stage_fp8_pair(cq, hb, ti)) - else: - for tj in range_constexpr(NB): - ts.append( - lambda ti=ti, tj=tj: _stage_bf16(cq, h, hb, ti, tj) - ) - return ts - - def _flush_thunks(h, nt, mask): - """The wave's staged 32 x 128 outputs -> token-major rows, full lines""" - col_wave = ( - (chunk_n0 + _pn(nt)) * fx.Int32(BN) + wave_j * WAVE_COLS - ) * OUT_ELEM - ts = [] - for k in range_constexpr(N_ST): - - def _st(k=k): - row = lane_id // CH + ROWS_PER_ST * k - chunk = lane_id % CH - data = _lds_load_vec(_stg_addr(row, chunk, 0), 4) - buffer_ops.buffer_store( - data, - out_rsrc, - out_off[h][k] + col_wave + chunk * 16, - mask=mask, - offset_is_bytes=True, - cache_modifier=_STORE_CPOL, - ) - - ts.append(_st) - if const_expr(FP8): - - def _st_sc(): - scv = _lds_load_i32(stg_sc_base + (lane_id % 32) * 4) - sc_col = (chunk_n0 + _pn(nt)) * fx.Int32(BN // 32) + wave_j * 4 - buffer_ops.buffer_store( - scv, - osc_rsrc, - sc_off[h] + sc_col, - mask=mask, - offset_is_bytes=True, - cache_modifier=_STORE_CPOL_SC, - ) - - ts.append(_st_sc) - return ts - - def _wb2(first, c_first, c_other): - """``first`` is a Python bool (static) or a wave-uniform DSL bool""" - if const_expr(isinstance(first, bool)): - wait_barrier(c_first if first else c_other) - elif const_expr(c_first == c_other): - wait_barrier(c_first) - else: - if first: - wait_barrier(c_first) - else: - wait_barrier(c_other) - - # vmcnt allowances (loads and stores retire in issue order) - TOP_K0, SEG_K0 = P_STEP + ST, NG + P_STEP + ST + NB - TOP_K1, SEG_K1 = ST + P_STEP + ST, NG + ST + P_STEP + ST + NB - TOP_K2, SEG_K2 = ST + P_STEP, NG + ST + P_STEP + NB - # first tile: after the prologue [.. B(0), B(1), g(1), g(2), B(2)] - TOP_K0_F = NG + 2 * NB # after g(1): g(2), B(2) - SEG_K0_F = NG + NG + 2 * NB + NB # after b1(1): g(1), g(2), B(2), b0(3) - TOP_K1_F = 2 * NB + P_STEP + ST # after g(2): B(2), step 0 - SEG_K1_F = P_STEP + ST + NB # after b1(2): step 0, b0(4) - for c in ( - TOP_K0, - SEG_K0, - TOP_K1, - SEG_K1, - TOP_K2, - SEG_K2, - TOP_K0_F, - SEG_K0_F, - TOP_K1_F, - SEG_K1_F, - ): - assert c <= 63, c - - def _one_step(nt, nt_next, kb, first, b0f, b1f, sc, accs, epi): - """Flat step s = (nt, kb): B(s) in LDS set kb; issues B(s+3) = (nt+1, - kb) into - the same set and its scales. ``epi``: {phase: thunk-list factory(accs)} - for - the epilogue work hidden in that phase's MFMA shadow.""" - kb1 = (kb + 1) % K_ITERS - nt1 = nt if (kb + 1) < K_ITERS else nt_next - bn0, bn1 = b_buf(kb1, 0), b_buf(kb1, 1) - sbC0, sbC1 = sc - c00, c01, c10, c11 = accs - a0f, a1f = aF[kb][0], aF[kb][1] - zero = kb == 0 - - def _late(ph): - return epi[ph](accs) if ph in epi else None - - _scn = [None] * 4 - rd_scn = _read_bsc_thunks(nt1, kb1, _scn) - b_off3 = _b_soff(nt_next, kb) - - if kb == 0: - _wb2(first, TOP_K0_F, TOP_K0) - elif kb == 1: - _wb2(first, TOP_K1_F, TOP_K1) - else: - wait_barrier(TOP_K2) - il = _g2s_thunks(b0_g2s, b_buf(kb, 0), b_off3, NB) + rd_scn[:2] - mfma.call( - a0f, - b0f, - c00, - [saA[0][kb]], - sbC0, - interleave=il, - zero_acc=zero, - late=_late(1), - ) - mfma.call( - a0f, - b1f, - c01, - [saA[0][kb]], - sbC1, - interleave=rd_scn[2:], - zero_acc=zero, - late=_late(2), - ) - - if kb == 0: - _wb2(first, SEG_K0_F, SEG_K0) - elif kb == 1: - _wb2(first, SEG_K1_F, SEG_K1) - else: - wait_barrier(SEG_K2) - _b0n = [None] * NB - _b1n = [None] * NB - # the gather sets m0: it goes after the m0-relative DMAs - il = _g2s_thunks(b1_g2s, b_buf(kb, 1), b_off3, NB) + [ - lambda: _gather(nt_next, kb) - ] - mfma.call( - a1f, - b0f, - c10, - [saA[1][kb]], - sbC0, - interleave=il, - zero_acc=zero, - late=_late(3), - ) - il = _s2r_thunks(b_s2r, bn0, _b0n, NB, True) + _s2r_thunks( - b_s2r, bn1, _b1n, NB, True - ) - mfma.call( - a1f, - b1f, - c11, - [saA[1][kb]], - sbC1, - interleave=il, - zero_acc=zero, - late=_late(4), - ) - return _b0n, _b1n, (_scn[:2], _scn[2:]) - - _R = fx.as_ir_value - - def _flat_b(frag): - return [_R(t[0]) for t in frag] + [_R(t[1]) for t in frag] - - def _unflat_b(flat): - return [[flat[i], flat[NB + i]] for i in range(NB)] - - def _flat_state(b0f, b1f, sc, c11): - return ( - _flat_b(b0f) - + _flat_b(b1f) - + [_R(v) for v in sc[0]] - + [_R(v) for v in sc[1]] - + [_R(v) for v in c11] - ) - - def _unflat_state(st): - o = 0 - b0f = _unflat_b(st[o : o + 2 * NB]) - o += 2 * NB - b1f = _unflat_b(st[o : o + 2 * NB]) - o += 2 * NB - sc = (list(st[o : o + 2]), list(st[o + 2 : o + 4])) - o += 4 - c11 = list(st[o : o + N_ACCUMS]) - return b0f, b1f, sc, c11 - - def _n_tile(nt, nt_next, first, b0f, b1f, sc, c11_prev, nt_prev, mask_prev): - """Epilogue placement (P = phase): tile t's c00 staged in (t,2) P2, c01 - in - (t,2) P3, rows h0 flushed + c10 staged in (t,2) P4, c11 staged in - (t+1,0) - P1, rows h1 flushed in (t+1,0) P4. Returns (b0f, b1f, sc, c11).""" - accs = tuple([None] * N_ACCUMS for _ in range(4)) - epi_by_kb = { - 0: { - 1: lambda a: _stage_thunks(c11_prev, 1, 1), - 4: lambda a: _flush_thunks(1, nt_prev, mask_prev), - }, - 1: {}, - 2: { - 2: lambda a: _stage_thunks(a[0], 0, 0), - 3: lambda a: _stage_thunks(a[1], 0, 1), - 4: lambda a: ( - _flush_thunks(0, nt, None) + _stage_thunks(a[2], 1, 0) - ), - }, - } - for kb in range_constexpr(K_ITERS): - b0f, b1f, sc = _one_step( - nt, nt_next, kb, first, b0f, b1f, sc, accs, epi_by_kb[kb] - ) - return b0f, b1f, sc, accs[3] - - zero_v4 = Vec.filled(4, 0.0, fx.Float32).ir_value() # accumulator zero - init_state = _flat_state( - b0f, b1f, (_sc0[:2], _sc0[2:]), [zero_v4] * N_ACCUMS - ) - for np_, state in range(0, NT // 2, init=init_state): - b0f, b1f, sc, c11p = _unflat_state(state) - np_i = fx.Int32(np_) - first = np_i == fx.Int32(0) - nt_e = np_i * fx.Int32(2) - nt_o = nt_e + fx.Int32(1) - nt_o_next = _min( - nt_e + fx.Int32(2), fx.Int32(NT - 1) - ) # last pair: redundant reloads - pend_valid = fx.as_ir_value(np_i > fx.Int32(0)) - b0f, b1f, sc, c11e = _n_tile( - nt_e, - nt_o, - first, - b0f, - b1f, - sc, - c11p, - nt_e - fx.Int32(1), - pend_valid, - ) - b0f, b1f, sc, c11o = _n_tile( - nt_o, nt_o_next, False, b0f, b1f, sc, c11e, nt_e, None - ) - state = yield _flat_state(b0f, b1f, sc, c11o) - - # the last tile's c11 has no next step to hide in - b0f, b1f, sc, c11p = _unflat_state(state) - for t in _stage_thunks(c11p, 1, 1) + _flush_thunks( - 1, fx.Int32(NT - 1), None - ): - t() - - # never retire with LDS DMA in flight (the CU reuses the LDS) - wait_barrier(0) - - @flyc.jit - def launch_gemm2( - A: fx.Tensor, - W2: fx.Tensor, - OUT: fx.Tensor, - A_scale: fx.Tensor, - W2_scale: fx.Tensor, - OUT_scale: fx.Tensor, - sorted_ids: fx.Tensor, - sorted_expert_ids: fx.Tensor, - sorted_weights: fx.Tensor, - num_valid_ids: fx.Tensor, - n_tokens: fx.Int32, - num_m_blocks: fx.Int32, - grid_size: fx.Int32, - stream: fx.Stream, - ): - kernel_gemm2( - A, - W2, - OUT, - A_scale, - W2_scale, - OUT_scale, - sorted_ids, - sorted_expert_ids, - sorted_weights, - num_valid_ids, - n_tokens, - num_m_blocks, - grid_size, - value_attrs={ - "rocdl.waves_per_eu": 1, - "rocdl.flat_work_group_size": "256,256", - }, - ).launch(grid=(grid_size, 1, 1), block=(256, 1, 1), stream=stream) - - return launch_gemm2 - - -def gemm2_grid(num_m_blocks: int, n_split: int) -> int: - """Blocks to launch: every (m-tile, chunk) of the allocation, rounded to the 8 XCDs - (the kernel drops the fully padded tail tiles at runtime).""" - return (num_m_blocks * n_split + _NUM_XCDS - 1) // _NUM_XCDS * _NUM_XCDS diff --git a/vllm/models/minimax_m3/amd/ops/moe_mxfp4/prefill.py b/vllm/models/minimax_m3/amd/ops/moe_mxfp4/prefill.py deleted file mode 100644 index 2740ab78f01c..000000000000 --- a/vllm/models/minimax_m3/amd/ops/moe_mxfp4/prefill.py +++ /dev/null @@ -1,217 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""FlyDSL W4A4 MoE prefill chain at TP4 on the ``AITER_MXFP4_MXFP4`` weights: sort, -aiter's scale sort, gemm1 (gate/up + SwiGLU-OAI + MXFP4 quant), gemm2 -(routing-weighted partials), fixed-order reduce. -""" - -import functools - -import torch - -from vllm.models.minimax_m3.amd.ops.flydsl_utils import run_compiled -from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.launch import ( - _get_reduce_bf16, - _get_sort, - _get_tile_map, - _u8_flat, -) - -MIN_PREFILL_TOKENS = 3072 -MAX_PREFILL_TOKENS = 65536 -BM256_FROM_TOKENS = 16384 -GEMM2_N_SPLIT = 2 -GEMM1_SWIGLU_ALPHA = 1.702 -GEMM1_SWIGLU_LIMIT = 7.0 -_GEMM1_BLOCK_K = 256 -# gemm2's K pipeline is written for 3 K-steps of 256 -_GEMM2_INTERMEDIATE = 768 - - -def supports_shapes(hidden_size: int, intermediate_size: int) -> bool: - """gemm1 peels 4 K-steps of 256 and unrolls the rest by 4.""" - k_iters = hidden_size // _GEMM1_BLOCK_K - return ( - hidden_size % _GEMM1_BLOCK_K == 0 - and k_iters >= 8 - and (k_iters - 4) % 4 == 0 - and intermediate_size == _GEMM2_INTERMEDIATE - ) - - -def block_m_for(n_tokens: int) -> int: - return 256 if n_tokens >= BM256_FROM_TOKENS else 128 - - -@functools.cache -def _get_gemm1(hidden_size: int, intermediate_size: int, num_experts: int, bm: int): - from .gemm1_prefill import compile_moe_gemm1 - - return compile_moe_gemm1( - H=hidden_size, I=intermediate_size, E=num_experts, BLOCK_M=bm - ) - - -@functools.cache -def _get_gemm2( - hidden_size: int, intermediate_size: int, num_experts: int, topk: int, bm: int -): - from .gemm2_prefill import compile_moe_gemm2 - - return compile_moe_gemm2( - H=hidden_size, - I=intermediate_size, - E=num_experts, - topk=topk, - n_split=GEMM2_N_SPLIT, - out_dtype="bf16", - sort_block_m=bm, - ) - - -def a4w4_prefill_moe( - x_quant: tuple[torch.Tensor, torch.Tensor], - w13: torch.Tensor, - w13_scale: torch.Tensor, - w2: torch.Tensor, - w2_scale: torch.Tensor, - topk_weights: torch.Tensor, - topk_ids: torch.Tensor, - *, - hidden_size: int, - intermediate_size: int, - num_experts: int, - out: torch.Tensor | None = None, -) -> torch.Tensor: - """``x_quant`` = (fp4 ``[M, H/2]``, e8m0 ``[M, H/32]``) of aiter's per-token - MXFP4 quant -> ``[M, H]`` bf16, on ``AiterMxfp4Experts``' weights.""" - from aiter import dtypes - from aiter.ops.quant import mxfp4_moe_sort_hip - - from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.sort import SortBuffers - from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.tile_map import ( - tile_map_grid, - ) - - from .gemm2_prefill import gemm2_grid - - a_q, x_s = x_quant - n_tokens = a_q.shape[0] - hidden = hidden_size - assert MIN_PREFILL_TOKENS <= n_tokens <= MAX_PREFILL_TOKENS, n_tokens - assert a_q.shape == (n_tokens, hidden // 2) and a_q.is_contiguous() - assert x_s.shape == (n_tokens, hidden // 32) and x_s.is_contiguous() - inter = intermediate_size - topk = topk_ids.shape[1] - topk_ids = topk_ids.to(torch.int32).contiguous() - topk_weights = topk_weights.to(torch.float32).contiguous() - device = topk_ids.device - stream = torch.cuda.current_stream() - bm = block_m_for(n_tokens) - - bufs = SortBuffers.allocate(n_tokens, num_experts, topk, bm, device) - _get_sort(num_experts, topk, bm)( - *bufs.launch_args(topk_ids, topk_weights, n_tokens) - ) - a_s = torch.empty( - ((bufs.sorted_ids.shape[0] + 31) // 32 * 32, (hidden // 32 + 7) // 8 * 8), - dtype=dtypes.fp8_e8m0, - device=device, - ) - mxfp4_moe_sort_hip( - a_s, - x_s.view(dtypes.fp8_e8m0), - bufs.sorted_ids, - bufs.num_valid_ids, - n_tokens, - hidden, - ) - num_m_blocks = bufs.max_sorted // bm - rows = num_m_blocks * bm - grid1 = tile_map_grid(num_m_blocks, inter) - tile_map = torch.empty((grid1 + 1,), dtype=torch.int32, device=device) - run_compiled( - _get_tile_map(inter, bm), - bufs.sorted_expert_ids, - bufs.num_valid_ids, - tile_map, - grid1, - stream, - ) - h_q = torch.empty((rows, inter // 2), dtype=torch.uint8, device=device) - h_s = torch.empty((rows * (inter // 32),), dtype=torch.uint8, device=device) - run_compiled( - _get_gemm1(hidden, inter, num_experts, bm), - _u8_flat(a_q), - _u8_flat(w13), - h_q.view(-1), - _u8_flat(a_s), - _u8_flat(w13_scale), - h_s, - bufs.sorted_ids, - bufs.sorted_expert_ids, - n_tokens, - num_m_blocks, - int(a_s.numel() * a_s.element_size()), - tile_map, - grid1, - stream, - ) - - partial = torch.empty( - (n_tokens * topk, hidden), dtype=torch.bfloat16, device=device - ) - # read only by gemm2's fp8-partial mode - partial_scale = torch.empty((16,), dtype=torch.uint8, device=device) - num_m_blocks2 = rows // 128 - run_compiled( - _get_gemm2(hidden, inter, num_experts, topk, bm), - h_q.view(-1), - _u8_flat(w2), - partial.view(-1), - h_s, - _u8_flat(w2_scale), - partial_scale, - bufs.sorted_ids, - bufs.sorted_expert_ids, - bufs.sorted_weights, - bufs.num_valid_ids, - n_tokens, - num_m_blocks2, - gemm2_grid(num_m_blocks2, GEMM2_N_SPLIT), - stream, - ) - if out is None: - out = torch.empty((n_tokens, hidden), dtype=torch.bfloat16, device=device) - run_compiled( - _get_reduce_bf16(hidden, topk), - partial.view(-1), - out.view(-1), - n_tokens, - stream, - ) - return out - - -def mxfp4_quant( - x: torch.Tensor, q_out: torch.Tensor | None, scale_out: torch.Tensor | None -) -> tuple[torch.Tensor, torch.Tensor]: - """Per-token MXFP4 quant of bf16 ``[M, H]`` by aiter's kernel (the regular - path's from 512 tokens) into ``q_out`` ``[M, H/2]`` / ``scale_out`` - ``[M, H/32]`` uint8.""" - from aiter import dtypes - from aiter.ops.quant import dynamic_per_group_scaled_quant - - m, h = x.shape - if q_out is None: - q_out = torch.empty((m, h // 2), dtype=torch.uint8, device=x.device) - if scale_out is None: - scale_out = torch.empty((m, h // 32), dtype=torch.uint8, device=x.device) - dynamic_per_group_scaled_quant( - q_out.view(dtypes.fp4x2), - x, - scale_out.view(dtypes.fp8_e8m0), - 32, - shuffle_scale=False, - ) - return q_out, scale_out diff --git a/vllm/models/minimax_m3/amd/ops/moe_mxfp8/__init__.py b/vllm/models/minimax_m3/amd/ops/moe_mxfp8/__init__.py deleted file mode 100644 index af74a2a464c0..000000000000 --- a/vllm/models/minimax_m3/amd/ops/moe_mxfp8/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""FlyDSL MXFP8 MoE prefill chain for MiniMax-M3 on gfx950 (``sp_prefill``).""" diff --git a/vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm1_prefill.py b/vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm1_prefill.py deleted file mode 100644 index 67cdba3c0093..000000000000 --- a/vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm1_prefill.py +++ /dev/null @@ -1,822 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""Prefill MoE gate/up GEMM (fp8 x fp8, MXFP8 scales) on sorted rows, with -SwiGLU-OAI and the MXFP8 quant of its output (the gemm2 input). - -Layouts (bytes): - A [n_tokens, H] per-token fp8 (aiter per_1x32 quant) - A_scale [pad32(max_sorted), H/32] sorted rows, e8m0-shuffled - W13 [E, I/16, 2, H/64, 4, 16, 16] shuffle_weight(is_guinterleave, gate_up) - W13_sc [E*I/16, H/256, 4, 16] dwords shuffle_scale(..., True, True) - OUT_Q [num_m_blocks*BLOCK_M, I] sorted rows, fp8 e4m3 - OUT_sc [pad32(num_m_blocks*BLOCK_M), I/32] sorted rows, e8m0-shuffled -""" - -import flydsl.compiler as flyc -import flydsl.expr as fx -from aiter.ops.flydsl.kernels import buffer_ops -from flydsl._mlir.dialects import llvm as _llvm -from flydsl.expr import range_constexpr -from flydsl.expr.typing import Vector as Vec - -from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.epilogue import ( - _cvt_pk_fp8, - _maxf_nn, - _undef_i32, - _v2i32, -) -from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.loaders import ( - _N_WAVES, - _SCALE_A_REGION, - _SCALE_B_REGION, - _SCALE_LDS_BYTES, - _SCALE_SLOTS, - G2SLoaderAsm, - S2RLoader128B, - ScaleGatherMoE, - ScaleLoaderLDS, - _as_f32, - _bits, - _Buf, - _divmod_nonneg, - _flat_frag, - _fmax, - _g2s_thunks, - _min, - _permlane16_swap, - _riffle, - _s2r_thunks, - _swiglu_oai, - _swizzled_col, - _unflat_frag, - wait_barrier, -) - -BLOCK_K = 128 # K bytes per pipeline step -# LLVM does not see the inline-asm MFMA -> v_accvgpr_read hazard and may read a final -# accumulator too early (BLOCK_M 256 lost the last K-step). The last step releases -# each group through ``hold`` one group later; 24 wait states cover one MFMA. -_MFMA_RESULT_WAIT = "s_nop 7\n s_nop 7\n s_nop 7" - - -def _e8m0_roundup_fp8(amax): - """Biased e8m0 of ceil_pow2(amax / 448), at least 1 (0 would give NaN codes).""" - u = _bits(amax * fx.Float32(1.0 / 448.0)) - e = (u >> 23) & fx.Int32(0xFF) - bump = ((u & fx.Int32(0x7FFFFF)) != fx.Int32(0)) & (e < fx.Int32(0xFF)) - e = bump.select(e + fx.Int32(1), e) - return (e < fx.Int32(1)).select(fx.Int32(1), e) - - -def _pack8(h0, h1): - """K [16*klane, +16) and [64 + 16*klane, +16) -> one 8 x i32 MFMA operand.""" - a, b = Vec(h0), Vec(h1) - return Vec.from_elements( - [a[k] for k in range(4)] + [b[k] for k in range(4)], fx.Int32 - ) - - -class Mfma16x16x128Fp8: - """Scaled fp8 MFMAs over an (n_tiles_a x n_tiles_b) quadrant, AGPR accumulators.""" - - def __init__(self, n_tiles_a, n_tiles_b): - assert n_tiles_a % 2 == 0 - self.n_tiles_a = n_tiles_a - self.n_tiles_b = n_tiles_b - self.res_ty = Vec.make_type(4, fx.Float32) - - def idx(self, i, j): - return i * self.n_tiles_b + j - - def _order(self): - order = [] - j0s = list(range(0, self.n_tiles_b, 2)) - for n, i0 in enumerate(range(0, self.n_tiles_a, 2)): - for j0 in reversed(j0s) if n % 2 else j0s: - order += [(i0 + di, j0 + dj) for di in range(2) for dj in range(2)] - return order - - def call( - self, - a, - b, - c, - sa, - sb, - gu, - k2, - interleave=None, - zero_acc=False, - late=None, - late_start=4, - sb_index=None, - ): - """``a[i]`` / ``b[j]``: [half0, half1]; ``sa[i // 2]``: A scale dword of a - 32-row group; ``sb_index(j, gu) -> (dword, byte)`` of the B scale. - ``interleave`` / ``late``: thunks spread over the MFMAs.""" - if sb_index is None: - sb_index = lambda j, gu: (j, gu) # noqa: E731 - thunks = list(interleave) if interleave else [] - late_thunks = list(late) if late else [] - order = self._order() - n_mfma = len(order) - by_slot = {} # type: dict[int, list] - for t, th in enumerate(thunks): - by_slot.setdefault((t * n_mfma) // len(thunks), []).append(th) - n_late_slots = max(n_mfma - late_start, 1) - for t, th in enumerate(late_thunks): - by_slot.setdefault( - late_start + (t * n_late_slots) // len(late_thunks), [] - ).append(th) - for m, (i, j) in enumerate(order): - a_op = _pack8(a[i][0], a[i][1]) - b_op = _pack8(b[j][0], b[j][1]) - acc = None if zero_acc else c[self.idx(i, j)] - sbj, sbb = sb_index(j, gu) - c[self.idx(i, j)] = self._mfma_agpr( - a_op, b_op, acc, sa[i // 2], sb[sbj], i % 2, sbb, k2 - ) - for th in by_slot.get(m, ()): - th() - for m in range( - n_mfma, n_mfma + max(len(thunks), len(late_thunks)) + late_start + 1 - ): - for th in by_slot.get(m, ()): - th() - return c - - def hold(self, c, wait=""): - """Pins ``c`` here (after asm ``wait``): reads cannot move above this point.""" - if wait: - _llvm.inline_asm(None, [], wait, "", has_side_effects=True) - return [ - _llvm.inline_asm( - self.res_ty, [fx.as_ir_value(v)], "", "=a,0", has_side_effects=True - ) - for v in c - ] - - def _mfma_agpr(self, a_op, b_op, acc, sa_v, sb_v, ia, jb, k2): - # (B, A) order: lane L holds C[L % 16, 4 * (L // 16) : +4] - a_op, b_op = b_op, a_op - sa_v, sb_v = sb_v, sa_v - ia, jb = jb, ia - opsel = f"op_sel:[{ia},{jb},0]" - opsel_hi = f"op_sel_hi:[{k2},{k2},0]" - src2 = "$0" if acc is not None else "0" - asm = ( - f"v_mfma_scale_f32_16x16x128_f8f6f4 $0, $1, $2, {src2}, $3, $4 " - f"{opsel} {opsel_hi} cbsz:0 blgp:0" - ) - ops = [ - fx.as_ir_value(a_op), - fx.as_ir_value(b_op), - fx.as_ir_value(sa_v), - fx.as_ir_value(sb_v), - ] - cons = "=a,v,v,v,v" - if acc is not None: - ops.append(fx.as_ir_value(acc)) - cons += ",0" - return _llvm.inline_asm(self.res_ty, ops, asm, cons, has_side_effects=True) - - -def compile_moe_gemm1( - *, - H: int, - I: int, # noqa: E741 - E: int, - BLOCK_M: int = 128, -): - """``BLOCK_M``: the ``moe_sorting`` block size of the inputs (128 or 256).""" - K = H - BLOCK_K_BYTES = BLOCK_K - BLOCK_N = 256 # 128 gate + 128 up cols - LDS_BLOCK_M = BLOCK_M // 2 - LDS_BLOCK_N = BLOCK_N // 2 - N_TILES_A = LDS_BLOCK_M // 2 // 16 # 16-row tiles per wave per LDS half - N_TILES_B = LDS_BLOCK_N // 2 // 16 - - assert BLOCK_M in (128, 256) - assert K % 256 == 0 and I % LDS_BLOCK_N == 0 - K_ITERS = K // BLOCK_K - UNROLL = 4 if (K_ITERS - 4) % 4 == 0 else 2 - assert K_ITERS >= 4 and (K_ITERS - 4) % UNROLL == 0, K_ITERS - N_ACCUMS = N_TILES_A * N_TILES_B - K_BYTES = K - N_BITS = (I // 128 - 1).bit_length() - N0 = I // 16 # 16-column (gate + up) groups per expert - - a_lds_size = LDS_BLOCK_M * BLOCK_K_BYTES - b_lds_size = LDS_BLOCK_N * BLOCK_K_BYTES - A_BUFS = 4 * a_lds_size - LDS_TILES_BYTES = A_BUFS + 4 * b_lds_size - - # scales: A in 32-row groups, W13 in 16-column groups (256 B = 8 K-groups) - A_WAVE_GROUPS = N_TILES_A // 2 # groups per wave per LDS half - A_HALF_GROUPS = LDS_BLOCK_M // 32 - B_WAVE_GROUPS = 4 # consecutive groups per wave quarter - B_HALF_GROUPS = 2 - SCALE_COLS_OUT = I // 32 - OUT_SC_BLOCKS_PER_ROW32 = SCALE_COLS_OUT // 8 - W_BYTES = (2 * I) * K - assert W_BYTES <= 0xFFFFFFFF, "buffer resources address 4 GB" - - @fx.struct - class SharedStorage: - all_lds: fx.Array[fx.Int8, LDS_TILES_BYTES, 16] - scale_lds: fx.Array[fx.Int8, _SCALE_LDS_BYTES, 16] - - @flyc.kernel - def kernel_gemm1( - A: fx.Tensor, - W13: fx.Tensor, - OUT_Q: fx.Tensor, - A_scale: fx.Tensor, - W13_scale: fx.Tensor, - OUT_scale: fx.Tensor, - sorted_ids: fx.Tensor, - sorted_expert_ids: fx.Tensor, - n_tokens: fx.Int32, - num_m_blocks: fx.Int32, - a_scale_bytes: fx.Int32, - tile_map_t: fx.Tensor, - grid_size: fx.Int32, - ): - lds = fx.SharedAllocator().allocate(SharedStorage).peek() - _base_ptr = lds.all_lds.ptr - - a_cur0 = _Buf(_base_ptr, 0 * a_lds_size) - a_cur1 = _Buf(_base_ptr, 1 * a_lds_size) - a_next0 = _Buf(_base_ptr, 2 * a_lds_size) - a_next1 = _Buf(_base_ptr, 3 * a_lds_size) - b_cur0 = _Buf(_base_ptr, A_BUFS + 0 * b_lds_size) - b_cur1 = _Buf(_base_ptr, A_BUFS + 1 * b_lds_size) - b_next0 = _Buf(_base_ptr, A_BUFS + 2 * b_lds_size) - b_next1 = _Buf(_base_ptr, A_BUFS + 3 * b_lds_size) - - lane_id = fx.thread_idx.x % 64 - wave_id = fx.thread_idx.x // 64 - - ids_rsrc = buffer_ops.create_buffer_resource( - sorted_ids, max_size=False, num_records_bytes=num_m_blocks * (BLOCK_M * 4) - ) - eid_rsrc = buffer_ops.create_buffer_resource( - sorted_expert_ids, max_size=False, num_records_bytes=num_m_blocks * 4 - ) - # tile_map[grid_size] = valid entries, split evenly over the 8 XCDs - intra_xcd, xcd = _divmod_nonneg(fx.block_idx.x, 8) - tm_rsrc = buffer_ops.create_buffer_resource( - tile_map_t, max_size=False, num_records_bytes=(grid_size + 1) * 4 - ) - n_valid = fx.Int32( - buffer_ops.buffer_load( - tm_rsrc, grid_size, vec_width=1, dtype=fx.Int32, is_scalar=True - ) - ) - per_xcd = (n_valid + fx.Int32(7)) // fx.Int32(8) - remapped = xcd * per_xcd + intra_xcd - in_chunk = (intra_xcd < per_xcd) & (remapped < n_valid) - entry = fx.Int32( - buffer_ops.buffer_load( - tm_rsrc, - in_chunk.select(remapped, fx.Int32(0)), - vec_width=1, - dtype=fx.Int32, - ) - ) - entry = in_chunk.select(entry, fx.Int32(-1)) - tile_i = entry >> N_BITS - tile_j = entry & ((1 << N_BITS) - 1) - block_valid = entry >= 0 - expert = fx.Int32( - buffer_ops.buffer_load( - eid_rsrc, tile_i, vec_width=1, dtype=fx.Int32, is_scalar=True - ) - ) - m_base = tile_i * BLOCK_M - - if block_valid: - wave_i = wave_id // 2 - wave_j = wave_id % 2 - - def _a_gather_offsets(half): - offs = [] - for rnd in range_constexpr(N_TILES_A): - row = lane_id // 8 + wave_id * 8 + rnd * (_N_WAVES * 8) - col = (lane_id % 8) * 16 - sid = fx.Int32( - buffer_ops.buffer_load( - ids_rsrc, - m_base + half * LDS_BLOCK_M + row, - vec_width=1, - dtype=fx.Int32, - ) - ) - # padded rows: tok == n_tokens, out of bounds -> zeros - tok = sid & fx.Int32(0x00FFFFFF) - offs.append(tok * fx.Int32(K_BYTES) + _swizzled_col(row, col)) - return offs - - gl_off_a0 = _a_gather_offsets(0) - gl_off_a1 = _a_gather_offsets(1) - - # B: LDS row r of half gu (gate 0 / up 1) is in W13 block n0 * 2 + gu, - # n0 = tile_j * 8 + r // 16 - weight_group0 = tile_j * fx.Int32(LDS_BLOCK_N // 16) - group0 = expert * fx.Int32(N0) + weight_group0 - - def _b_offsets(gu): - offs = [] - for rnd in range_constexpr(N_TILES_B): - row = lane_id % 8 + wave_id * 8 + rnd * (_N_WAVES * 8) - col = (lane_id // 8) * 16 - blk = (weight_group0 + fx.Int32(row // 16)) * fx.Int32( - 2 - ) + fx.Int32(gu) - offs.append( - blk * fx.Int32(K_BYTES * 16) - + fx.Int32( - (row % 16) * 16 - + (col // 64) * 1024 - + ((col % 64) // 16) * 256 - + (col % 16) - ) - ) - return offs - - gl_off_b0 = _b_offsets(0) - gl_off_b1 = _b_offsets(1) - A_K_STEP = BLOCK_K_BYTES - B_K_STEP = 2 * 1024 # 128 B of K = two 1 KB blocks - - mfma = Mfma16x16x128Fp8(N_TILES_A, N_TILES_B) - - _scale_base_ptr = lds.scale_lds.ptr - scale_gather = ScaleGatherMoE( - A_scale, - W13_scale, - K, - lane_id, - wave_id, - _scale_base_ptr, - a_scale_bytes, - E * 2 * I * (K // 32), - A_WAVE_GROUPS, - A_HALF_GROUPS, - B_WAVE_GROUPS, - B_HALF_GROUPS, - ) - scale_gather.set_wave_base(m_base, group0 * fx.Int32(32)) - a_scale_ld = ScaleLoaderLDS( - N_TILES_A, lane_id, wave_i, _scale_base_ptr, _SCALE_A_REGION - ) - b_scale_ld = ScaleLoaderLDS( - N_TILES_B, lane_id, wave_j, _scale_base_ptr, _SCALE_B_REGION - ) - - def _slot(g): - return fx.Int32(g) % fx.Int32(_SCALE_SLOTS) - - a_rsrc = buffer_ops.create_buffer_resource( - A, max_size=False, num_records_bytes=n_tokens * K_BYTES - ) - b_rsrc = buffer_ops.create_buffer_resource( - W13, - max_size=False, - num_records_bytes=W_BYTES, - base_byte_offset=fx.Int64(expert) * W_BYTES, - ) - a0_g2s = G2SLoaderAsm(a_rsrc, gl_off_a0, N_TILES_A, wave_id) - a1_g2s = G2SLoaderAsm(a_rsrc, gl_off_a1, N_TILES_A, wave_id) - b0_g2s = G2SLoaderAsm(b_rsrc, gl_off_b0, N_TILES_B, wave_id) - b1_g2s = G2SLoaderAsm(b_rsrc, gl_off_b1, N_TILES_B, wave_id) - for ld in (a0_g2s, a1_g2s, b0_g2s, b1_g2s): - ld.set_wave_base(_base_ptr) - a_s2r = S2RLoader128B(wave_i, N_TILES_A) - b_s2r = S2RLoader128B(wave_j, N_TILES_B) - - # scale block g covers steps 2g, 2g + 1; block g >= 2 is gathered on - # step 2g - 3 - scale_gather.gather(0, _slot(0)) - scale_gather.gather(1, _slot(1)) - - a0_g2s.load(a_cur0, fx.Int32(0 * A_K_STEP)) - b0_g2s.load(b_cur0, fx.Int32(0 * B_K_STEP)) - b1_g2s.load(b_cur1, fx.Int32(0 * B_K_STEP)) - a1_g2s.load(a_cur1, fx.Int32(0 * A_K_STEP)) - - a0_g2s.load(a_next0, fx.Int32(1 * A_K_STEP)) - b0_g2s.load(b_next0, fx.Int32(1 * B_K_STEP)) - b1_g2s.load(b_next1, fx.Int32(1 * B_K_STEP)) - a1_g2s.load(a_next1, fx.Int32(1 * A_K_STEP)) - - # gathers + a_cur0 landed: b0/b1/a1 + the 4 next batches may fly - wait_barrier((3 * N_TILES_A) + (4 * N_TILES_B)) - a0_frag = a_s2r.load(a_cur0) - # b_cur0 AND b_cur1 landed: a1 + the 4 next batches may fly - wait_barrier((3 * N_TILES_A) + (2 * N_TILES_B)) - b0_frag = b_s2r.load(b_cur0, preshuffled=True) - b1_frag = b_s2r.load(b_cur1, preshuffled=True) - - sc0_saR0, sc0_saR1 = a_scale_ld.read(_slot(0)) - sc0_sbC0, sc0_sbC1 = b_scale_ld.read(_slot(0)) - sc0 = (sc0_saR0, sc0_saR1, sc0_sbC0 + sc0_sbC1) - - # Step kc issues a0, b0, [SEG2] b1, the scale gather (odd kc), a1 for step - # kc + 2. Top wait: step kc - 2 complete; SEG2 wait: a0 / b0 / b1 of step - # kc - 1 landed. Step kc - 1 gathered iff its parity k2 == 0. - def _top_vmcnt(k2): - return 2 * N_TILES_A + 2 * N_TILES_B + (1 - k2) - - def _seg2_vmcnt(k2): - return 2 * N_TILES_A + N_TILES_B + (1 - k2) - - # step 0 follows the prologue, which has no gather after a_cur1 - _STEP0_VMCNT = 2 * N_TILES_A + 2 * N_TILES_B - _STEP0_SEG2_VMCNT = 2 * N_TILES_A + N_TILES_B - - def _read_scale_thunks(kc_idx, holder): - s = _slot(fx.Int32(kc_idx) // fx.Int32(2)) - - def _r(dst, ld, half, _s=s): - holder[dst] = ld.read_half(_s, half) - - return [ - lambda: _r(0, a_scale_ld, 0), - lambda: _r(1, a_scale_ld, 1), - lambda: _r(2, b_scale_ld, 0), - lambda: _r(3, b_scale_ld, 1), - ] - - def _one_step( - kc, - k2, - a0f, - b0f, - b1f_in, - sc, - accs, - bufs, - zero_acc=False, - top_vmcnt=None, - seg2_vmcnt=None, - ): - """``kc``: step index; ``k2``: its parity as a Python int.""" - kc_i = fx.Int32(kc) - top_vmcnt = _top_vmcnt(k2) if top_vmcnt is None else top_vmcnt - seg2_vmcnt = _seg2_vmcnt(k2) if seg2_vmcnt is None else seg2_vmcnt - ac0, ac1, an0, an1, bc0, bc1, bn0, bn1 = bufs - saR0, saR1, sbC = sc - c00f, c01f, c10f, c11f = accs - - _a1 = [None] * N_TILES_A - _a0n = [None] * N_TILES_A - _b0n = [None] * N_TILES_B - _b1n = [None] * N_TILES_B - a_off = (kc_i + fx.Int32(2)) * fx.Int32(A_K_STEP) - b_off = (kc_i + fx.Int32(2)) * fx.Int32(B_K_STEP) - - _scn = [None, None, None, None] # type: list - _rd_scn = _read_scale_thunks(kc_i + fx.Int32(1), _scn) - # odd steps only: a list repeat, as an if would become an scf dispatch - _gk = _min( - (kc_i + fx.Int32(3)) // fx.Int32(2), fx.Int32(K_ITERS // 2 - 1) - ) - _sc_gather = [lambda: scale_gather.gather(_gk, _slot(_gk))] * k2 - - wait_barrier(top_vmcnt) - il = ( - _riffle( - _g2s_thunks(a0_g2s, ac0, a_off, N_TILES_A), - _s2r_thunks(a_s2r, ac1, _a1, N_TILES_A, False), - ) - + _rd_scn[:2] - ) - c00f = mfma.call( - a0f, b0f, c00f, saR0, sbC, 0, k2, interleave=il, zero_acc=zero_acc - ) - - il = _riffle(_g2s_thunks(b0_g2s, bc0, b_off, N_TILES_B), _rd_scn[2:]) - c01f = mfma.call( - a0f, - b1f_in, - c01f, - saR0, - sbC, - 1, - k2, - interleave=il, - zero_acc=zero_acc, - ) - a1f = _a1 - - wait_barrier(seg2_vmcnt) - il = ( - _riffle( - _g2s_thunks(b1_g2s, bc1, b_off, N_TILES_B), - _s2r_thunks(a_s2r, an0, _a0n, N_TILES_A, False), - ) - + _sc_gather - ) - c10f = mfma.call( - a1f, b0f, c10f, saR1, sbC, 0, k2, interleave=il, zero_acc=zero_acc - ) - a0nf = _a0n - - il = _riffle( - _g2s_thunks(a1_g2s, ac1, a_off, N_TILES_A), - _s2r_thunks(b_s2r, bn0, _b0n, N_TILES_B, True) - + _s2r_thunks(b_s2r, bn1, _b1n, N_TILES_B, True), - ) - c11f = mfma.call( - a1f, - b1f_in, - c11f, - saR1, - sbC, - 1, - k2, - interleave=il, - zero_acc=zero_acc, - ) - b0nf = _b0n - b1nf = _b1n - - sc_next = (_scn[0], _scn[1], _scn[2] + _scn[3]) - new_bufs = (an0, an1, ac0, ac1, bn0, bn1, bc0, bc1) - return a0nf, b0nf, b1nf, sc_next, (c00f, c01f, c10f, c11f), new_bufs - - bufs0 = (a_cur0, a_cur1, a_next0, a_next1, b_cur0, b_cur1, b_next0, b_next1) - - def _swap_bufs(bufs): - ac0, ac1, an0, an1, bc0, bc1, bn0, bn1 = bufs - return (an0, an1, ac0, ac1, bn0, bn1, bc0, bc1) - - n_a = 2 * N_TILES_A - n_b = 2 * N_TILES_B - n_ga = N_TILES_A // 2 - n_sc = 2 * n_ga + N_TILES_B - _R = fx.as_ir_value - - def _flat_sc(sc): - saR0, saR1, sbC = sc - return ( - [_R(v) for v in saR0] + [_R(v) for v in saR1] + [_R(v) for v in sbC] - ) - - def _unflat_sc(flat): - o = 0 - saR0 = list(flat[o : o + n_ga]) - o += n_ga - saR1 = list(flat[o : o + n_ga]) - o += n_ga - sbC = list(flat[o : o + N_TILES_B]) - return (saR0, saR1, sbC) - - _accs0 = tuple([None] * N_ACCUMS for _ in range(4)) - a0f, b0f, b1f, sc, accs, _ = _one_step( - 0, - 0, - a0_frag, - b0_frag, - b1_frag, - sc0, - _accs0, - bufs0, - zero_acc=True, - top_vmcnt=_STEP0_VMCNT, - seg2_vmcnt=_STEP0_SEG2_VMCNT, - ) - a0f, b0f, b1f, sc, accs, _ = _one_step( - 1, 1, a0f, b0f, b1f, sc, accs, _swap_bufs(bufs0) - ) - - init_state = ( - _flat_frag(a0f) - + _flat_frag(b0f) - + _flat_frag(b1f) - + _flat_sc(sc) - + [_R(x) for x in accs[0]] - + [_R(x) for x in accs[1]] - + [_R(x) for x in accs[2]] - + [_R(x) for x in accs[3]] - ) - # FlyDSL rewrites range(init=...) to a loop carrying state. - for kk, state in range( # type: ignore[call-overload] - 2, K_ITERS - 2, UNROLL, init=init_state - ): - off = 0 - a0f = _unflat_frag(state[off : off + n_a], N_TILES_A) - off += n_a - b0f = _unflat_frag(state[off : off + n_b], N_TILES_B) - off += n_b - b1f = _unflat_frag(state[off : off + n_b], N_TILES_B) - off += n_b - sc = _unflat_sc(state[off : off + n_sc]) - off += n_sc - c00f = list(state[off : off + N_ACCUMS]) - off += N_ACCUMS - c01f = list(state[off : off + N_ACCUMS]) - off += N_ACCUMS - c10f = list(state[off : off + N_ACCUMS]) - off += N_ACCUMS - c11f = list(state[off : off + N_ACCUMS]) - off += N_ACCUMS - accs = (c00f, c01f, c10f, c11f) - - bufs = bufs0 - for u in range_constexpr(UNROLL): - # kk is even: kk + u has u's parity - a0f, b0f, b1f, sc, accs, bufs = _one_step( - kk + u, u % 2, a0f, b0f, b1f, sc, accs, bufs - ) - - new_state = ( - _flat_frag(a0f) - + _flat_frag(b0f) - + _flat_frag(b1f) - + _flat_sc(sc) - + [_R(x) for x in accs[0]] - + [_R(x) for x in accs[1]] - + [_R(x) for x in accs[2]] - + [_R(x) for x in accs[3]] - ) - state = yield new_state - - off = 0 - a0_frag = _unflat_frag(state[off : off + n_a], N_TILES_A) - off += n_a - b0_frag = _unflat_frag(state[off : off + n_b], N_TILES_B) - off += n_b - b1_frag = _unflat_frag(state[off : off + n_b], N_TILES_B) - off += n_b - sc = _unflat_sc(state[off : off + n_sc]) - off += n_sc - c00_frag = list(state[off : off + N_ACCUMS]) - off += N_ACCUMS - c01_frag = list(state[off : off + N_ACCUMS]) - off += N_ACCUMS - c10_frag = list(state[off : off + N_ACCUMS]) - off += N_ACCUMS - c11_frag = list(state[off : off + N_ACCUMS]) - off += N_ACCUMS - - # tail step K_ITERS - 2 (even) - saR0, saR1, sbC = sc - _scn = [None, None, None, None] # type: list - _rd_scn = _read_scale_thunks(fx.Int32(K_ITERS - 1), _scn) - _a1 = [None] * N_TILES_A - wait_barrier((2 * N_TILES_A) + (2 * N_TILES_B)) - il = _s2r_thunks(a_s2r, a_cur1, _a1, N_TILES_A, False) + _rd_scn - c00_frag = mfma.call( - a0_frag, b0_frag, c00_frag, saR0, sbC, 0, 0, interleave=il - ) - a1_frag = _a1 - c01_frag = mfma.call(a0_frag, b1_frag, c01_frag, saR0, sbC, 1, 0) - _a0n = [None] * N_TILES_A - _b0n = [None] * N_TILES_B - _b1n = [None] * N_TILES_B - wait_barrier(1 * N_TILES_A) - il = ( - _s2r_thunks(a_s2r, a_next0, _a0n, N_TILES_A, False) - + _s2r_thunks(b_s2r, b_next0, _b0n, N_TILES_B, True) - + _s2r_thunks(b_s2r, b_next1, _b1n, N_TILES_B, True) - ) - c10_frag = mfma.call( - a1_frag, b0_frag, c10_frag, saR1, sbC, 0, 0, interleave=il - ) - c11_frag = mfma.call(a1_frag, b1_frag, c11_frag, saR1, sbC, 1, 0) - a0_frag = _a0n - b0_frag = _b0n - b1_frag = _b1n - - # tail step K_ITERS - 1 (odd; A half 1 in a_next1) - _a1 = [None] * N_TILES_A - wait_barrier(0) - saR0, saR1, sbC = (_scn[0], _scn[1], _scn[2] + _scn[3]) - il = _s2r_thunks(a_s2r, a_next1, _a1, N_TILES_A, False) - # each final group is released one group later (_MFMA_RESULT_WAIT) - c00_frag = mfma.call( - a0_frag, b0_frag, c00_frag, saR0, sbC, 0, 1, interleave=il - ) - a1_frag = _a1 - c01_frag = mfma.call(a0_frag, b1_frag, c01_frag, saR0, sbC, 1, 1) - c00_frag = mfma.hold(c00_frag) - c10_frag = mfma.call(a1_frag, b0_frag, c10_frag, saR1, sbC, 0, 1) - c01_frag = mfma.hold(c01_frag) - c11_frag = mfma.call(a1_frag, b1_frag, c11_frag, saR1, sbC, 1, 1) - c10_frag = mfma.hold(c10_frag) - c11_frag = mfma.hold(c11_frag, wait=_MFMA_RESULT_WAIT) - - out_rsrc = buffer_ops.create_buffer_resource( - OUT_Q, max_size=False, num_records_bytes=num_m_blocks * (BLOCK_M * I) - ) - osc_rsrc = buffer_ops.create_buffer_resource( - OUT_scale, - max_size=False, - num_records_bytes=num_m_blocks * (BLOCK_M * SCALE_COLS_OUT), - ) - g = lane_id // 16 - r16 = lane_id % 16 - col_base = tile_j * LDS_BLOCK_N + wave_j * (N_TILES_B * 16) - colgrp_base = col_base // 32 - - def _epilogue(c_gate, c_up, base_row): - """Rows ``base_row + ti * 16 + r16`` x the wave's 64 gate columns.""" - for p in range_constexpr(N_TILES_B // 2): - colgrp = colgrp_base + p - sc_in_block = (colgrp % 4) * 64 + r16 * 4 + ((colgrp % 8) // 4) * 2 - e8m0_of_ti = [] - for ti in range_constexpr(N_TILES_A): - gv = Vec(c_gate[mfma.idx(ti, 2 * p)]) - gw = Vec(c_gate[mfma.idx(ti, 2 * p + 1)]) - uv = Vec(c_up[mfma.idx(ti, 2 * p)]) - uw = Vec(c_up[mfma.idx(ti, 2 * p + 1)]) - h = [ - _swiglu_oai(fx.Float32(gv[v]), fx.Float32(uv[v])) - for v in range_constexpr(4) - ] + [ - _swiglu_oai(fx.Float32(gw[v]), fx.Float32(uw[v])) - for v in range(4) - ] - amax = _maxf_nn(fx.math.absf(h[0]), fx.math.absf(h[1])) - for v in range_constexpr(2, 8): - amax = _maxf_nn(amax, fx.math.absf(h[v])) - # the 4 lanes {L, L^16, L^32, L^48} hold the same row - amax = _fmax(amax, amax.shuffle_xor(16, 64)) - amax = _fmax(amax, amax.shuffle_xor(32, 64)) - e8m0 = _e8m0_roundup_fp8(amax) - e8m0_of_ti.append(e8m0) - scale_f = _as_f32(e8m0 << 23) - da = _cvt_pk_fp8(_undef_i32(), h[0], h[1], scale_f, False) - da = _cvt_pk_fp8(da, h[2], h[3], scale_f, True) - db = _cvt_pk_fp8(_undef_i32(), h[4], h[5], scale_f, False) - db = _cvt_pk_fp8(db, h[6], h[7], scale_f, True) - da, db = _permlane16_swap(da, db) - row = base_row + ti * 16 + r16 - # after the swap: tile 2p + g % 2, cols (g // 2) * 8 + [0, 8) - col = col_base + (2 * p + (g % 2)) * 16 + (g // 2) * 8 - buffer_ops.buffer_store( - _v2i32(da, db), - out_rsrc, - row * I + col, - offset_is_bytes=True, - ) - # the e8m0 of tiles 2tp, 2tp + 1 (one 32-row group) as one i16 - for tp in range_constexpr(N_TILES_A // 2): - row32 = (base_row // 32) + tp - blk = row32 * OUT_SC_BLOCKS_PER_ROW32 + colgrp // 8 - pair = e8m0_of_ti[2 * tp] | (e8m0_of_ti[2 * tp + 1] << 8) - pair16 = fx.Int32(pair).to(fx.Int16) - buffer_ops.buffer_store( - pair16, - osc_rsrc, - blk * 256 + sc_in_block, - offset_is_bytes=True, - ) - - row_r0 = m_base + wave_i * (N_TILES_A * 16) - row_r1 = row_r0 + LDS_BLOCK_M - _epilogue(c00_frag, c01_frag, row_r0) - _epilogue(c10_frag, c11_frag, row_r1) - - @flyc.jit - def launch_gemm1( - A: fx.Tensor, - W13: fx.Tensor, - OUT_Q: fx.Tensor, - A_scale: fx.Tensor, - W13_scale: fx.Tensor, - OUT_scale: fx.Tensor, - sorted_ids: fx.Tensor, - sorted_expert_ids: fx.Tensor, - n_tokens: fx.Int32, - num_m_blocks: fx.Int32, - a_scale_bytes: fx.Int32, - tile_map_t: fx.Tensor, - grid_size: fx.Int32, - stream: fx.Stream, - ): - grid_x = grid_size - kernel_gemm1( - A, - W13, - OUT_Q, - A_scale, - W13_scale, - OUT_scale, - sorted_ids, - sorted_expert_ids, - n_tokens, - num_m_blocks, - a_scale_bytes, - tile_map_t, - grid_size, - value_attrs={ - "rocdl.waves_per_eu": 1, - "rocdl.flat_work_group_size": "256,256", - }, - ).launch(grid=(grid_x, 1, 1), block=(256, 1, 1), stream=stream) - - return launch_gemm1 diff --git a/vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm2_prefill.py b/vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm2_prefill.py deleted file mode 100644 index 0751680e016e..000000000000 --- a/vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm2_prefill.py +++ /dev/null @@ -1,682 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""Prefill MoE down GEMM (fp8 x fp8, MXFP8 scales) on sorted rows: routing-weighted -bf16 partials ``OUT[tok * topk + slot]``, summed by ``moe_flydsl_common.reduce_bf16``. -A CTA owns a 128-row m-tile and sweeps ``NT`` n-tiles of 256 W2 rows as one K-step -sequence; W2 runs three steps ahead (3 LDS stages), A two. - -Layouts (bytes): - A [num_m_blocks*BM, I] sorted rows, fp8 (gemm1 OUT_Q) - A_scale [pad32(num_m_blocks*BM), I/32] sorted rows, e8m0-shuffled (gemm1 OUT_sc) - W2 [E, H, I] aiter shuffle_weight (16 x 64 K blocks) - W2_sc [E*H/32, I/256, 4, 16] dwords aiter shuffle_scale - sorted_w [num_m_blocks*BM] f32 routing weight per sorted row - OUT [n_tokens*topk, H] bf16 -""" - -import flydsl.compiler as flyc -import flydsl.expr as fx -from aiter.ops.flydsl.kernels import buffer_ops -from flydsl.expr import const_expr, range_constexpr -from flydsl.expr.typing import Vector as Vec - -from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.epilogue import ( - _NUM_XCDS, - _STORE_CPOL, - _bf16x2, - _lds_load_vec, - _lds_store_vec, - _v2i32, -) -from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.loaders import ( - _N_WAVES, - _SCALE_A_REGION, - _SCALE_B_REGION, - _SCALE_SLOT_BYTES, - G2SLoaderAsm, - S2RLoader128B, - ScaleGatherMoE, - ScaleLoaderLDS, - _asm_void, - _Buf, - _divmod_nonneg, - _flat_frag, - _g2s_thunks, - _riffle, - _s2r_thunks, - _swizzled_col, - _unflat_frag, - wait_barrier, -) - -from .gemm1_prefill import BLOCK_K, Mfma16x16x128Fp8 - -_SCALE_SLOTS2 = 4 - - -def compile_moe_gemm2( - *, - H: int, - I: int, # noqa: E741 - E: int, - topk: int, - n_split: int = 2, - sort_block_m: int = 128, -): - """``sort_block_m``: the sort block of the inputs (128 or 256); the kernel tiles - 128 rows and skips the all-padding halves of a 256-sort.""" - BM = 128 - BN = 256 - K = I - K_BYTES = K - BLOCK_K_BYTES = BLOCK_K - EID_SHIFT = (sort_block_m // BM).bit_length() - 1 - assert sort_block_m in (BM, 2 * BM) - N_TILES_ALL = H // BN - assert H % BN == 0 and N_TILES_ALL % n_split == 0 - NT = N_TILES_ALL // n_split # n-tiles per CTA - K_ITERS = K // BLOCK_K - assert K_ITERS in (6, 12, 24) and K % 256 == 0 - SCALE_BLOCKS = K_ITERS // 2 - LDS_BLOCK_M = BM // 2 - LDS_BLOCK_N = BN // 2 - N_TILES_A = LDS_BLOCK_M // 2 // 16 - N_TILES_B = LDS_BLOCK_N // 2 // 16 - N_ACCUMS = N_TILES_A * N_TILES_B - NB = N_TILES_B - NA = N_TILES_A - OUT_ROW_BYTES = H * 2 - W2_BYTES = H * K - assert W2_BYTES <= 0xFFFFFFFF - B_TILE_BYTES = BN * K_BYTES - - B_STAGES = 3 - a_lds_size = LDS_BLOCK_M * BLOCK_K_BYTES - b_lds_size = LDS_BLOCK_N * BLOCK_K_BYTES - A_BUFS = 4 * a_lds_size # 2 stages x 2 halves - LDS_TILES_BYTES = A_BUFS + 2 * B_STAGES * b_lds_size - SCALE_LDS_BYTES2 = _SCALE_SLOTS2 * _SCALE_SLOT_BYTES - # wave-private epilogue staging: 16 rows x the wave's 128 bf16 cols - STG_ROW = 2 * N_TILES_B * 16 * 2 # the wave's two 128-B line segments - STG_CH = STG_ROW // 16 - STG_ROWS = 16 # one (row half, a-tile) at a time - STG_WAVE = STG_ROWS * STG_ROW - STG_LDS_BYTES = _N_WAVES * STG_WAVE - N_FLUSH = (STG_ROWS * 2) // 8 # dwordx4 stores per lane per staged block - assert LDS_TILES_BYTES + SCALE_LDS_BYTES2 + STG_LDS_BYTES <= 160 * 1024 - - A_WAVE_GROUPS = N_TILES_A // 2 - A_HALF_GROUPS = LDS_BLOCK_M // 32 - B_WAVE_GROUPS = 2 # 32-row groups per wave (64 W2 rows) - B_HALF_GROUPS = LDS_BLOCK_N // 32 - SC_COLS = K // 32 - W2_SC_BYTES = E * H * SC_COLS - - @fx.struct - class SharedStorage: - all_lds: fx.Array[fx.Int8, LDS_TILES_BYTES, 16] - scale_lds: fx.Array[fx.Int8, SCALE_LDS_BYTES2, 16] - stage_lds: fx.Array[fx.Int8, STG_LDS_BYTES, 16] - - @flyc.kernel - def kernel_gemm2( - A: fx.Tensor, - W2: fx.Tensor, - OUT: fx.Tensor, - A_scale: fx.Tensor, - W2_scale: fx.Tensor, - sorted_ids: fx.Tensor, - sorted_expert_ids: fx.Tensor, - sorted_weights: fx.Tensor, - num_valid_ids: fx.Tensor, - n_tokens: fx.Int32, - num_m_blocks: fx.Int32, - grid_size: fx.Int32, - ): - lds = fx.SharedAllocator().allocate(SharedStorage).peek() - _base_ptr = lds.all_lds.ptr - _scale_base_ptr = lds.scale_lds.ptr - _stg_ptr = lds.stage_lds.ptr - - a_cur0 = _Buf(_base_ptr, 0 * a_lds_size) - a_cur1 = _Buf(_base_ptr, 1 * a_lds_size) - a_next0 = _Buf(_base_ptr, 2 * a_lds_size) - a_next1 = _Buf(_base_ptr, 3 * a_lds_size) - # B: 3 stages x 2 halves - b_st = [ - [_Buf(_base_ptr, A_BUFS + (2 * st + hf) * b_lds_size) for hf in range(2)] - for st in range(B_STAGES) - ] - - lane_id = fx.thread_idx.x % 64 - wave_id = fx.thread_idx.x // 64 - wave_i = wave_id // 2 - wave_j = wave_id % 2 - g4 = lane_id // 16 - r16 = lane_id % 16 - - # work item (m-tile, n-chunk); consecutive m-tiles share an XCD - nv_rsrc = buffer_ops.create_buffer_resource( - num_valid_ids, max_size=False, num_records_bytes=4 - ) - num_valid = fx.Int32( - buffer_ops.buffer_load( - nv_rsrc, fx.Int32(0), vec_width=1, dtype=fx.Int32, is_scalar=True - ) - ) - n_work = (num_valid // fx.Int32(BM)) * fx.Int32(n_split) - per_xcd = (n_work + fx.Int32(_NUM_XCDS - 1)) // fx.Int32(_NUM_XCDS) - intra, xcd = _divmod_nonneg(fx.block_idx.x, _NUM_XCDS) - work = xcd * per_xcd + intra - block_valid = (intra < per_xcd) & (work < n_work) - work_safe = block_valid.select(work, fx.Int32(0)) - tile_i, chunk = _divmod_nonneg(work_safe, n_split) - m_base = tile_i * BM - eid_rsrc = buffer_ops.create_buffer_resource( - sorted_expert_ids, max_size=False, num_records_bytes=num_m_blocks * 4 - ) - expert = fx.Int32( - buffer_ops.buffer_load( - eid_rsrc, - tile_i >> EID_SHIFT, - vec_width=1, - dtype=fx.Int32, - is_scalar=True, - ) - ) - ids_rsrc = buffer_ops.create_buffer_resource( - sorted_ids, max_size=False, num_records_bytes=num_m_blocks * (BM * 4) - ) - if const_expr(EID_SHIFT > 0): - # a 256-sort pads each expert: a 128-row tile starting with padding is empty - first_sid = fx.Int32( - buffer_ops.buffer_load( - ids_rsrc, m_base, vec_width=1, dtype=fx.Int32, is_scalar=True - ) - ) - block_valid = block_valid & ((first_sid & fx.Int32(0x00FFFFFF)) < n_tokens) - chunk_n0 = chunk * NT - # rotate the n-tile sweep inside same-expert runs: neighbours find W2 in L2 - ROT_STRIDE, ROT_GATE = 2, 3 - _d = fx.Int32(ROT_GATE) - _lo_ok = tile_i >= _d - _hi_ok = tile_i + _d < num_m_blocks - _e_lo = fx.Int32( - buffer_ops.buffer_load( - eid_rsrc, - _lo_ok.select(tile_i - _d, fx.Int32(0)) >> EID_SHIFT, - vec_width=1, - dtype=fx.Int32, - is_scalar=True, - ) - ) - _e_hi = fx.Int32( - buffer_ops.buffer_load( - eid_rsrc, - _hi_ok.select(tile_i + _d, fx.Int32(0)) >> EID_SHIFT, - vec_width=1, - dtype=fx.Int32, - is_scalar=True, - ) - ) - rot_on = (_lo_ok & (_e_lo == expert)) | (_hi_ok & (_e_hi == expert)) - nt_rot = rot_on.select( - _divmod_nonneg(tile_i * fx.Int32(ROT_STRIDE), NT)[1], fx.Int32(0) - ) - - def _pn(nt): - """Sweep-order n-tile -> n-tile of the chunk.""" - x = nt + nt_rot - return (x >= fx.Int32(NT)).select(x - fx.Int32(NT), x) - - def _n_glob(nt): - """Global n-tile of sweep-order ``nt``, clamped to the last one.""" - ntc = (nt >= fx.Int32(NT)).select(fx.Int32(NT - 1), nt) - return chunk_n0 + _pn(ntc) - - if block_valid: - sw_rsrc = buffer_ops.create_buffer_resource( - sorted_weights, - max_size=False, - num_records_bytes=num_m_blocks * (BM * 4), - ) - a_rsrc = buffer_ops.create_buffer_resource( - A, max_size=False, num_records_bytes=num_m_blocks * (BM * K_BYTES) - ) - b_rsrc = buffer_ops.create_buffer_resource( - W2, - max_size=False, - num_records_bytes=W2_BYTES, - base_byte_offset=fx.Int64(expert) * W2_BYTES, - ) - # padded rows (tok == n_tokens) fall outside the resource - out_rows = n_tokens * fx.Int32(topk) - out_rsrc = buffer_ops.create_buffer_resource( - OUT, max_size=False, num_records_bytes=out_rows * OUT_ROW_BYTES - ) - - def _a_offsets(half): - offs = [] - for rnd in range_constexpr(N_TILES_A): - row = lane_id // 8 + wave_id * 8 + rnd * (_N_WAVES * 8) - col = (lane_id % 8) * 16 - grow = m_base + half * LDS_BLOCK_M + row - offs.append(grow * fx.Int32(K_BYTES) + _swizzled_col(row, col)) - return offs - - gl_off_a0 = _a_offsets(0) - gl_off_a1 = _a_offsets(1) - - # W2 offsets inside an n-tile; the n-tile goes in soffset - e_row0 = expert * fx.Int32(H) - - def _b_offsets(hf): - offs = [] - for rnd in range_constexpr(N_TILES_B): - row = lane_id % 8 + wave_id * 8 + rnd * (_N_WAVES * 8) - col = (lane_id // 8) * 16 - wrow = fx.Int32(hf * LDS_BLOCK_N + row) - offs.append( - (wrow // fx.Int32(16)) * fx.Int32(K_BYTES * 16) - + fx.Int32( - (row % 16) * 16 - + (col // 64) * 1024 - + ((col % 64) // 16) * 256 - + (col % 16) - ) - ) - return offs - - gl_off_b0 = _b_offsets(0) - gl_off_b1 = _b_offsets(1) - A_K_STEP = BLOCK_K_BYTES - B_K_STEP = 2 * 1024 - - mfma = Mfma16x16x128Fp8(N_TILES_A, N_TILES_B) - sb_index = lambda j, hf: (j // 2, j % 2) # noqa: E731 (32-row groups) - - scale_gather = ScaleGatherMoE( - A_scale, - W2_scale, - K, - lane_id, - wave_id, - _scale_base_ptr, - num_m_blocks * (BM * SC_COLS), - W2_SC_BYTES, - A_WAVE_GROUPS, - A_HALF_GROUPS, - B_WAVE_GROUPS, - B_HALF_GROUPS, - ) - - def _set_scale_tile(nt): - scale_gather.set_wave_base(m_base, e_row0 + _n_glob(nt) * fx.Int32(BN)) - - a_scale_ld = ScaleLoaderLDS( - N_TILES_A, lane_id, wave_i, _scale_base_ptr, _SCALE_A_REGION - ) - b_scale_ld = ScaleLoaderLDS( - N_TILES_B, lane_id, wave_j, _scale_base_ptr, _SCALE_B_REGION - ) - - def _slot(nt, g): - return (fx.Int32(nt) * fx.Int32(SCALE_BLOCKS) + fx.Int32(g)) % fx.Int32( - _SCALE_SLOTS2 - ) - - a0_g2s = G2SLoaderAsm(a_rsrc, gl_off_a0, N_TILES_A, wave_id) - a1_g2s = G2SLoaderAsm(a_rsrc, gl_off_a1, N_TILES_A, wave_id) - b0_g2s = G2SLoaderAsm(b_rsrc, gl_off_b0, N_TILES_B, wave_id) - b1_g2s = G2SLoaderAsm(b_rsrc, gl_off_b1, N_TILES_B, wave_id) - for ld in (a0_g2s, a1_g2s, b0_g2s, b1_g2s): - ld.set_wave_base(_base_ptr) - a_s2r = S2RLoader128B(wave_i, N_TILES_A) - b_s2r = S2RLoader128B(wave_j, N_TILES_B) - - def _orow(sid): - tok = sid & fx.Int32(0x00FFFFFF) # padded: tok == n_tokens -> OOB - slot = (sid >> 24) & fx.Int32(0xFF) - return tok * fx.Int32(topk) + slot - - # routing weights of the lane's rows; output offsets of the rows it - # flushes (store k: staged row 4k + lane // 16) - wave_row0 = m_base + wave_i * (N_TILES_A * 16) - row_w = [] - for h in range_constexpr(2): - for ti in range_constexpr(N_TILES_A): - row = wave_row0 + fx.Int32(h * LDS_BLOCK_M + ti * 16) + r16 - row_w.append( - fx.Float32( - buffer_ops.buffer_load( - sw_rsrc, row, vec_width=1, dtype=fx.Float32 - ) - ) - ) - flush_off = [] - for h in range_constexpr(2): - for ti in range_constexpr(NA): - for k in range_constexpr(N_FLUSH): - row = ( - wave_row0 - + fx.Int32(h * LDS_BLOCK_M + ti * 16 + 4 * k) - + lane_id // 16 - ) - sid = fx.Int32( - buffer_ops.buffer_load( - ids_rsrc, row, vec_width=1, dtype=fx.Int32 - ) - ) - flush_off.append(_orow(sid) * fx.Int32(OUT_ROW_BYTES)) - stg_base = fx.Int32(fx.ptrtoint(_stg_ptr)) + wave_id * fx.Int32(STG_WAVE) - - def _stg_addr(row, chunk, half): - """Staged (row, 16-B chunk, 8-B half), chunks XOR-swizzled by row.""" - return ( - stg_base - + row * fx.Int32(STG_ROW) - + ((chunk ^ (row % STG_CH)) * 16 + half * 8) - ) - - # prologue = steps -3, -2, -1 of the steady-state issue order - _set_scale_tile(fx.Int32(0)) - scale_gather.gather(0, _slot(0, 0)) - b_soff0 = _n_glob(fx.Int32(0)) * fx.Int32(B_TILE_BYTES) - b0_g2s.load(b_st[0][0], b_soff0 + fx.Int32(0 * B_K_STEP)) - b1_g2s.load(b_st[0][1], b_soff0 + fx.Int32(0 * B_K_STEP)) - b0_g2s.load(b_st[1][0], b_soff0 + fx.Int32(1 * B_K_STEP)) - b1_g2s.load(b_st[1][1], b_soff0 + fx.Int32(1 * B_K_STEP)) - a0_g2s.load(a_cur0, fx.Int32(0 * A_K_STEP)) - a1_g2s.load(a_cur1, fx.Int32(0 * A_K_STEP)) - b0_g2s.load(b_st[2][0], b_soff0 + fx.Int32(2 * B_K_STEP)) - b1_g2s.load(b_st[2][1], b_soff0 + fx.Int32(2 * B_K_STEP)) - a0_g2s.load(a_next0, fx.Int32(1 * A_K_STEP)) - scale_gather.gather(1, _slot(0, 1)) - a1_g2s.load(a_next1, fx.Int32(1 * A_K_STEP)) - - # gather 0, B(0) and a0(0) landed: a1(0), B(2), a0(1), gather, a1(1) may fly - wait_barrier(NA + 2 * NB + NA + 1 + NA) - a0_frag = a_s2r.load(a_cur0) - b0_frag = b_s2r.load(b_st[0][0], preshuffled=True) - b1_frag = b_s2r.load(b_st[0][1], preshuffled=True) - sc0_saR0, sc0_saR1 = a_scale_ld.read(_slot(0, 0)) - sc0_sbC0, sc0_sbC1 = b_scale_ld.read(_slot(0, 0)) - sc0 = (sc0_saR0, sc0_saR1, sc0_sbC0, sc0_sbC1) - - # Step kc issues B(kc + 3), a0(kc + 2), [MID] the scale gather (odd kc), - # a1(kc + 2). Top wait: a1(kc) landed; MID wait: a0(kc + 1) landed. The - # counts leave out the epilogue stores: they retire out of order. - def _top_vmcnt(kc): - return 2 * NB + 2 * NA + (1 - kc % 2) - - def _mid_vmcnt(kc): - return NA + 2 * NB + NA + (1 - kc % 2) - - def _read_scale_thunks(nt, kc_next, holder): - # the next flat step's scales; Python ints only (an ``if`` here would - # become an scf.if) - s = _slot(nt + fx.Int32(kc_next // K_ITERS), (kc_next % K_ITERS) // 2) - - def _r(dst, ld, half, _s=s): - holder[dst] = ld.read_half(_s, half) - - return [ - lambda: _r(0, a_scale_ld, 0), - lambda: _r(1, a_scale_ld, 1), - lambda: _r(2, b_scale_ld, 0), - lambda: _r(3, b_scale_ld, 1), - ] - - def _one_step(nt, kc, a0f, b0f, b1f_in, sc, accs, abufs): - """``nt`` is the n-tile; ``kc`` is a constexpr K-step within it.""" - k2 = kc % 2 - ac0, ac1, an0, an1 = abufs - bst = b_st[kc % 3] # read now, refilled for step kc + 3 - bnx = b_st[(kc + 1) % 3] - saR0, saR1, sbC0, sbC1 = sc - c00f, c01f, c10f, c11f = accs - zero_acc = kc == 0 - - _a1 = [None] * NA - _a0n = [None] * NA - _b0n = [None] * NB - _b1n = [None] * NB - # A for flat step kc + 2, B for kc + 3 (possibly in tile nt + 1) - ka = (kc + 2) % K_ITERS - kb = (kc + 3) % K_ITERS - nt_b = nt + fx.Int32((kc + 3) // K_ITERS) - a_off = fx.Int32(ka * A_K_STEP) - b_off = _n_glob(nt_b) * fx.Int32(B_TILE_BYTES) + fx.Int32(kb * B_K_STEP) - - _scn = [None, None, None, None] - _rd_scn = _read_scale_thunks(nt, kc + 1, _scn) - # Gather scales three steps ahead, crossing n-tiles as needed. - future_block = (kc + 3) // 2 - _g_blk = future_block % SCALE_BLOCKS - _g_slot = _slot(nt + fx.Int32(future_block // SCALE_BLOCKS), _g_blk) - _sc_gather = [lambda: scale_gather.gather(_g_blk, _g_slot)] * k2 - - wait_barrier(_top_vmcnt(kc)) - il = ( - _riffle( - _g2s_thunks(b0_g2s, bst[0], b_off, NB), - _s2r_thunks(a_s2r, ac1, _a1, NA, False), - ) - + _rd_scn[:2] - ) - c00f = mfma.call( - a0f, - b0f, - c00f, - saR0, - sbC0, - 0, - k2, - interleave=il, - zero_acc=zero_acc, - sb_index=sb_index, - ) - # never riffle two G2S loaders: each one's steps share m0, so - # interleaving them corrupts the LDS destinations - il = ( - _g2s_thunks(b1_g2s, bst[1], b_off, NB) - + _g2s_thunks(a0_g2s, ac0, a_off, NA) - + _rd_scn[2:] - ) - c01f = mfma.call( - a0f, - b1f_in, - c01f, - saR0, - sbC1, - 1, - k2, - interleave=il, - zero_acc=zero_acc, - sb_index=sb_index, - ) - a1f = _a1 - - wait_barrier(_mid_vmcnt(kc)) - il = _s2r_thunks(a_s2r, an0, _a0n, NA, False) + _sc_gather - c10f = mfma.call( - a1f, - b0f, - c10f, - saR1, - sbC0, - 0, - k2, - interleave=il, - zero_acc=zero_acc, - sb_index=sb_index, - ) - a0nf = _a0n - il = _riffle( - _g2s_thunks(a1_g2s, ac1, a_off, NA), - _s2r_thunks(b_s2r, bnx[0], _b0n, NB, True) - + _s2r_thunks(b_s2r, bnx[1], _b1n, NB, True), - ) - c11f = mfma.call( - a1f, - b1f_in, - c11f, - saR1, - sbC1, - 1, - k2, - interleave=il, - zero_acc=zero_acc, - sb_index=sb_index, - ) - sc_next = (_scn[0], _scn[1], _scn[2], _scn[3]) - return ( - a0nf, - _b0n, - _b1n, - sc_next, - (c00f, c01f, c10f, c11f), - (an0, an1, ac0, ac1), - ) - - def _stage(accs, h, ti): - """Routing-weighted bf16 of rows (``h``, ``ti``) into the staging - buffer; a wave's LDS ops run in order, after the last flush's reads.""" - w = row_w[h * NA + ti] - for hf in range_constexpr(2): - cq = accs[h * 2 + hf] - for j in range_constexpr(NB): - v = Vec(cq[mfma.idx(ti, j)]) - d0 = _bf16x2(fx.Float32(v[0]) * w, fx.Float32(v[1]) * w) - d1 = _bf16x2(fx.Float32(v[2]) * w, fx.Float32(v[3]) * w) - chunk = fx.Int32(hf * 8 + j * 2) + g4 // 2 - _lds_store_vec(_v2i32(d0, d1), _stg_addr(r16, chunk, g4 % 2), 2) - - def _flush(nt, h, ti): - """The staged rows -> full token-major 128-B lines, non-temporal.""" - col_wave = (_n_glob(nt) * fx.Int32(BN) + wave_j * (N_TILES_B * 16)) * 2 - hf_l = (lane_id // 8) % 2 - ch_l = lane_id % 8 - _asm_void([], "s_waitcnt lgkmcnt(0)", "") - for k in range_constexpr(N_FLUSH): - row = fx.Int32(4 * k) + lane_id // 16 - data = _lds_load_vec(_stg_addr(row, hf_l * 8 + ch_l, 0), 4) - buffer_ops.buffer_store( - data, - out_rsrc, - flush_off[(h * NA + ti) * N_FLUSH + k] - + col_wave - + hf_l * fx.Int32(LDS_BLOCK_N * 2) - + ch_l * fx.Int32(16), - offset_is_bytes=True, - cache_modifier=_STORE_CPOL, - ) - - def _epilogue(nt, accs): - for h in range_constexpr(2): - for ti in range_constexpr(NA): - _stage(accs, h, ti) - _flush(nt, h, ti) - - abufs0 = (a_cur0, a_cur1, a_next0, a_next1) - n_a = 2 * NA - n_b = 2 * NB - n_sc = 2 * (NA // 2) + 2 * (NB // 2) - _R = fx.as_ir_value - - def _flat_sc(sc): - return [_R(v) for part in sc for v in part] - - def _unflat_sc(flat): - sizes = (NA // 2, NA // 2, NB // 2, NB // 2) - out, o = [], 0 - for n in sizes: - out.append(list(flat[o : o + n])) - o += n - return tuple(out) - - init_state = ( - _flat_frag(a0_frag) - + _flat_frag(b0_frag) - + _flat_frag(b1_frag) - + _flat_sc(sc0) - ) - # FlyDSL rewrites range(init=...) to a loop carrying state. - for nt_idx, state in range( # type: ignore[call-overload] - 0, NT, 1, init=init_state - ): - nt = fx.Int32(nt_idx) - off = 0 - a0f = _unflat_frag(state[off : off + n_a], NA) - off += n_a - b0f = _unflat_frag(state[off : off + n_b], NB) - off += n_b - b1f = _unflat_frag(state[off : off + n_b], NB) - off += n_b - sc = _unflat_sc(state[off : off + n_sc]) - accs = ( - [None] * N_ACCUMS, - [None] * N_ACCUMS, - [None] * N_ACCUMS, - [None] * N_ACCUMS, - ) - abufs = abufs0 - # Switch the scale base before the first next-tile gather. - _set_scale_tile(nt) - for kc in range_constexpr(K_ITERS): - if const_expr(kc == K_ITERS - 4): - _set_scale_tile(nt + fx.Int32(1)) - a0f, b0f, b1f, sc, accs, abufs = _one_step( - nt, kc, a0f, b0f, b1f, sc, accs, abufs - ) - _epilogue(nt, accs) - state = ( - yield _flat_frag(a0f) - + _flat_frag(b0f) - + _flat_frag(b1f) - + _flat_sc(sc) - ) - # the redundant loads after the last tile must land before the LDS is reused - wait_barrier(0) - - @flyc.jit - def launch_gemm2( - A: fx.Tensor, - W2: fx.Tensor, - OUT: fx.Tensor, - A_scale: fx.Tensor, - W2_scale: fx.Tensor, - sorted_ids: fx.Tensor, - sorted_expert_ids: fx.Tensor, - sorted_weights: fx.Tensor, - num_valid_ids: fx.Tensor, - n_tokens: fx.Int32, - num_m_blocks: fx.Int32, - grid_size: fx.Int32, - stream: fx.Stream, - ): - kernel_gemm2( - A, - W2, - OUT, - A_scale, - W2_scale, - sorted_ids, - sorted_expert_ids, - sorted_weights, - num_valid_ids, - n_tokens, - num_m_blocks, - grid_size, - value_attrs={ - "rocdl.waves_per_eu": 1, - "rocdl.flat_work_group_size": "256,256", - }, - ).launch(grid=(grid_size, 1, 1), block=(256, 1, 1), stream=stream) - - return launch_gemm2 - - -def gemm2_grid(num_m_blocks: int, n_split: int) -> int: - """Every (m-tile, chunk), rounded up to the 8 XCDs; padded tiles exit early.""" - return (num_m_blocks * n_split + _NUM_XCDS - 1) // _NUM_XCDS * _NUM_XCDS diff --git a/vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm2_prefill_bm256.py b/vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm2_prefill_bm256.py deleted file mode 100644 index 289584059196..000000000000 --- a/vllm/models/minimax_m3/amd/ops/moe_mxfp8/gemm2_prefill_bm256.py +++ /dev/null @@ -1,697 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""``gemm2_prefill`` on 256-row m-tiles (each wave 128 x 128, 256 AGPR accumulators): -W2 streams once per 256 sorted rows. W2 and A run two K-steps ahead (2 LDS stages) to -fit 160 KB of LDS. Same partials as the 128-row kernel. - -Layouts (bytes): - A [num_m_blocks*BM, I] sorted rows, fp8 (gemm1 OUT_Q) - A_scale [pad32(num_m_blocks*BM), I/32] sorted rows, e8m0-shuffled (gemm1 OUT_sc) - W2 [E, H, I] aiter shuffle_weight (16 x 64 K blocks) - W2_sc [E*H/32, I/256, 4, 16] dwords aiter shuffle_scale - sorted_w [num_m_blocks*BM] f32 routing weight per sorted row - OUT [n_tokens*topk, H] bf16 -""" - -import flydsl.compiler as flyc -import flydsl.expr as fx -from aiter.ops.flydsl.kernels import buffer_ops -from flydsl._mlir.dialects import llvm as _llvm -from flydsl.expr import const_expr, range_constexpr -from flydsl.expr.typing import Vector as Vec - -from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.epilogue import ( - _NUM_XCDS, - _STORE_CPOL, - _bf16x2, - _lds_load_vec, - _lds_store_vec, - _v2i32, -) -from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.loaders import ( - _N_WAVES, - _SCALE_A_REGION, - _SCALE_B_REGION, - _SCALE_SLOT_BYTES, - G2SLoaderAsm, - S2RLoader128B, - ScaleGatherMoE, - ScaleLoaderLDS, - _asm_void, - _Buf, - _divmod_nonneg, - _flat_frag, - _g2s_thunks, - _riffle, - _s2r_thunks, - _swizzled_col, - _unflat_frag, - wait_barrier, -) - -from .gemm1_prefill import BLOCK_K, Mfma16x16x128Fp8 - -_SCALE_SLOTS2 = 4 - - -def compile_moe_gemm2_bm256( - *, - H: int, - I: int, # noqa: E741 - E: int, - topk: int, - n_split: int = 2, - sort_block_m: int = 128, -): - """``compile_moe_gemm2`` on 256-row tiles; ``sort_block_m`` must be 256.""" - BM = 256 - BN = 256 - K = I - K_BYTES = K - BLOCK_K_BYTES = BLOCK_K - EID_SHIFT = (sort_block_m // BM).bit_length() - 1 - assert sort_block_m in (BM, 2 * BM) - N_TILES_ALL = H // BN - assert H % BN == 0 and N_TILES_ALL % n_split == 0 - NT = N_TILES_ALL // n_split # n-tiles per CTA - K_ITERS = K // BLOCK_K - assert K_ITERS in (6, 12, 24) and K % 256 == 0 - SCALE_BLOCKS = K_ITERS // 2 - LDS_BLOCK_M = BM // 2 - LDS_BLOCK_N = BN // 2 - N_TILES_A = LDS_BLOCK_M // 2 // 16 - N_TILES_B = LDS_BLOCK_N // 2 // 16 - N_ACCUMS = N_TILES_A * N_TILES_B - NB = N_TILES_B - NA = N_TILES_A - OUT_ROW_BYTES = H * 2 - W2_BYTES = H * K - assert W2_BYTES <= 0xFFFFFFFF - B_TILE_BYTES = BN * K_BYTES - - B_STAGES = 2 - a_lds_size = LDS_BLOCK_M * BLOCK_K_BYTES - b_lds_size = LDS_BLOCK_N * BLOCK_K_BYTES - A_BUFS = 4 * a_lds_size # 2 stages x 2 halves - LDS_TILES_BYTES = A_BUFS + 2 * B_STAGES * b_lds_size - SCALE_LDS_BYTES2 = _SCALE_SLOTS2 * _SCALE_SLOT_BYTES - # wave-private epilogue staging: 16 rows x the wave's 128 bf16 cols - STG_ROW = 2 * N_TILES_B * 16 * 2 # the wave's two 128-B line segments - STG_CH = STG_ROW // 16 - STG_ROWS = 16 # one (row half, a-tile) at a time - STG_WAVE = STG_ROWS * STG_ROW - STG_LDS_BYTES = _N_WAVES * STG_WAVE - N_FLUSH = (STG_ROWS * 2) // 8 # dwordx4 stores per lane per staged block - assert LDS_TILES_BYTES + SCALE_LDS_BYTES2 + STG_LDS_BYTES <= 160 * 1024 - - A_WAVE_GROUPS = N_TILES_A // 2 - A_HALF_GROUPS = LDS_BLOCK_M // 32 - B_WAVE_GROUPS = 2 # 32-row groups per wave (64 W2 rows) - B_HALF_GROUPS = LDS_BLOCK_N // 32 - SC_COLS = K // 32 - W2_SC_BYTES = E * H * SC_COLS - - @fx.struct - class SharedStorage: - all_lds: fx.Array[fx.Int8, LDS_TILES_BYTES, 16] - scale_lds: fx.Array[fx.Int8, SCALE_LDS_BYTES2, 16] - stage_lds: fx.Array[fx.Int8, STG_LDS_BYTES, 16] - - @flyc.kernel - def kernel_gemm2_bm256( - A: fx.Tensor, - W2: fx.Tensor, - OUT: fx.Tensor, - A_scale: fx.Tensor, - W2_scale: fx.Tensor, - sorted_ids: fx.Tensor, - sorted_expert_ids: fx.Tensor, - sorted_weights: fx.Tensor, - num_valid_ids: fx.Tensor, - n_tokens: fx.Int32, - num_m_blocks: fx.Int32, - grid_size: fx.Int32, - ): - lds = fx.SharedAllocator().allocate(SharedStorage).peek() - _base_ptr = lds.all_lds.ptr - _scale_base_ptr = lds.scale_lds.ptr - _stg_ptr = lds.stage_lds.ptr - - a_cur0 = _Buf(_base_ptr, 0 * a_lds_size) - a_cur1 = _Buf(_base_ptr, 1 * a_lds_size) - a_next0 = _Buf(_base_ptr, 2 * a_lds_size) - a_next1 = _Buf(_base_ptr, 3 * a_lds_size) - # B: 2 stages x 2 halves - b_st = [ - [_Buf(_base_ptr, A_BUFS + (2 * st + hf) * b_lds_size) for hf in range(2)] - for st in range(B_STAGES) - ] - - lane_id = fx.thread_idx.x % 64 - wave_id = fx.thread_idx.x // 64 - wave_i = wave_id // 2 - wave_j = wave_id % 2 - g4 = lane_id // 16 - r16 = lane_id % 16 - - # work item (m-tile, n-chunk); consecutive m-tiles share an XCD - nv_rsrc = buffer_ops.create_buffer_resource( - num_valid_ids, max_size=False, num_records_bytes=4 - ) - num_valid = fx.Int32( - buffer_ops.buffer_load( - nv_rsrc, fx.Int32(0), vec_width=1, dtype=fx.Int32, is_scalar=True - ) - ) - n_work = (num_valid // fx.Int32(BM)) * fx.Int32(n_split) - per_xcd = (n_work + fx.Int32(_NUM_XCDS - 1)) // fx.Int32(_NUM_XCDS) - intra, xcd = _divmod_nonneg(fx.block_idx.x, _NUM_XCDS) - work = xcd * per_xcd + intra - block_valid = (intra < per_xcd) & (work < n_work) - work_safe = block_valid.select(work, fx.Int32(0)) - tile_i, chunk = _divmod_nonneg(work_safe, n_split) - m_base = tile_i * BM - eid_rsrc = buffer_ops.create_buffer_resource( - sorted_expert_ids, max_size=False, num_records_bytes=num_m_blocks * 4 - ) - expert = fx.Int32( - buffer_ops.buffer_load( - eid_rsrc, - tile_i >> EID_SHIFT, - vec_width=1, - dtype=fx.Int32, - is_scalar=True, - ) - ) - ids_rsrc = buffer_ops.create_buffer_resource( - sorted_ids, max_size=False, num_records_bytes=num_m_blocks * (BM * 4) - ) - if const_expr(EID_SHIFT > 0): - # a 256-sort pads each expert: a 128-row tile starting with padding is empty - first_sid = fx.Int32( - buffer_ops.buffer_load( - ids_rsrc, m_base, vec_width=1, dtype=fx.Int32, is_scalar=True - ) - ) - block_valid = block_valid & ((first_sid & fx.Int32(0x00FFFFFF)) < n_tokens) - chunk_n0 = chunk * NT - # rotate the n-tile sweep inside same-expert runs: neighbours find W2 in L2 - ROT_STRIDE, ROT_GATE = 2, 3 - _d = fx.Int32(ROT_GATE) - _lo_ok = tile_i >= _d - _hi_ok = tile_i + _d < num_m_blocks - _e_lo = fx.Int32( - buffer_ops.buffer_load( - eid_rsrc, - _lo_ok.select(tile_i - _d, fx.Int32(0)) >> EID_SHIFT, - vec_width=1, - dtype=fx.Int32, - is_scalar=True, - ) - ) - _e_hi = fx.Int32( - buffer_ops.buffer_load( - eid_rsrc, - _hi_ok.select(tile_i + _d, fx.Int32(0)) >> EID_SHIFT, - vec_width=1, - dtype=fx.Int32, - is_scalar=True, - ) - ) - rot_on = (_lo_ok & (_e_lo == expert)) | (_hi_ok & (_e_hi == expert)) - nt_rot = rot_on.select( - _divmod_nonneg(tile_i * fx.Int32(ROT_STRIDE), NT)[1], fx.Int32(0) - ) - - def _pn(nt): - """Sweep-order n-tile -> n-tile of the chunk.""" - x = nt + nt_rot - return (x >= fx.Int32(NT)).select(x - fx.Int32(NT), x) - - def _n_glob(nt): - """Global n-tile of sweep-order ``nt``, clamped to the last one.""" - ntc = (nt >= fx.Int32(NT)).select(fx.Int32(NT - 1), nt) - return chunk_n0 + _pn(ntc) - - if block_valid: - sw_rsrc = buffer_ops.create_buffer_resource( - sorted_weights, - max_size=False, - num_records_bytes=num_m_blocks * (BM * 4), - ) - a_rsrc = buffer_ops.create_buffer_resource( - A, max_size=False, num_records_bytes=num_m_blocks * (BM * K_BYTES) - ) - b_rsrc = buffer_ops.create_buffer_resource( - W2, - max_size=False, - num_records_bytes=W2_BYTES, - base_byte_offset=fx.Int64(expert) * W2_BYTES, - ) - # padded rows (tok == n_tokens) fall outside the resource - out_rows = n_tokens * fx.Int32(topk) - out_rsrc = buffer_ops.create_buffer_resource( - OUT, max_size=False, num_records_bytes=out_rows * OUT_ROW_BYTES - ) - - def _a_offsets(half): - offs = [] - for rnd in range_constexpr(N_TILES_A): - row = lane_id // 8 + wave_id * 8 + rnd * (_N_WAVES * 8) - col = (lane_id % 8) * 16 - grow = m_base + half * LDS_BLOCK_M + row - offs.append(grow * fx.Int32(K_BYTES) + _swizzled_col(row, col)) - return offs - - # rounds and halves move whole 32-row groups (same swizzle): one per-lane - # base plus soffset strides - gl_off_a = _a_offsets(0)[:1] - A_RND_BYTES = _N_WAVES * 8 * K_BYTES - A_HALF_BYTES = LDS_BLOCK_M * K_BYTES - - # W2 offsets inside an n-tile; the n-tile goes in soffset - e_row0 = expert * fx.Int32(H) - - def _b_offsets(hf): - offs = [] - for rnd in range_constexpr(N_TILES_B): - row = lane_id % 8 + wave_id * 8 + rnd * (_N_WAVES * 8) - col = (lane_id // 8) * 16 - wrow = fx.Int32(hf * LDS_BLOCK_N + row) - offs.append( - (wrow // fx.Int32(16)) * fx.Int32(K_BYTES * 16) - + fx.Int32( - (row % 16) * 16 - + (col // 64) * 1024 - + ((col % 64) // 16) * 256 - + (col % 16) - ) - ) - return offs - - gl_off_b = _b_offsets(0)[:1] - B_RND_BYTES = (_N_WAVES * 8 // 16) * K_BYTES * 16 - B_HALF_BYTES = (LDS_BLOCK_N // 16) * K_BYTES * 16 - A_K_STEP = BLOCK_K_BYTES - B_K_STEP = 2 * 1024 - - mfma = Mfma16x16x128Fp8(N_TILES_A, N_TILES_B) - sb_index = lambda j, hf: (j // 2, j % 2) # noqa: E731 (32-row groups) - - scale_gather = ScaleGatherMoE( - A_scale, - W2_scale, - K, - lane_id, - wave_id, - _scale_base_ptr, - num_m_blocks * (BM * SC_COLS), - W2_SC_BYTES, - A_WAVE_GROUPS, - A_HALF_GROUPS, - B_WAVE_GROUPS, - B_HALF_GROUPS, - ) - - def _set_scale_tile(nt): - scale_gather.set_wave_base(m_base, e_row0 + _n_glob(nt) * fx.Int32(BN)) - - a_scale_ld = ScaleLoaderLDS( - N_TILES_A, lane_id, wave_i, _scale_base_ptr, _SCALE_A_REGION - ) - b_scale_ld = ScaleLoaderLDS( - N_TILES_B, lane_id, wave_j, _scale_base_ptr, _SCALE_B_REGION - ) - - def _slot(nt, g): - return (fx.Int32(nt) * fx.Int32(SCALE_BLOCKS) + fx.Int32(g)) % fx.Int32( - _SCALE_SLOTS2 - ) - - a0_g2s = G2SLoaderAsm(a_rsrc, gl_off_a, N_TILES_A, wave_id, A_RND_BYTES) - a1_g2s = G2SLoaderAsm( - a_rsrc, gl_off_a, N_TILES_A, wave_id, A_RND_BYTES, A_HALF_BYTES - ) - b0_g2s = G2SLoaderAsm(b_rsrc, gl_off_b, N_TILES_B, wave_id, B_RND_BYTES) - b1_g2s = G2SLoaderAsm( - b_rsrc, gl_off_b, N_TILES_B, wave_id, B_RND_BYTES, B_HALF_BYTES - ) - for ld in (a0_g2s, a1_g2s, b0_g2s, b1_g2s): - ld.set_wave_base(_base_ptr) - a_s2r = S2RLoader128B(wave_i, N_TILES_A) - b_s2r = S2RLoader128B(wave_j, N_TILES_B) - - def _orow(sid): - tok = sid & fx.Int32(0x00FFFFFF) # padded: tok == n_tokens -> OOB - slot = (sid >> 24) & fx.Int32(0xFF) - return tok * fx.Int32(topk) + slot - - # routing weights of the lane's rows; output offsets of the rows it - # flushes (store k: staged row 8 (k % 2) + lane // 8, segment k // 2) - wave_row0 = m_base + wave_i * (N_TILES_A * 16) - row_w = [] - for h in range_constexpr(2): - for ti in range_constexpr(N_TILES_A): - row = wave_row0 + fx.Int32(h * LDS_BLOCK_M + ti * 16) + r16 - row_w.append( - fx.Float32( - buffer_ops.buffer_load( - sw_rsrc, row, vec_width=1, dtype=fx.Float32 - ) - ) - ) - flush_off = [] - for h in range_constexpr(2): - for ti in range_constexpr(NA): - for k in range_constexpr(2): - row = ( - wave_row0 - + fx.Int32(h * LDS_BLOCK_M + ti * 16 + 8 * k) - + lane_id // 8 - ) - sid = fx.Int32( - buffer_ops.buffer_load( - ids_rsrc, row, vec_width=1, dtype=fx.Int32 - ) - ) - flush_off.append(_orow(sid) * fx.Int32(OUT_ROW_BYTES)) - stg_base = fx.Int32(fx.ptrtoint(_stg_ptr)) + wave_id * fx.Int32(STG_WAVE) - - def _stg_addr(row, chunk, half): - """Staged (row, 16-B chunk, 8-B half), chunks XOR-swizzled by row; - inline asm keeps it at the use instead of in hoisted VGPRs.""" - base = stg_base + row * fx.Int32(STG_ROW) + fx.Int32(half * 8) - x = fx.Int32( - _llvm.inline_asm( - fx.Int32.ir_type, - [fx.as_ir_value(fx.Int32(chunk)), fx.as_ir_value(row % STG_CH)], - "v_xor_b32 $0, $1, $2", - "=v,v,v", - has_side_effects=True, - ) - ) - return fx.Int32( - _llvm.inline_asm( - fx.Int32.ir_type, - [fx.as_ir_value(x), fx.as_ir_value(base)], - "v_lshl_add_u32 $0, $1, 4, $2", - "=v,v,v", - has_side_effects=True, - ) - ) - - # prologue = steps -2, -1 of the steady-state issue order - _set_scale_tile(fx.Int32(0)) - scale_gather.gather(0, _slot(0, 0)) - b_soff0 = _n_glob(fx.Int32(0)) * fx.Int32(B_TILE_BYTES) - b0_g2s.load(b_st[0][0], b_soff0 + fx.Int32(0 * B_K_STEP)) - b1_g2s.load(b_st[0][1], b_soff0 + fx.Int32(0 * B_K_STEP)) - a0_g2s.load(a_cur0, fx.Int32(0 * A_K_STEP)) - a1_g2s.load(a_cur1, fx.Int32(0 * A_K_STEP)) - b0_g2s.load(b_st[1][0], b_soff0 + fx.Int32(1 * B_K_STEP)) - b1_g2s.load(b_st[1][1], b_soff0 + fx.Int32(1 * B_K_STEP)) - a0_g2s.load(a_next0, fx.Int32(1 * A_K_STEP)) - scale_gather.gather(1, _slot(0, 1)) - a1_g2s.load(a_next1, fx.Int32(1 * A_K_STEP)) - - # gather 0, B(0) and a0(0) landed: a1(0), B(1), a0(1), gather, a1(1) may fly - wait_barrier(NA + 2 * NB + NA + 1 + NA) - a0_frag = a_s2r.load(a_cur0) - b0_frag = b_s2r.load(b_st[0][0], preshuffled=True) - b1_frag = b_s2r.load(b_st[0][1], preshuffled=True) - sc0_saR0, sc0_saR1 = a_scale_ld.read(_slot(0, 0)) - sc0_sbC0, sc0_sbC1 = b_scale_ld.read(_slot(0, 0)) - sc0 = (sc0_saR0, sc0_saR1, sc0_sbC0, sc0_sbC1) - - # Step kc issues B(kc + 2), a0(kc + 2), [MID] the scale gather (odd kc), - # a1(kc + 2). Top wait: a1(kc) landed; MID wait: a0(kc + 1) landed. The - # counts leave out the epilogue stores: they retire out of order. - def _top_vmcnt(kc): - return 2 * NB + 2 * NA + (1 - kc % 2) - - def _mid_vmcnt(kc): - return NA + 2 * NB + NA + (1 - kc % 2) - - def _read_scale_thunks(nt, kc_next, holder): - # the next flat step's scales; Python ints only (an ``if`` here would - # become an scf.if) - s = _slot(nt + fx.Int32(kc_next // K_ITERS), (kc_next % K_ITERS) // 2) - - def _r(dst, ld, half, _s=s): - holder[dst] = ld.read_half(_s, half) - - return [ - lambda: _r(0, a_scale_ld, 0), - lambda: _r(1, a_scale_ld, 1), - lambda: _r(2, b_scale_ld, 0), - lambda: _r(3, b_scale_ld, 1), - ] - - def _one_step(nt, kc, a0f, b0f, b1f_in, sc, accs, abufs): - """``nt`` is the n-tile; ``kc`` is a constexpr K-step within it.""" - k2 = kc % 2 - ac0, ac1, an0, an1 = abufs - bst = b_st[kc % B_STAGES] # read now, refilled for step kc + 2 - bnx = b_st[(kc + 1) % B_STAGES] - saR0, saR1, sbC0, sbC1 = sc - c00f, c01f, c10f, c11f = accs - zero_acc = kc == 0 - - _a1 = [None] * NA - _a0n = [None] * NA - _b0n = [None] * NB - _b1n = [None] * NB - # A and B for flat step kc + 2 (B possibly in tile nt + 1) - ka = (kc + 2) % K_ITERS - kb = (kc + B_STAGES) % K_ITERS - nt_b = nt + fx.Int32((kc + B_STAGES) // K_ITERS) - a_off = fx.Int32(ka * A_K_STEP) - b_off = _n_glob(nt_b) * fx.Int32(B_TILE_BYTES) + fx.Int32(kb * B_K_STEP) - - _scn = [None, None, None, None] - _rd_scn = _read_scale_thunks(nt, kc + 1, _scn) - # Gather scales three steps ahead, crossing n-tiles as needed. - future_block = (kc + 3) // 2 - _g_blk = future_block % SCALE_BLOCKS - _g_slot = _slot(nt + fx.Int32(future_block // SCALE_BLOCKS), _g_blk) - _sc_gather = [lambda: scale_gather.gather(_g_blk, _g_slot)] * k2 - - wait_barrier(_top_vmcnt(kc)) - il = ( - _riffle( - _g2s_thunks(b0_g2s, bst[0], b_off, NB), - _s2r_thunks(a_s2r, ac1, _a1, NA, False), - ) - + _rd_scn[:2] - ) - c00f = mfma.call( - a0f, - b0f, - c00f, - saR0, - sbC0, - 0, - k2, - interleave=il, - zero_acc=zero_acc, - sb_index=sb_index, - ) - # never riffle two G2S loaders: each one's steps share m0, so - # interleaving them corrupts the LDS destinations - il = ( - _g2s_thunks(b1_g2s, bst[1], b_off, NB) - + _g2s_thunks(a0_g2s, ac0, a_off, NA) - + _rd_scn[2:] - ) - c01f = mfma.call( - a0f, - b1f_in, - c01f, - saR0, - sbC1, - 1, - k2, - interleave=il, - zero_acc=zero_acc, - sb_index=sb_index, - ) - a1f = _a1 - - wait_barrier(_mid_vmcnt(kc)) - il = _s2r_thunks(a_s2r, an0, _a0n, NA, False) + _sc_gather - c10f = mfma.call( - a1f, - b0f, - c10f, - saR1, - sbC0, - 0, - k2, - interleave=il, - zero_acc=zero_acc, - sb_index=sb_index, - ) - a0nf = _a0n - il = _riffle( - _g2s_thunks(a1_g2s, ac1, a_off, NA), - _s2r_thunks(b_s2r, bnx[0], _b0n, NB, True) - + _s2r_thunks(b_s2r, bnx[1], _b1n, NB, True), - ) - c11f = mfma.call( - a1f, - b1f_in, - c11f, - saR1, - sbC1, - 1, - k2, - interleave=il, - zero_acc=zero_acc, - sb_index=sb_index, - ) - sc_next = (_scn[0], _scn[1], _scn[2], _scn[3]) - return ( - a0nf, - _b0n, - _b1n, - sc_next, - (c00f, c01f, c10f, c11f), - (an0, an1, ac0, ac1), - ) - - def _stage(accs, h, ti): - """Routing-weighted bf16 of rows (``h``, ``ti``) into the staging - buffer; a wave's LDS ops run in order, after the last flush's reads.""" - w = row_w[h * NA + ti] - for hf in range_constexpr(2): - cq = accs[h * 2 + hf] - for j in range_constexpr(NB): - v = Vec(cq[mfma.idx(ti, j)]) - d0 = _bf16x2(fx.Float32(v[0]) * w, fx.Float32(v[1]) * w) - d1 = _bf16x2(fx.Float32(v[2]) * w, fx.Float32(v[3]) * w) - chunk = fx.Int32(hf * 8 + j * 2) + g4 // 2 - _lds_store_vec(_v2i32(d0, d1), _stg_addr(r16, chunk, g4 % 2), 2) - - def _flush(nt, h, ti): - """The staged rows -> full token-major 128-B lines, non-temporal.""" - col_wave = (_n_glob(nt) * fx.Int32(BN) + wave_j * (N_TILES_B * 16)) * 2 - ch_l = lane_id % 8 - _asm_void([], "s_waitcnt lgkmcnt(0)", "") - for k in range_constexpr(N_FLUSH): - hf = k // 2 - row = fx.Int32(8 * (k % 2)) + lane_id // 8 - data = _lds_load_vec(_stg_addr(row, hf * 8 + ch_l, 0), 4) - buffer_ops.buffer_store( - data, - out_rsrc, - flush_off[(h * NA + ti) * 2 + k % 2] - + col_wave - + fx.Int32(hf * LDS_BLOCK_N * 2) - + ch_l * fx.Int32(16), - offset_is_bytes=True, - cache_modifier=_STORE_CPOL, - ) - - def _epilogue(nt, accs): - for h in range_constexpr(2): - for ti in range_constexpr(NA): - _stage(accs, h, ti) - _flush(nt, h, ti) - - abufs0 = (a_cur0, a_cur1, a_next0, a_next1) - n_a = 2 * NA - n_b = 2 * NB - n_sc = 2 * (NA // 2) + 2 * (NB // 2) - _R = fx.as_ir_value - - def _flat_sc(sc): - return [_R(v) for part in sc for v in part] - - def _unflat_sc(flat): - sizes = (NA // 2, NA // 2, NB // 2, NB // 2) - out, o = [], 0 - for n in sizes: - out.append(list(flat[o : o + n])) - o += n - return tuple(out) - - init_state = ( - _flat_frag(a0_frag) - + _flat_frag(b0_frag) - + _flat_frag(b1_frag) - + _flat_sc(sc0) - ) - # FlyDSL rewrites range(init=...) to a loop carrying state. - for nt_idx, state in range( # type: ignore[call-overload] - 0, NT, 1, init=init_state - ): - nt = fx.Int32(nt_idx) - off = 0 - a0f = _unflat_frag(state[off : off + n_a], NA) - off += n_a - b0f = _unflat_frag(state[off : off + n_b], NB) - off += n_b - b1f = _unflat_frag(state[off : off + n_b], NB) - off += n_b - sc = _unflat_sc(state[off : off + n_sc]) - accs = ( - [None] * N_ACCUMS, - [None] * N_ACCUMS, - [None] * N_ACCUMS, - [None] * N_ACCUMS, - ) - abufs = abufs0 - # Switch the scale base before the first next-tile gather. - _set_scale_tile(nt) - for kc in range_constexpr(K_ITERS): - if const_expr(kc == K_ITERS - 4): - _set_scale_tile(nt + fx.Int32(1)) - a0f, b0f, b1f, sc, accs, abufs = _one_step( - nt, kc, a0f, b0f, b1f, sc, accs, abufs - ) - _epilogue(nt, accs) - state = ( - yield _flat_frag(a0f) - + _flat_frag(b0f) - + _flat_frag(b1f) - + _flat_sc(sc) - ) - # the redundant loads after the last tile must land before the LDS is reused - wait_barrier(0) - - @flyc.jit - def launch_gemm2_bm256( - A: fx.Tensor, - W2: fx.Tensor, - OUT: fx.Tensor, - A_scale: fx.Tensor, - W2_scale: fx.Tensor, - sorted_ids: fx.Tensor, - sorted_expert_ids: fx.Tensor, - sorted_weights: fx.Tensor, - num_valid_ids: fx.Tensor, - n_tokens: fx.Int32, - num_m_blocks: fx.Int32, - grid_size: fx.Int32, - stream: fx.Stream, - ): - kernel_gemm2_bm256( - A, - W2, - OUT, - A_scale, - W2_scale, - sorted_ids, - sorted_expert_ids, - sorted_weights, - num_valid_ids, - n_tokens, - num_m_blocks, - grid_size, - value_attrs={ - "rocdl.waves_per_eu": 1, - "rocdl.flat_work_group_size": "256,256", - }, - ).launch(grid=(grid_size, 1, 1), block=(256, 1, 1), stream=stream) - - return launch_gemm2_bm256 diff --git a/vllm/models/minimax_m3/amd/ops/moe_mxfp8/prefill.py b/vllm/models/minimax_m3/amd/ops/moe_mxfp8/prefill.py deleted file mode 100644 index 19a4931b658f..000000000000 --- a/vllm/models/minimax_m3/amd/ops/moe_mxfp8/prefill.py +++ /dev/null @@ -1,228 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""FlyDSL MXFP8 MoE prefill chain on AITER's MXFP8 weights: sort, gemm1 (gate/up + -SwiGLU-OAI + MXFP8 quant), gemm2 (routing-weighted partials), fixed-order reduce.""" - -import functools - -import torch - -from vllm.models.minimax_m3.amd.ops.flydsl_utils import run_compiled -from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.launch import ( - _get_reduce_bf16, - _get_sort, - _get_tile_map, - _u8_flat, -) - -MIN_PREFILL_TOKENS = 3072 -MAX_PREFILL_TOKENS = 65536 -BM256_FROM_TOKENS = 16384 - -GEMM1_SWIGLU_ALPHA = 1.702 -GEMM1_SWIGLU_LIMIT = 7.0 -# CTAs sharing one m-block's n-tiles in gemm2 -GEMM2_N_SPLIT = 6 -GEMM2_N_SPLIT_LARGE = 4 -GEMM2_N_SPLIT_LARGE_FROM_TOKENS = 32768 -GEMM2_BM256_MIN_INTERMEDIATE = 768 -GEMM2_BM256_FROM_TOKENS = 16384 - -_GEMM1_BLOCK_K = 128 -_GEMM2_INTERMEDIATES = (768, 1536, 3072) - - -def block_m_for( - n_tokens: int, hidden_size: int, intermediate_size: int, num_experts: int, topk: int -) -> int: - if (hidden_size, intermediate_size, num_experts, topk) == (6144, 3072, 128, 4): - threshold = 8192 - elif (hidden_size, intermediate_size) == (6144, 768): - threshold = 4096 - else: - threshold = BM256_FROM_TOKENS - return 256 if n_tokens >= threshold else 128 - - -def gemm2_n_split_for(n_tokens: int) -> int: - if n_tokens >= GEMM2_N_SPLIT_LARGE_FROM_TOKENS: - return GEMM2_N_SPLIT_LARGE - return GEMM2_N_SPLIT - - -def gemm2_block_m_for(sort_block_m: int, n_tokens: int, intermediate_size: int) -> int: - if ( - sort_block_m == 256 - and intermediate_size >= GEMM2_BM256_MIN_INTERMEDIATE - and n_tokens >= GEMM2_BM256_FROM_TOKENS - ): - return 256 - return 128 - - -def supports_shapes(hidden_size: int, intermediate_size: int) -> bool: - """gemm1 peels 4 K-steps of 128 and unrolls the rest by 4.""" - k_iters = hidden_size // _GEMM1_BLOCK_K - return ( - hidden_size % 256 == 0 - and k_iters >= 8 - and (k_iters - 4) % 4 == 0 - and intermediate_size in _GEMM2_INTERMEDIATES - ) - - -@functools.cache -def _get_gemm1(hidden_size: int, intermediate_size: int, num_experts: int, bm: int): - from .gemm1_prefill import compile_moe_gemm1 - - return compile_moe_gemm1( - H=hidden_size, I=intermediate_size, E=num_experts, BLOCK_M=bm - ) - - -@functools.cache -def _get_gemm2( - hidden_size: int, - intermediate_size: int, - num_experts: int, - topk: int, - bm: int, - n_split: int, - gemm2_bm: int, -): - if gemm2_bm == 256: - from .gemm2_prefill_bm256 import compile_moe_gemm2_bm256 as compile_moe_gemm2 - else: - from .gemm2_prefill import compile_moe_gemm2 - - return compile_moe_gemm2( - H=hidden_size, - I=intermediate_size, - E=num_experts, - topk=topk, - n_split=n_split, - sort_block_m=bm, - ) - - -def a8w8_prefill_moe( - x_quant: tuple[torch.Tensor, torch.Tensor], - w13: torch.Tensor, - w13_scale: torch.Tensor, - w2: torch.Tensor, - w2_scale: torch.Tensor, - topk_weights: torch.Tensor, - topk_ids: torch.Tensor, - *, - hidden_size: int, - intermediate_size: int, - num_experts: int, - out: torch.Tensor | None = None, -) -> torch.Tensor: - """``x_quant`` = (fp8 ``[M, H]``, e8m0 ``[M, H/32]``) -> ``[M, H]`` bf16, on - ``AiterMxfp8Experts``' weights.""" - from aiter import dtypes - from aiter.ops.quant import mxfp4_moe_sort_hip - - from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.sort import SortBuffers - from vllm.models.minimax_m3.amd.ops.moe_flydsl_common.tile_map import ( - tile_map_grid, - ) - - from .gemm2_prefill import gemm2_grid - - a_q, x_s = x_quant - n_tokens, hidden = a_q.shape - assert MIN_PREFILL_TOKENS <= n_tokens <= MAX_PREFILL_TOKENS, n_tokens - assert hidden == hidden_size and a_q.is_contiguous() and x_s.is_contiguous() - assert x_s.shape == (n_tokens, hidden // 32), x_s.shape - inter = intermediate_size - topk = topk_ids.shape[1] - topk_ids = topk_ids.to(torch.int32).contiguous() - topk_weights = topk_weights.to(torch.float32).contiguous() - device = topk_ids.device - stream = torch.cuda.current_stream() - bm = block_m_for(n_tokens, hidden_size, inter, num_experts, topk) - - bufs = SortBuffers.allocate(n_tokens, num_experts, topk, bm, device) - _get_sort(num_experts, topk, bm)( - *bufs.launch_args(topk_ids, topk_weights, n_tokens) - ) - a_s = torch.empty( - ((bufs.sorted_ids.shape[0] + 31) // 32 * 32, (hidden // 32 + 7) // 8 * 8), - dtype=dtypes.fp8_e8m0, - device=device, - ) - mxfp4_moe_sort_hip( - a_s, - x_s.view(dtypes.fp8_e8m0), - bufs.sorted_ids, - bufs.num_valid_ids, - n_tokens, - hidden, - ) - num_m_blocks = bufs.max_sorted // bm - rows = num_m_blocks * bm - grid1 = tile_map_grid(num_m_blocks, inter) - tile_map = torch.empty((grid1 + 1,), dtype=torch.int32, device=device) - run_compiled( - _get_tile_map(inter, bm), - bufs.sorted_expert_ids, - bufs.num_valid_ids, - tile_map, - grid1, - stream, - ) - h_q = torch.empty((rows, inter), dtype=torch.uint8, device=device) - h_s = torch.empty((rows * (inter // 32),), dtype=torch.uint8, device=device) - run_compiled( - _get_gemm1(hidden_size, inter, num_experts, bm), - _u8_flat(a_q), - w13.view(torch.int64).view(-1), - h_q.view(-1), - _u8_flat(a_s), - _u8_flat(w13_scale), - h_s, - bufs.sorted_ids, - bufs.sorted_expert_ids, - n_tokens, - num_m_blocks, - int(a_s.numel() * a_s.element_size()), - tile_map, - grid1, - stream, - ) - - if out is None: - out = torch.empty((n_tokens, hidden_size), dtype=torch.bfloat16, device=device) - gemm2_out = torch.empty( - (n_tokens * topk, hidden_size), dtype=torch.bfloat16, device=device - ) - n_split = gemm2_n_split_for(n_tokens) - gemm2_bm = gemm2_block_m_for(bm, n_tokens, inter) - num_m_blocks2 = rows // gemm2_bm - # 4 GB of partials at 65536 tokens: a byte view would exceed 2^31 elements - run_compiled( - _get_gemm2(hidden_size, inter, num_experts, topk, bm, n_split, gemm2_bm), - h_q.view(-1), - w2.view(torch.int64).view(-1), - gemm2_out.view(-1), - h_s, - _u8_flat(w2_scale), - bufs.sorted_ids, - bufs.sorted_expert_ids, - bufs.sorted_weights, - bufs.num_valid_ids, - n_tokens, - num_m_blocks2, - gemm2_grid(num_m_blocks2, n_split), - stream, - ) - run_compiled( - _get_reduce_bf16(hidden_size, topk), - gemm2_out.view(-1), - out.view(-1), - n_tokens, - stream, - ) - return out diff --git a/vllm/models/minimax_m3/amd/ops/sp_coll/__init__.py b/vllm/models/minimax_m3/amd/ops/sp_coll/__init__.py deleted file mode 100644 index bea7a19672b6..000000000000 --- a/vllm/models/minimax_m3/amd/ops/sp_coll/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""FlyDSL collectives of MiniMax-M3's sequence-parallel prefill (TP4, MI355X).""" - -from .host import WORLD, Collectives, Pools - -__all__ = ["WORLD", "Collectives", "Pools"] diff --git a/vllm/models/minimax_m3/amd/ops/sp_coll/host.py b/vllm/models/minimax_m3/amd/ops/sp_coll/host.py deleted file mode 100644 index c9a3cf8d6715..000000000000 --- a/vllm/models/minimax_m3/amd/ops/sp_coll/host.py +++ /dev/null @@ -1,321 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""Pools and collectives on the sp_coll kernels: per rank ``sets x 2`` IPC-mapped -slots, one set per DBO microbatch. Two slots suffice: slot k is rewritten for phase -c + 2 only after every peer published c + 1, i.e. finished pulling phase c.""" - -import ctypes -import functools -import math - -import torch -import torch.distributed as dist - -from vllm import _custom_ops as ops -from vllm.logger import init_logger -from vllm.models.minimax_m3.amd.ops.flydsl_utils import run_compiled as _run_compiled - -from . import kernel as _kernel - -logger = init_logger(__name__) - -WORLD = _kernel.WORLD -SLOTS = 2 -_ALIGN = 256 - - -@functools.cache -def _kernels(): - k = _kernel - return ( - k.compile_publish(), - k.compile_fence_publish(), - k.compile_pull(), - k.compile_pull_unpack(), - k.compile_sum4(), - ) - - -class _IpcHandle(ctypes.Structure): - _fields_ = [("reserved", ctypes.c_char * 64)] - - -@functools.cache -def _hip(): - lib = ctypes.CDLL("libamdhip64.so") - lib.hipMalloc.argtypes = [ctypes.POINTER(ctypes.c_void_p), ctypes.c_size_t] - lib.hipIpcGetMemHandle.argtypes = [ctypes.POINTER(_IpcHandle), ctypes.c_void_p] - lib.hipIpcOpenMemHandle.argtypes = [ - ctypes.POINTER(ctypes.c_void_p), - _IpcHandle, - ctypes.c_uint, - ] - return lib - - -class _DevicePointer: - def __init__(self, ptr: int, nbytes: int): - self.__cuda_array_interface__ = { - "data": (ptr, False), - "shape": (nbytes,), - "typestr": "|u1", - "strides": None, - "version": 3, - } - - -def _alloc_pool(nbytes: int, device: torch.device) -> tuple[int, bytes, torch.Tensor]: - """-> (pointer, IPC handle bytes, uint8 tensor); never freed.""" - hip = _hip() - ptr = ctypes.c_void_p() - with torch.cuda.device(device): - rc = hip.hipMalloc(ctypes.byref(ptr), nbytes) - assert rc == 0, f"hipMalloc({nbytes}) failed: {rc}" - handle = _IpcHandle() - rc = hip.hipIpcGetMemHandle(ctypes.byref(handle), ptr) - assert rc == 0, f"hipIpcGetMemHandle failed: {rc}" - pool = torch.as_tensor(_DevicePointer(ptr.value, nbytes), device=device) - assert pool.data_ptr() == ptr.value - # raw bytes: a c_char field reads back only up to its first NUL - raw = ctypes.string_at(ctypes.addressof(handle), ctypes.sizeof(handle)) - return ptr.value, raw, pool - - -def _open_pool(handle: bytes, device: torch.device) -> int: - hip = _hip() - ptr = ctypes.c_void_p() - h = _IpcHandle() - assert len(handle) == ctypes.sizeof(h) - ctypes.memmove(ctypes.addressof(h), handle, len(handle)) - with torch.cuda.device(device): - rc = hip.hipIpcOpenMemHandle(ctypes.byref(ptr), h, 1) # lazy peer access - assert rc == 0, f"hipIpcOpenMemHandle failed: {rc}" - return ptr.value - - -def _exchange(obj, rank: int, world: int, group) -> list: - """Every rank's ``obj``. Broadcasts: gloo's ``all_gather_object`` fails under - inference mode (the profile run).""" - out = [[None] for _ in range(world)] - out[rank][0] = obj - ranks = sorted(dist.get_process_group_ranks(group=group)) - for i, r in enumerate(ranks): - dist.broadcast_object_list(out[i], src=r, group=group, device="cpu") - return [o[0] for o in out] - - -class Pools: - """One rank's pool and flags plus the peers'; ``slot_bytes`` fits the largest - phase.""" - - def __init__( - self, - rank: int, - world: int, - group, - device: torch.device, - slot_bytes: int, - sets: int = 2, - ): - assert world == WORLD, world - self.rank, self.world, self.device = rank, world, device - self.sets, self.slot_bytes = sets, slot_bytes - nbytes = sets * SLOTS * slot_bytes - ptr, handle, self.pool = _alloc_pool(nbytes, device) - flag_ptr, flag_handle = ops.allocate_shared_buffer_and_handle(_ALIGN) - peers = _exchange((handle, flag_handle), rank, world, group) - self.pool_ptrs = [ - ptr if r == rank else _open_pool(h, device) - for r, (h, _) in enumerate(peers) - ] - self.flag_ptrs = [ - flag_ptr if r == rank else ops.open_mem_handle(h) - for r, (_, h) in enumerate(peers) - ] - self.seq = [0] * sets - self.phase = [0] * sets - publish, fence_publish, pull, pull_unpack, sum4 = _kernels() - self.fence_publish, self.pull, self.sum4 = fence_publish, pull, sum4 - self.pull_unpack = pull_unpack - stream = torch.cuda.current_stream(device) - # zero every set's flag word and ticket counter (base + 4) - for s in range(sets): - base = self.flag_ptrs[rank] + _kernel.FLAG_STRIDE * s - _run_compiled(publish, base, 0, stream) - _run_compiled(publish, base + 4, 0, stream) - torch.cuda.synchronize(device) - dist.barrier(group=group) - logger.info( - "sp_coll: %d sets x %d slots x %.0f MB pools, FlyDSL collectives on", - sets, - SLOTS, - slot_bytes / 2**20, - ) - - def slot(self, set_id: int) -> tuple[int, int]: - """Next slot of ``set_id``: (its byte offset in every pool, flag offset).""" - k = self.phase[set_id] % SLOTS - self.phase[set_id] += 1 - return (set_id * SLOTS + k) * self.slot_bytes, _kernel.FLAG_STRIDE * set_id - - def next_seq(self, set_id: int) -> int: - self.seq[set_id] += 1 - return self.seq[set_id] - - -class Collectives: - """One phase's collectives in the next slot of ``set_id``. ``alloc`` gives - producers views of the slot that the collectives read in place; inputs that do - not fit fall back to ``rccl`` (same sizes on every rank, so all ranks agree).""" - - def __init__(self, pools: Pools, set_id: int): - self.p = pools - self.set_id = set_id - self.base, self.flag_off = pools.slot(set_id) - self.off = 0 - self.stream: torch.cuda.Stream | None = None - self.rccl = None - - def bind(self, stream: torch.cuda.Stream, rccl) -> "Collectives": - self.stream, self.rccl = stream, rccl - return self - - def alloc(self, shape: tuple[int, ...], dtype: torch.dtype) -> torch.Tensor | None: - """A view of the slot for a producer to write; None when it does not fit.""" - n = math.prod(shape) * dtype.itemsize - off = self._take(n) - if off is None: - return None - return self.p.pool[off : off + n].view(dtype).view(shape) - - def _take(self, nbytes: int) -> int | None: - """Reserve ``nbytes`` of the slot (256 B aligned); None when it does not fit.""" - off = (self.off + _ALIGN - 1) // _ALIGN * _ALIGN - if off + nbytes > self.p.slot_bytes: - return None - self.off = off + nbytes - return self.base + off - - def _stage(self, x: torch.Tensor) -> int | None: - """``x``'s offset in every pool: in place if ``alloc`` placed it, else - copied in; None when it does not fit.""" - n = x.numel() * x.element_size() - start = self.p.pool.data_ptr() + self.base - if start <= x.data_ptr() < start + self.p.slot_bytes: - assert x.data_ptr() + n <= start + self.p.slot_bytes - return x.data_ptr() - self.p.pool.data_ptr() - off = self._take(n) - if off is None: - return None - dst = self.p.pool[off : off + n].view(x.dtype).view(x.shape) - dst.copy_(x) - return off - - def _publish_wait(self) -> None: - """Fence + publish this rank's slot; the pulls wait for the peers' flags.""" - p = self.p - self.seq = p.next_seq(self.set_id) - me_flag = p.flag_ptrs[p.rank] + self.flag_off - _run_compiled(p.fence_publish, me_flag, self.seq, self.stream) - - def _pull(self, dst: torch.Tensor, off: int, block: int, src_off: int) -> None: - p = self.p - srcs = [ptr + off for ptr in p.pool_ptrs] - flags = [f + self.flag_off for f in p.flag_ptrs] - _run_compiled( - p.pull, - dst.data_ptr(), - *srcs, - *flags, - block, - src_off, - self.seq, - p.rank, - self.stream, - ) - - def all_gather(self, outs: list[torch.Tensor], ins: list[torch.Tensor]) -> None: - """Each ``[rows, ...]`` shard into its ``[padded, ...]`` output.""" - ins = [i.contiguous() for i in ins] - offs = [self._stage(i) for i in ins] - if any(o is None for o in offs): - self.rccl.all_gather(outs, ins) - return - self._publish_wait() - for o, i, off in zip(outs, ins, offs): - assert o.is_contiguous() and o.dtype == i.dtype - block = i.numel() * i.element_size() - assert o.numel() * o.element_size() == WORLD * block, (o.shape, i.shape) - self._pull(o, off, block, 0) - - def all_to_all(self, out: torch.Tensor, x: torch.Tensor) -> None: - """Row block r of ``x`` to rank r; row block r of ``out`` from rank r.""" - x = x.contiguous() - n = x.numel() * x.element_size() - assert n % WORLD == 0 and out.is_contiguous() - assert out.numel() * out.element_size() == n - off = self._stage(x) - if off is None: - self.rccl.all_to_all(out, x) - return - self._publish_wait() - block = n // WORLD - self._pull(out, off, block, self.p.rank * block) - - def all_to_all_unpack( - self, x: torch.Tensor, d: int - ) -> tuple[torch.Tensor, torch.Tensor] | None: - """``all_to_all`` of packed rows ``[WORLD * rows, d + d / 32]``, unpacked: - (e4m3 codes ``[rows, WORLD * d]``, scales ``[rows, WORLD * d / 32]``), or - None when ``x`` does not fit the slot.""" - x = x.contiguous() - rows = x.shape[0] // WORLD - assert x.dtype == torch.uint8 and x.shape == (WORLD * rows, d + d // 32) - assert d % 32 == 0 and d % 16 == 0 - n = x.numel() - off = self._stage(x) - if off is None: - return None - self._publish_wait() - codes = torch.empty((rows, WORLD * d), dtype=torch.uint8, device=x.device) - scales = torch.empty( - (rows, WORLD * d // 32), dtype=torch.uint8, device=x.device - ) - p = self.p - block = n // WORLD - srcs = [ptr + off for ptr in p.pool_ptrs] - flags = [f + self.flag_off for f in p.flag_ptrs] - _run_compiled( - p.pull_unpack, - codes.data_ptr(), - scales.data_ptr(), - *srcs, - *flags, - block, - p.rank * block, - self.seq, - p.rank, - rows, - d, - self.stream, - ) - return codes.view(torch.float8_e4m3fn), scales - - def reduce_scatter(self, out: torch.Tensor, x: torch.Tensor) -> None: - """``[padded, H]`` partial sums -> this rank's ``[rows, H]`` sums (fp32, - rank order).""" - assert x.dtype == torch.bfloat16 and out.dtype == torch.bfloat16 - x = x.contiguous() - n = x.numel() * x.element_size() - block = n // WORLD - assert out.is_contiguous() and out.numel() * out.element_size() == block - off = self._stage(x) - if off is None: - self.rccl.reduce_scatter(out, x) - return - self._publish_wait() - # allocated and read on this stream only - staging = torch.empty(n, dtype=torch.uint8, device=x.device) - self._pull(staging, off, block, self.p.rank * block) - srcs = [staging.data_ptr() + r * block for r in range(WORLD)] - _run_compiled(self.p.sum4, out.data_ptr(), *srcs, block, self.stream) diff --git a/vllm/models/minimax_m3/amd/ops/sp_coll/kernel.py b/vllm/models/minimax_m3/amd/ops/sp_coll/kernel.py deleted file mode 100644 index 13bca0f19978..000000000000 --- a/vllm/models/minimax_m3/amd/ops/sp_coll/kernel.py +++ /dev/null @@ -1,438 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""FlyDSL pull collectives (TP4, gfx950). ``fence_publish`` writes every XCD's L2 -back (a coarse-grained buffer's dirty lines are not flushed for peers' xGMI reads at -a kernel boundary), then the last workgroup stores the sequence into the flag; -``pull`` is a small persistent grid: CU slots are scarce next to compute kernels.""" - -import flydsl.compiler as flyc -import flydsl.expr as fx -from aiter.ops.flydsl.kernels import buffer_ops -from flydsl._mlir.dialects import llvm as _llvm -from flydsl.expr import range_constexpr -from flydsl.expr.typing import T -from flydsl.expr.typing import Vector as Vec - -WORLD = 4 -NT = 256 -UNROLL = 8 # 16 B per thread per step -STEP = NT * 4 * UNROLL # dwords per workgroup per loop step -SYS = 0x11 # sc0 | sc1: system-coherent loads / stores -# 8 workgroups per XCD (w runs on XCD w % 8, each with its own L2) -FENCE_WGS = 64 -PER_PEER = 256 # chunks per rank block -# 4 workgroups per rank reach the link rate (50 MB: 0.87 vs RCCL 0.95 ms) -PULL_WGS = 16 -SUM_WGS = 1024 -# bytes per set: the flag word, then the fence ticket counter -FLAG_STRIDE = 16 - - -def _global_i32_ptr(addr_i64): - ptr_ty = fx.PointerType.get( - T.i32, address_space=fx.AddressSpace.Global, alignment=4 - ) - return fx.inttoptr(ptr_ty, fx.Int64(addr_i64)) - - -def _flag_read(addr_i64): - """System-scope atomic add of 0: never hoisted out of the spin loop.""" - return fx.Int32( - _llvm.AtomicRMWOp( - _llvm.AtomicBinOp.add, - _global_i32_ptr(addr_i64).llvm_ptr, - fx.Int32(0).ir_value(), - _llvm.AtomicOrdering.monotonic, - syncscope="", - alignment=4, - ).result - ) - - -def _flag_add(addr_i64, v): - """System-scope atomic add; returns the old value.""" - return fx.Int32( - _llvm.AtomicRMWOp( - _llvm.AtomicBinOp.add, - _global_i32_ptr(addr_i64).llvm_ptr, - fx.Int32(v).ir_value(), - _llvm.AtomicOrdering.monotonic, - syncscope="", - alignment=4, - ).result - ) - - -def _sel4(p, a0, a1, a2, a3): - return (p == 0).select(a0, (p == 1).select(a1, (p == 2).select(a2, a3))) - - -def _as_f32(i): - return fx.Int32(i).bitcast(fx.Float32) - - -def _pk_bf16(a, b): - return fx.Int32( - fx.rocdl.cvt_pk_bf16_f32( - fx.as_ir_value(fx.Float32(a)), fx.as_ir_value(fx.Float32(b)) - ) - ) - - -def compile_publish(): - """Store a value into the flag, system-coherent (the init's zeroing).""" - - @flyc.kernel(name="sp_coll_publish", known_block_size=[64, 1, 1]) - def kernel(arg_flag: fx.Int64, i32_seq: fx.Int32): - fr = buffer_ops.create_buffer_resource_from_addr(arg_flag, num_records_bytes=64) - buffer_ops.buffer_store( - i32_seq, fr, 0, mask=fx.thread_idx.x == 0, cache_modifier=SYS - ) - - @flyc.jit - def launch(arg_flag: fx.Int64, i32_seq: fx.Int32, stream: fx.Stream): - kernel(arg_flag, i32_seq).launch( - grid=(1, 1, 1), block=(64, 1, 1), stream=stream - ) - - launch.kernel_name = "sp_coll_publish" - return launch - - -def compile_fence_publish(): - """Every workgroup releases its XCD's L2 and takes a ticket; the last one - resets the counter and stores ``seq`` into the flag.""" - - @flyc.kernel(name="sp_coll_fence_publish", known_block_size=[64, 1, 1]) - def kernel(arg_flag: fx.Int64, i32_seq: fx.Int32): - _llvm.FenceOp(_llvm.AtomicOrdering.release, syncscope="") - if fx.thread_idx.x == 0: - t = _flag_add(arg_flag + 4, 1) - if t == FENCE_WGS - 1: - _flag_add(arg_flag + 4, -FENCE_WGS) - fr = buffer_ops.create_buffer_resource_from_addr( - arg_flag, num_records_bytes=64 - ) - buffer_ops.buffer_store(i32_seq, fr, 0, cache_modifier=SYS) - - @flyc.jit - def launch(arg_flag: fx.Int64, i32_seq: fx.Int32, stream: fx.Stream): - kernel(arg_flag, i32_seq).launch( - grid=(FENCE_WGS, 1, 1), block=(64, 1, 1), stream=stream - ) - - launch.kernel_name = "sp_coll_fence_publish" - return launch - - -def compile_pull(): - """dst[p * block, (p + 1) * block) <- rank p's bytes [src_off, src_off + block). - Workgroup w serves rank w % 4: waits for its flag to reach ``seq``, then copies - chunks w // 4, w // 4 + PULL_WGS // 4, ...""" - - @flyc.kernel(name="sp_coll_pull", known_block_size=[NT, 1, 1]) - def kernel( - arg_dst: fx.Int64, - arg_s0: fx.Int64, - arg_s1: fx.Int64, - arg_s2: fx.Int64, - arg_s3: fx.Int64, - arg_f0: fx.Int64, - arg_f1: fx.Int64, - arg_f2: fx.Int64, - arg_f3: fx.Int64, - i64_block: fx.Int64, # bytes per rank block (multiple of 16) - i64_src_off: fx.Int64, # byte offset of the block inside a rank's region - i32_seq: fx.Int32, - i32_me: fx.Int32, - ): - tx = fx.thread_idx.x - bid = fx.block_idx.x - p = bid % WORLD - if (tx == 0) & (p != i32_me): - fa = _sel4(p, arg_f0, arg_f1, arg_f2, arg_f3) - f = _flag_read(fa) - while f < i32_seq: - f = _flag_read(fa) - fx.gpu.barrier() - _llvm.FenceOp(_llvm.AtomicOrdering.acquire, syncscope="") - src_a = _sel4(p, arg_s0, arg_s1, arg_s2, arg_s3) + i64_src_off - src = buffer_ops.create_buffer_resource_from_addr( - src_a, num_records_bytes=i64_block - ) - dst = buffer_ops.create_buffer_resource_from_addr( - arg_dst + fx.Int64(p) * i64_block, num_records_bytes=i64_block - ) - n_dw = fx.Int32(i64_block // 4) - per_block = (n_dw + (PER_PEER - 1)) // PER_PEER - per_block = (per_block + (STEP - 1)) // STEP * STEP - pb = bid // WORLD - while pb < PER_PEER: - start = pb * per_block - end = start + per_block - off = start + tx * 4 - while off < end: - vals = [] - for u in range_constexpr(UNROLL): - o = off + u * NT * 4 - vals.append( - Vec( - buffer_ops.buffer_load( - src, - o, - vec_width=4, - dtype=fx.Int32, - mask=o < n_dw, - cache_modifier=SYS, - ) - ) - ) - for u in range_constexpr(UNROLL): - o = off + u * NT * 4 - buffer_ops.buffer_store(vals[u], dst, o, mask=o < n_dw) - off = off + STEP - pb = pb + (PULL_WGS // WORLD) - - @flyc.jit - def launch( - arg_dst: fx.Int64, - arg_s0: fx.Int64, - arg_s1: fx.Int64, - arg_s2: fx.Int64, - arg_s3: fx.Int64, - arg_f0: fx.Int64, - arg_f1: fx.Int64, - arg_f2: fx.Int64, - arg_f3: fx.Int64, - i64_block: fx.Int64, - i64_src_off: fx.Int64, - i32_seq: fx.Int32, - i32_me: fx.Int32, - stream: fx.Stream, - ): - kernel( - arg_dst, - arg_s0, - arg_s1, - arg_s2, - arg_s3, - arg_f0, - arg_f1, - arg_f2, - arg_f3, - i64_block, - i64_src_off, - i32_seq, - i32_me, - ).launch(grid=(PULL_WGS, 1, 1), block=(NT, 1, 1), stream=stream) - - launch.kernel_name = "sp_coll_pull" - return launch - - -def compile_pull_unpack(): - """``pull`` that also unpacks (``sp_pack.mxfp8_unpack``): rank p's rows of ``d`` - codes + ``d / 32`` scales land in codes[:, p * d :] and scales[:, p * d / 32 :]. - A 16 B unit never straddles codes and scales since d % 16 == 0.""" - - @flyc.kernel(name="sp_coll_pull_unpack", known_block_size=[NT, 1, 1]) - def kernel( - arg_codes: fx.Int64, - arg_scales: fx.Int64, - arg_s0: fx.Int64, - arg_s1: fx.Int64, - arg_s2: fx.Int64, - arg_s3: fx.Int64, - arg_f0: fx.Int64, - arg_f1: fx.Int64, - arg_f2: fx.Int64, - arg_f3: fx.Int64, - i64_block: fx.Int64, # bytes per rank block = rows * row_bytes - i64_src_off: fx.Int64, - i32_seq: fx.Int32, - i32_me: fx.Int32, - i32_rows: fx.Int32, - i32_d: fx.Int32, # codes per row (bytes); scales per row = d / 32 - ): - tx = fx.thread_idx.x - bid = fx.block_idx.x - p = bid % WORLD - if (tx == 0) & (p != i32_me): - fa = _sel4(p, arg_f0, arg_f1, arg_f2, arg_f3) - f = _flag_read(fa) - while f < i32_seq: - f = _flag_read(fa) - fx.gpu.barrier() - _llvm.FenceOp(_llvm.AtomicOrdering.acquire, syncscope="") - src_a = _sel4(p, arg_s0, arg_s1, arg_s2, arg_s3) + i64_src_off - src = buffer_ops.create_buffer_resource_from_addr( - src_a, num_records_bytes=i64_block - ) - row_bytes = i32_d + i32_d // 32 - codes = buffer_ops.create_buffer_resource_from_addr( - arg_codes, num_records_bytes=fx.Int64(i32_rows) * fx.Int64(i32_d * WORLD) - ) - scales = buffer_ops.create_buffer_resource_from_addr( - arg_scales, - num_records_bytes=fx.Int64(i32_rows) * fx.Int64((i32_d // 32) * WORLD), - ) - n_dw = fx.Int32(i64_block // 4) - per_block = (n_dw + (PER_PEER - 1)) // PER_PEER - per_block = (per_block + (STEP - 1)) // STEP * STEP - pb = bid // WORLD - while pb < PER_PEER: - start = pb * per_block - end = start + per_block - off = start + tx * 4 - while off < end: - vals = [] - for u in range_constexpr(UNROLL): - o = off + u * NT * 4 - vals.append( - Vec( - buffer_ops.buffer_load( - src, - o, - vec_width=4, - dtype=fx.Int32, - mask=o < n_dw, - cache_modifier=SYS, - ) - ) - ) - for u in range_constexpr(UNROLL): - o = off + u * NT * 4 - byte = o * 4 - row = byte // row_bytes - b = byte - row * row_bytes - is_code = b < i32_d - off_c = (row * (i32_d * WORLD) + p * i32_d + b) // 4 - off_s = ( - row * ((i32_d // 32) * WORLD) + p * (i32_d // 32) + (b - i32_d) - ) // 4 - ok = o < n_dw - buffer_ops.buffer_store(vals[u], codes, off_c, mask=ok & is_code) - buffer_ops.buffer_store(vals[u], scales, off_s, mask=ok & ~is_code) - off = off + STEP - pb = pb + (PULL_WGS // WORLD) - - @flyc.jit - def launch( - arg_codes: fx.Int64, - arg_scales: fx.Int64, - arg_s0: fx.Int64, - arg_s1: fx.Int64, - arg_s2: fx.Int64, - arg_s3: fx.Int64, - arg_f0: fx.Int64, - arg_f1: fx.Int64, - arg_f2: fx.Int64, - arg_f3: fx.Int64, - i64_block: fx.Int64, - i64_src_off: fx.Int64, - i32_seq: fx.Int32, - i32_me: fx.Int32, - i32_rows: fx.Int32, - i32_d: fx.Int32, - stream: fx.Stream, - ): - kernel( - arg_codes, - arg_scales, - arg_s0, - arg_s1, - arg_s2, - arg_s3, - arg_f0, - arg_f1, - arg_f2, - arg_f3, - i64_block, - i64_src_off, - i32_seq, - i32_me, - i32_rows, - i32_d, - ).launch(grid=(PULL_WGS, 1, 1), block=(NT, 1, 1), stream=stream) - - launch.kernel_name = "sp_coll_pull_unpack" - return launch - - -def compile_sum4(): - """Sum the four staged bf16 blocks in fp32, in rank order 0..3.""" - - @flyc.kernel(name="sp_coll_sum4", known_block_size=[NT, 1, 1]) - def kernel( - arg_out: fx.Int64, - arg_s0: fx.Int64, - arg_s1: fx.Int64, - arg_s2: fx.Int64, - arg_s3: fx.Int64, - i64_block: fx.Int64, # bytes per block (bf16, multiple of 16) - ): - tx = fx.thread_idx.x - bid = fx.block_idx.x - srcs = [ - buffer_ops.create_buffer_resource_from_addr(a, num_records_bytes=i64_block) - for a in (arg_s0, arg_s1, arg_s2, arg_s3) - ] - out = buffer_ops.create_buffer_resource_from_addr( - arg_out, num_records_bytes=i64_block - ) - n_dw = fx.Int32(i64_block // 4) - per_block = (n_dw + (SUM_WGS - 1)) // SUM_WGS - per_block = (per_block + (STEP - 1)) // STEP * STEP - start = bid * per_block - end = start + per_block - off = start + tx * 4 - while off < end: - words = [] - for u in range_constexpr(UNROLL): - o = off + u * NT * 4 - words.append( - [ - Vec( - buffer_ops.buffer_load( - srcs[r], - o, - vec_width=4, - dtype=fx.Int32, - mask=o < n_dw, - ) - ) - for r in range_constexpr(WORLD) - ] - ) - for u in range_constexpr(UNROLL): - o = off + u * NT * 4 - packed = [] - for i in range_constexpr(4): - lo = fx.Float32(0.0) - hi = fx.Float32(0.0) - for r in range_constexpr(WORLD): - w = fx.Int32(words[u][r][i]) - lo = lo + _as_f32(w << 16) - hi = hi + _as_f32(w & fx.Int32(-65536)) - packed.append(_pk_bf16(lo, hi)) - buffer_ops.buffer_store( - Vec.from_elements(packed, fx.Int32), out, o, mask=o < n_dw - ) - off = off + STEP - - @flyc.jit - def launch( - arg_out: fx.Int64, - arg_s0: fx.Int64, - arg_s1: fx.Int64, - arg_s2: fx.Int64, - arg_s3: fx.Int64, - i64_block: fx.Int64, - stream: fx.Stream, - ): - kernel(arg_out, arg_s0, arg_s1, arg_s2, arg_s3, i64_block).launch( - grid=(SUM_WGS, 1, 1), block=(NT, 1, 1), stream=stream - ) - - launch.kernel_name = "sp_coll_sum4" - return launch diff --git a/vllm/models/minimax_m3/amd/ops/sp_norm_quant.py b/vllm/models/minimax_m3/amd/ops/sp_norm_quant.py deleted file mode 100644 index 24ad40ad8d8d..000000000000 --- a/vllm/models/minimax_m3/amd/ops/sp_norm_quant.py +++ /dev/null @@ -1,113 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""Gemma RMSNorm (optionally after the residual add) + per-token MXFP8 quant in one -pass for ``sp_prefill``, with ``gemma_rmsnorm``'s sum order. The scale byte is -clamped to [0, 254] (``mxfp8_e4m3_quantize``) or [85, 254] (aiter's MoE quant).""" - -import torch - -from vllm.triton_utils import tl, triton - -# aiter's MoE input quant: scale at least 2^-42. -MOE_MIN_SCALE_BYTE = 85 - - -@triton.jit -def _rmsnorm_mx_kernel( - x_ptr, - res_ptr, - w_ptr, - out_ptr, - res_out_ptr, - q_ptr, - s_ptr, - n_cols, - eps, - HAS_RES: tl.constexpr, - STORE_OUT: tl.constexpr, - MIN_SB: tl.constexpr, - BLOCK_N: tl.constexpr, - FP8_MAX: tl.constexpr, - TINY: tl.constexpr, -): - row = tl.program_id(0) - cols = tl.arange(0, BLOCK_N) - mask = cols < n_cols - s = tl.load(x_ptr + row * n_cols + cols, mask=mask, other=0.0).to(tl.float32) - if HAS_RES: - r = tl.load(res_ptr + row * n_cols + cols, mask=mask, other=0.0) - s = s + r.to(tl.float32) - tl.store( - res_out_ptr + row * n_cols + cols, - s.to(res_out_ptr.dtype.element_ty), - mask=mask, - ) - var = tl.sum(s * s, axis=0) / n_cols - rstd = 1.0 / tl.sqrt(var + eps) - w = tl.load(w_ptr + cols, mask=mask, other=0.0).to(tl.float32) - out = (s * rstd * (1.0 + w)).to(out_ptr.dtype.element_ty) - if STORE_OUT: - tl.store(out_ptr + row * n_cols + cols, out, mask=mask) - y = tl.reshape(out.to(tl.float32), (BLOCK_N // 32, 32)) - amax = tl.maximum(tl.max(tl.abs(y), axis=1), TINY) - sb = tl.ceil(tl.log2(amax / FP8_MAX)) + 127.0 - sb = tl.minimum(tl.maximum(sb, MIN_SB), 254.0) - q = (y * tl.exp2(127.0 - sb)[:, None]).to(q_ptr.dtype.element_ty) - tl.store(q_ptr + row * n_cols + cols, tl.reshape(q, (BLOCK_N,)), mask=mask) - groups = tl.arange(0, BLOCK_N // 32) - tl.store( - s_ptr + row * (n_cols // 32) + groups, - sb.to(tl.uint8), - mask=groups < n_cols // 32, - ) - - -def _out_or_empty(out, shape, dtype, device) -> torch.Tensor: - if out is None: - return torch.empty(shape, dtype=dtype, device=device) - assert out.shape == shape and out.dtype == dtype and out.is_contiguous() - return out - - -def gemma_rmsnorm_mx( - x: torch.Tensor, - residual: torch.Tensor | None, - weight: torch.Tensor, - eps: float, - *, - min_scale_byte: int = 0, - store_out: bool = False, - q_out: torch.Tensor | None = None, - scale_out: torch.Tensor | None = None, -) -> tuple[torch.Tensor | None, torch.Tensor, torch.Tensor, torch.Tensor]: - """-> (normalized bf16 if ``store_out``, x + residual (``x`` without one), - MXFP8 codes, e8m0 scales ``[M, N/32]``); the codes / scales into ``q_out`` / - ``scale_out`` when given.""" - m, n = x.shape - assert x.is_contiguous() and n % 32 == 0 - assert residual is None or residual.is_contiguous() - out = torch.empty_like(x) if store_out else None - res_out = torch.empty_like(x) if residual is not None else x - q = _out_or_empty(q_out, (m, n), torch.float8_e4m3fn, x.device) - scale = _out_or_empty(scale_out, (m, n // 32), torch.uint8, x.device) - block_n = triton.next_power_of_2(n) - _rmsnorm_mx_kernel[(m,)]( - x, - x if residual is None else residual, - weight, - x if out is None else out, - res_out, - q, - scale, - n, - eps, - HAS_RES=residual is not None, - STORE_OUT=store_out, - MIN_SB=float(min_scale_byte), - BLOCK_N=block_n, - FP8_MAX=float(torch.finfo(torch.float8_e4m3fn).max), - TINY=float(torch.finfo(torch.float32).tiny), - # gemma_rmsnorm._num_warps (its sum order) - num_warps=16 if block_n >= 4096 else (8 if block_n >= 1024 else 4), - ) - return out, res_out, q, scale diff --git a/vllm/models/minimax_m3/amd/ops/sp_pack.py b/vllm/models/minimax_m3/amd/ops/sp_pack.py deleted file mode 100644 index 099f9503594b..000000000000 --- a/vllm/models/minimax_m3/amd/ops/sp_pack.py +++ /dev/null @@ -1,114 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""MXFP8 pack / unpack for the all-to-all of the sequence-parallel o_proj: a row is -its e4m3 codes, then its e8m0 scales (``mxfp8_e4m3_quantize``'s quant).""" - -import torch - -from vllm.triton_utils import tl, triton - - -@triton.jit -def _quant_pack_kernel( - x_ptr, - out_ptr, - M, - D: tl.constexpr, - BLOCK_M: tl.constexpr, - FP8_MAX: tl.constexpr, - TINY: tl.constexpr, -): - pid = tl.program_id(0) - rows = pid * BLOCK_M + tl.arange(0, BLOCK_M) - cols = tl.arange(0, D) - mask = rows < M - x = tl.load( - x_ptr + rows[:, None] * D + cols[None, :], mask=mask[:, None], other=0.0 - ) - x = tl.reshape(x.to(tl.float32), (BLOCK_M, D // 32, 32)) - amax = tl.maximum(tl.max(tl.abs(x), axis=2), TINY) - sb = tl.minimum(tl.maximum(tl.ceil(tl.log2(amax / FP8_MAX)) + 127.0, 0.0), 254.0) - q = (x * tl.exp2(127.0 - sb)[:, :, None]).to(tl.float8e4nv) - row_bytes = D + D // 32 - q = tl.reshape(q.to(tl.uint8, bitcast=True), (BLOCK_M, D)) - tl.store(out_ptr + rows[:, None] * row_bytes + cols[None, :], q, mask=mask[:, None]) - groups = tl.arange(0, D // 32) - tl.store( - out_ptr + rows[:, None] * row_bytes + D + groups[None, :], - sb.to(tl.uint8), - mask=mask[:, None], - ) - - -@triton.jit -def _unpack_kernel( - in_ptr, - codes_ptr, - scales_ptr, - ROWS, - WORLD: tl.constexpr, - D: tl.constexpr, - BLOCK_M: tl.constexpr, -): - pid = tl.program_id(0) - w = tl.program_id(1) - rows = pid * BLOCK_M + tl.arange(0, BLOCK_M) - mask = rows < ROWS - row_bytes = D + D // 32 - src = in_ptr + (w * ROWS + rows[:, None]) * row_bytes - cols = tl.arange(0, D) - codes = tl.load(src + cols[None, :], mask=mask[:, None]) - tl.store( - codes_ptr + rows[:, None] * (WORLD * D) + w * D + cols[None, :], - codes, - mask=mask[:, None], - ) - groups = tl.arange(0, D // 32) - scales = tl.load(src + D + groups[None, :], mask=mask[:, None]) - tl.store( - scales_ptr - + rows[:, None] * (WORLD * D // 32) - + w * (D // 32) - + groups[None, :], - scales, - mask=mask[:, None], - ) - - -def mxfp8_quant_pack(x: torch.Tensor, out: torch.Tensor | None = None) -> torch.Tensor: - """``[M, D]`` bf16 -> ``[M, D + D/32]`` uint8.""" - m, d = x.shape - assert x.is_contiguous() and d % 32 == 0 and d & (d - 1) == 0, x.shape - if out is None: - out = torch.empty((m, d + d // 32), dtype=torch.uint8, device=x.device) - assert out.shape == (m, d + d // 32) and out.dtype == torch.uint8 - assert out.is_contiguous() - block_m = 4 - _quant_pack_kernel[(triton.cdiv(m, block_m),)]( - x, - out, - m, - D=d, - BLOCK_M=block_m, - FP8_MAX=float(torch.finfo(torch.float8_e4m3fn).max), - TINY=float(torch.finfo(torch.float32).tiny), - num_warps=8, - ) - return out - - -def mxfp8_unpack( - packed: torch.Tensor, world: int, rows: int, d: int -) -> tuple[torch.Tensor, torch.Tensor]: - """``[world * rows, d + d/32]`` (block w from rank w) -> codes - ``[rows, world * d]`` and scales ``[rows, world * d / 32]``.""" - assert packed.shape == (world * rows, d + d // 32) and packed.is_contiguous() - codes = torch.empty((rows, world * d), dtype=torch.uint8, device=packed.device) - scales = torch.empty( - (rows, world * d // 32), dtype=torch.uint8, device=packed.device - ) - block_m = 4 - _unpack_kernel[(triton.cdiv(rows, block_m), world)]( - packed, codes, scales, rows, WORLD=world, D=d, BLOCK_M=block_m, num_warps=8 - ) - return codes.view(torch.float8_e4m3fn), scales diff --git a/vllm/models/minimax_m3/amd/sp_prefill.py b/vllm/models/minimax_m3/amd/sp_prefill.py deleted file mode 100644 index 6e639a059d81..000000000000 --- a/vllm/models/minimax_m3/amd/sp_prefill.py +++ /dev/null @@ -1,737 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""Sequence-parallel prefill for MiniMax-M3 under pure TP (ROCm). - -From ``SP_MIN_TOKENS`` tokens (``SP_MIN_UBATCH_TOKENS`` per DBO microbatch) each rank -keeps ``rows`` tokens of the residual stream. Per layer the two bf16 all-reduces -become an all-to-all of the MXFP8 attention output (each rank applies the whole -o_proj) and a reduce-scatter of the FFN output, each followed by an all-gather of -the next MXFP8 input; norms, quants and the router run on the shard. -""" - -import ctypes -from dataclasses import dataclass, field - -import torch - -import vllm.envs as envs -from vllm.distributed import ( - get_tensor_model_parallel_rank, - get_tensor_model_parallel_world_size, - get_tp_group, -) -from vllm.logger import init_logger - -logger = init_logger(__name__) - -# TP4 isolated prefill: 4096 tokens 133 vs 140 ms. -SP_MIN_TOKENS = 4096 -# Every microbatch of a DBO step needs this many tokens (their hand-offs alternate, -# so all take one path); below, the phases overlap too little. -SP_MIN_UBATCH_TOKENS = 8192 -# The MXFP8 prefill MoE chain's limit. -SP_MAX_TOKENS = 65536 -_ROW_ALIGN = 32 - - -def _run(issue) -> None: - from vllm.v1.worker.ubatching import dbo_tp_collective - - if dbo_tp_collective(issue): - return - comm = get_tp_group().device_communicator.pynccl_comm - issue(comm, torch.cuda.current_stream()) - - -# ops.sp_coll.Pools after init_collectives; None = RCCL. -_POOLS = None -# The pools fit one microbatch of a 65536-token DBO step; larger phases use RCCL. -SP_COLL_MAX_TOKENS = SP_MAX_TOKENS // 2 - - -def collectives_slot_bytes(hidden: int, q_size: int) -> int: - """Bytes of one pool slot: the FFN phase's inputs at ``SP_COLL_MAX_TOKENS`` - (bf16 partials, codes + scales + routing, two bf16 gathers, slack).""" - world = 4 - rows = SP_COLL_MAX_TOKENS // world - padded = rows * world - assert padded * (q_size + q_size // 32) <= padded * hidden * 2 - return ( - padded * hidden * 2 - + rows * (hidden + hidden // 32 + 64 * 4) - + 2 * rows * hidden * 2 - + 8 * 256 - ) - - -def init_collectives( - hidden: int, q_size: int, device: torch.device, sets: int = 2 -) -> None: - """Create the FlyDSL pools, one slot set per DBO microbatch (TP4 on gfx950). - Collective: every TP rank calls it once.""" - global _POOLS - if _POOLS is not None: - return - from vllm.platforms.rocm import on_gfx950 - - world = get_tensor_model_parallel_world_size() - if world != 4 or not on_gfx950(): - logger.info_once( - "MiniMax-M3 sequence-parallel prefill: RCCL collectives (the FlyDSL " - "ones serve TP4 on gfx950)" - ) - return - from vllm.models.minimax_m3.amd.ops import sp_coll - - tp = get_tp_group() - _POOLS = sp_coll.Pools( - tp.rank_in_group, - world, - tp.cpu_group, - device, - collectives_slot_bytes(hidden, q_size), - sets=max(2, sets), - ) - - -def _bytes(t: torch.Tensor) -> torch.Tensor: - return t.reshape(-1).view(torch.uint8) - - -class Collectives: - """RCCL collectives of one communication phase.""" - - def __init__(self, comm, stream, world: int): - self.comm = comm - self.stream = stream - self.world = world - - def alloc(self, shape: tuple[int, ...], dtype: torch.dtype) -> torch.Tensor | None: - """RCCL reads any tensor: the producer allocates.""" - return None - - def all_gather(self, outs: list[torch.Tensor], ins: list[torch.Tensor]) -> None: - """Each ``[rows, ...]`` shard into its ``[padded, ...]`` output.""" - self.comm.group_start() - for i, o in zip(ins, outs): - self.comm.all_gather(_bytes(o), _bytes(i.contiguous()), stream=self.stream) - self.comm.group_end() - - def reduce_scatter(self, out: torch.Tensor, x: torch.Tensor) -> None: - """``[padded, H]`` partial sums -> this rank's ``[rows, H]`` sums.""" - self.comm.reduce_scatter(out, x, stream=self.stream) - - def all_to_all(self, out: torch.Tensor, x: torch.Tensor) -> None: - """Row block r of ``x`` to rank r, row block r of ``out`` from rank r.""" - from vllm.distributed.device_communicators.pynccl_wrapper import ( - cudaStream_t, - ncclDataTypeEnum, - ) - - fn = self.comm.nccl.lib.ncclAllToAll - if fn.argtypes is None: - fn.restype = ctypes.c_int - fn.argtypes = [ - ctypes.c_void_p, - ctypes.c_void_p, - ctypes.c_size_t, - ctypes.c_int, - ctypes.c_void_p, - ctypes.c_void_p, - ] - xb, ob = _bytes(x), _bytes(out) - assert xb.numel() == ob.numel() and xb.numel() % self.world == 0 - res = fn( - xb.data_ptr(), - ob.data_ptr(), - xb.numel() // self.world, - ncclDataTypeEnum.ncclUint8, - self.comm.comm, - cudaStream_t(self.stream.cuda_stream), - ) - assert res == 0, f"ncclAllToAll failed: {res}" - - -class _Phase: - """The FlyDSL collectives ``begin_phase`` reserved for the next phase.""" - - coll = None - - -@dataclass(frozen=True) -class SeqShard: - num_tokens: int - rows: int - world: int - rank: int - state: _Phase = field(default_factory=_Phase, compare=False, repr=False) - - @property - def padded(self) -> int: - return self.rows * self.world - - def shard(self, x: torch.Tensor) -> torch.Tensor: - """This rank's rows of the full ``[num_tokens, ...]`` ``x`` (zero padded).""" - start = self.rank * self.rows - n = min(self.rows, max(0, self.num_tokens - start)) - if n == self.rows: - return x[start : start + n].contiguous() - out = x.new_zeros((self.rows, *x.shape[1:])) - if n: - out[:n].copy_(x[start : start + n]) - return out - - def pad(self, x: torch.Tensor) -> torch.Tensor: - """``[num_tokens, ...]`` -> ``[padded, ...]``, the padding rows zero.""" - if x.shape[0] == self.padded: - return x - out = x.new_empty((self.padded, *x.shape[1:])) - out[: x.shape[0]].copy_(x) - out[x.shape[0] :].zero_() - return out - - def _fly_collectives(self): - from vllm.models.minimax_m3.amd.ops import sp_coll - from vllm.v1.worker.ubatching import dbo_current_ubatch_id - - return sp_coll.Collectives(_POOLS, dbo_current_ubatch_id()) - - def begin_phase(self) -> None: - """Reserve the next phase's pool slot before the compute that fills it, so - its inputs land in place. Every rank calls it in the same order.""" - if _POOLS is None: - return - assert self.state.coll is None, "the previous phase did not run" - self.state.coll = self._fly_collectives() - - def alloc( - self, shape: tuple[int, ...], dtype: torch.dtype, device: torch.device - ) -> torch.Tensor: - """A view of the next phase's pool slot when it fits, else a new tensor.""" - coll = self.state.coll - t = coll.alloc(shape, dtype) if coll is not None else None - if t is None: - t = torch.empty(shape, dtype=dtype, device=device) - return t - - def phase(self, fn) -> None: - """Run ``fn(collectives)`` as one phase (one DBO hand-off). The caller - allocates the outputs: a block the comm stream allocated could be reused - while the other microbatch still reads it.""" - - def issue(comm, stream): - rccl = Collectives(comm, stream, self.world) - coll = self.state.coll - self.state.coll = None - if coll is None and _POOLS is not None: - coll = self._fly_collectives() - fn(rccl if coll is None else coll.bind(stream, rccl)) - - _run(issue) - - -def plan(num_tokens: int) -> SeqShard | None: - world = get_tensor_model_parallel_world_size() - if world == 1 or num_tokens == 0 or num_tokens > SP_MAX_TOKENS: - return None - from vllm.forward_context import get_forward_context - from vllm.v1.worker.ubatching import dbo_enabled - - if dbo_enabled(): - slices = get_forward_context().ubatch_slices - # without the step's split, this microbatch's size - smallest = num_tokens if slices is None else min(s.num_tokens for s in slices) - if smallest < SP_MIN_UBATCH_TOKENS: - return None - elif num_tokens < SP_MIN_TOKENS: - return None - rows = (num_tokens + world - 1) // world - rows = (rows + _ROW_ALIGN - 1) // _ROW_ALIGN * _ROW_ALIGN - return SeqShard(num_tokens, rows, world, get_tensor_model_parallel_rank()) - - -# Model glue, called from amd/model.py. - -_FP8 = torch.float8_e4m3fn -# DBO microbatches per step (one pool set each), set at model init. -_NUM_UBATCHES = 2 - - -def _mxfp8_kernel(layer): - """``layer``'s MXFP8 linear kernel when it takes pre-quantized input.""" - from vllm.model_executor.kernels.linear.mxfp8.rocm_native import ( - RocmDotScaledMxfp8LinearKernel, - ) - - kernel = getattr(layer.quant_method, "kernel", None) - if isinstance(kernel, RocmDotScaledMxfp8LinearKernel): - return kernel - return None - - -def _linear(layer, x_q: torch.Tensor, x_s: torch.Tensor) -> torch.Tensor: - return layer.quant_method.kernel.apply_quantized(layer, x_q, x_s, torch.bfloat16) - - -def make_o_proj_full(layer, quant_config, prefix: str): - """An unsharded copy of ``layer``'s o_proj (+3.1 GB per rank at TP4), or None - where sequence parallelism cannot run.""" - global _NUM_UBATCHES - from vllm.config import get_current_vllm_config - from vllm.distributed import get_pp_group - from vllm.model_executor.layers.linear import ReplicatedLinear - from vllm.platforms.rocm import on_gfx950 - - o_proj = layer.self_attn.o_proj - if ( - not envs.VLLM_ROCM_MINIMAX_M3_SP_PREFILL - or get_tensor_model_parallel_world_size() == 1 - or get_pp_group().world_size > 1 - or not on_gfx950() - or _mxfp8_kernel(o_proj) is None - ): - return None - _NUM_UBATCHES = max(2, get_current_vllm_config().parallel_config.num_ubatches) - return ReplicatedLinear( - o_proj.input_size, - o_proj.output_size, - bias=False, - quant_config=quant_config, - prefix=f"{prefix}.self_attn.o_proj", - ) - - -def _moe_quant(moe) -> str | None: - """The routed experts' format a FlyDSL prefill chain covers ("mxfp8" or - "mxfp4"), else None.""" - import math - - from vllm.model_executor.layers.fused_moe.experts.aiter_mxfp8_moe import ( - AiterMxfp8Experts, - ) - from vllm.model_executor.layers.fused_moe.experts.rocm_aiter_moe import ( - AiterMxfp4Experts, - ) - from vllm.models.minimax_m3.amd.ops.moe_mxfp4 import prefill as prefill4 - from vllm.models.minimax_m3.amd.ops.moe_mxfp8 import prefill as prefill8 - - runner = moe.experts - kernel = getattr(runner._quant_method, "moe_kernel", None) - cfg = runner.moe_config - if ( - kernel is None - or runner.routed_input_transform is not None - or runner.routed_output_transform is not None - or cfg.moe_parallel_config.use_ep - or not math.isclose(cfg.swiglu_alpha or 0.0, prefill8.GEMM1_SWIGLU_ALPHA) - or not math.isclose(cfg.swiglu_limit or 0.0, prefill8.GEMM1_SWIGLU_LIMIT) - ): - return None - experts = kernel.fused_experts - hidden, inter = cfg.hidden_dim, cfg.intermediate_size_per_partition - if isinstance(experts, AiterMxfp8Experts): - return "mxfp8" if prefill8.supports_shapes(hidden, inter) else None - routed = runner.routed_experts - if ( - isinstance(experts, AiterMxfp4Experts) - and experts.quant_config.use_mxfp4_w4a4 - and prefill4.supports_shapes(hidden, inter) - and routed.w13_weight.shape[1:] == (2 * inter, hidden // 2) - and routed.w2_weight.shape[1:] == (hidden, inter // 2) - ): - return "mxfp4" - return None - - -def _layer_supports_sp(layer) -> bool: - attn = layer.self_attn - linears = [attn.qkv_proj, attn.o_proj_full] - if layer.is_moe_layer: - moe = layer.block_sparse_moe - moe._sp_quant = _moe_quant(moe) - if moe._sp_quant is None: - return False - if moe.shared_experts is not None: - linears.append(moe.shared_experts.gate_up_proj) - else: - linears.append(layer.mlp.gate_up_proj) - return all( - lin is not None - and (kernel := _mxfp8_kernel(lin)) is not None - and kernel.supports_quantized_input(lin) - for lin in linears - ) - - -def plan_model(model, hidden_states: torch.Tensor) -> SeqShard | None: - """The token sharding of a sequence-parallel forward of ``model``, or None.""" - if not envs.VLLM_ROCM_MINIMAX_M3_SP_PREFILL: - return None - if getattr(model, "_sp_supported", True) is False: - return None - if torch.cuda.is_current_stream_capturing(): - return None - sp = plan(hidden_states.shape[0]) - if sp is None: - return None - if not hasattr(model, "_sp_supported"): - layers = model.layers[model.start_layer : model.end_layer] - model._sp_supported = all(_layer_supports_sp(layer) for layer in layers) - logger.info( - "MiniMax-M3 sequence-parallel prefill (from %d tokens, DBO microbatches " - "from %d): %s", - SP_MIN_TOKENS, - SP_MIN_UBATCH_TOKENS, - "on" if model._sp_supported else "off", - ) - if model._sp_supported: - init_collectives( - hidden_states.shape[1], - layers[0].self_attn.q_size, - hidden_states.device, - sets=_NUM_UBATCHES, - ) - return sp if model._sp_supported else None - - -def _input_phase(sp: SeqShard, layer, embeddings: torch.Tensor): - """First input norm + MXFP8 quant on this rank's rows -> gathered codes, - scales, residual.""" - from .ops.sp_norm_quant import gemma_rmsnorm_mx - - norm = layer.input_layernorm - hidden = embeddings.shape[1] - codes = torch.empty((sp.padded, hidden), dtype=_FP8, device=embeddings.device) - scales = torch.empty( - (sp.padded, hidden // 32), dtype=torch.uint8, device=embeddings.device - ) - box = [] - - def run(coll): - _, r, x_q, x_s = gemma_rmsnorm_mx( - sp.shard(embeddings), - None, - norm.weight, - norm.variance_epsilon, - q_out=coll.alloc((sp.rows, hidden), _FP8), - scale_out=coll.alloc((sp.rows, hidden // 32), torch.uint8), - ) - coll.all_gather([codes, scales], [x_q, x_s]) - box.append(r) - - sp.phase(run) - return codes, scales, box[0] - - -def _o_proj_all_to_all(attn, attn_output: torch.Tensor, sp: SeqShard, coll): - """This rank's heads of every token -> the whole o_proj of this rank's rows, - through an all-to-all of the MXFP8 codes + scales.""" - from .ops.sp_pack import mxfp8_quant_pack, mxfp8_unpack - - t, d = attn_output.shape - shape = (sp.padded, d + d // 32) - send = coll.alloc(shape, torch.uint8) - if send is None: - send = torch.empty(shape, dtype=torch.uint8, device=attn_output.device) - mxfp8_quant_pack(attn_output, out=send[:t]) - send[t:].zero_() - unpacked = None - if hasattr(coll, "all_to_all_unpack"): - unpacked = coll.all_to_all_unpack(send, d) - if unpacked is None: - recv = torch.empty_like(send) - coll.all_to_all(recv, send) - unpacked = mxfp8_unpack(recv, sp.world, sp.rows, d) - return _linear(attn.o_proj_full, *unpacked) - - -def _routing_width(moe) -> int: - """Columns of the gathered routing: the top-k ids, then their fp32 weights.""" - fused = moe.n_shared_experts if moe.is_fused_shared_expert_enabled else 0 - return 2 * (moe.experts.router.top_k + fused) - - -def _route(moe, x: torch.Tensor, out: torch.Tensor | None) -> torch.Tensor: - runner = moe.experts - router_logits, _ = moe.gate(x) - topk_weights, topk_ids = runner.router.select_experts( - hidden_states=x, - router_logits=router_logits, - topk_indices_dtype=runner._quant_method.topk_indices_dtype, - ) - return torch.cat( - [topk_ids.to(torch.int32), topk_weights.float().view(torch.int32)], - dim=1, - out=out, - ) - - -def _post_attention_phase(sp: SeqShard, layer, attn_output, residual): - """o_proj, post-attention norm, FFN input quant and routing on this rank's - rows -> gathered MXFP8 codes and scales (None when only MXFP4 experts read - them), routing (None for a dense MLP), MXFP4 codes and scales (MXFP4 experts - only), residual.""" - from .ops.moe_mxfp4.prefill import mxfp4_quant - from .ops.sp_norm_quant import MOE_MIN_SCALE_BYTE, gemma_rmsnorm_mx - - hidden = residual.shape[1] - device = residual.device - moe = layer.block_sparse_moe if layer.is_moe_layer else None - mxfp4 = moe is not None and moe._sp_quant == "mxfp4" - need_fp8 = not mxfp4 or moe.shared_experts is not None - codes = scales = fp4 = None - if need_fp8: - codes = torch.empty((sp.padded, hidden), dtype=_FP8, device=device) - scales = torch.empty( - (sp.padded, hidden // 32), dtype=torch.uint8, device=device - ) - if mxfp4: - fp4 = ( - torch.empty((sp.padded, hidden // 2), dtype=torch.uint8, device=device), - torch.empty((sp.padded, hidden // 32), dtype=torch.uint8, device=device), - ) - routing = None - if moe is not None: - width = _routing_width(moe) - routing = torch.empty((sp.padded, width), dtype=torch.int32, device=device) - norm = layer.post_attention_layernorm - box = [] - - def run(coll): - h = _o_proj_all_to_all(layer.self_attn, attn_output, sp, coll) - x, r, x_q, x_s = gemma_rmsnorm_mx( - h, - residual, - norm.weight, - norm.variance_epsilon, - min_scale_byte=MOE_MIN_SCALE_BYTE if moe is not None and not mxfp4 else 0, - store_out=moe is not None, - q_out=coll.alloc((sp.rows, hidden), _FP8) if need_fp8 else None, - scale_out=( - coll.alloc((sp.rows, hidden // 32), torch.uint8) if need_fp8 else None - ), - ) - outs, ins = [], [] - if need_fp8: - outs += [codes, scales] - ins += [x_q, x_s] - if mxfp4: - outs += list(fp4) - ins += mxfp4_quant( - x, - coll.alloc((sp.rows, hidden // 2), torch.uint8), - coll.alloc((sp.rows, hidden // 32), torch.uint8), - ) - if moe is not None: - rt = _route(moe, x, coll.alloc((sp.rows, width), torch.int32)) - outs.append(routing) - ins.append(rt) - coll.all_gather(outs, ins) - box.append(r) - - sp.phase(run) - return codes, scales, routing, fp4, box[0] - - -def max_regular_tokens(num_ubatches: int = 1) -> int: - """The largest forward or microbatch on the regular path. The SP profile run - skips the modular kernel, so it reserves that MoE workspace before the lock; - the last microbatch takes up to ``num_ubatches - 1`` extra tokens.""" - return max(SP_MIN_TOKENS, SP_MIN_UBATCH_TOKENS) - 1 + max(num_ubatches, 1) - 1 - - -def _reserve_moe_workspace(moe, num_tokens: int, topk: int) -> None: - """Size the workspace for a regular MoE call of ``num_tokens`` rows.""" - from vllm.v1.worker.workspace import ( - current_workspace_manager, - is_workspace_manager_initialized, - ) - - if ( - not is_workspace_manager_initialized() - or current_workspace_manager().is_locked() - ): - return - runner = moe.experts - kernel = runner._quant_method.moe_kernel - routed = runner.routed_experts - w1, w2 = routed.w13_weight, routed.w2_weight - hidden = w2.shape[1] - a1 = torch.empty((num_tokens, hidden), dtype=torch.bfloat16, device=w1.device) - topk_ids = torch.empty((num_tokens, topk), dtype=torch.int32, device=w1.device) - _, m, n, k, top_k = kernel.fused_experts.moe_problem_size(a1, w1, w2, topk_ids) - global_num_experts = routed.global_num_experts - if global_num_experts == -1: - global_num_experts = w1.shape[0] - kernel.impl._allocate_buffers( - a1.dtype, - a1.device, - m, - m, - n, - k, - top_k, - global_num_experts, - w1.shape[0], - None, - routed.activation, - ) - - -# The profile run compiles the MoE configs of these sizes, so no request waits. -_WARM_UP_TOKENS = (SP_MIN_TOKENS, 16384, 32768) -_warmed = False - - -def _moe_experts(sp: SeqShard, moe, codes, scales, routing, fp4) -> torch.Tensor: - """The MoE of every token -> its TP partial ``[padded, H]``.""" - global _warmed - runner = moe.experts - t = sp.num_tokens - topk = routing.shape[1] // 2 - _reserve_moe_workspace(moe, max_regular_tokens(_NUM_UBATCHES), topk) - w13, w2 = runner.routed_experts.w13_weight, runner.routed_experts.w2_weight - hidden = w2.shape[1] - experts = runner._quant_method.moe_kernel.fused_experts - if fp4 is None: - from .ops.moe_mxfp8.prefill import a8w8_prefill_moe as moe_chain - - x_q, x_s = codes, scales - w13_s, w2_s = experts.w1_scale_val, experts.w2_scale_val - else: - from .ops.moe_mxfp4.prefill import a4w4_prefill_moe as moe_chain - - x_q, x_s = fp4 - w13_s, w2_s = experts.quant_config.w1_scale, experts.quant_config.w2_scale - - def chain(m: int, out: torch.Tensor | None) -> torch.Tensor: - return moe_chain( - (x_q[:m], x_s[:m]), - w13, - w13_s, - w2, - w2_s, - routing[:m, topk:].view(torch.float32), - routing[:m, :topk], - hidden_size=hidden, - intermediate_size=runner.moe_config.intermediate_size_per_partition, - num_experts=w13.shape[0], - out=out, - ) - - if not _warmed: - _warmed = True - for m in _WARM_UP_TOKENS: - if m < t: - chain(m, None) - out = sp.alloc((sp.padded, hidden), torch.bfloat16, routing.device) - out[t:].zero_() - chain(t, out[:t]) - if runner.routed_scaling_factor != 1.0: - out[:t] *= runner.routed_scaling_factor - if moe.shared_experts is not None: - out[:t] += _mlp(moe.shared_experts, codes[:t], scales[:t]) - return out - - -def _mlp(mlp, x_q: torch.Tensor, x_s: torch.Tensor) -> torch.Tensor: - """A dense MLP on pre-quantized rows -> its TP partial (no reduce).""" - from .ops import swiglu_oai_split - - x = swiglu_oai_split( - _linear(mlp.gate_up_proj, x_q, x_s), - alpha=mlp.swiglu_alpha, - beta=mlp.swiglu_beta, - limit=mlp.swiglu_limit, - ) - return mlp.down_proj.quant_method.apply(mlp.down_proj, x) - - -def _ffn(sp: SeqShard, layer, codes, scales, routing, fp4) -> torch.Tensor: - """The MoE / dense MLP of every token -> its TP partial ``[padded, H]``.""" - if layer.is_moe_layer: - return _moe_experts(sp, layer.block_sparse_moe, codes, scales, routing, fp4) - t = sp.num_tokens - return sp.pad(_mlp(layer.mlp, codes[:t], scales[:t])) - - -def _ffn_out_phase(sp: SeqShard, model, partial, residual, nxt, want_aux, aux_out): - """Reduce-scatter of the FFN partial, then ``nxt``'s input norm + quant (the - final norm after the last layer) on this rank's rows and the gather; an aux - hidden state is gathered into ``aux_out``.""" - from .ops.sp_norm_quant import gemma_rmsnorm_mx - - hidden = partial.shape[1] - device = partial.device - aux = None - if want_aux: - aux = torch.empty((sp.padded, hidden), dtype=partial.dtype, device=device) - aux_out.append(aux) - scales = None - if nxt is not None: - codes = torch.empty((sp.padded, hidden), dtype=_FP8, device=device) - scales = torch.empty( - (sp.padded, hidden // 32), dtype=torch.uint8, device=device - ) - else: - codes = torch.empty((sp.padded, hidden), dtype=partial.dtype, device=device) - box = [] - - def run(coll): - h = torch.empty((sp.rows, hidden), dtype=partial.dtype, device=device) - coll.reduce_scatter(h, partial) - if nxt is not None: - norm = nxt.input_layernorm - _, r, x_q, x_s = gemma_rmsnorm_mx( - h, - residual, - norm.weight, - norm.variance_epsilon, - q_out=coll.alloc((sp.rows, hidden), _FP8), - scale_out=coll.alloc((sp.rows, hidden // 32), torch.uint8), - ) - outs, ins = [codes, scales], [x_q, x_s] - else: - normed, r = model.norm(h, residual) - outs, ins = [codes], [normed] - if aux is not None: - outs.append(aux) - ins.append(r) - coll.all_gather(outs, ins) - box.append(r) - - sp.phase(run) - return codes, scales, box[0] - - -def forward( - model, - positions: torch.Tensor, - hidden_states: torch.Tensor, - aux_hidden_states: list[torch.Tensor], - sp: SeqShard, -) -> torch.Tensor | tuple[torch.Tensor, list[torch.Tensor]]: - """Sequence-parallel forward of ``model`` from the embeddings to the final - norm.""" - layers = model.layers[model.start_layer : model.end_layer] - t = sp.num_tokens - codes, scales, residual = _input_phase(sp, layers[0], hidden_states) - aux_gathered: list[torch.Tensor] = [] - for idx, layer in enumerate(layers): - sp.begin_phase() - qkv = _linear(layer.self_attn.qkv_proj, codes[:t], scales[:t]) - attn_output = layer.self_attn.attend(positions, qkv) - codes, scales, routing, fp4, residual = _post_attention_phase( - sp, layer, attn_output, residual - ) - sp.begin_phase() - partial = _ffn(sp, layer, codes, scales, routing, fp4) - nxt = layers[idx + 1] if idx + 1 < len(layers) else None - want_aux = model.start_layer + idx + 1 in model.aux_hidden_state_layers - codes, scales, residual = _ffn_out_phase( - sp, model, partial, residual, nxt, want_aux, aux_gathered - ) - aux_hidden_states += [a[:t] for a in aux_gathered] - if aux_hidden_states: - return codes[:t], aux_hidden_states - return codes[:t] diff --git a/vllm/v1/worker/gpu/dp_utils.py b/vllm/v1/worker/gpu/dp_utils.py index 7ffd9db5c5e8..fb9f4c02d3e4 100644 --- a/vllm/v1/worker/gpu/dp_utils.py +++ b/vllm/v1/worker/gpu/dp_utils.py @@ -290,23 +290,6 @@ def dispatch_cg_and_sync_dp( ) if dp_size == 1: - # One DP rank: the split is a local decision; a split step runs eager. - if ( - allow_ubatching - and dp_sync_state is None - and parallel_config is not None - and num_tokens >= get_num_ubatches(parallel_config) - and check_ubatch_thresholds( - parallel_config, num_tokens, uniform_decode=uniform_decode - ) - ): - batch_desc = BatchExecutionDescriptor( - cg_mode=CUDAGraphMode.NONE, - num_tokens=num_tokens, - num_reqs=num_reqs, - num_active_loras=num_active_loras, - num_ubatches=get_num_ubatches(parallel_config), - ) return batch_desc, None if dp_sync_state is not None: diff --git a/vllm/v1/worker/gpu/ubatch_utils.py b/vllm/v1/worker/gpu/ubatch_utils.py index 2e9ff4a736e6..608231a3ed42 100644 --- a/vllm/v1/worker/gpu/ubatch_utils.py +++ b/vllm/v1/worker/gpu/ubatch_utils.py @@ -20,7 +20,6 @@ override_forward_context, ) from vllm.logger import init_logger -from vllm.platforms import current_platform from vllm.sequence import IntermediateTensors from vllm.utils.torch_utils import current_stream from vllm.v1.kv_cache_interface import KVCacheConfig @@ -34,11 +33,7 @@ create_sm_control_context, maybe_create_ubatch_slices, ) -from vllm.v1.worker.ubatching import ( - dbo_comm_stream_priority, - init_dbo_tp_comms, - make_ubatch_contexts, -) +from vllm.v1.worker.ubatching import make_ubatch_contexts from vllm.v1.worker.utils import AttentionGroup logger = init_logger(__name__) @@ -269,8 +264,7 @@ def merge_ubatch_outputs(outputs: list[Any]) -> Any: """Reassemble the full-batch model output from the per-microbatch ones. Models return hidden states, a tuple of those plus auxiliary hidden states - (EAGLE3; a list of them for DSpark), or IntermediateTensors on non-final - pipeline ranks. + (EAGLE3), or IntermediateTensors on non-final pipeline ranks. """ first = outputs[0] if isinstance(first, IntermediateTensors): @@ -280,10 +274,8 @@ def merge_ubatch_outputs(outputs: list[Any]) -> Any: for key in first.tensors } ) - if isinstance(first, (tuple, list)): - return type(first)(merge_ubatch_outputs(list(parts)) for parts in zip(*outputs)) - if first is None: - return None + if isinstance(first, tuple): + return tuple(torch.cat(parts, dim=0) for parts in zip(*outputs)) return torch.cat(outputs, dim=0) @@ -332,41 +324,13 @@ def __init__( else None for _ in range(self.num_ubatches) ] - self.comm_stream = torch.cuda.Stream( - device=device, priority=dbo_comm_stream_priority() - ) + self.comm_stream = torch.cuda.Stream(device=device) # Threads and graph capture must use the same compute stream. self.capture_stream = torch.cuda.Stream(device=device) # The microbatch threads plus the thread that starts them. self.ready_barrier = threading.Barrier(self.num_ubatches + 1) - init_dbo_tp_comms(self.parallel_config) self._pending_finish: Callable[[], Any] | None = None self.sm_control = create_sm_control_context(self.parallel_config) - if current_platform.is_rocm(): - self._warm_blas_lt_handles() - - def _warm_blas_lt_handles(self) -> None: - """Fill torch's hipBLASLt handle pool for the microbatch threads. - - hipblasLtCreate clears a new handle's Stream-K flags with a null-stream - hipMemset that can land after a GEMM on the comm stream has started, and - the GEMM then never finishes. Microbatch threads are new every step and - take their per-stream handles from the pool.""" - a = torch.zeros((64, 64), dtype=torch.bfloat16, device=self.device) - streams = (current_stream(), self.capture_stream, self.comm_stream) - - def touch() -> None: - torch.accelerator.set_device_index(self.device.index) - for stream in streams: - with torch.cuda.stream(stream): - torch.mm(a, a, out_dtype=torch.float32) - - threads = [threading.Thread(target=touch) for _ in range(self.num_ubatches)] - for t in threads: - t.start() - for t in threads: - t.join() - torch.cuda.synchronize(self.device) def prepare( self, @@ -454,12 +418,8 @@ def _make_forward_contexts( self.vllm_config, dp_metadata=DPMetadata.make( self.parallel_config, num_tokens, num_tokens_across_dp - ) - if dp_size > 1 - else None, + ), cudagraph_runtime_mode=CUDAGraphMode.NONE, - # A model picking a path per step sees the whole split. - ubatch_slices=ubatch_slices, slot_mapping=slot_mappings_by_layer[i], is_padding=is_padding[i], ) @@ -529,8 +489,6 @@ def run_ubatch(ubatch_context, inputs: dict[str, Any]) -> None: # changing the shared handoff protocol in ubatching.py, which # is deliberately out of scope here. errors[ubatch_context.id] = e - # The sibling may wait on a hand-off forever: log before the join. - logger.exception("Microbatch %d failed", ubatch_context.id) # Threads own the forward context; keep it cleared and SMs reserved # until finish joins them. @@ -598,9 +556,7 @@ def maybe_build_ubatch_runner( available with more than one DP rank (as in the V1 runner). """ parallel_config = vllm_config.parallel_config - if not parallel_config.use_ubatching: - return None - if parallel_config.data_parallel_size <= 1 and not parallel_config.dbo_tp_only: + if not parallel_config.use_ubatching or parallel_config.data_parallel_size <= 1: return None logger.info_once("Dual batch overlap is enabled.") diff --git a/vllm/v1/worker/gpu_model_runner.py b/vllm/v1/worker/gpu_model_runner.py index 71c4f1a92e14..ac3ff3b65865 100644 --- a/vllm/v1/worker/gpu_model_runner.py +++ b/vllm/v1/worker/gpu_model_runner.py @@ -213,7 +213,6 @@ from vllm.v1.worker.ubatch_utils import ( UBatchSlices, check_ubatch_thresholds, - is_last_ubatch_empty, maybe_create_ubatch_slices, split_attn_metadata, ) @@ -3768,17 +3767,6 @@ def dispatch_cudagraph(num_tokens, disable_full=False, valid_modes=None): # Assert to make sure the agreed upon token count is correct otherwise # num_tokens_across_dp will no-longer be valid assert batch_descriptor.num_tokens == num_tokens_padded - elif self.parallel_config.dbo_tp_only and allow_microbatching: - # One DP rank: decide the split locally; only eager steps split. - should_ubatch = ( - cudagraph_mode == CUDAGraphMode.NONE - and check_ubatch_thresholds( - self.parallel_config, num_tokens, uniform_decode=uniform_decode - ) - and not is_last_ubatch_empty( - num_tokens, num_tokens_padded, self.parallel_config.num_ubatches - ) - ) cudagraph_stats = None if self.vllm_config.observability_config.cudagraph_metrics: @@ -6140,16 +6128,6 @@ def profile_run(self, randomize_inputs: bool = False) -> None: for i, output in enumerate(dummy_encoder_outputs): self.encoder_cache[f"tmp_{i}"] = output - if ( - self.parallel_config.use_ubatching - and not self.parallel_config.enable_expert_parallel - ): - # The profile step below is split; size the workspaces for the - # unsplit step first. - unsplit_hidden, unsplit_last = self._dummy_run( - self.max_num_tokens, is_profile=True, allow_microbatching=False - ) - del unsplit_hidden, unsplit_last # Add `is_profile` here to pre-allocate communication buffers hidden_states, last_hidden_states = self._dummy_run( self.max_num_tokens, is_profile=True, randomize_inputs=randomize_inputs diff --git a/vllm/v1/worker/gpu_ubatch_wrapper.py b/vllm/v1/worker/gpu_ubatch_wrapper.py index 6e5865903246..816df537762b 100644 --- a/vllm/v1/worker/gpu_ubatch_wrapper.py +++ b/vllm/v1/worker/gpu_ubatch_wrapper.py @@ -9,10 +9,6 @@ import torch -from vllm.compilation.breakable_cudagraph import ( - BreakableCUDAGraphWrapper, - is_breakable_cudagraph_enabled, -) from vllm.compilation.cuda_graph import CUDAGraphWrapper from vllm.config import CUDAGraphMode, VllmConfig from vllm.distributed.device_communicators.pynccl_allocator import set_graph_pool_id @@ -27,12 +23,7 @@ from vllm.platforms import current_platform from vllm.sequence import IntermediateTensors from vllm.v1.worker.ubatch_utils import create_sm_control_context -from vllm.v1.worker.ubatching import ( - UBatchContext, - dbo_comm_stream_priority, - init_dbo_tp_comms, - make_ubatch_contexts, -) +from vllm.v1.worker.ubatching import UBatchContext, make_ubatch_contexts logger = init_logger(__name__) @@ -50,9 +41,7 @@ def _cat_ubatch_outputs( produced for a single ubatch (#40769). """ if sorted_results and isinstance(sorted_results[0], tuple): - return tuple(_cat_ubatch_outputs(list(parts)) for parts in zip(*sorted_results)) - if sorted_results and isinstance(sorted_results[0], list): - return [torch.cat(parts, dim=0) for parts in zip(*sorted_results)] + return tuple(torch.cat(parts, dim=0) for parts in zip(*sorted_results)) return torch.cat(sorted_results, dim=0) @@ -84,9 +73,7 @@ def __init__( self.runnable = runnable self.vllm_config = vllm_config self.compilation_config = vllm_config.compilation_config - self.comm_stream = torch.cuda.Stream( - device=device, priority=dbo_comm_stream_priority() - ) + self.comm_stream = torch.cuda.Stream(device=device) # Ubatch threads plus the main thread self.ready_barrier = threading.Barrier( self.vllm_config.parallel_config.num_ubatches + 1 @@ -99,14 +86,6 @@ def __init__( self.cudagraph_wrapper = CUDAGraphWrapper( runnable, vllm_config, runtime_mode=runtime_mode ) - # Unsplit steps keep their breakable piecewise graphs. - self.piecewise_wrapper = None - if ( - is_breakable_cudagraph_enabled() - and self.compilation_config.cudagraph_mode != CUDAGraphMode.NONE - ): - self.piecewise_wrapper = BreakableCUDAGraphWrapper(runnable, vllm_config) - init_dbo_tp_comms(self.vllm_config.parallel_config) self.sm_control = create_sm_control_context(vllm_config.parallel_config) self.device = device @@ -394,11 +373,6 @@ def __call__(self, *args, **kwargs): if batch_descriptor.num_tokens in self.cudagraphs: cudagraph_runtime_mode = CUDAGraphMode.NONE - if ( - cudagraph_runtime_mode is CUDAGraphMode.PIECEWISE - and self.piecewise_wrapper is not None - ): - return self.piecewise_wrapper(*args, **kwargs) if cudagraph_runtime_mode in (CUDAGraphMode.NONE, CUDAGraphMode.PIECEWISE): return self.runnable(*args, **kwargs) else: @@ -417,11 +391,10 @@ def __call__(self, *args, **kwargs): dp_metadata = forward_context.dp_metadata - ubatch_dp_metadata: list = [] + # We shouldn't be here unless we are running with multiple DP ranks + assert dp_metadata is not None + ubatch_dp_metadata = [] for ubatch_slice in ubatch_slices: - if dp_metadata is None: - ubatch_dp_metadata.append(None) - continue dp_size = self.vllm_config.parallel_config.data_parallel_size ubatch_num_tokens_across_dp = torch.tensor( [ubatch_slice.num_tokens] * dp_size, device="cpu", dtype=torch.int32 diff --git a/vllm/v1/worker/gpu_worker.py b/vllm/v1/worker/gpu_worker.py index cb37316cdcf5..537a262dd42b 100644 --- a/vllm/v1/worker/gpu_worker.py +++ b/vllm/v1/worker/gpu_worker.py @@ -562,10 +562,6 @@ def _init_workspace_and_model_runner(self) -> None: """Set up the workspace manager, build the model runner, report usage.""" # DSpark target and draft CUDA graphs retain workspace views concurrently. num_ubatches = 2 if self.vllm_config.parallel_config.enable_dbo else 1 - pc = self.vllm_config.parallel_config - if self.use_v2_model_runner and pc.dbo_tp_only: - # Both microbatches compute on one stream: one workspace set. - num_ubatches = 1 init_workspace_manager( self.device, num_ubatches, diff --git a/vllm/v1/worker/ubatch_utils.py b/vllm/v1/worker/ubatch_utils.py index 08398ca664da..85e83489c94b 100644 --- a/vllm/v1/worker/ubatch_utils.py +++ b/vllm/v1/worker/ubatch_utils.py @@ -320,14 +320,6 @@ def _make_metadata_with_slice( block_table_tensor = attn_metadata.block_table_tensor[request_slice] slot_mapping = attn_metadata.slot_mapping[token_slice] - causal = attn_metadata.causal - if isinstance(causal, torch.Tensor): - causal = causal[request_slice] - is_prefilling = ( - attn_metadata.is_prefilling[request_slice] - if attn_metadata.is_prefilling is not None - else None - ) positions = attn_metadata.positions if positions is not None: @@ -343,9 +335,7 @@ def _make_metadata_with_slice( max_seq_len=max_seq_len, block_table_tensor=block_table_tensor, slot_mapping=slot_mapping, - causal=causal, positions=positions, - is_prefilling=is_prefilling, seq_lens_cpu_upper_bound=seq_lens_cpu_upper_bound, ) diff --git a/vllm/v1/worker/ubatching.py b/vllm/v1/worker/ubatching.py index 9a1b79d4f6a8..a39f85d388f2 100644 --- a/vllm/v1/worker/ubatching.py +++ b/vllm/v1/worker/ubatching.py @@ -5,7 +5,6 @@ import torch from vllm import forward_context -from vllm.distributed import parallel_state from vllm.forward_context import ForwardContext from vllm.logger import init_logger from vllm.utils.torch_utils import current_stream @@ -253,77 +252,3 @@ def make_ubatch_contexts( ctxs.append(ctx) return ctxs - - -# DBO under pure TP: each TP all-reduce is a hand-off point and runs on the comm -# stream, on a per-microbatch communicator, while the other microbatch computes. -_TP_UBATCH_COMMS: list | None = None - - -def init_dbo_tp_comms(parallel_config) -> None: - """Build the per-microbatch TP communicators and install the all-reduce hook - (DBO under pure TP only). Collective: every rank calls it in the same order.""" - global _TP_UBATCH_COMMS - if not parallel_config.dbo_tp_only or _TP_UBATCH_COMMS is not None: - return - from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator - - tp = parallel_state.get_tp_group() - comms = [ - PyNcclCommunicator(group=tp.cpu_group, device=tp.device) - for _ in range(parallel_config.num_ubatches) - ] - if any(c.disabled for c in comms): - logger.warning( - "DBO: the NCCL library is unavailable, the TP all-reduces of a " - "microbatch stay on the compute stream (no overlap)" - ) - return - _TP_UBATCH_COMMS = comms - parallel_state.set_dbo_tp_all_reduce_hook(_dbo_tp_all_reduce) - logger.info( - "DBO: %d per-microbatch TP communicators for the comm-stream all-reduce", - len(comms), - ) - - -def dbo_comm_stream_priority() -> int: - """High on ROCm: at the default priority comm and compute can share one - hardware queue and serialize.""" - from vllm.platforms import current_platform - - return -1 if current_platform.is_rocm() else 0 - - -def dbo_tp_collective(issue) -> bool: - """Run ``issue(comm, stream)`` as a microbatch hand-off on its comm stream; - False outside a microbatch.""" - if len(_THREAD_ID_TO_CONTEXT) == 0 or _TP_UBATCH_COMMS is None: - return False - ctx_idx = _THREAD_ID_TO_CONTEXT.get(threading.get_ident()) - if ctx_idx is None: - return False - ctx = _CURRENT_CONTEXTS[ctx_idx] - ctx.yield_and_switch_from_compute_to_comm() - issue(_TP_UBATCH_COMMS[ctx_idx], ctx.comm_stream) - ctx.switch_to_compute_sync() - return True - - -def _dbo_tp_all_reduce(group, input_: torch.Tensor) -> torch.Tensor | None: - """The TP all-reduce of a microbatch, on the comm stream.""" - if len(_THREAD_ID_TO_CONTEXT) == 0: - return None - ctx_idx = _THREAD_ID_TO_CONTEXT.get(threading.get_ident()) - if ctx_idx is None or group is not parallel_state._TP: - return None - assert _TP_UBATCH_COMMS is not None - ctx = _CURRENT_CONTEXTS[ctx_idx] - logger.info_once("DBO: TP all-reduces of a microbatch go to the comm stream") - # No record_stream: the stream waits already order the buffers, and it would - # pin every block until the GPU catches up (out of memory at a 32k step). - out = torch.empty_like(input_) - ctx.yield_and_switch_from_compute_to_comm() - _TP_UBATCH_COMMS[ctx_idx].all_reduce(input_, out_tensor=out, stream=ctx.comm_stream) - ctx.switch_to_compute_sync() - return out diff --git a/vllm/v1/worker/workspace.py b/vllm/v1/worker/workspace.py index 48ebdc2609d1..a05534281c11 100644 --- a/vllm/v1/worker/workspace.py +++ b/vllm/v1/worker/workspace.py @@ -127,10 +127,7 @@ def _get_workspace_id(self) -> int: f"Workspace lane {lane} is not configured; manager has " f"{self._num_lanes} lane(s)." ) - # One set of workspaces shared by every microbatch (TP-only DBO) or one - # per microbatch. - ubatch = dbo_current_ubatch_id() if self._num_ubatches > 1 else 0 - return ubatch * self._num_lanes + lane + return dbo_current_ubatch_id() * self._num_lanes + lane def get_persistent_resource(self, key: Hashable, factory: Callable[[], T]) -> T: """Return the resource cached for ``key`` in the current ubatch and lane. From a0ea94109745d3e21b1f9557fe8c75ba3c7048b5 Mon Sep 17 00:00:00 2001 From: Seungmin Kim <8457324+ehfd@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:44:59 +0900 Subject: [PATCH 3/7] [Bugfix][MiniMax-M3] Scope prompt reasoning-end checks to the last message (#63492) Signed-off-by: Seungmin Kim <8457324+ehfd@users.noreply.github.com> --- .../test_minimax_m3_reasoning_parser.py | 37 ++++++++++++++++++- vllm/reasoning/minimax_m3_reasoning_parser.py | 15 ++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/tests/reasoning/test_minimax_m3_reasoning_parser.py b/tests/reasoning/test_minimax_m3_reasoning_parser.py index 561e4020cb1f..3769b481f0b5 100644 --- a/tests/reasoning/test_minimax_m3_reasoning_parser.py +++ b/tests/reasoning/test_minimax_m3_reasoning_parser.py @@ -16,7 +16,7 @@ class MiniMaxM3Tokenizer: """Small tokenizer with MiniMax M3 reasoning tags as special tokens.""" - special_tokens = ("", "") + special_tokens = ("", "", "]~b]") def __init__(self): self._token_to_id: dict[str, int] = {} @@ -459,3 +459,38 @@ def test_token_id_helpers_enabled_mode(): assert parser.count_reasoning_tokens(open_reasoning_ids) == len( tokenizer.encode("abc") ) + + +# Rendered like the MiniMax-M3.1 chat template: the system message spells out +# both markers, and a prior assistant turn without reasoning is prefixed with +# the closer. +PROMPT = ( + "]~b]system\nWrap your reasoning in tags, or begin " + "directly after the prefix.[e~[\n" + "]~b]user\nCapital of France?[e~[\n" + "]~b]ai\nParis.[e~[\n" + "]~b]user\nAnd Germany?[e~[\n" + "]~b]ai\n" +) + + +def test_prompt_markers_do_not_end_reasoning(): + parser, tokenizer = make_parser() + prompt_ids = tokenizer.encode(PROMPT) + + assert not parser.is_reasoning_end(prompt_ids) + assert not parser.is_reasoning_end(tokenizer.encode(PROMPT + "ab")) + assert parser.is_reasoning_end(tokenizer.encode(PROMPT + "a")) + assert parser.is_reasoning_end(tokenizer.encode(PROMPT + "Berlin")) + + +def test_streaming_end_check_ignores_prompt_markers(): + parser, tokenizer = make_parser() + prompt_ids = tokenizer.encode(PROMPT) + open_ids = tokenizer.encode("ab") + closed_ids = tokenizer.encode("") + + assert not parser.is_reasoning_end_streaming(prompt_ids + open_ids, open_ids[-1:]) + assert parser.is_reasoning_end_streaming( + prompt_ids + open_ids + closed_ids, closed_ids + ) diff --git a/vllm/reasoning/minimax_m3_reasoning_parser.py b/vllm/reasoning/minimax_m3_reasoning_parser.py index d49f9311f460..b6a8e48e49ef 100644 --- a/vllm/reasoning/minimax_m3_reasoning_parser.py +++ b/vllm/reasoning/minimax_m3_reasoning_parser.py @@ -39,6 +39,9 @@ def __init__(self, tokenizer, *args, **kwargs): super().__init__(tokenizer, *args, **kwargs) self._start_token_ids = self._encode_marker(self.start_token) self._end_token_ids = self._encode_marker(self.end_token) + # The chat template opens every message, including the generation + # prompt, with this token. + self._message_begin_token_id = self.vocab.get("]~b]") chat_kwargs = kwargs.get("chat_template_kwargs", {}) or {} self._initial_in_reasoning = chat_kwargs.get("thinking_mode") == "enabled" self._reasoning_ended_streaming = False @@ -117,6 +120,16 @@ def _ends_with_token_sequence_prefix( return True return False + def _last_message_ids(self, input_ids: Sequence[int]) -> Sequence[int]: + # The system message's thinking instructions and earlier turns contain + # reasoning markers; only the last message (the generation prompt) + # tells whether generation starts inside reasoning. Output-only ids + # contain no message-begin token and are returned whole. + for i in range(len(input_ids) - 1, -1, -1): + if input_ids[i] == self._message_begin_token_id: + return input_ids[i + 1 :] + return input_ids + @staticmethod def _strip_partial_marker_suffix(text: str, marker: str) -> str: max_len = min(len(text), len(marker) - 1) @@ -204,6 +217,7 @@ def is_reasoning_end_streaming( return False delta_ids = tuple(delta_ids) + input_ids = self._last_message_ids(input_ids) if self._contains_token_sequence(delta_ids, self._end_token_ids): return True if self._contains_token_sequence(input_ids, self._end_token_ids): @@ -311,6 +325,7 @@ def count_reasoning_tokens(self, token_ids: Sequence[int]) -> int: return count def is_reasoning_end(self, input_ids: Sequence[int]) -> bool: + input_ids = self._last_message_ids(input_ids) start_index = self._rfind_token_sequence(input_ids, self._start_token_ids) end_index = self._rfind_token_sequence(input_ids, self._end_token_ids) if end_index < 0: From 65fb7703b89784c53a93c88623207ec5a4336b66 Mon Sep 17 00:00:00 2001 From: "Limpus, David" Date: Wed, 28 Oct 2026 11:44:51 -0500 Subject: [PATCH 4/7] [KV cache] Add an mxfp4 kv_cache_dtype Per-head MXFP4 KV: E2M1 data plus one E8M0 scale per 32 elements, stored as uint8 (head_size/2 + head_size/32 bytes per head row, 68 for 128), with its own KVQuantMode.MXFP4. Backends opt in through supported_kv_cache_dtypes. Signed-off-by: Limpus, David --- tests/config/test_kv_cache_dtype.py | 14 ++++++++++++++ vllm/config/cache.py | 1 + vllm/utils/torch_utils.py | 10 ++++++++++ vllm/v1/kv_cache_interface.py | 8 ++++++++ 4 files changed, 33 insertions(+) diff --git a/tests/config/test_kv_cache_dtype.py b/tests/config/test_kv_cache_dtype.py index e6b9426fb9cb..c21b5f5877fd 100644 --- a/tests/config/test_kv_cache_dtype.py +++ b/tests/config/test_kv_cache_dtype.py @@ -119,6 +119,20 @@ def test_backend_sentinel_properties(): assert mode.is_nvfp4 is False +def test_mxfp4_kv_cache_dtype(): + """The per-head MXFP4 KV cache: its own quant mode, uint8 pages, 68 B rows.""" + from vllm.utils.torch_utils import mxfp4_kv_cache_full_dim + + assert is_known_kv_cache_dtype("mxfp4") + assert CacheConfig(cache_dtype="mxfp4").cache_dtype == "mxfp4" + assert STR_DTYPE_TO_TORCH_DTYPE["mxfp4"] == torch.uint8 + mode = get_kv_quant_mode("mxfp4") + assert mode == KVQuantMode.MXFP4 and mode.is_mxfp4 + assert not mode.is_nvfp4 + assert is_quantized_kv_cache("mxfp4") + assert mxfp4_kv_cache_full_dim(128) == 64 + 4 + + def test_no_snapshot_of_shared_dtype_registry(): """The registration-time-mutable registries must never be snapshotted. diff --git a/vllm/config/cache.py b/vllm/config/cache.py index 626825dba8c7..557a4285a937 100644 --- a/vllm/config/cache.py +++ b/vllm/config/cache.py @@ -64,6 +64,7 @@ def _layout_from_name(layout_name: str) -> KVCacheLayout: "fp8_per_token_head", "nvfp4", "nvfp4_4over6", + "mxfp4", ] # Mutable mirror of the CacheDType Literal. Custom dtypes registered by diff --git a/vllm/utils/torch_utils.py b/vllm/utils/torch_utils.py index d808f36b0676..d89b86fe9805 100644 --- a/vllm/utils/torch_utils.py +++ b/vllm/utils/torch_utils.py @@ -64,6 +64,7 @@ "ultraquant_4bit": torch.uint8, "nvfp4": torch.uint8, "nvfp4_4over6": torch.uint8, + "mxfp4": torch.uint8, } TORCH_DTYPE_TO_NUMPY_DTYPE = { @@ -550,6 +551,15 @@ def nvfp4_kv_cache_full_dim(head_size: int) -> int: return head_size // 2 + head_size // 16 +def mxfp4_kv_cache_full_dim(head_size: int) -> int: + """Packed last dim for MXFP4 KV cache: fp4 data + one E8M0 scale per block.""" + from vllm.model_executor.layers.quantization.utils.ocp_mx_utils import ( + OCP_MX_BLOCK_SIZE, + ) + + return head_size // 2 + head_size // OCP_MX_BLOCK_SIZE + + def nvfp4_split_data_scale( kv_side: torch.Tensor, ) -> tuple[torch.Tensor, torch.Tensor]: diff --git a/vllm/v1/kv_cache_interface.py b/vllm/v1/kv_cache_interface.py index a943594addc2..c1d09fe82135 100644 --- a/vllm/v1/kv_cache_interface.py +++ b/vllm/v1/kv_cache_interface.py @@ -61,6 +61,7 @@ class KVQuantMode(IntEnum): OCTAVE_K3V4 = 12 OCTAVE_K3V3 = 13 OCTAVE_K3V3_COMPACT = 14 + MXFP4 = 15 # packed E2M1 data + E8M0 scales per 32 elements # Backend self-manages kernel dispatch. Reads as quantized but matches no # generic kernel mode (is_per_token_head / is_nvfp4 / is_turboquant all @@ -82,6 +83,11 @@ def is_nvfp4(self) -> bool: """True for NVFP4 packed quantization mode.""" return self == KVQuantMode.NVFP4 + @property + def is_mxfp4(self) -> bool: + """True for MXFP4 packed quantization mode.""" + return self == KVQuantMode.MXFP4 + @property def is_octave(self) -> bool: """True for any Octave quantization mode.""" @@ -138,6 +144,8 @@ def get_kv_quant_mode(kv_cache_dtype: str) -> KVQuantMode: return KVQuantMode.NVFP4_DS_MLA if kv_cache_dtype.startswith("nvfp4"): return KVQuantMode.NVFP4 + if kv_cache_dtype == "mxfp4": + return KVQuantMode.MXFP4 if isinstance(kv_cache_dtype, str) and kv_cache_dtype.startswith("turboquant_"): return KVQuantMode[kv_cache_dtype.upper()] if isinstance(kv_cache_dtype, str) and kv_cache_dtype.startswith("octave_"): From 425d35ac5cf251d92c10f606b8c5002217574b45 Mon Sep 17 00:00:00 2001 From: "Limpus, David" Date: Wed, 28 Oct 2026 15:13:44 -0500 Subject: [PATCH 5/7] [ROCm][MiniMax-M3] MXFP4 mode for the fused norm / RoPE / KV insert Writes K, V and index-K as MXFP4 pages (E2M1 data, E8M0 scale per 32 dims, no global scale; 68 B per token and head) from the same FlyDSL launch as the NVFP4 insert. The data layout is NVFP4's; K and index-K scales are [token][4], V scales [group][token]. The scale is 2^ceil(log2(amax / 6)), 2^0 for an all-zero group. The bit-exact test runs both formats against a torch reference. Signed-off-by: Limpus, David --- .../kernels/attention/minimax_m3_nvfp4_ref.py | 76 +++++++++++++------ .../test_minimax_m3_norm_rope_nvfp4_insert.py | 40 ++++++---- .../amd/ops/norm_rope_nvfp4_insert/host.py | 30 ++++---- .../amd/ops/norm_rope_nvfp4_insert/kernel.py | 71 ++++++++++++----- 4 files changed, 148 insertions(+), 69 deletions(-) diff --git a/tests/kernels/attention/minimax_m3_nvfp4_ref.py b/tests/kernels/attention/minimax_m3_nvfp4_ref.py index 05f264eeb882..41017b38bbdc 100644 --- a/tests/kernels/attention/minimax_m3_nvfp4_ref.py +++ b/tests/kernels/attention/minimax_m3_nvfp4_ref.py @@ -8,6 +8,9 @@ order, V data ``[token octet][dim octet][8 dims][4 B]`` (a byte holds two consecutive tokens of one dim), V scales ``[group][token]``. An index page is ``[128 x 64 B data][128 x 8 B scales]``. + +MXFP4 pages (``mxfp4=True``) keep the data layout with E8M0 scales per 32 dims +(512 B per head): K and index-K scales ``[token][4]``, V scales ``[group][token]``. """ import torch @@ -31,16 +34,32 @@ def quantize_nvfp4(x: torch.Tensor, global_scale: float): scale_e4m3 = scale.to(torch.float8_e4m3fn) scale_value = scale_e4m3.float() quant = torch.where(scale_value != 0, 1.0 / (scale_value * gs), 0.0) - y = groups * quant[..., None] - grid = torch.tensor(E2M1_GRID, device=x.device) + codes = _e2m1_codes(groups * quant[..., None]) + return codes.view(-1, D), scale_e4m3.view(torch.uint8).view(-1, 8) + + +def quantize_mxfp4(x: torch.Tensor): + """E2M1 codes ``[T, 128]`` and E8M0 scale bytes ``[T, 4]`` of fp32 rows: the + scale is 2^ceil(log2(amax / 6)), clamped to 2^-126, and 2^0 for zeros.""" + groups = x.view(-1, 4, 32) + s = groups.abs().amax(-1) / 6.0 + mant, exp = torch.frexp(s) + exp = torch.where(mant == 0.5, exp - 1, exp).clamp(min=-126) + exp = torch.where(s == 0, 0, exp) + codes = _e2m1_codes(groups / torch.exp2(exp.float())[..., None]) + return codes.view(-1, D), (exp + 127).to(torch.uint8) + + +def _e2m1_codes(y: torch.Tensor) -> torch.Tensor: + """Nearest E2M1 code of each value, ties to the even code.""" + grid = torch.tensor(E2M1_GRID, device=y.device) dist = (y.abs()[..., None] - grid).abs() is_min = dist == dist.amin(-1, keepdim=True) - ids = torch.arange(8, device=x.device) + ids = torch.arange(8, device=y.device) # Neighbouring codes alternate parity, so every tie has an even candidate. even_min = torch.where(is_min & (ids % 2 == 0), ids, 8).amin(-1) mag = torch.where(even_min < 8, even_min, dist.argmin(-1)) - codes = mag | (torch.signbit(y).long() << 3) - return codes.view(-1, D), scale_e4m3.view(torch.uint8).view(-1, 8) + return mag | (torch.signbit(y).long() << 3) def dequant(data: torch.Tensor, scales: torch.Tensor) -> torch.Tensor: @@ -52,21 +71,24 @@ def dequant(data: torch.Tensor, scales: torch.Tensor) -> torch.Tensor: return (mag.unflatten(-1, (8, 16)) * s[..., None]).flatten(-2) -def head_offsets(side: int, device): +def head_offsets(side: int, device, mxfp4: bool = False): """Byte offsets inside one head's regions of side 0 (K) or 1 (V). Returns the data byte and nibble shift of each (token, dim) ``[128, 128]`` - and the scale byte of each (token, group) ``[128, 8]``. + and the scale byte of each (token, group) ``[128, 8 (MXFP4: 4)]``. """ + ng = 4 if mxfp4 else 8 t = torch.arange(BLOCK, device=device)[:, None] d = torch.arange(D, device=device)[None, :] - g = torch.arange(8, device=device)[None, :] + g = torch.arange(ng, device=device)[None, :] if side == 0: r = t % 32 n = 4 * (r // 8) + r % 4 data = t * 64 + d // 2 shift = (d % 2) * 4 + 0 * t scale = ((((t // 32) * 4 + g // 2) * 16 + n) * 2 + (r % 8) // 4) * 2 + g % 2 + if mxfp4: + scale = t * ng + g else: data = ((t // 8 * 16 + d // 8) * 8 + d % 8) * 4 + (t % 8) // 2 shift = (t % 2) * 4 + 0 * d @@ -74,11 +96,12 @@ def head_offsets(side: int, device): return data, shift, scale -def _region_bases(side: int, heads: int, device): +def _region_bases(side: int, heads: int, device, mxfp4: bool = False): """``[H, 1, 1]`` page offsets of each head's data and scale regions.""" + ng = 4 if mxfp4 else 8 h = torch.arange(heads, device=device)[:, None, None] - side0 = side * heads * BLOCK * 72 - return side0 + h * BLOCK * 64, side0 + heads * BLOCK * 64 + h * BLOCK * 8 + side0 = side * heads * BLOCK * (64 + ng) + return side0 + h * BLOCK * 64, side0 + heads * BLOCK * 64 + h * BLOCK * ng def _flat(cache: torch.Tensor) -> torch.Tensor: @@ -87,16 +110,20 @@ def _flat(cache: torch.Tensor) -> torch.Tensor: return cache.as_strided((n,), (1,)) -def _insert_side(cache, rows, slots, side, global_scale): +def _quantize(x, global_scale, mxfp4): + return quantize_mxfp4(x) if mxfp4 else quantize_nvfp4(x, global_scale) + + +def _insert_side(cache, rows, slots, side, global_scale, mxfp4=False): tokens, heads, _ = rows.shape - codes, scales = quantize_nvfp4(rows.reshape(-1, D).float(), global_scale) + codes, scales = _quantize(rows.reshape(-1, D).float(), global_scale, mxfp4) slots = slots.long() keep = slots >= 0 codes = codes.view(tokens, heads, D)[keep].to(torch.uint8) - scales = scales.view(tokens, heads, 8)[keep] + scales = scales.view(tokens, heads, -1)[keep] blk, pos = slots[keep] // BLOCK, slots[keep] % BLOCK - data_off, shift, scale_off = head_offsets(side, rows.device) - data_base, scale_base = _region_bases(side, heads, rows.device) + data_off, shift, scale_off = head_offsets(side, rows.device, mxfp4) + data_base, scale_base = _region_bases(side, heads, rows.device, mxfp4) page = (blk * cache.stride(0))[:, None, None] byte = page + data_base[:, 0] + data_off[pos][:, None] # [n, H, 128] sh = shift[pos][:, None].expand_as(byte) @@ -107,15 +134,16 @@ def _insert_side(cache, rows, slots, side, global_scale): flat[page + scale_base[:, 0] + scale_off[pos][:, None]] = scales -def insert_nvfp4_kv(k, v, kv_cache, slots, k_scale, v_scale): +def insert_nvfp4_kv(k, v, kv_cache, slots, k_scale, v_scale, mxfp4=False): """Quantize K / V ``[T, Hkv, 128]`` into their pages; slots < 0 skip.""" - _insert_side(kv_cache, k, slots, 0, float(k_scale)) - _insert_side(kv_cache, v, slots, 1, float(v_scale)) + _insert_side(kv_cache, k, slots, 0, float(k_scale), mxfp4) + _insert_side(kv_cache, v, slots, 1, float(v_scale), mxfp4) -def insert_nvfp4_index(index_cache, keys, slots): +def insert_nvfp4_index(index_cache, keys, slots, mxfp4=False): """Quantize index keys ``[T, 128]`` into their pages (no global scale).""" - codes, scales = quantize_nvfp4(keys.float(), 1.0) + codes, scales = _quantize(keys.float(), 1.0, mxfp4) + ng = scales.shape[1] slots = slots.long() keep = slots >= 0 codes, scales = codes[keep].to(torch.uint8), scales[keep] @@ -125,9 +153,9 @@ def insert_nvfp4_index(index_cache, keys, slots): flat[base + pos[:, None] * 64 + torch.arange(64, device=keys.device)] = codes[ :, 0::2 ] | (codes[:, 1::2] << 4) - flat[base + BLOCK * 64 + pos[:, None] * 8 + torch.arange(8, device=keys.device)] = ( - scales - ) + flat[ + base + BLOCK * 64 + pos[:, None] * ng + torch.arange(ng, device=keys.device) + ] = scales def nvfp4_kv_cache_token_major(kv_cache: torch.Tensor): diff --git a/tests/kernels/attention/test_minimax_m3_norm_rope_nvfp4_insert.py b/tests/kernels/attention/test_minimax_m3_norm_rope_nvfp4_insert.py index 2d7572de52e3..8a6e4e6d3e9e 100644 --- a/tests/kernels/attention/test_minimax_m3_norm_rope_nvfp4_insert.py +++ b/tests/kernels/attention/test_minimax_m3_norm_rope_nvfp4_insert.py @@ -46,9 +46,11 @@ def _request_slots(starts, lens, num_pages, gen): class _Batch: - def __init__(self, starts, lens, pad, heads, scales, seed=0): + def __init__(self, starts, lens, pad, heads, scales, seed=0, mxfp4=False): g = torch.Generator().manual_seed(seed) self.nq, self.nkv, self.niq = heads + self.mxfp4 = mxfp4 + W = self.W = 68 if mxfp4 else 72 n = self.n = sum(lens) + pad row = (self.nq + 2 * self.nkv + self.niq + 1) * D # magnitudes 1e-3 .. 3e3 per 16-value group, some all-zero groups @@ -72,19 +74,20 @@ def __init__(self, starts, lens, pad, heads, scales, seed=0): [_request_slots(starts, lens, pages, g), pad_slots] ).cuda() # stale bytes; the layer views have a block stride past one page - main = 2 * self.nkv * BLK * 72 + main = 2 * self.nkv * BLK * W self.kv_full = torch.randint(0, 256, (pages, main + 256), generator=g) self.kv_full = self.kv_full.to(torch.uint8).cuda() - self.idx_full = torch.randint(0, 256, (pages, BLK * 72 + 64), generator=g) + self.idx_full = torch.randint(0, 256, (pages, BLK * W + 64), generator=g) self.idx_full = self.idx_full.to(torch.uint8).cuda() self.ks = torch.tensor(scales[0], dtype=torch.float32, device="cuda") self.vs = torch.tensor(scales[1], dtype=torch.float32, device="cuda") def kv(self, full): - return full[:, : 2 * self.nkv * BLK * 72].view(-1, 2 * self.nkv, BLK, 72) + W = self.W + return full[:, : 2 * self.nkv * BLK * W].view(-1, 2 * self.nkv, BLK, W) def idx(self, full): - return full[:, : BLK * 72].view(-1, BLK, 72) + return full[:, : BLK * self.W].view(-1, BLK, self.W) def reference(self): qkv = self.qkv.clone() @@ -104,8 +107,11 @@ def reference(self): self.slots, self.ks, self.vs, + self.mxfp4, + ) + insert_nvfp4_index( + self.idx(idx_full), qkv[:, ik0 : ik0 + D], self.islots, self.mxfp4 ) - insert_nvfp4_index(self.idx(idx_full), qkv[:, ik0 : ik0 + D], self.islots) return q, iq, kv_full, idx_full def run(self, qkv, pos, slots, islots, kv_full, idx_full, q, iq): @@ -113,6 +119,7 @@ def run(self, qkv, pos, slots, islots, kv_full, idx_full, q, iq): qkv, *self.w, self.cs, pos, slots, islots, self.kv(kv_full), self.idx(idx_full), self.ks, self.vs, q, iq, num_heads=self.nq, num_kv_heads=self.nkv, num_index_heads=self.niq, eps=EPS, + mxfp4=self.mxfp4, ) # fmt: skip def fused(self, iq): @@ -160,9 +167,12 @@ def _check(batch, iq_mode="contiguous"): ([0, 100], [4096, 4000], 3), # the prefill tier ], ) -@pytest.mark.parametrize("scales", [(1.0, 1.0), (0.002, 3.0)]) -def test_matches_two_kernel_path(heads, starts, lens, pad, scales): - _check(_Batch(starts, lens, pad, heads, scales)) +@pytest.mark.parametrize( + ("scales", "mxfp4"), + [((1.0, 1.0), False), ((0.002, 3.0), False), ((1.0, 1.0), True)], +) +def test_matches_two_kernel_path(heads, starts, lens, pad, scales, mxfp4): + _check(_Batch(starts, lens, pad, heads, scales, mxfp4=mxfp4)) @pytest.mark.parametrize("iq_mode", ["rank", "cols"]) @@ -175,19 +185,21 @@ def test_64k_tokens(): _check(_Batch([0, 777], [32768, 32768], 0, TP4, (1.0, 1.0))) -def test_all_padding(): +@pytest.mark.parametrize("mxfp4", [False, True]) +def test_all_padding(mxfp4): """A graph-capture dummy batch: every slot -1, the pages stay as they were.""" - batch = _Batch([], [], 64, TP4, (1.0, 1.0)) + batch = _Batch([], [], 64, TP4, (1.0, 1.0), mxfp4=mxfp4) _check(batch) iq = torch.empty(batch.n, D, dtype=torch.float8_e4m3fn, device="cuda") _, kv, idx = batch.fused(iq) assert torch.equal(kv, batch.kv_full) and torch.equal(idx, batch.idx_full) -def test_cuda_graph_replay(): +@pytest.mark.parametrize("mxfp4", [False, True]) +def test_cuda_graph_replay(mxfp4): """Captured once, replayed on new qkv / positions / slots in place.""" - a = _Batch(*DSPARK, 4, TP4, (1.0, 1.0), seed=1) - b = _Batch(*DSPARK, 4, TP4, (1.0, 1.0), seed=2) + a = _Batch(*DSPARK, 4, TP4, (1.0, 1.0), seed=1, mxfp4=mxfp4) + b = _Batch(*DSPARK, 4, TP4, (1.0, 1.0), seed=2, mxfp4=mxfp4) b.w, b.cs = a.w, a.cs # captured with the layer's weights and RoPE cache qkv, pos = a.qkv.clone(), a.pos.clone() slots, islots = a.slots.clone(), a.islots.clone() diff --git a/vllm/models/minimax_m3/amd/ops/norm_rope_nvfp4_insert/host.py b/vllm/models/minimax_m3/amd/ops/norm_rope_nvfp4_insert/host.py index d6590ee458a4..7c6af396138b 100644 --- a/vllm/models/minimax_m3/amd/ops/norm_rope_nvfp4_insert/host.py +++ b/vllm/models/minimax_m3/amd/ops/norm_rope_nvfp4_insert/host.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""Launch wrapper of the fused norm / RoPE / NVFP4 insert.""" +"""Launch wrapper of the fused norm / RoPE / NVFP4 or MXFP4 insert.""" import functools import struct @@ -10,13 +10,14 @@ from vllm.models.minimax_m3.amd.ops.flydsl_utils import ( run_compiled, ) +from vllm.utils.torch_utils import mxfp4_kv_cache_full_dim, nvfp4_kv_cache_full_dim from . import kernel as _kernel @functools.cache -def _get_kernel(nq: int, nkv: int, niq: int, rotary_dim: int, tp: int): - return _kernel.compile_norm_rope_insert(nq, nkv, niq, rotary_dim, tp) +def _get_kernel(nq: int, nkv: int, niq: int, rotary_dim: int, tp: int, mx: bool): + return _kernel.compile_norm_rope_insert(nq, nkv, niq, rotary_dim, tp, mx) def _token_pairs_per_wave(n: int) -> int: @@ -33,9 +34,9 @@ def minimax_m3_norm_rope_nvfp4_insert( positions: torch.Tensor, # [n] int64 slot_mapping: torch.Tensor, # [n] int64, -1 skips the token index_slot_mapping: torch.Tensor, # [n] int64, -1 skips the token - kv_cache: torch.Tensor, # [blocks, 2 nkv, 128, 72] uint8 - index_cache: torch.Tensor, # [blocks, 128, 72] uint8 - k_scale: torch.Tensor, # fp32 global scales + kv_cache: torch.Tensor, # [blocks, 2 nkv, 128, 72 (MXFP4: 68)] uint8 + index_cache: torch.Tensor, # [blocks, 128, 72 (MXFP4: 68)] uint8 + k_scale: torch.Tensor, # fp32 global scales, unused for MXFP4 v_scale: torch.Tensor, q_out: torch.Tensor, # [n, nq * 128] bf16 index_q_out: torch.Tensor, # [n, niq * 128] e4m3, row stride free @@ -43,13 +44,16 @@ def minimax_m3_norm_rope_nvfp4_insert( num_kv_heads: int, num_index_heads: int, eps: float, + mxfp4: bool = False, ) -> None: - """Norm + RoPE of q / k / index-q / index-k and the NVFP4 K/V and index-K - inserts in one launch; k and index-k are not written back into ``qkv``.""" + """Norm + RoPE of q / k / index-q / index-k and the NVFP4 (``mxfp4``: MXFP4) + K/V and index-K inserts in one launch; k and index-k are not written back + into ``qkv``.""" n = qkv.shape[0] if n == 0: return nq, nkv, niq = num_heads, num_kv_heads, num_index_heads + slot_w = (mxfp4_kv_cache_full_dim if mxfp4 else nvfp4_kv_cache_full_dim)(_kernel.D) rotary_dim = cos_sin_cache.shape[1] assert eps >= 2.0**-126 # the kernel's rsqrt skips ocml's denormal scaling assert qkv.dtype == torch.bfloat16 and qkv.is_contiguous() @@ -60,12 +64,12 @@ def minimax_m3_norm_rope_nvfp4_insert( assert q_out.dtype == torch.bfloat16 and q_out.is_contiguous() assert index_q_out.dtype == torch.float8_e4m3fn and index_q_out.stride(1) == 1 assert index_q_out.stride(0) % 4 == 0 - assert kv_cache.shape[1:] == (2 * nkv, _kernel.BLK, 72) - assert kv_cache.stride(1) == _kernel.BLK * 72 and kv_cache.stride(3) == 1 - assert index_cache.shape[1:] == (_kernel.BLK, 72) and index_cache.stride(2) == 1 - assert index_cache.stride(1) == 72 + assert kv_cache.shape[1:] == (2 * nkv, _kernel.BLK, slot_w) + assert kv_cache.stride(1) == _kernel.BLK * slot_w and kv_cache.stride(3) == 1 + assert index_cache.shape[1:] == (_kernel.BLK, slot_w) and index_cache.stride(2) == 1 + assert index_cache.stride(1) == slot_w run_compiled( - _get_kernel(nq, nkv, niq, rotary_dim, _token_pairs_per_wave(n)), + _get_kernel(nq, nkv, niq, rotary_dim, _token_pairs_per_wave(n), mxfp4), qkv.data_ptr(), q_out.data_ptr(), index_q_out.data_ptr(), diff --git a/vllm/models/minimax_m3/amd/ops/norm_rope_nvfp4_insert/kernel.py b/vllm/models/minimax_m3/amd/ops/norm_rope_nvfp4_insert/kernel.py index e728cc983d3b..7a0fb32baf27 100644 --- a/vllm/models/minimax_m3/amd/ops/norm_rope_nvfp4_insert/kernel.py +++ b/vllm/models/minimax_m3/amd/ops/norm_rope_nvfp4_insert/kernel.py @@ -1,11 +1,15 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""Gemma norm + RoPE of q / k / index-q / index-k and the NVFP4 K/V + index-K -page inserts in one launch (FlyDSL, gfx950), bit for bit the ROCm -``fused_minimax_m3_qknorm_rope_kv_insert`` followed by the NVFP4 page insert. +"""Gemma norm + RoPE of q / k / index-q / index-k and the NVFP4 or MXFP4 K/V + +index-K page inserts in one launch (FlyDSL, gfx950), bit for bit the ROCm +``fused_minimax_m3_qknorm_rope_kv_insert`` followed by the page insert. Waves of 2 * tp tokens: [q heads | k heads | index-k | index-q heads | v heads x tp]; a norm wave holds 4 dims of a token per lane (the HIP kernel's lane map). + +MXFP4 pages keep NVFP4's data layout with E8M0 scales per 32 dims and no global +scale (68 B per token and head): K and index-K scales ``[token][4]``, V scales +``[group][token]``. """ import flydsl.compiler as flyc @@ -182,12 +186,29 @@ def _quant4(xs, gs, inv_gs): return _e2m1x2(y[2], y[3], _e2m1x2(y[0], y[1], fx.Int32(0), 0), 1), byte -def _v_row(state, row, r, n_run, p0, vs, inv_vs): +def _quant4_mx(xs): + """E2M1 codes of this lane's 4 values (16 bits) and the E8M0 scale byte of + their 32-value group (lanes l ^ 0..7): 2^ceil(log2(amax / 6)), 2^0 for an + all-zero group.""" + a = [fx.math.absf(x) for x in xs] + m = _maxnum(_maxnum(a[0], a[1]), _maxnum(a[2], a[3])) + m = _xmax(_xmax(_xmax(m, 1), 2), 4) + qb = bits(m / fx.Float32(6.0)) + inexact = (qb & 0x7FFFFF) != 0 + e = ((qb >> 23) & 0xFF) - 127 + inexact.select(fx.Int32(1), fx.Int32(0)) + # amax / 6 < 2^126, so only the low end clamps (denormal quotients). + e = (m == 0.0).select(fx.Int32(0), (e < -126).select(fx.Int32(-126), e)) + inv = as_f32((fx.Int32(127) - e) << 23) + y = [x * inv for x in xs] + return _e2m1x2(y[2], y[3], _e2m1x2(y[0], y[1], fx.Int32(0), 0), 1), e + 127 + + +def _v_row(state, row, r, n_run, p0, quant): """Adds row ``r`` of a V run at octet positions p0.. to ``state``: new nibbles and scale bytes, with their masks.""" words, written = state[0:4], state[4] sc, sc_mask = state[5:7], state[7:9] - nib, sf = _quant4(_bf16x4(row), vs, inv_vs) + nib, sf = quant(_bf16x4(row)) in_run = n_run > r p = p0 + r sh = p * 4 @@ -218,16 +239,25 @@ def _k_scale_off(tok, grp): return ((((tok // 32) * 4 + grp // 2) * 16 + n) * 2 + (r % 8) // 4) * 2 + grp % 2 -def compile_norm_rope_insert(nq: int, nkv: int, niq: int, rotary_dim: int, tp: int): - """Build the kernel; ``tp`` token pairs per norm / RoPE wave, one per V wave.""" +def compile_norm_rope_insert( + nq: int, nkv: int, niq: int, rotary_dim: int, tp: int, mx: bool = False +): + """Build the kernel; ``tp`` token pairs per norm / RoPE wave, one per V wave; + ``mx`` writes MXFP4 pages instead of NVFP4.""" assert rotary_dim in (8, 16, 32, 64, 128) NR = nq + nkv + 1 + niq # norm + RoPE waves S = NR + nkv * tp # waves per 2 * tp tokens ROW = (nq + 2 * nkv + niq + 1) * D HALF = rotary_dim // 2 - SIDE = nkv * BLK * 72 # bytes of one side of a main page + NG = 4 if mx else 8 # scale groups per token and head + GL = D // NG // 4 # lanes per scale group + SIDE = nkv * BLK * (64 + NG) # bytes of one side of a main page TPW = 2 * tp - name = f"m3_norm_rope_nvfp4_insert_q{nq}_kv{nkv}_iq{niq}_r{rotary_dim}_t{tp}" + fmt = "mxfp4" if mx else "nvfp4" + name = f"m3_norm_rope_{fmt}_insert_q{nq}_kv{nkv}_iq{niq}_r{rotary_dim}_t{tp}" + + def quant(xs, gs, inv_gs): + return _quant4_mx(xs) if mx else _quant4(xs, gs, inv_gs) @flyc.kernel(name=name, known_block_size=[64 * NW, 1, 1]) def kernel( @@ -419,10 +449,10 @@ def kernel( ) inv_gs = fx.Float32(1.0) / gs quants = [ - _quant4(_bf16x4(qvs[t]), gs, inv_gs) for t in range_constexpr(tp) + quant(_bf16x4(qvs[t]), gs, inv_gs) for t in range_constexpr(tp) ] h = s - nq - grp = hl // 4 + grp = hl // GL for t in range_constexpr(tp): slot = slots[t] tp_ = slot & (BLK - 1) @@ -431,9 +461,10 @@ def kernel( arg_idx + fx.Int64(slot >> 7) * i64_idx_st, ) d_off = is_k.select(h * (BLK * 64), fx.Int32(0)) + tp_ * 64 + hl * 2 + k_sf = tp_ * NG + grp if mx else _k_scale_off(tp_, grp) s_off = is_k.select( - nkv * BLK * 64 + h * (BLK * 8) + _k_scale_off(tp_, grp), - BLK * 64 + tp_ * 8 + grp, + nkv * BLK * 64 + h * (BLK * NG) + k_sf, + BLK * 64 + tp_ * NG + grp, ) d_ptr = _gptr(page + fx.Int64(d_off), T.i16, 2) s_ptr = _gptr(page + fx.Int64(s_off), T.i8, 1) @@ -441,7 +472,7 @@ def kernel( sf8 = quants[t][1].to(fx.Int8) if lives[t] & (slot >= 0): d_ptr[0] = packed - if hl % 4 == 0: + if hl % GL == 0: s_ptr[0] = sf8 else: vh = (s - NR) // tp @@ -497,11 +528,15 @@ def kernel( tp_ = slot & (BLK - 1) v_side = arg_kv + fx.Int64(slot >> 7) * i64_kv_st + SIDE v_data = v_side + fx.Int64(vh * (BLK * 64) + (tp_ // 8) * (D * 4)) - v_sf = v_side + fx.Int64(nkv * BLK * 64 + vh * (BLK * 8) + tp_ - tp_ % 8) + v_sf = v_side + fx.Int64(nkv * BLK * 64 + vh * (BLK * NG) + tp_ - tp_ % 8) dp = _gptr(v_data + fx.Int64(dim0 * 4), T.i32, 4) - sp = _gptr(v_sf + fx.Int64((hl // 4) * BLK), T.i32, 4) + sp = _gptr(v_sf + fx.Int64((hl // GL) * BLK), T.i32, 4) go = live & (slot >= 0) & run_first inv_vs = fx.Float32(1.0) / vs + + def v_quant(xs): + return quant(xs, vs, inv_vs) + # Runs of <= 4 tokens (decode) take the short tile. for run_rows, take in ( (rows[:4], go & (n_run <= 4)), @@ -512,13 +547,13 @@ def kernel( old_sc = [fx.Int32(sp[i]) for i in range_constexpr(2)] st = [fx.Int32(0)] * 9 for r in range_constexpr(len(run_rows)): - st = _v_row(st, run_rows[r], r, n_run, tp_ % 8, vs, inv_vs) + st = _v_row(st, run_rows[r], r, n_run, tp_ % 8, v_quant) keep = ~st[4] for i in range_constexpr(4): dp[i] = st[i] | (old[i] & keep) sc0 = st[5] | (old_sc[0] & ~st[7]) sc1 = st[6] | (old_sc[1] & ~st[8]) - if hl % 4 == 0: + if hl % GL == 0: sp[0] = sc0 sp[1] = sc1 From 90bf3fc5ff350786f24510d918851bb32b9ebc10 Mon Sep 17 00:00:00 2001 From: "Limpus, David" Date: Wed, 28 Oct 2026 17:05:30 -0500 Subject: [PATCH 6/7] [KV cache] Move KVQuantMode.MXFP4 to 17 15 is MXFP4_DS_MLA in #64120 and 16 is MXFP4 in #64198. Signed-off-by: Limpus, David (cherry picked from commit b3a9d3eac22b79f205c26d8bd3785ae221ffe127) --- vllm/v1/kv_cache_interface.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vllm/v1/kv_cache_interface.py b/vllm/v1/kv_cache_interface.py index c1d09fe82135..e44e06e584e9 100644 --- a/vllm/v1/kv_cache_interface.py +++ b/vllm/v1/kv_cache_interface.py @@ -61,7 +61,7 @@ class KVQuantMode(IntEnum): OCTAVE_K3V4 = 12 OCTAVE_K3V3 = 13 OCTAVE_K3V3_COMPACT = 14 - MXFP4 = 15 # packed E2M1 data + E8M0 scales per 32 elements + MXFP4 = 17 # packed E2M1 data + E8M0 scales per 32 elements # Backend self-manages kernel dispatch. Reads as quantized but matches no # generic kernel mode (is_per_token_head / is_nvfp4 / is_turboquant all From f4bf30462b804057d320c63714f55e522b1d3c12 Mon Sep 17 00:00:00 2001 From: Yongye Zhu Date: Thu, 29 Oct 2026 07:22:27 +0000 Subject: [PATCH 7/7] [Perf][FlashAttention] FA4: pass no FP8 descale for a unit per-tensor scale FA4 reads a missing descale as 1.0, and it copies every expanded descale view into a contiguous tensor: three copy kernels per layer and step. The scales are fixed once the weights are loaded, so a per-tensor scale of 1.0 (an FP8 KV cache without calibrated scales) passes no descale. Calibrated and per-head scales keep theirs; a (1, 1) expanded view gets canonical strides, because FA4 treats it as contiguous and its layout check then rejects the zero stride. Co-authored-by: qizixi <22851944+zixi-qi@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Yongye Zhu --- tests/v1/attention/test_attention_backends.py | 73 +++++++++++++++++++ vllm/v1/attention/backends/flash_attn.py | 26 ++++++- 2 files changed, 95 insertions(+), 4 deletions(-) diff --git a/tests/v1/attention/test_attention_backends.py b/tests/v1/attention/test_attention_backends.py index 0f911594931b..bac201fe1593 100644 --- a/tests/v1/attention/test_attention_backends.py +++ b/tests/v1/attention/test_attention_backends.py @@ -864,6 +864,79 @@ def causal_mask_mod( ) +@pytest.mark.skipif( + not current_platform.is_device_capability_family(100), + reason="FA4 takes FP8 Q/K/V with descales on Blackwell.", +) +def test_flash_attn_fa4_unit_fp8_descale_is_exact(default_vllm_config): + """FlashAttentionImpl passes FA4 no descale for a per-tensor scale of 1.0, + which FA4 reads as exactly 1.0; calibrated scales keep their descale.""" + from vllm.v1.attention.backends.fa_utils import ( + flash_attn_varlen_func, + is_fa_version_supported, + ) + from vllm.v1.attention.backends.flash_attn import FlashAttentionImpl + + if not is_fa_version_supported(4): + pytest.skip("FA4 is not supported.") + set_random_seed(0) + device = torch.device(f"{DEVICE_TYPE}:0") + fp8 = current_platform.fp8_dtype() + seq_lens, q_len = [1328, 523, 2011], 3 + num_heads, num_kv_heads, head_size = 64, 4, 128 + impl = FlashAttentionImpl( + num_heads=num_heads, + head_size=head_size, + scale=head_size**-0.5, + num_kv_heads=num_kv_heads, + alibi_slopes=None, + sliding_window=None, + kv_cache_dtype="fp8", + ) + assert impl.vllm_flash_attn_version == 4 + + q = torch.randn(len(seq_lens) * q_len, num_heads, head_size, device=device) + k_cache, v_cache = ( + torch.randn(64, 128, num_kv_heads, head_size, device=device).to(fp8) + for _ in range(2) + ) + block_table = torch.randperm(64, dtype=torch.int32, device=device)[:48] + + def run(descale: torch.Tensor | None) -> torch.Tensor: + return flash_attn_varlen_func( + q=q.to(fp8), + k=k_cache, + v=v_cache, + cu_seqlens_q=torch.arange( + 0, q.shape[0] + 1, q_len, dtype=torch.int32, device=device + ), + seqused_k=torch.tensor(seq_lens, dtype=torch.int32, device=device), + max_seqlen_q=q_len, + max_seqlen_k=max(seq_lens), + softmax_scale=head_size**-0.5, + causal=True, + block_table=block_table.view(len(seq_lens), -1), + fa_version=4, + q_descale=descale, + k_descale=descale, + v_descale=descale, + ) + + shape = (len(seq_lens), num_kv_heads) + unit = torch.ones(1, device=device) + assert impl._descale(unit, 1.0, shape) is None + expanded = unit.expand(shape) # What FA4 got for a unit scale before. + output = run(impl._descale(unit, 1.0, shape)) + torch.testing.assert_close(output, run(expanded), atol=0, rtol=0) + # Descales are applied when given, so the comparison above is not vacuous. + assert not torch.equal(output, run(2 * expanded)) + # Calibrated and per-head scales (whose float holds the max) keep theirs. + calibrated = impl._descale(0.5 * unit, 0.5, shape) + assert calibrated is not None and torch.equal(calibrated, 0.5 * expanded) + per_head = torch.tensor([1.0, 0.5, 1.0, 0.25], device=device) + assert impl._descale(per_head, 1.0, shape) is not None + + @pytest.mark.skipif( AttentionBackendEnum.FLASHINFER not in BACKENDS_TO_TEST, reason="FlashInfer is not available.", diff --git a/vllm/v1/attention/backends/flash_attn.py b/vllm/v1/attention/backends/flash_attn.py index c33def11a8ea..88fe210b9390 100755 --- a/vllm/v1/attention/backends/flash_attn.py +++ b/vllm/v1/attention/backends/flash_attn.py @@ -1179,6 +1179,25 @@ def __init__( vllm_config.scheduler_config.max_num_batched_tokens ) + def _descale( + self, scale: torch.Tensor, scale_float: float, shape: tuple[int, int] + ) -> torch.Tensor | None: + # FA4 reads a missing descale as 1.0, and it copies every expanded view + # into a contiguous tensor: three copy kernels per layer and step. The + # scales are fixed once weights are loaded, so a per-tensor scale of 1.0 + # (FP8 KV cache without calibrated scales) needs none. Per-head scales + # keep their tensor: their float mirror holds only the maximum. + if ( + self.vllm_flash_attn_version == 4 + and scale.numel() == 1 + and scale_float == 1.0 + ): + return None + # A (1, 1) expanded view (one sequence, one KV head per rank) counts + # as contiguous, so FA4 skips its copy and its CuTe layout check then + # rejects the zero stride. + return canonicalize_singleton_dim_strides(scale.expand(shape)) + def forward( self, layer: torch.nn.Module, @@ -1286,14 +1305,13 @@ def forward( scheduler_metadata = attn_metadata.scheduler_metadata descale_shape = (cu_seqlens_q.shape[0] - 1, self.num_kv_heads) - q_descale = ( - layer._q_scale.expand(descale_shape) + self._descale(layer._q_scale, layer._q_scale_float, descale_shape) if self.supports_quant_query_input else None ) - k_descale = layer._k_scale.expand(descale_shape) - v_descale = layer._v_scale.expand(descale_shape) + k_descale = self._descale(layer._k_scale, layer._k_scale_float, descale_shape) + v_descale = self._descale(layer._v_scale, layer._v_scale_float, descale_shape) if self.dcp_world_size > 1: self._forward_with_dcp(