From 13999673ef26f7e1ccd55f7b6e47e7fbd7199119 Mon Sep 17 00:00:00 2001 From: Yanbin Jiang Date: Thu, 22 Oct 2026 13:40:56 -0700 Subject: [PATCH] [Feat] lora: Add plan-driven dense and MoE LoRA engines (#45892) --- python/sglang/kernels/ops/lora/__init__.py | 98 +- .../kernels/ops/lora/common/__init__.py | 1 + .../sglang/kernels/ops/lora/common/lora_a.py | 399 ++ .../sglang/kernels/ops/lora/common/lora_b.py | 710 ++++ .../kernels/ops/lora/common/route_view.py | 80 + .../sglang/kernels/ops/lora/common/routing.py | 812 ++++ .../ops/lora/dense/embedding_lora_a.py | 109 + .../sglang/kernels/ops/lora/moe/__init__.py | 5 +- .../sglang/kernels/ops/lora/moe/activation.py | 17 + .../kernels/ops/lora/moe/activation_delta.py | 174 + .../sglang/kernels/ops/lora/moe/align_rows.py | 99 + .../kernels/ops/lora/moe/cutedsl/__init__.py | 4 + .../kernels/ops/lora/moe/cutedsl/api.py | 367 ++ .../ops/lora/moe/cutedsl/kernel_sm100_bf16.py | 799 ++++ .../ops/lora/moe/cutedsl/kernel_sm100_fp8.py | 574 +++ .../ops/lora/moe/cutedsl/kernel_sm90_bf16.py | 802 ++++ .../ops/lora/moe/cutedsl/kernel_sm90_fp8.py | 1044 +++++ .../ops/lora/moe/cutedsl/schedule_builder.py | 335 ++ .../kernels/ops/lora/moe/cutedsl/scheduler.py | 294 ++ .../kernels/ops/lora/moe/dispatch_checks.py | 28 + .../ops/lora/moe/dispatch_contiguous.py | 249 ++ .../kernels/ops/lora/moe/dispatch_masked.py | 146 + .../ops/lora/moe/dispatch_masked_small.py | 183 + .../sglang/kernels/ops/lora/moe/finalize.py | 423 ++ .../sglang/kernels/ops/lora/moe/fp8_quant.py | 34 + .../sglang/kernels/ops/lora/moe/fused_act.py | 295 ++ python/sglang/kernels/ops/lora/moe/lora_b.py | 229 ++ .../kernels/ops/lora/moe/virtual_experts.py | 20 +- .../sglang/kernels/ops/moe/ep_moe_kernels.py | 32 +- python/sglang/srt/arg_groups/choices.py | 3 + python/sglang/srt/arg_groups/fields/lora.py | 2 +- python/sglang/srt/arg_groups/lora_hook.py | 78 + python/sglang/srt/arg_groups/overrides.py | 8 + python/sglang/srt/environ.py | 5 + .../srt/layers/moe/fused_moe_triton/layer.py | 12 +- python/sglang/srt/layers/moe/utils.py | 13 + .../srt/layers/quantization/modelopt_quant.py | 13 +- .../sglang/srt/lora/backend/ascend_backend.py | 2 +- .../sglang/srt/lora/backend/base_backend.py | 185 +- .../srt/lora/backend/chunked_backend.py | 2 +- .../sglang/srt/lora/backend/lora_registry.py | 7 + .../sglang/srt/lora/backend/torch_backend.py | 2 +- .../sglang/srt/lora/backend/triton_backend.py | 4 +- .../srt/lora/backend/triton_v2_backend.py | 343 ++ python/sglang/srt/lora/dense/__init__.py | 0 .../sglang/srt/lora/dense/configs/README.md | 42 + .../srt/lora/dense/configs/default.plans.json | 433 ++ .../srt/lora/dense/configs/sm100.plans.json | 3096 +++++++++++++++ .../srt/lora/dense/configs/sm90.plans.json | 3484 +++++++++++++++++ .../sglang/srt/lora/dense/mla_correction.py | 138 + python/sglang/srt/lora/dense/plan.py | 283 ++ python/sglang/srt/lora/dense/runner.py | 468 +++ python/sglang/srt/lora/layers.py | 291 +- python/sglang/srt/lora/lora_manager.py | 136 +- python/sglang/srt/lora/mem_pool.py | 11 +- python/sglang/srt/lora/moe/__init__.py | 1 + .../lora/moe/base_gemm_provider/__init__.py | 85 + .../srt/lora/moe/base_gemm_provider/base.py | 305 ++ .../contiguous_row_domain.py | 212 + .../moe/base_gemm_provider/cutedsl_bf16.py | 383 ++ .../moe/base_gemm_provider/cutedsl_common.py | 282 ++ .../moe/base_gemm_provider/cutedsl_fp8.py | 446 +++ .../base_gemm_provider/gemm_config_store.py | 142 + .../moe/base_gemm_provider/input_alignment.py | 38 + .../moe/base_gemm_provider/marlin_nvfp4.py | 216 + .../base_gemm_provider/masked_row_domain.py | 189 + .../moe/base_gemm_provider/triton_bf16.py | 202 + .../lora/moe/base_gemm_provider/triton_fp8.py | 106 + python/sglang/srt/lora/moe/configs/README.md | 56 + .../srt/lora/moe/configs/base_gemm/README.md | 39 + ...2=2048,K=2048,device_name=NVIDIA_H200.json | 34 + ...2=2048,K=2048,device_name=NVIDIA_B200.json | 41 + ...2=2048,K=2048,device_name=NVIDIA_H200.json | 31 + ...2=4096,K=4096,device_name=NVIDIA_B200.json | 31 + ...2=4096,K=4096,device_name=NVIDIA_H200.json | 31 + ...2=4096,K=4096,device_name=NVIDIA_B200.json | 46 + ...=4096,K=4096,device_name=NVIDIA_GB300.json | 34 + ...2=2048,K=2048,device_name=NVIDIA_B200.json | 45 + ...=2048,K=2048,device_name=NVIDIA_GB300.json | 45 + ...2=2048,K=2048,device_name=NVIDIA_H200.json | 38 + ...2=4096,K=4096,device_name=NVIDIA_B200.json | 41 + ...2=4096,K=4096,device_name=NVIDIA_H200.json | 38 + ...=4096,K=4096,device_name=NVIDIA_GB300.json | 41 + .../srt/lora/moe/configs/default.plans.json | 101 + .../srt/lora/moe/configs/sm100.plans.json | 974 +++++ .../srt/lora/moe/configs/sm90.plans.json | 634 +++ python/sglang/srt/lora/moe/plan.py | 759 ++++ python/sglang/srt/lora/moe/quant_info.py | 135 + python/sglang/srt/lora/moe/routing.py | 132 + python/sglang/srt/lora/moe/runner.py | 856 ++++ python/sglang/srt/lora/utils.py | 38 +- python/sglang/srt/lora/workspace.py | 180 + .../srt/model_executor/runner/__init__.py | 1 - .../runner/decode_cuda_graph_runner.py | 60 +- .../runner/prefill_cuda_graph_runner.py | 2 + .../runner_utils/capture_mode.py | 12 +- .../attention_forward_methods/forward_mla.py | 42 +- .../srt/models/inkling_common/dense_mlp.py | 34 +- .../sglang/srt/models/inkling_common/lora.py | 170 +- .../sglang/srt/models/inkling_common/moe.py | 18 +- .../lora/test_lora_moe_prefill_cuda_graph.py | 21 +- .../ops/lora/test_chunked_sgmv_cuda_graph.py | 2 +- .../ops/lora/test_dense_lora_backend.py | 762 ++++ .../ops/lora/test_dense_lora_geometry.py | 129 + .../ops/lora/test_dense_lora_inkling_sink.py | 604 +++ .../ops/lora/test_dense_lora_kernels.py | 782 ++++ .../lora/test_dense_lora_mla_correction.py | 356 ++ .../ops/lora/test_dense_lora_routing_graph.py | 243 ++ .../ops/lora/test_moe_lora_bind_execution.py | 65 + .../test_moe_lora_contiguous_row_domain.py | 520 +++ .../lora/test_moe_lora_down_b_into_base.py | 647 +++ .../test_moe_lora_fp8_provider_numerics.py | 201 + .../ops/lora/test_moe_lora_fused_dispatch.py | 305 ++ .../test_moe_lora_masked_capacity_graph.py | 212 + .../lora/test_moe_lora_moe_runner_numerics.py | 421 ++ .../test_moe_lora_nvfp4_provider_numerics.py | 461 +++ .../ops/lora/test_moe_lora_per_row_b.py | 248 ++ .../test_moe_lora_prepared_input_reuse.py | 231 ++ .../kernels/ops/lora/test_moe_lora_routing.py | 285 ++ .../ops/lora/test_moe_lora_runner_attach.py | 146 + .../lora/test_moe_lora_schedule_builder.py | 131 + .../test_moe_lora_shared_outer_numerics.py | 333 ++ ...est_moe_lora_small_masked_prepare_paths.py | 213 + test/registered/lora/test_moe_lora_info.py | 85 +- .../layers/moe/test_moe_runner_extensions.py | 2 +- .../lora/test_inkling_linearized_lora_unit.py | 177 +- .../unit/lora/test_lora_forward_with_base.py | 156 + .../lora/test_lora_inactive_batch_skip.py | 89 + .../lora/test_lora_manager_init_modules.py | 70 +- .../unit/lora/test_lora_moe_inplace_unit.py | 2 +- .../lora/test_lora_spec_verify_batch_info.py | 4 +- .../lora/test_moe_lora_gemm_config_store.py | 112 + .../lora/test_moe_lora_masked_capacity.py | 27 + .../unit/lora/test_moe_lora_plan_tables.py | 77 + .../test_moe_lora_prefill_graph_contract.py | 415 ++ .../lora/test_moe_lora_provider_contract.py | 137 + .../unit/lora/test_moe_lora_route_factory.py | 186 + .../unit/lora/test_moe_lora_stage_dispatch.py | 76 + .../lora/test_triton_dp_attention_unit.py | 2 +- .../unit/models/test_nemotron_h_shared_add.py | 3 + .../unit/server_args/test_server_args.py | 23 + 141 files changed, 33405 insertions(+), 325 deletions(-) create mode 100644 python/sglang/kernels/ops/lora/common/__init__.py create mode 100644 python/sglang/kernels/ops/lora/common/lora_a.py create mode 100644 python/sglang/kernels/ops/lora/common/lora_b.py create mode 100644 python/sglang/kernels/ops/lora/common/route_view.py create mode 100644 python/sglang/kernels/ops/lora/common/routing.py create mode 100644 python/sglang/kernels/ops/lora/moe/activation.py create mode 100644 python/sglang/kernels/ops/lora/moe/activation_delta.py create mode 100644 python/sglang/kernels/ops/lora/moe/align_rows.py create mode 100644 python/sglang/kernels/ops/lora/moe/cutedsl/__init__.py create mode 100644 python/sglang/kernels/ops/lora/moe/cutedsl/api.py create mode 100644 python/sglang/kernels/ops/lora/moe/cutedsl/kernel_sm100_bf16.py create mode 100644 python/sglang/kernels/ops/lora/moe/cutedsl/kernel_sm100_fp8.py create mode 100644 python/sglang/kernels/ops/lora/moe/cutedsl/kernel_sm90_bf16.py create mode 100644 python/sglang/kernels/ops/lora/moe/cutedsl/kernel_sm90_fp8.py create mode 100644 python/sglang/kernels/ops/lora/moe/cutedsl/schedule_builder.py create mode 100644 python/sglang/kernels/ops/lora/moe/cutedsl/scheduler.py create mode 100644 python/sglang/kernels/ops/lora/moe/dispatch_checks.py create mode 100644 python/sglang/kernels/ops/lora/moe/dispatch_contiguous.py create mode 100644 python/sglang/kernels/ops/lora/moe/dispatch_masked.py create mode 100644 python/sglang/kernels/ops/lora/moe/dispatch_masked_small.py create mode 100644 python/sglang/kernels/ops/lora/moe/finalize.py create mode 100644 python/sglang/kernels/ops/lora/moe/fp8_quant.py create mode 100644 python/sglang/kernels/ops/lora/moe/fused_act.py create mode 100644 python/sglang/kernels/ops/lora/moe/lora_b.py create mode 100644 python/sglang/srt/lora/backend/triton_v2_backend.py create mode 100644 python/sglang/srt/lora/dense/__init__.py create mode 100644 python/sglang/srt/lora/dense/configs/README.md create mode 100644 python/sglang/srt/lora/dense/configs/default.plans.json create mode 100644 python/sglang/srt/lora/dense/configs/sm100.plans.json create mode 100644 python/sglang/srt/lora/dense/configs/sm90.plans.json create mode 100644 python/sglang/srt/lora/dense/mla_correction.py create mode 100644 python/sglang/srt/lora/dense/plan.py create mode 100644 python/sglang/srt/lora/dense/runner.py create mode 100644 python/sglang/srt/lora/moe/__init__.py create mode 100644 python/sglang/srt/lora/moe/base_gemm_provider/__init__.py create mode 100644 python/sglang/srt/lora/moe/base_gemm_provider/base.py create mode 100644 python/sglang/srt/lora/moe/base_gemm_provider/contiguous_row_domain.py create mode 100644 python/sglang/srt/lora/moe/base_gemm_provider/cutedsl_bf16.py create mode 100644 python/sglang/srt/lora/moe/base_gemm_provider/cutedsl_common.py create mode 100644 python/sglang/srt/lora/moe/base_gemm_provider/cutedsl_fp8.py create mode 100644 python/sglang/srt/lora/moe/base_gemm_provider/gemm_config_store.py create mode 100644 python/sglang/srt/lora/moe/base_gemm_provider/input_alignment.py create mode 100644 python/sglang/srt/lora/moe/base_gemm_provider/marlin_nvfp4.py create mode 100644 python/sglang/srt/lora/moe/base_gemm_provider/masked_row_domain.py create mode 100644 python/sglang/srt/lora/moe/base_gemm_provider/triton_bf16.py create mode 100644 python/sglang/srt/lora/moe/base_gemm_provider/triton_fp8.py create mode 100644 python/sglang/srt/lora/moe/configs/README.md create mode 100644 python/sglang/srt/lora/moe/configs/base_gemm/README.md create mode 100644 python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=256,N1=1024,N2=2048,K=2048,device_name=NVIDIA_H200.json create mode 100644 python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_B200.json create mode 100644 python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_H200.json create mode 100644 python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=512,N1=256,N2=4096,K=4096,device_name=NVIDIA_B200.json create mode 100644 python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=512,N1=256,N2=4096,K=4096,device_name=NVIDIA_H200.json create mode 100644 python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=512,N1=512,N2=4096,K=4096,device_name=NVIDIA_B200.json create mode 100644 python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=512,N1=512,N2=4096,K=4096,device_name=NVIDIA_GB300.json create mode 100644 python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_B200.json create mode 100644 python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_GB300.json create mode 100644 python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_H200.json create mode 100644 python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=512,N1=256,N2=4096,K=4096,device_name=NVIDIA_B200.json create mode 100644 python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=512,N1=256,N2=4096,K=4096,device_name=NVIDIA_H200.json create mode 100644 python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=512,N1=512,N2=4096,K=4096,device_name=NVIDIA_GB300.json create mode 100644 python/sglang/srt/lora/moe/configs/default.plans.json create mode 100644 python/sglang/srt/lora/moe/configs/sm100.plans.json create mode 100644 python/sglang/srt/lora/moe/configs/sm90.plans.json create mode 100644 python/sglang/srt/lora/moe/plan.py create mode 100644 python/sglang/srt/lora/moe/quant_info.py create mode 100644 python/sglang/srt/lora/moe/routing.py create mode 100644 python/sglang/srt/lora/moe/runner.py create mode 100644 python/sglang/srt/lora/workspace.py create mode 100644 test/registered/kernels/ops/lora/test_dense_lora_backend.py create mode 100644 test/registered/kernels/ops/lora/test_dense_lora_geometry.py create mode 100644 test/registered/kernels/ops/lora/test_dense_lora_inkling_sink.py create mode 100644 test/registered/kernels/ops/lora/test_dense_lora_kernels.py create mode 100644 test/registered/kernels/ops/lora/test_dense_lora_mla_correction.py create mode 100644 test/registered/kernels/ops/lora/test_dense_lora_routing_graph.py create mode 100644 test/registered/kernels/ops/lora/test_moe_lora_bind_execution.py create mode 100644 test/registered/kernels/ops/lora/test_moe_lora_contiguous_row_domain.py create mode 100644 test/registered/kernels/ops/lora/test_moe_lora_down_b_into_base.py create mode 100644 test/registered/kernels/ops/lora/test_moe_lora_fp8_provider_numerics.py create mode 100644 test/registered/kernels/ops/lora/test_moe_lora_fused_dispatch.py create mode 100644 test/registered/kernels/ops/lora/test_moe_lora_masked_capacity_graph.py create mode 100644 test/registered/kernels/ops/lora/test_moe_lora_moe_runner_numerics.py create mode 100644 test/registered/kernels/ops/lora/test_moe_lora_nvfp4_provider_numerics.py create mode 100644 test/registered/kernels/ops/lora/test_moe_lora_per_row_b.py create mode 100644 test/registered/kernels/ops/lora/test_moe_lora_prepared_input_reuse.py create mode 100644 test/registered/kernels/ops/lora/test_moe_lora_routing.py create mode 100644 test/registered/kernels/ops/lora/test_moe_lora_runner_attach.py create mode 100644 test/registered/kernels/ops/lora/test_moe_lora_schedule_builder.py create mode 100644 test/registered/kernels/ops/lora/test_moe_lora_shared_outer_numerics.py create mode 100644 test/registered/kernels/ops/lora/test_moe_lora_small_masked_prepare_paths.py create mode 100644 test/registered/unit/lora/test_lora_forward_with_base.py create mode 100644 test/registered/unit/lora/test_lora_inactive_batch_skip.py create mode 100644 test/registered/unit/lora/test_moe_lora_gemm_config_store.py create mode 100644 test/registered/unit/lora/test_moe_lora_masked_capacity.py create mode 100644 test/registered/unit/lora/test_moe_lora_plan_tables.py create mode 100644 test/registered/unit/lora/test_moe_lora_prefill_graph_contract.py create mode 100644 test/registered/unit/lora/test_moe_lora_provider_contract.py create mode 100644 test/registered/unit/lora/test_moe_lora_route_factory.py create mode 100644 test/registered/unit/lora/test_moe_lora_stage_dispatch.py diff --git a/python/sglang/kernels/ops/lora/__init__.py b/python/sglang/kernels/ops/lora/__init__.py index a6b5a074bb..315805e4ab 100644 --- a/python/sglang/kernels/ops/lora/__init__.py +++ b/python/sglang/kernels/ops/lora/__init__.py @@ -1,8 +1,10 @@ -"""LoRA adapter kernels that only the LoRA runtime calls: ``dense/`` SGMV GEMMs, -``moe/`` fused MoE-LoRA, and the experimental TRT-LLM LoRA path.""" +"""LoRA kernels: shared routing/GEMMs, legacy dense adapters and MoE stages. + +Runtime plans/providers select implementations; this package records lazy metadata. +""" from sglang.kernels.registry import register_kernel -from sglang.kernels.spec import KernelBackend, KernelSpec +from sglang.kernels.spec import CapabilityRequirement, KernelBackend, KernelSpec # Triton kernels registered for inventory. Import them from their modules. _TRITON_KERNELS = [ @@ -31,4 +33,94 @@ for _mod, _fn in _TRITON_KERNELS: ) del _mod, _fn + +# Host launch APIs; importing this inventory does not import their implementations. +_ENGINE_TRITON_KERNELS = [ + ("common.routing", "build_route", "build_route"), + ("common.lora_a", "grouped_lora_a", "grouped_lora_a"), + ("common.lora_a", "per_row_lora_a", "per_row_lora_a"), + ("common.lora_b", "grouped_lora_b", "grouped_lora_b"), + ("common.lora_b", "per_row_lora_b", "per_row_lora_b"), + ( + "dense.embedding_lora_a", + "embedding_lora_a_tokens_fwd", + "embedding_lora_a_tokens_fwd", + ), + ("moe.activation_delta", "act_delta", "act_delta"), + ("moe.align_rows", "pair_to_row_map", "pair_to_row_map"), + ("moe.align_rows", "moe_align_single_token", "moe_align_single_token"), + ( + "moe.dispatch_contiguous", + "dispatch_layout_contiguous", + "dispatch_layout_contiguous", + ), + ( + "moe.dispatch_contiguous", + "dispatch_fill_rows_contiguous_bf16", + "dispatch_fill_rows_contiguous_bf16", + ), + ( + "moe.dispatch_contiguous", + "dispatch_fill_rows_contiguous_fp8", + "dispatch_fill_rows_contiguous_fp8", + ), + ("moe.dispatch_masked", "dispatch_fill_masked_bf16", "dispatch_fill_masked_bf16"), + ("moe.dispatch_masked", "dispatch_fill_masked_fp8", "dispatch_fill_masked_fp8"), + ("moe.dispatch_masked_small", "small_masked_prepare", "small_masked_prepare"), + ( + "moe.finalize", + "invoke_shared_token_delta_reduce", + "invoke_shared_token_delta_reduce", + ), + ( + "moe.finalize", + "invoke_shared_token_delta_tail", + "invoke_shared_token_delta_tail", + ), + ("moe.finalize", "invoke_shared_one_pass", "invoke_shared_one_pass"), + ("moe.finalize", "invoke_small_finalize", "invoke_small_finalize"), + ("moe.fused_act", "fused_b_act", "fused_b_act"), + ("moe.lora_b", "grouped_lora_b", "moe_grouped_lora_b"), + ("moe.lora_b", "invoke_down_b_into_base", "invoke_down_b_into_base"), + ( + "moe.cutedsl.schedule_builder", + "build_dual_stage_schedules_masked", + "build_dual_stage_schedules_masked", + ), + ( + "moe.cutedsl.schedule_builder", + "build_dual_stage_schedules_contiguous", + "build_dual_stage_schedules_contiguous", + ), +] +for _mod, _fn, _op in _ENGINE_TRITON_KERNELS: + register_kernel( + KernelSpec( + op=f"lora.{_op}", + backend=KernelBackend.TRITON, + target=f"sglang.kernels.ops.lora.{_mod}:{_fn}", + capabilities=frozenset({CapabilityRequirement.CUDA}), + ) + ) +del _mod, _fn, _op + +# CuTeDSL grouped GEMMs: each compiles once and returns the launchable kernel. +# Their kernel classes exist for SM90 (WGMMA) and SM100 (tcgen05) only. +_ENGINE_CUTE_DSL_KERNELS = ( + "prepare_masked_bf16", + "prepare_contiguous_bf16", + "prepare_masked_fp8", + "prepare_contiguous_fp8", +) +for _fn in _ENGINE_CUTE_DSL_KERNELS: + register_kernel( + KernelSpec( + op=f"lora.{_fn}", + backend=KernelBackend.CUTE_DSL, + target=f"sglang.kernels.ops.lora.moe.cutedsl.api:{_fn}", + capabilities=frozenset({CapabilityRequirement.cuda(min_sm=(9, 0))}), + ) + ) +del _fn + __all__: list[str] = [] diff --git a/python/sglang/kernels/ops/lora/common/__init__.py b/python/sglang/kernels/ops/lora/common/__init__.py new file mode 100644 index 0000000000..8cece04ac3 --- /dev/null +++ b/python/sglang/kernels/ops/lora/common/__init__.py @@ -0,0 +1 @@ +"""Shared LoRA routing, shrink and expand kernels.""" diff --git a/python/sglang/kernels/ops/lora/common/lora_a.py b/python/sglang/kernels/ops/lora/common/lora_a.py new file mode 100644 index 0000000000..72775ca162 --- /dev/null +++ b/python/sglang/kernels/ops/lora/common/lora_a.py @@ -0,0 +1,399 @@ +"""LoRA-A shrink over aligned groups or raw pairs. + +Dense slots use ``lora_ranks`` to bound live width at rank * STACK; +MoE slots use the full N. +""" + +from __future__ import annotations + +from collections.abc import Mapping + +import torch +import triton +import triton.language as tl + +from sglang.kernels.ops.lora.common.route_view import RouteView +from sglang.kernels.ops.lora.common.routing import ( + grouped_tile_coords, + route_bucket_ids, +) + + +@triton.jit(do_not_specialize=["num_input_rows", "num_pairs", "num_m_blocks"]) +def _grouped_lora_a_kernel( + input_ptr, + weight_ptr, + output_ptr, + partial_ptr, + counter_ptr, + pair_to_row_ptr, + sorted_pair_ids_ptr, + block_bucket_ids_ptr, + num_pairs_post_padded_ptr, + lora_ranks_ptr, + num_input_rows, + num_pairs, + stride_im, + stride_ik, + stride_we, + stride_wn, + stride_wk, + stride_om, + stride_on, + stride_pp, + stride_pm, + stride_pn, + num_m_blocks, + WIDTH: tl.constexpr, + N: tl.constexpr, + K: tl.constexpr, + PAIR_INPUT: tl.constexpr, + STACK: tl.constexpr, + SPLIT_K: tl.constexpr, + SPLIT_MODE: tl.constexpr, + GROUPS_PER_SLOT: tl.constexpr, + WEIGHT_DIV: tl.constexpr, + BLOCK_SIZE_M: tl.constexpr, + BLOCK_SIZE_N: tl.constexpr, + BLOCK_SIZE_K: tl.constexpr, + GROUP_SIZE_M: tl.constexpr, + WINDOWED: tl.constexpr = False, +): + # WINDOWED tiles cannot straddle rank blocks or apply the live-rank prefix. + pid = tl.program_id(0) + pid_k = tl.program_id(1) + if WINDOWED: + N_BLOCK: tl.constexpr = N // STACK + TILES_PER_BLOCK: tl.constexpr = (N_BLOCK + BLOCK_SIZE_N - 1) // BLOCK_SIZE_N + num_pid_n = STACK * TILES_PER_BLOCK + else: + num_pid_n = tl.cdiv(N, BLOCK_SIZE_N) + pid_m, pid_n = grouped_tile_coords(pid, num_pid_n, num_m_blocks, GROUP_SIZE_M) + if pid_m * BLOCK_SIZE_M >= tl.load(num_pairs_post_padded_ptr): + return + bucket_id = tl.load(block_bucket_ids_ptr + pid_m) + if bucket_id == -1: + return + if WINDOWED: + block = pid_n // TILES_PER_BLOCK + n_begin = block * N_BLOCK + (pid_n % TILES_PER_BLOCK) * BLOCK_SIZE_N + n_end = (block + 1) * N_BLOCK + k_base = (block * K).to(tl.int64) + else: + n_begin = pid_n * BLOCK_SIZE_N + n_end = N + k_base = 0 + if lora_ranks_ptr is not None and not WINDOWED: + n_live = ( + tl.load(lora_ranks_ptr + bucket_id // GROUPS_PER_SLOT).to(tl.int32) * STACK + ) + if n_begin >= n_live: + return + else: + n_live = n_end + + pair_slots = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M).to(tl.int64) + pair_ids = tl.load(sorted_pair_ids_ptr + pair_slots).to(tl.int64) + pair_mask = pair_ids < num_pairs + if pair_to_row_ptr is not None: + input_rows = tl.load( + pair_to_row_ptr + pair_ids, + mask=pair_mask, + other=-1, + ).to(tl.int64) + elif PAIR_INPUT: + input_rows = pair_ids + else: + input_rows = pair_ids // WIDTH + input_mask = pair_mask & (input_rows >= 0) & (input_rows < num_input_rows) + n_offsets = n_begin + tl.arange(0, BLOCK_SIZE_N).to(tl.int64) + n_mask = n_offsets < n_live + plane = (bucket_id // WEIGHT_DIV).to(tl.int64) + + K_PER_SPLIT: tl.constexpr = (K + SPLIT_K - 1) // SPLIT_K + if SPLIT_K == 1: + k_start = 0 + k_end = K + else: + k_start = pid_k * K_PER_SPLIT + k_end = tl.minimum(k_start + K_PER_SPLIT, K) + accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) + for k_begin in range(k_start, k_end, BLOCK_SIZE_K): + k_offsets = k_begin + tl.arange(0, BLOCK_SIZE_K).to(tl.int64) + k_mask = k_offsets < k_end + lhs = tl.load( + input_ptr + + input_rows[:, None] * stride_im + + (k_base + k_offsets)[None, :] * stride_ik, + mask=input_mask[:, None] & k_mask[None, :], + other=0.0, + ) + rhs = tl.load( + weight_ptr + + plane * stride_we + + n_offsets[None, :] * stride_wn + + k_offsets[:, None] * stride_wk, + mask=n_mask[None, :] & k_mask[:, None], + other=0.0, + ) + accumulator += tl.dot(lhs, rhs, out_dtype=tl.float32) + + out_mask = pair_mask[:, None] & n_mask[None, :] + output_ptrs = ( + output_ptr + pair_ids[:, None] * stride_om + n_offsets[None, :] * stride_on + ) + if SPLIT_K == 1: + tl.store( + output_ptrs, accumulator.to(output_ptr.dtype.element_ty), mask=out_mask + ) + else: + plane_ptrs = ( + partial_ptr + pair_ids[:, None] * stride_pm + n_offsets[None, :] * stride_pn + ) + tl.store( + plane_ptrs + pid_k.to(tl.int64) * stride_pp, accumulator, mask=out_mask + ) + if SPLIT_MODE == "serial": + # The barrier orders this program's plane stores before its release; + # the last arrival's acquire makes every plane visible. + tl.debug_barrier() + tile = pid_m * num_pid_n + pid_n + arrived = tl.atomic_add(counter_ptr + tile, 1, sem="acq_rel", scope="gpu") + if arrived == SPLIT_K - 1: + total = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) + for s in tl.static_range(SPLIT_K): + total += tl.load( + plane_ptrs + s * stride_pp, mask=out_mask, other=0.0 + ) + tl.store( + output_ptrs, total.to(output_ptr.dtype.element_ty), mask=out_mask + ) + tl.atomic_xchg(counter_ptr + tile, 0, sem="release", scope="gpu") + + +def grouped_lora_a( + input: torch.Tensor, + weight: torch.Tensor, + output: torch.Tensor, + routing: RouteView, + *, + config: Mapping[str, int], + pair_input: bool = False, + pair_to_row: torch.Tensor | None = None, + lora_ranks: torch.Tensor | None = None, + stack: int = 1, + partial: torch.Tensor | None = None, + counters: torch.Tensor | None = None, + weight_div: int = 1, + windowed: bool = False, +) -> None: + """Shrink aligned rows into a pair-major bridge. + + ``pair_to_row`` overrides pair/token input indexing; the weight plane is + bucket // weight_div. ``lora_ranks`` limits output to rank * stack. + ``windowed`` block s reads input[:, s*K:(s+1)*K], ignoring ``lora_ranks``. + Split-K uses FP32 partial[split, row, N]; serial needs zeroed counters and + sums planes in a fixed order. Planes mode leaves reduction to B. + """ + num_pairs = routing.num_rows + if num_pairs == 0: + return + block_size_n, num_n_blocks = shrink_column_tiles( + int(config["BLOCK_SIZE_N"]), weight.shape[1], stack, windowed + ) + split_k = int(config.get("SPLIT_K", 1)) + split_mode = config.get("SPLIT_MODE", "serial") + num_m_blocks = triton.cdiv(routing.sorted_pair_ids.numel(), routing.block_size) + if split_k > 1: + if partial is None or (split_mode == "serial" and counters is None): + raise ValueError("a split-K shrink needs partial planes (and counters)") + if split_mode == "serial" and counters.numel() < num_m_blocks * num_n_blocks: + raise ValueError("split-K tile counters are smaller than the tile grid") + stride_pp, stride_pm, stride_pn = partial.stride() + else: + partial = counters = None + stride_pp = stride_pm = stride_pn = 0 + _grouped_lora_a_kernel[(num_m_blocks * num_n_blocks, split_k)]( + input, + weight, + output, + partial, + counters, + pair_to_row, + routing.sorted_pair_ids, + routing.block_bucket_ids, + routing.num_pairs_post_padded, + lora_ranks, + input.shape[0], + num_pairs, + input.stride(0), + input.stride(1), + weight.stride(0), + weight.stride(1), + weight.stride(2), + output.stride(0), + output.stride(1), + stride_pp, + stride_pm, + stride_pn, + num_m_blocks=num_m_blocks, + WIDTH=routing.width, + N=weight.shape[1], + K=weight.shape[2], + PAIR_INPUT=pair_input, + STACK=stack, + SPLIT_K=split_k, + SPLIT_MODE=split_mode, + GROUPS_PER_SLOT=routing.groups_per_slot, + WEIGHT_DIV=weight_div, + BLOCK_SIZE_M=routing.block_size, + BLOCK_SIZE_N=block_size_n, + BLOCK_SIZE_K=int(config["BLOCK_SIZE_K"]), + GROUP_SIZE_M=int(config["GROUP_SIZE_M"]), + WINDOWED=windowed, + num_warps=int(config["num_warps"]), + num_stages=int(config["num_stages"]), + ) + + +def shrink_column_tiles( + block_size_n: int, n: int, stack: int, windowed: bool +) -> tuple[int, int]: + """Return (tile width, tile count), keeping windowed rank blocks separate.""" + if not windowed: + return block_size_n, triton.cdiv(n, block_size_n) + n_block = n // stack + block_size_n = max(16, min(block_size_n, triton.next_power_of_2(n_block))) + return block_size_n, stack * triton.cdiv(n_block, block_size_n) + + +@triton.jit +def _per_row_lora_a_kernel( + input_ptr, + weight_ptr, + group_ids_ptr, + token_slots_ptr, + output_ptr, + stride_im, + stride_ik, + stride_wg, + stride_wn, + stride_wk, + stride_om, + stride_on, + N: tl.constexpr, + K: tl.constexpr, + GROUPS_PER_SLOT: tl.constexpr, + MAX_LORAS: tl.constexpr, + WIDTH: tl.constexpr, + HAS_GROUPS: tl.constexpr, + PAIR_INPUT: tl.constexpr, + BLOCK_SIZE_N: tl.constexpr, + BLOCK_SIZE_K: tl.constexpr, + STACK: tl.constexpr = 1, + WINDOWED: tl.constexpr = False, +): + # One program per (row, column tile). WINDOWED uses the grouped contract. + pair_id = tl.program_id(0) + pid_n = tl.program_id(1) + bucket_id = route_bucket_ids( + group_ids_ptr, + token_slots_ptr, + pair_id, + pair_id >= 0, + GROUPS_PER_SLOT=GROUPS_PER_SLOT, + MAX_LORAS=MAX_LORAS, + WIDTH=WIDTH, + HAS_GROUPS=HAS_GROUPS, + ) + if bucket_id == -1: + # B skips or zeroes these rows without reading the bridge. + return + bucket_id = bucket_id.to(tl.int64) + pair64 = pair_id.to(tl.int64) + input_row = pair64 if PAIR_INPUT else pair64 // WIDTH + + if WINDOWED: + N_BLOCK: tl.constexpr = N // STACK + TILES_PER_BLOCK: tl.constexpr = (N_BLOCK + BLOCK_SIZE_N - 1) // BLOCK_SIZE_N + block = pid_n // TILES_PER_BLOCK + n_begin = block * N_BLOCK + (pid_n % TILES_PER_BLOCK) * BLOCK_SIZE_N + n_end = (block + 1) * N_BLOCK + k_base = (block * K).to(tl.int64) + else: + n_begin = pid_n * BLOCK_SIZE_N + n_end = N + k_base = 0 + n_offsets = n_begin.to(tl.int64) + tl.arange(0, BLOCK_SIZE_N).to(tl.int64) + n_mask = n_offsets < n_end + accumulator = tl.zeros((BLOCK_SIZE_N,), dtype=tl.float32) + for k_begin in range(0, K, BLOCK_SIZE_K): + k_offsets = k_begin + tl.arange(0, BLOCK_SIZE_K).to(tl.int64) + k_mask = k_offsets < K + lhs = tl.load( + input_ptr + input_row * stride_im + (k_base + k_offsets) * stride_ik, + mask=k_mask, + other=0.0, + ) + rhs = tl.load( + weight_ptr + + bucket_id * stride_wg + + n_offsets[:, None] * stride_wn + + k_offsets[None, :] * stride_wk, + mask=n_mask[:, None] & k_mask[None, :], + other=0.0, + ) + accumulator += tl.sum(rhs.to(tl.float32) * lhs[None, :].to(tl.float32), axis=1) + + tl.store( + output_ptr + pair64 * stride_om + n_offsets * stride_on, + accumulator.to(output_ptr.dtype.element_ty), + mask=n_mask, + ) + + +def per_row_lora_a( + input: torch.Tensor, + weight: torch.Tensor, + output: torch.Tensor, + routing: RouteView, + *, + config: Mapping[str, int], + pair_input: bool = False, + stack: int = 1, + windowed: bool = False, +) -> None: + num_pairs = routing.num_rows + if num_pairs == 0: + return + + block_size_n, num_n_blocks = shrink_column_tiles( + int(config["BLOCK_SIZE_N"]), weight.shape[1], stack, windowed + ) + _per_row_lora_a_kernel[(num_pairs, num_n_blocks)]( + input, + weight, + routing.kernel_groups, + routing.token_slots, + output, + input.stride(0), + input.stride(1), + weight.stride(0), + weight.stride(1), + weight.stride(2), + output.stride(0), + output.stride(1), + N=weight.shape[1], + K=weight.shape[2], + GROUPS_PER_SLOT=routing.groups_per_slot, + MAX_LORAS=routing.max_loras, + WIDTH=routing.width, + HAS_GROUPS=routing.group_ids is not None, + PAIR_INPUT=pair_input, + BLOCK_SIZE_N=block_size_n, + BLOCK_SIZE_K=int(config["BLOCK_SIZE_K"]), + STACK=stack, + WINDOWED=windowed, + num_warps=int(config["num_warps"]), + num_stages=int(config["num_stages"]), + ) diff --git a/python/sglang/kernels/ops/lora/common/lora_b.py b/python/sglang/kernels/ops/lora/common/lora_b.py new file mode 100644 index 0000000000..2fe551edb6 --- /dev/null +++ b/python/sglang/kernels/ops/lora/common/lora_b.py @@ -0,0 +1,710 @@ +"""LoRA-B expands over aligned groups or individual raw-route pairs.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from typing import NamedTuple + +import torch +import triton +import triton.language as tl + +from sglang.kernels.ops.lora.common.route_view import RouteView +from sglang.kernels.ops.lora.common.routing import ( + grouped_tile_coords, + route_bucket_ids, +) + + +@triton.jit +def _slice_of_tile( + slice_offsets_ptr, pid_n, NUM_SLICES: tl.constexpr, BLOCK_SIZE_N: tl.constexpr +): + """Map a column tile to (slice, tile in slice, slice start, width); + -1 for a tile past the last slice.""" + start = tl.zeros((), dtype=tl.int32) + slice_id = tl.full((), -1, tl.int32) + n_tile = tl.zeros((), dtype=tl.int32) + n_start = tl.zeros((), dtype=tl.int64) + width = tl.zeros((), dtype=tl.int64) + for s in tl.static_range(NUM_SLICES): + lo = tl.load(slice_offsets_ptr + s).to(tl.int64) + hi = tl.load(slice_offsets_ptr + s + 1).to(tl.int64) + tiles = ((hi - lo + BLOCK_SIZE_N - 1) // BLOCK_SIZE_N).to(tl.int32) + hit = (pid_n >= start) & (pid_n < start + tiles) + slice_id = tl.where(hit, s, slice_id) + n_tile = tl.where(hit, pid_n - start, n_tile) + n_start = tl.where(hit, lo, n_start) + width = tl.where(hit, hi - lo, width) + start += tiles + return slice_id, n_tile, n_start, width + + +class SliceGeometry(NamedTuple): + """Map expand tiles to weight slices and destination columns. + + Zero uniform_width/out_stride denotes irregular geometry. full_tiles means + every slice width is a multiple of the column tile. + """ + + slice_offsets: torch.Tensor # [S + 1] int32, the weight rows of each slice + out_offsets: torch.Tensor # [S] int32, the destination column of each slice + num_slices: int + num_column_tiles: int + uniform_width: int + out_stride: int + full_tiles: bool + block_size_n: int + + +_GEOMETRY: dict[tuple, SliceGeometry] = {} + + +def _geometry_inputs(offsets, block_size_n, out_offsets): + if ( + type(block_size_n) is not int + or block_size_n <= 0 + or block_size_n & (block_size_n - 1) + ): + raise ValueError("block_size_n must be a positive power of two") + try: + rows = tuple(offsets) + columns = rows[:-1] if out_offsets is None else tuple(out_offsets) + except TypeError: + raise ValueError("slice offsets must be integer sequences") from None + if len(rows) < 2 or any(type(o) is not int for o in rows) or rows[0] != 0: + raise ValueError("offsets must be increasing int32 prefixes starting at zero") + if out_offsets is not None and ( + len(columns) != len(rows) - 1 or any(type(o) is not int for o in columns) + ): + raise ValueError("out_offsets needs one nonnegative int32 entry per slice") + return rows, columns + + +def slice_geometry( + offsets: Sequence[int], + block_size_n: int, + device: torch.device, + out_offsets: Sequence[int] | None = None, +) -> SliceGeometry: + """Cache weight slices ``offsets`` [S+1] and destination columns [S]. + + None out_offsets uses weight-row offsets. Entries are never evicted because + graphs retain their device tables. Blocking host-to-device initialization + must precede capture; a cache miss during capture raises. + """ + offsets, out_offsets = _geometry_inputs(offsets, block_size_n, out_offsets) + if device.type != "cuda": + raise ValueError(_NOT_CUDA) + # An index-less device may name a different current device on each call. + if device.index is None: + device = torch.device("cuda", torch.cuda.current_device()) + key = (offsets, out_offsets, block_size_n, device) + geometry = _GEOMETRY.get(key) + if geometry is None: + geometry = _build_geometry(offsets, block_size_n, device, out_offsets) + _GEOMETRY[key] = geometry + return geometry + + +_NOT_CUDA = "the expand kernels read their offset tables from a CUDA device" + + +def _build_geometry( + rows: tuple[int, ...], + block_size_n: int, + device: torch.device, + columns: tuple[int, ...], +) -> SliceGeometry: + if any(o < 0 or o >= 2**31 for o in rows) or any( + lo >= hi for lo, hi in zip(rows, rows[1:]) + ): + raise ValueError("offsets must be increasing int32 prefixes starting at zero") + if any(o < 0 or o >= 2**31 for o in columns): + raise ValueError("out_offsets needs one nonnegative int32 entry per slice") + with torch.cuda.device(device): + if torch.cuda.is_current_stream_capturing(): + raise RuntimeError( + f"slice geometry {(rows, columns, block_size_n, device)} was first " + "needed inside a CUDA graph capture; run the site eagerly once " + "before capturing" + ) + widths = [hi - lo for lo, hi in zip(rows, rows[1:])] + uniform = widths[0] if len(set(widths)) == 1 else 0 + stride = columns[1] if len(columns) > 1 else uniform + regular = stride > 0 and all(c == s * stride for s, c in enumerate(columns)) + # Share an allocation for cache locality; align the columns to 16 bytes. + head = -(-len(rows) // 4) * 4 + table = torch.tensor( + list(rows) + [0] * (head - len(rows)) + list(columns), + dtype=torch.int32, + device=device, + ) + return SliceGeometry( + slice_offsets=table[: len(rows)], + out_offsets=table[head:], + num_slices=len(widths), + num_column_tiles=sum(triton.cdiv(w, block_size_n) for w in widths), + uniform_width=uniform, + out_stride=stride if regular else 0, + full_tiles=all(w % block_size_n == 0 for w in widths), + block_size_n=block_size_n, + ) + + +@triton.jit(do_not_specialize=["num_pairs", "num_m_blocks", "sorted_capacity"]) +def _grouped_lora_b_kernel( + bridge_ptr, + weight_ptr, + destination_ptr, + sorted_pair_ids_ptr, + block_bucket_ids_ptr, + num_pairs_post_padded_ptr, + lora_ranks_ptr, + scalings_ptr, + slice_offsets_ptr, + out_offsets_ptr, + num_pairs, + stride_bp, + stride_bm, + stride_bk, + stride_wg, + stride_wn, + stride_wk, + stride_dn, + stride_dt, + stride_dh, + num_m_blocks, + sorted_capacity, + num_pid_n: tl.constexpr, + WIDTH: tl.constexpr, + PAIR_BRIDGE: tl.constexpr, + RANK: tl.constexpr, + ADD_INPLACE: tl.constexpr, + ZERO_SENTINEL: tl.constexpr, + GROUPS_PER_SLOT: tl.constexpr, + WEIGHT_DIV: tl.constexpr, + NUM_SLICES: tl.constexpr, + UNIFORM_WIDTH: tl.constexpr, + OUT_STRIDE: tl.constexpr, + FULL_TILES: tl.constexpr, + BLOCK_SIZE_M: tl.constexpr, + BLOCK_SIZE_N: tl.constexpr, + BLOCK_SIZE_K: tl.constexpr, + GROUP_SIZE_M: tl.constexpr, + BRIDGE_SLICES: tl.constexpr, + PLANES: tl.constexpr = 1, + PAIR_HEADS: tl.constexpr = 1, +): + pid = tl.program_id(0) + if UNIFORM_WIDTH > 0: + tiles_per_slice: tl.constexpr = ( + UNIFORM_WIDTH + BLOCK_SIZE_N - 1 + ) // BLOCK_SIZE_N + pid_m, pid_n = grouped_tile_coords( + pid, NUM_SLICES * tiles_per_slice, num_m_blocks, GROUP_SIZE_M + ) + else: + pid_m, pid_n = grouped_tile_coords(pid, num_pid_n, num_m_blocks, GROUP_SIZE_M) + # Issue route loads together, but the JIT route's final block can be short. + num_pairs_post_padded = tl.load(num_pairs_post_padded_ptr) + bucket_id = tl.load(block_bucket_ids_ptr + pid_m) + pair_slots = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M).to(tl.int64) + pair_ids = tl.load( + sorted_pair_ids_ptr + pair_slots, + mask=pair_slots < sorted_capacity, + other=num_pairs, + ).to(tl.int64) + if pid_m * BLOCK_SIZE_M >= num_pairs_post_padded: + return + if not ZERO_SENTINEL: + if bucket_id == -1: + return + slot = bucket_id // GROUPS_PER_SLOT + if UNIFORM_WIDTH > 0: + slice_id = pid_n // tiles_per_slice + n_tile = pid_n % tiles_per_slice + n_start = (slice_id * UNIFORM_WIDTH).to(tl.int64) + width = UNIFORM_WIDTH + else: + slice_id, n_tile, n_start, width = _slice_of_tile( + slice_offsets_ptr, pid_n, NUM_SLICES, BLOCK_SIZE_N + ) + if slice_id < 0: + return + if OUT_STRIDE > 0: + out_start = (slice_id * OUT_STRIDE).to(tl.int64) + else: + out_start = tl.load(out_offsets_ptr + slice_id).to(tl.int64) + + pair_mask = pair_ids < num_pairs + n_offsets = n_tile.to(tl.int64) * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N).to( + tl.int64 + ) + if FULL_TILES: + # Every slice is whole tiles wide: no column mask to carry. + n_mask = tl.full((BLOCK_SIZE_N,), 1, tl.int1) + else: + n_mask = n_offsets < width + row_offsets = (pair_ids // PAIR_HEADS) * stride_dt + ( + pair_ids % PAIR_HEADS + ) * stride_dh + destination_ptrs = ( + destination_ptr + + row_offsets[:, None] + + (out_start + n_offsets)[None, :] * stride_dn + ) + store_mask = pair_mask[:, None] & n_mask[None, :] + if ZERO_SENTINEL: + if bucket_id == -1: + # A fresh delta buffer must not keep stale graph memory. + zeros = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) + tl.store( + destination_ptrs, + zeros.to(destination_ptr.dtype.element_ty), + mask=store_mask, + ) + return + + if lora_ranks_ptr is not None: + rank = tl.load(lora_ranks_ptr + slot).to(tl.int32) + else: + rank = RANK + if scalings_ptr is not None: + scaling = tl.load(scalings_ptr + slot).to(tl.float32) + plane = (bucket_id // WEIGHT_DIV).to(tl.int64) + if PAIR_BRIDGE: + bridge_rows = pair_ids + else: + bridge_rows = pair_ids // WIDTH + # Read the prior output before the dot so the load overlaps the operands. + if ADD_INPLACE: + prior = tl.load(destination_ptrs, mask=store_mask, other=0.0).to(tl.float32) + + if lora_ranks_ptr is not None: + if rank == 0: + return + # A single slice starts at column 0; shared bridge blocks need modulo. + if NUM_SLICES == 1: + bridge_col0 = tl.zeros((), dtype=tl.int64) + elif BRIDGE_SLICES < NUM_SLICES: + bridge_col0 = (slice_id % BRIDGE_SLICES).to(tl.int64) * rank + else: + bridge_col0 = slice_id.to(tl.int64) * rank + # Load the first K block under the pool's static rank mask, then select + # the slot's live rank so these loads do not wait for the rank lookup. + K0: tl.constexpr = min(BLOCK_SIZE_K, RANK) + k_offsets = tl.arange(0, BLOCK_SIZE_K).to(tl.int64) + k_static = k_offsets < K0 + weight_tile = ( + weight_ptr + + plane * stride_wg + + (n_start + n_offsets)[None, :] * stride_wn + + k_offsets[:, None] * stride_wk + ) + rhs = tl.load(weight_tile, mask=n_mask[None, :] & k_static[:, None], other=0.0) + lhs_ptrs = ( + bridge_ptr + + bridge_rows[:, None] * stride_bm + + (bridge_col0 + k_offsets)[None, :] * stride_bk + ) + lhs_mask = pair_mask[:, None] & k_static[None, :] + lhs = tl.load(lhs_ptrs, mask=lhs_mask, other=0.0) + if PLANES > 1: + lhs = lhs.to(tl.float32) + for p in tl.static_range(1, PLANES): + lhs += tl.load(lhs_ptrs + p * stride_bp, mask=lhs_mask, other=0.0).to( + tl.float32 + ) + if lora_ranks_ptr is not None: + if rank < K0: + k_mask = k_offsets < rank + # Select, not multiply: the unselected lanes may hold anything. + lhs = tl.where(k_mask[None, :], lhs, 0.0) + rhs = tl.where(k_mask[:, None], rhs, 0.0) + # Match a locally materialized bridge's rounding before B; an intervening + # TP reduction can change that rounding order. + accumulator = tl.dot(lhs.to(weight_ptr.dtype.element_ty), rhs, out_dtype=tl.float32) + for k_begin in range(BLOCK_SIZE_K, RANK, BLOCK_SIZE_K): + k_offsets = k_begin + tl.arange(0, BLOCK_SIZE_K).to(tl.int64) + # Mask whole blocks, not lanes: a live-rank lane mask makes these loads + # scalar, and the compiler then converts the planes to the MMA layout + # one by one. A block the rank splits is trimmed after the loads. + k_block = (k_offsets < RANK) & (k_begin < rank) + lhs_ptrs = ( + bridge_ptr + + bridge_rows[:, None] * stride_bm + + (bridge_col0 + k_offsets)[None, :] * stride_bk + ) + lhs_mask = pair_mask[:, None] & k_block[None, :] + lhs = tl.load(lhs_ptrs, mask=lhs_mask, other=0.0) + if PLANES > 1: + lhs = lhs.to(tl.float32) + for p in tl.static_range(1, PLANES): + lhs += tl.load(lhs_ptrs + p * stride_bp, mask=lhs_mask, other=0.0).to( + tl.float32 + ) + rhs = tl.load( + weight_ptr + + plane * stride_wg + + (n_start + n_offsets)[None, :] * stride_wn + + k_offsets[:, None] * stride_wk, + mask=n_mask[None, :] & k_block[:, None], + other=0.0, + ) + if lora_ranks_ptr is not None: + if (rank > k_begin) & (rank < k_begin + BLOCK_SIZE_K): + k_mask = k_offsets < rank + lhs = tl.where(k_mask[None, :], lhs, 0.0) + rhs = tl.where(k_mask[:, None], rhs, 0.0) + accumulator += tl.dot( + lhs.to(weight_ptr.dtype.element_ty), rhs, out_dtype=tl.float32 + ) + + if scalings_ptr is not None: + accumulator *= scaling + if ADD_INPLACE: + accumulator += prior + tl.store( + destination_ptrs, + accumulator.to(destination_ptr.dtype.element_ty), + mask=store_mask, + ) + + +def _k_tile(block_k: int, rank: int) -> int: + """Limit the configured tile to rounded-up rank, with MMA's minimum of 16.""" + return max(16, min(block_k, triton.next_power_of_2(rank))) + + +def grouped_lora_b( + bridge: torch.Tensor, + weight: torch.Tensor, + destination: torch.Tensor, + routing: RouteView, + *, + geometry: SliceGeometry, + config: Mapping[str, int], + add_inplace: bool, + zero_sentinel: bool, + pair_bridge: bool = True, + lora_ranks: torch.Tensor | None = None, + scalings: torch.Tensor | None = None, + weight_div: int = 1, + planes: int = 1, + pair_heads: int = 0, + bridge_slices: int = 0, +) -> None: + """Expand an aligned route with ``scaling * bridge @ weight.T`` per slice. + + ``geometry`` maps weight-row slices to destination columns, replaced unless + ``add_inplace``. Bucket ``g`` selects adapter ``g // groups_per_slot`` and + weight plane ``g // weight_div``. ``lora_ranks`` gives the slot's live rank + ``r``; None uses the pooled rank. Absent ``scalings`` means pre-scaled weights. + Slice ``s`` reads bridge columns ``[s*r, (s+1)*r)``; ``bridge_slices`` > 0 + shares blocks via ``s % bridge_slices``. ``pair_bridge=False`` reads token + ``pair // routing.width`` instead of the pair's bridge row. ``planes`` > 1 + sums split-K FP32 ``[planes, rows, bridge_width]`` in plane order; + ``bridge_width`` includes all stacked rank blocks. + + Live rank-zero slots leave output untouched. Invalid pairs are cleared only with + ``zero_sentinel``. ``pair_heads`` > 0 addresses a strided ``[tokens, heads, + width]`` destination at ``[pair // heads, pair % heads]``; otherwise it is 2D. + """ + if geometry.block_size_n != config["BLOCK_SIZE_N"]: + raise ValueError("expand BLOCK_SIZE_N must match its slice geometry") + num_pairs = routing.num_rows + if num_pairs == 0: + return + if bridge.dim() != 2 + (planes > 1): + raise ValueError( + "the grouped expand reads a [rows, rank] bridge (or [planes, rows, rank] " + "fp32 planes); an all_slots bridge (one plane per slot) needs the " + "per-row expand" + ) + if pair_heads: + if destination.dim() != 3 or destination.shape[1] != pair_heads: + raise ValueError( + "a pair-addressed destination is [tokens, heads, width] with heads == pair_heads" + ) + stride_dt, stride_dh, stride_dn = destination.stride() + else: + stride_dt, stride_dh, stride_dn = ( + destination.stride(0), + 0, + destination.stride(1), + ) + num_m_blocks = triton.cdiv(routing.sorted_pair_ids.numel(), routing.block_size) + _grouped_lora_b_kernel[(num_m_blocks * geometry.num_column_tiles,)]( + bridge, + weight, + destination, + routing.sorted_pair_ids, + routing.block_bucket_ids, + routing.num_pairs_post_padded, + lora_ranks, + scalings, + geometry.slice_offsets, + geometry.out_offsets, + num_pairs, + bridge.stride(0) if planes > 1 else 0, + bridge.stride(-2), + bridge.stride(-1), + weight.stride(0), + weight.stride(1), + weight.stride(2), + stride_dn, + stride_dt, + stride_dh, + num_m_blocks=num_m_blocks, + sorted_capacity=routing.sorted_pair_ids.numel(), + num_pid_n=geometry.num_column_tiles, + WIDTH=routing.width, + PAIR_BRIDGE=pair_bridge, + RANK=weight.shape[2], + ADD_INPLACE=add_inplace, + ZERO_SENTINEL=zero_sentinel, + GROUPS_PER_SLOT=routing.groups_per_slot, + WEIGHT_DIV=weight_div, + NUM_SLICES=geometry.num_slices, + UNIFORM_WIDTH=geometry.uniform_width, + OUT_STRIDE=geometry.out_stride, + FULL_TILES=geometry.full_tiles, + BLOCK_SIZE_M=routing.block_size, + BLOCK_SIZE_N=int(config["BLOCK_SIZE_N"]), + BLOCK_SIZE_K=_k_tile(int(config["BLOCK_SIZE_K"]), weight.shape[2]), + GROUP_SIZE_M=int(config["GROUP_SIZE_M"]), + BRIDGE_SLICES=int(bridge_slices) or geometry.num_slices, + PLANES=int(planes), + PAIR_HEADS=int(pair_heads) or 1, + num_warps=int(config["num_warps"]), + num_stages=int(config["num_stages"]), + ) + + +@triton.jit +def _per_row_lora_b_kernel( + bridge_ptr, + weight_ptr, + destination_ptr, + group_ids_ptr, + token_slots_ptr, + lora_ranks_ptr, + scalings_ptr, + slice_offsets_ptr, + out_offsets_ptr, + # Keep the weight-stride pair 8-byte aligned for a single sm103 constant load. + stride_wg, + stride_wn, + stride_wk, + stride_bs, + stride_bp, + stride_bm, + stride_bk, + stride_dm, + stride_dn, + PAIR_BRIDGE: tl.constexpr, + RANK: tl.constexpr, + ADD_INPLACE: tl.constexpr, + ZERO_SENTINEL: tl.constexpr, + GROUPS_PER_SLOT: tl.constexpr, + MAX_LORAS: tl.constexpr, + WIDTH: tl.constexpr, + HAS_GROUPS: tl.constexpr, + NUM_SLICES: tl.constexpr, + UNIFORM_WIDTH: tl.constexpr, + OUT_STRIDE: tl.constexpr, + FULL_TILES: tl.constexpr, + BLOCK_SIZE_N: tl.constexpr, + BLOCK_SIZE_K: tl.constexpr, + BRIDGE_SLICES: tl.constexpr, + PLANES: tl.constexpr = 1, +): + # GEMV reduction order differs from grouped B's dot. The grid has no tail rows. + pair_id = tl.program_id(0) + pid_n = tl.program_id(1) + pair64 = pair_id.to(tl.int64) + bucket_id = route_bucket_ids( + group_ids_ptr, + token_slots_ptr, + pair_id, + pair_id >= 0, + GROUPS_PER_SLOT=GROUPS_PER_SLOT, + MAX_LORAS=MAX_LORAS, + WIDTH=WIDTH, + HAS_GROUPS=HAS_GROUPS, + ) + if not ZERO_SENTINEL: + if bucket_id == -1: + return + safe_bucket_id = tl.maximum(bucket_id, 0).to(tl.int64) + slot = safe_bucket_id // GROUPS_PER_SLOT + if lora_ranks_ptr is not None: + rank = tl.load(lora_ranks_ptr + slot).to(tl.int32) + else: + rank = RANK + if UNIFORM_WIDTH > 0: + tiles_per_slice: tl.constexpr = ( + UNIFORM_WIDTH + BLOCK_SIZE_N - 1 + ) // BLOCK_SIZE_N + slice_id = pid_n // tiles_per_slice + n_tile = pid_n % tiles_per_slice + n_start = (slice_id * UNIFORM_WIDTH).to(tl.int64) + width = UNIFORM_WIDTH + else: + slice_id, n_tile, n_start, width = _slice_of_tile( + slice_offsets_ptr, pid_n, NUM_SLICES, BLOCK_SIZE_N + ) + if slice_id < 0: + return + if OUT_STRIDE > 0: + out_start = (slice_id * OUT_STRIDE).to(tl.int64) + else: + out_start = tl.load(out_offsets_ptr + slice_id).to(tl.int64) + n_offsets = n_tile.to(tl.int64) * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N).to( + tl.int64 + ) + if FULL_TILES: + n_mask = tl.full((BLOCK_SIZE_N,), 1, tl.int1) + else: + n_mask = n_offsets < width + destination_ptrs = ( + destination_ptr + pair64 * stride_dm + (out_start + n_offsets) * stride_dn + ) + if ZERO_SENTINEL: + if bucket_id == -1: + # A fresh delta buffer must not keep stale graph memory. + zeros = tl.zeros((BLOCK_SIZE_N,), dtype=tl.float32) + tl.store( + destination_ptrs, + zeros.to(destination_ptr.dtype.element_ty), + mask=n_mask, + ) + return + + if lora_ranks_ptr is not None: + if rank == 0: + return + + if PAIR_BRIDGE: + bridge_row = bridge_ptr + slot * stride_bs + pair64 * stride_bm + else: + bridge_row = bridge_ptr + slot * stride_bs + (pair64 // WIDTH) * stride_bm + if ADD_INPLACE: + prior = tl.load(destination_ptrs, mask=n_mask, other=0.0).to(tl.float32) + if BRIDGE_SLICES < NUM_SLICES: + bridge_col0 = (slice_id % BRIDGE_SLICES).to(tl.int64) * rank + else: + bridge_col0 = slice_id.to(tl.int64) * rank + accumulator = tl.zeros((BLOCK_SIZE_N,), dtype=tl.float32) + for k_begin in range(0, RANK, BLOCK_SIZE_K): + k_offsets = k_begin + tl.arange(0, BLOCK_SIZE_K).to(tl.int64) + # Mask whole blocks, as grouped B does: a live-rank lane mask makes + # every load scalar. A block the rank splits is trimmed after the loads. + k_block = (k_offsets < RANK) & (k_begin < rank) + lhs_ptrs = bridge_row + (bridge_col0 + k_offsets) * stride_bk + lhs = tl.load(lhs_ptrs, mask=k_block, other=0.0) + if PLANES > 1: + lhs = lhs.to(tl.float32) + for p in tl.static_range(1, PLANES): + lhs += tl.load(lhs_ptrs + p * stride_bp, mask=k_block, other=0.0).to( + tl.float32 + ) + rhs = tl.load( + weight_ptr + + safe_bucket_id * stride_wg + + (n_start + n_offsets)[:, None] * stride_wn + + k_offsets[None, :] * stride_wk, + mask=n_mask[:, None] & k_block[None, :], + other=0.0, + ) + if lora_ranks_ptr is not None: + if (rank > k_begin) & (rank < k_begin + BLOCK_SIZE_K): + k_mask = k_offsets < rank + lhs = tl.where(k_mask, lhs, 0.0) + rhs = tl.where(k_mask[None, :], rhs, 0.0) + # Match grouped B's bridge cast before the FP32 multiply. + lhs = lhs.to(weight_ptr.dtype.element_ty).to(tl.float32) + accumulator += tl.sum(rhs.to(tl.float32) * lhs[None, :], axis=1) + + if scalings_ptr is not None: + accumulator *= tl.load(scalings_ptr + slot).to(tl.float32) + if ADD_INPLACE: + accumulator += prior + tl.store( + destination_ptrs, + accumulator.to(destination_ptr.dtype.element_ty), + mask=n_mask, + ) + + +def per_row_lora_b( + bridge: torch.Tensor, + weight: torch.Tensor, + destination: torch.Tensor, + routing: RouteView, + *, + geometry: SliceGeometry, + config: Mapping[str, int], + add_inplace: bool, + zero_sentinel: bool, + pair_bridge: bool = True, + lora_ranks: torch.Tensor | None = None, + scalings: torch.Tensor | None = None, + planes: int = 1, + slot_planes: bool = False, + bridge_slices: int = 0, +) -> None: + """Use ``grouped_lora_b``'s contract over a raw route and 2D destination. + + Weights have one plane per bucket. ``slot_planes`` reads a ``[slots, rows, + bridge_width]`` bridge instead of split-K planes; the modes cannot be combined. + """ + if geometry.block_size_n != config["BLOCK_SIZE_N"]: + raise ValueError("expand BLOCK_SIZE_N must match its slice geometry") + num_pairs = routing.num_rows + if num_pairs == 0: + return + if (slot_planes and planes > 1) or bridge.dim() != 2 + (slot_planes or planes > 1): + raise ValueError( + "the per-row expand reads a [rows, rank] bridge, [slots, rows, rank] " + "slot planes or [planes, rows, rank] fp32 split-K planes" + ) + _per_row_lora_b_kernel[(num_pairs, geometry.num_column_tiles)]( + bridge, + weight, + destination, + routing.kernel_groups, + routing.token_slots, + lora_ranks, + scalings, + geometry.slice_offsets, + geometry.out_offsets, + weight.stride(0), + weight.stride(1), + weight.stride(2), + bridge.stride(0) if slot_planes else 0, + bridge.stride(0) if planes > 1 else 0, + bridge.stride(-2), + bridge.stride(-1), + destination.stride(0), + destination.stride(1), + PAIR_BRIDGE=pair_bridge, + RANK=weight.shape[2], + ADD_INPLACE=add_inplace, + ZERO_SENTINEL=zero_sentinel, + GROUPS_PER_SLOT=routing.groups_per_slot, + MAX_LORAS=routing.max_loras, + WIDTH=routing.width, + HAS_GROUPS=routing.group_ids is not None, + NUM_SLICES=geometry.num_slices, + UNIFORM_WIDTH=geometry.uniform_width, + OUT_STRIDE=geometry.out_stride, + FULL_TILES=geometry.full_tiles, + BLOCK_SIZE_N=int(config["BLOCK_SIZE_N"]), + BLOCK_SIZE_K=_k_tile(int(config["BLOCK_SIZE_K"]), weight.shape[2]), + BRIDGE_SLICES=int(bridge_slices) or geometry.num_slices, + PLANES=int(planes), + num_warps=int(config["num_warps"]), + num_stages=int(config["num_stages"]), + ) diff --git a/python/sglang/kernels/ops/lora/common/route_view.py b/python/sglang/kernels/ops/lora/common/route_view.py new file mode 100644 index 0000000000..ca13f264f1 --- /dev/null +++ b/python/sglang/kernels/ops/lora/common/route_view.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +from enum import Enum + +import msgspec +import torch + + +class RouteViewKind(str, Enum): + RAW = "raw" + ALIGNED = "aligned" + + +class RouteView(msgspec.Struct, frozen=True, kw_only=True): + """Token or (token, group) routes, optionally sorted and padded to blocks. + + ALIGNED views group rows by adapter/group bucket. With groups_per_slot=1, + all nonnegative group IDs share their adapter's bucket. + """ + + view: RouteViewKind + block_size: int + token_slots: torch.Tensor + group_ids: torch.Tensor | None + groups_per_slot: int + max_loras: int + maybe_sorted_pair_ids: torch.Tensor | None = None + maybe_block_bucket_ids: torch.Tensor | None = None + maybe_num_pairs_post_padded: torch.Tensor | None = None + + @property + def num_tokens(self) -> int: + return self.token_slots.numel() + + @property + def num_rows(self) -> int: + return ( + self.token_slots.numel() + if self.group_ids is None + else self.group_ids.numel() + ) + + @property + def width(self) -> int: + return 1 if self.group_ids is None else self.group_ids.shape[1] + + @property + def kernel_groups(self) -> torch.Tensor: + """Group IDs, or an unread placeholder when HAS_GROUPS=False.""" + return self.token_slots if self.group_ids is None else self.group_ids + + def _require(self, value, field: str, needed: RouteViewKind): + if value is None: + raise ValueError( + f"route view {self.view.value!r} did not build {field}; the " + f"consumer must request view {needed.value!r} or derive it inline" + ) + return value + + @property + def sorted_pair_ids(self) -> torch.Tensor: + return self._require( + self.maybe_sorted_pair_ids, "sorted_pair_ids", RouteViewKind.ALIGNED + ) + + @property + def block_bucket_ids(self) -> torch.Tensor: + return self._require( + self.maybe_block_bucket_ids, + "block_bucket_ids", + RouteViewKind.ALIGNED, + ) + + @property + def num_pairs_post_padded(self) -> torch.Tensor: + return self._require( + self.maybe_num_pairs_post_padded, + "num_pairs_post_padded", + RouteViewKind.ALIGNED, + ) diff --git a/python/sglang/kernels/ops/lora/common/routing.py b/python/sglang/kernels/ops/lora/common/routing.py new file mode 100644 index 0000000000..23b6c699e7 --- /dev/null +++ b/python/sglang/kernels/ops/lora/common/routing.py @@ -0,0 +1,812 @@ +"""Build and index adapter/group routes for dense and MoE LoRA.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch +import triton +import triton.language as tl + +from sglang.kernels.ops.lora.common.route_view import RouteView, RouteViewKind +from sglang.kernels.ops.lora.moe.virtual_experts import ( + _align_block_size_jit, +) + +if TYPE_CHECKING: + from sglang.srt.lora.workspace import LoraWorkspace + +# Route-builder dispatch limits; CUDA alignment caps at 8192 buckets. +_LARGE_ROUTE_MIN_BUCKETS = 8192 +_LARGE_ROUTE_MIN_PAIRS = 16384 +_SMALL_ROUTE_MAX_PAIRS = 512 +_SMALL_ROUTE_LOW_BUCKET_MAX_BUCKETS = 4 +_SMALL_ROUTE_LOW_BUCKET_MAX_PAIRS = 768 + +_HIST_BLOCK = 512 +_HIST_WARPS = 8 +_EXPAND_BLOCK = 128 +_EXPAND_WARPS = 4 +_SCAN_CHUNK = 2048 +_SCAN_WARPS = 4 + +# Use in-block histograms to reduce global atomics within these limits. +_COUNT_MAX_BINS = 512 +_COUNT_MIN_PAIRS = 16384 +_CLAIM_MIN_PAIRS_PER_BUCKET = 12288 + + +@triton.jit +def route_bucket_ids( + group_ids_ptr, + token_slots_ptr, + pair_ids, + pair_mask, + GROUPS_PER_SLOT: tl.constexpr, + MAX_LORAS: tl.constexpr, + WIDTH: tl.constexpr, + HAS_GROUPS: tl.constexpr, +): + # Invalid slots/groups map to -1. With one group per slot, any nonnegative + # group folds into that slot; otherwise bound it to the bucket table. + token_ids = pair_ids // WIDTH + slots = tl.load(token_slots_ptr + token_ids, mask=pair_mask, other=-1).to(tl.int32) + live = (slots >= 0) & (slots < MAX_LORAS) + if HAS_GROUPS: + groups = tl.load(group_ids_ptr + pair_ids, mask=pair_mask, other=-1).to( + tl.int32 + ) + live = live & (groups >= 0) + if GROUPS_PER_SLOT == 1: + buckets = slots + else: + live = live & (groups < GROUPS_PER_SLOT) + buckets = slots * GROUPS_PER_SLOT + groups + else: + buckets = slots + return tl.where(live, buckets, -1) + + +@triton.jit +def grouped_tile_coords( + pid, + num_pid_n, + num_m_blocks, + GROUP_SIZE_M: tl.constexpr, +): + # Group M blocks for weight reuse; keep num_m_blocks runtime to avoid + # compiling a kernel per prefill size. + programs_per_group = GROUP_SIZE_M * num_pid_n + group_id = pid // programs_per_group + first_pid_m = group_id * GROUP_SIZE_M + group_size_m = tl.minimum(num_m_blocks - first_pid_m, GROUP_SIZE_M) + pid_m = first_pid_m + ((pid % programs_per_group) % group_size_m) + pid_n = (pid % programs_per_group) // group_size_m + return pid_m, pid_n + + +@triton.jit +def _add_counts( + counts_ptr, + bucket_ids, + mask, + NUM_BUCKETS: tl.constexpr, + BINS: tl.constexpr, +): + buckets = tl.where(bucket_ids < 0, NUM_BUCKETS - 1, bucket_ids) + if BINS == 0: + tl.atomic_add(counts_ptr + buckets, 1, mask=mask) + else: + mine = tl.histogram(tl.where(mask, buckets, BINS - 1), BINS) + bins = tl.arange(0, BINS) + tl.atomic_add(counts_ptr + bins, mine, mask=(bins < NUM_BUCKETS) & (mine > 0)) + + +@triton.jit +def _route_histogram_kernel( + group_ids_ptr, + token_slots_ptr, + counts_ptr, + num_pairs, + NUM_BUCKETS: tl.constexpr, + GROUPS_PER_SLOT: tl.constexpr, + MAX_LORAS: tl.constexpr, + WIDTH: tl.constexpr, + HAS_GROUPS: tl.constexpr, + BLOCK: tl.constexpr, + BINS: tl.constexpr, + USE_PDL: tl.constexpr, +): + # The previous scan (or first allocation) cleared counts. + pair_ids = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK) + pair_mask = pair_ids < num_pairs + _add_counts( + counts_ptr, + route_bucket_ids( + group_ids_ptr, + token_slots_ptr, + pair_ids, + pair_mask, + GROUPS_PER_SLOT=GROUPS_PER_SLOT, + MAX_LORAS=MAX_LORAS, + WIDTH=WIDTH, + HAS_GROUPS=HAS_GROUPS, + ), + pair_mask, + NUM_BUCKETS=NUM_BUCKETS, + BINS=BINS, + ) + if USE_PDL: + tl.extra.cuda.gdc_launch_dependents() + + +@triton.jit +def _scan_one( + counts_ptr, + block_cumulative_ptr, + cursor_ptr, + bucket_end_ptr, + padded_pairs_ptr, + num_buckets, + BLOCK_SIZE_M: tl.constexpr, + CHUNK: tl.constexpr, +): + # Clear counts during the scan for the next replay. + running = 0 + for base in range(0, num_buckets, CHUNK): + offsets = base + tl.arange(0, CHUNK) + mask = offsets < num_buckets + counts = tl.load(counts_ptr + offsets, mask=mask, other=0) + tl.store(counts_ptr + offsets, 0, mask=mask) + blocks = (counts + BLOCK_SIZE_M - 1) // BLOCK_SIZE_M + block_start = running + tl.cumsum(blocks) - blocks + tl.store(block_cumulative_ptr + offsets, block_start, mask=mask) + slot_start = block_start * BLOCK_SIZE_M + tl.store(cursor_ptr + offsets, slot_start, mask=mask) + tl.store(bucket_end_ptr + offsets, slot_start + counts, mask=mask) + running += tl.sum(blocks) + tl.store(block_cumulative_ptr + num_buckets, running) + tl.store(padded_pairs_ptr, running * BLOCK_SIZE_M) + + +@triton.jit +def _route_scan_kernel( + counts_ptr, + block_cumulative_ptr, + cursor_ptr, + bucket_end_ptr, + padded_pairs_ptr, + num_buckets, + BLOCK_SIZE_M: tl.constexpr, + CHUNK: tl.constexpr, + USE_PDL: tl.constexpr, +): + if USE_PDL: + tl.extra.cuda.gdc_wait() + # Both place paths wait before reading scan outputs. + tl.extra.cuda.gdc_launch_dependents() + _scan_one( + counts_ptr, + block_cumulative_ptr, + cursor_ptr, + bucket_end_ptr, + padded_pairs_ptr, + num_buckets, + BLOCK_SIZE_M=BLOCK_SIZE_M, + CHUNK=CHUNK, + ) + + +@triton.jit +def _label_blocks( + pid, + block_cumulative_ptr, + bucket_end_ptr, + sorted_pair_ids_ptr, + block_bucket_ids_ptr, + num_blocks, + num_pairs, + NUM_BUCKETS: tl.constexpr, + NUM_ROUTE_BUCKETS: tl.constexpr, + BLOCK: tl.constexpr, + BLOCK_SIZE_M: tl.constexpr, + SEARCH_STEPS: tl.constexpr, +): + block_ids = pid * BLOCK + tl.arange(0, BLOCK) + block_mask = block_ids < num_blocks + low = tl.zeros(block_ids.shape, dtype=tl.int32) + high = tl.full(block_ids.shape, NUM_BUCKETS, dtype=tl.int32) + for _ in range(SEARCH_STEPS): + midpoint = (low + high) // 2 + bound = tl.load( + block_cumulative_ptr + tl.minimum(midpoint + 1, NUM_BUCKETS), + mask=block_mask, + other=0, + ) + take_upper = block_ids >= bound + low = tl.where(take_upper & (low < high), midpoint + 1, low) + high = tl.where(take_upper | (low >= high), high, midpoint) + owner = tl.minimum(low, NUM_BUCKETS - 1) + total_blocks = tl.load(block_cumulative_ptr + NUM_BUCKETS) + in_plan = block_mask & (block_ids < total_blocks) + tl.store( + block_bucket_ids_ptr + block_ids, + tl.where(in_plan & (owner < NUM_ROUTE_BUCKETS), owner, -1), + mask=block_mask, + ) + # B reads sentinel blocks too, so initialize their padding slots. + real_end = tl.load(bucket_end_ptr + owner, mask=in_plan, other=0) + slots = block_ids[:, None] * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)[None, :] + tl.store( + sorted_pair_ids_ptr + slots, + num_pairs, + mask=in_plan[:, None] & (slots >= real_end[:, None]), + ) + + +@triton.jit +def _claim_slots( + cursor_ptr, + bucket_ids, + mask, + NUM_BUCKETS: tl.constexpr, + PER_BLOCK: tl.constexpr, +): + # Per-block claims may reorder pairs within each bucket. + buckets = tl.where(bucket_ids < 0, NUM_BUCKETS - 1, bucket_ids) + if not PER_BLOCK: + return tl.atomic_add(cursor_ptr + buckets, 1, mask=mask) + slots = tl.zeros(buckets.shape, dtype=tl.int32) + for bucket in tl.static_range(NUM_BUCKETS): + mine = tl.where(mask & (buckets == bucket), 1, 0).to(tl.int32) + start = tl.atomic_add(cursor_ptr + bucket, tl.sum(mine)) + slots = tl.where(mine == 1, start + tl.cumsum(mine) - mine, slots) + return slots + + +@triton.jit +def _route_place_kernel( + group_ids_ptr, + token_slots_ptr, + cursor_ptr, + bucket_end_ptr, + block_cumulative_ptr, + sorted_ptr, + block_bucket_ids_ptr, + num_blocks, + label_programs, + num_pairs, + NUM_BUCKETS: tl.constexpr, + NUM_ROUTE_BUCKETS: tl.constexpr, + GROUPS_PER_SLOT: tl.constexpr, + MAX_LORAS: tl.constexpr, + WIDTH: tl.constexpr, + HAS_GROUPS: tl.constexpr, + BLOCK: tl.constexpr, + BLOCK_SIZE_M: tl.constexpr, + SEARCH_STEPS: tl.constexpr, + CLAIM_PER_BLOCK: tl.constexpr, + USE_PDL: tl.constexpr, +): + # Low program IDs label blocks; the rest place pairs. + pid = tl.program_id(0) + if pid < label_programs: + if USE_PDL: + tl.extra.cuda.gdc_wait() + _label_blocks( + pid, + block_cumulative_ptr, + bucket_end_ptr, + sorted_ptr, + block_bucket_ids_ptr, + num_blocks, + num_pairs, + NUM_BUCKETS=NUM_BUCKETS, + NUM_ROUTE_BUCKETS=NUM_ROUTE_BUCKETS, + BLOCK=BLOCK, + BLOCK_SIZE_M=BLOCK_SIZE_M, + SEARCH_STEPS=SEARCH_STEPS, + ) + return + + # Recompute keys while the scan runs; this needs no scan output. + pair_ids = (pid - label_programs) * BLOCK + tl.arange(0, BLOCK) + pair_mask = pair_ids < num_pairs + bucket_ids = route_bucket_ids( + group_ids_ptr, + token_slots_ptr, + pair_ids, + pair_mask, + GROUPS_PER_SLOT=GROUPS_PER_SLOT, + MAX_LORAS=MAX_LORAS, + WIDTH=WIDTH, + HAS_GROUPS=HAS_GROUPS, + ) + if USE_PDL: + # Cursors are this path's first scan dependency. + tl.extra.cuda.gdc_wait() + slots = _claim_slots( + cursor_ptr, + bucket_ids, + pair_mask, + NUM_BUCKETS=NUM_BUCKETS, + PER_BLOCK=CLAIM_PER_BLOCK, + ) + tl.store(sorted_ptr + slots, pair_ids, mask=pair_mask) + + +@triton.jit +def _build_route_bucket_ids_kernel( + group_ids_ptr, + token_slots_ptr, + buckets_ptr, + num_pairs, + GROUPS_PER_SLOT: tl.constexpr, + MAX_LORAS: tl.constexpr, + WIDTH: tl.constexpr, + HAS_GROUPS: tl.constexpr, + BLOCK_SIZE: tl.constexpr, +): + pair_ids = tl.program_id(0) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + pair_mask = pair_ids < num_pairs + buckets = route_bucket_ids( + group_ids_ptr, + token_slots_ptr, + pair_ids, + pair_mask, + GROUPS_PER_SLOT=GROUPS_PER_SLOT, + MAX_LORAS=MAX_LORAS, + WIDTH=WIDTH, + HAS_GROUPS=HAS_GROUPS, + ) + tl.store(buckets_ptr + pair_ids, buckets, mask=pair_mask) + + +def _histogram_bins(num_buckets: int, num_pairs: int) -> int: + # 0 = one atomic per pair; otherwise in-block counting over 2^k bins. + if num_buckets >= _COUNT_MAX_BINS or num_pairs < _COUNT_MIN_PAIRS: + return 0 + return 1 << num_buckets.bit_length() # the extra bin holds the masked-off lanes + + +def _aligned_route_capacity( + num_pairs: int, + block_size: int, + num_route_buckets: int, +) -> int: + """Bound padded pairs, including the invalid-ID bucket.""" + if num_pairs == 0: + return 0 + max_nonempty_buckets = min(num_pairs, num_route_buckets + 1) + upper_bound = num_pairs + max_nonempty_buckets * (block_size - 1) + return triton.cdiv(triton.cdiv(upper_bound, block_size) * block_size, 4) * 4 + + +def _aligned_route_scratch( + workspace: LoraWorkspace | None, + *, + prefix: str, + num_buckets: int, + capacity: int, + block_size: int, + device: torch.device, +) -> dict[str, torch.Tensor]: + def alloc(name: str, numel: int, zero: bool = False) -> torch.Tensor: + if workspace is None: + make = torch.zeros if zero else torch.empty + return make((numel,), dtype=torch.int32, device=device) + return workspace.tensor( + f"{prefix}:{name}", + (numel,), + dtype=torch.int32, + device=device, + zero_on_first_allocation=zero, + ) + + return { + "counts": alloc("counts", num_buckets, zero=True), + "block_cumulative": alloc("block_cumulative", num_buckets + 1), + "cursor": alloc("cursor", num_buckets), + "bucket_end": alloc("bucket_end", num_buckets), + "padded_pairs": alloc("padded_pairs", 1), + "sorted": alloc("sorted", capacity), + "block_bucket_ids": alloc("block_bucket_ids", capacity // block_size), + } + + +def _build_large_route( + token_slots: torch.Tensor, + group_ids: torch.Tensor | None, + *, + groups_per_slot: int, + max_loras: int, + block_size: int, + workspace: LoraWorkspace | None, + tensor_prefix: str | None, + capacity: int | None = None, +) -> RouteView: + from sglang.kernels.jit.utils import is_arch_support_pdl + + groups = token_slots if group_ids is None else group_ids # placeholder pointer + num_pairs = groups.numel() + width = 1 if group_ids is None else group_ids.shape[1] + num_route_buckets = groups_per_slot * max_loras + num_buckets = num_route_buckets + 1 + # Shared buffers may reserve more rows than this builder needs. + capacity = max( + _aligned_route_capacity(num_pairs, block_size, num_route_buckets), capacity or 0 + ) + capacity = triton.cdiv(capacity, block_size) * block_size + if num_route_buckets + 1 >= 2**31 or capacity >= 2**31: + raise ValueError( + f"aligned routes use int32 plan math: {tensor_prefix} needs " + f"{num_route_buckets + 1} buckets and {capacity} slots, both must be < 2**31" + ) + # Scratch per bucket layout: one prefix may carry routes of different widths. + own = _aligned_route_scratch( + workspace, + prefix=f"{tensor_prefix}:groups{groups_per_slot}", + num_buckets=num_buckets, + capacity=capacity, + block_size=block_size, + device=token_slots.device, + ) + use_pdl = is_arch_support_pdl() + pdl_kwargs = {"launch_pdl": True} if use_pdl else {} + _route_histogram_kernel[(triton.cdiv(max(num_pairs, 1), _HIST_BLOCK),)]( + groups, + token_slots, + own["counts"], + num_pairs, + NUM_BUCKETS=num_buckets, + GROUPS_PER_SLOT=groups_per_slot, + MAX_LORAS=max_loras, + WIDTH=width, + HAS_GROUPS=group_ids is not None, + BLOCK=_HIST_BLOCK, + BINS=_histogram_bins(num_buckets, num_pairs), + USE_PDL=use_pdl, + num_warps=_HIST_WARPS, + ) + _route_scan_kernel[(1,)]( + own["counts"], + own["block_cumulative"], + own["cursor"], + own["bucket_end"], + own["padded_pairs"], + num_buckets, + BLOCK_SIZE_M=block_size, + CHUNK=_SCAN_CHUNK, + USE_PDL=use_pdl, + num_warps=_SCAN_WARPS, + **pdl_kwargs, + ) + num_blocks = capacity // block_size + label_programs = triton.cdiv(max(num_blocks, 1), _EXPAND_BLOCK) + _route_place_kernel[ + (label_programs + triton.cdiv(max(num_pairs, 1), _EXPAND_BLOCK),) + ]( + groups, + token_slots, + own["cursor"], + own["bucket_end"], + own["block_cumulative"], + own["sorted"], + own["block_bucket_ids"], + num_blocks, + label_programs, + num_pairs, + NUM_BUCKETS=num_buckets, + NUM_ROUTE_BUCKETS=num_buckets - 1, + GROUPS_PER_SLOT=groups_per_slot, + MAX_LORAS=max_loras, + WIDTH=width, + HAS_GROUPS=group_ids is not None, + BLOCK=_EXPAND_BLOCK, + BLOCK_SIZE_M=block_size, + # Include the sentinel in the binary-search depth. + SEARCH_STEPS=num_buckets.bit_length(), + CLAIM_PER_BLOCK=num_pairs >= _CLAIM_MIN_PAIRS_PER_BUCKET * num_buckets, + USE_PDL=use_pdl, + num_warps=_EXPAND_WARPS, + **pdl_kwargs, + ) + return RouteView( + view=RouteViewKind.ALIGNED, + block_size=block_size, + token_slots=token_slots, + group_ids=group_ids, + groups_per_slot=groups_per_slot, + max_loras=max_loras, + maybe_sorted_pair_ids=own["sorted"], + maybe_block_bucket_ids=own["block_bucket_ids"], + maybe_num_pairs_post_padded=own["padded_pairs"], + ) + + +def _build_route_bucket_ids( + token_slots: torch.Tensor, + group_ids: torch.Tensor | None, + *, + groups_per_slot: int, + max_loras: int, + out: torch.Tensor, +) -> torch.Tensor: + groups = token_slots if group_ids is None else group_ids # placeholder pointer + num_pairs = out.numel() + if num_pairs == 0: + return out + + block_size = 1024 + _build_route_bucket_ids_kernel[(triton.cdiv(num_pairs, block_size),)]( + groups, + token_slots, + out, + num_pairs, + GROUPS_PER_SLOT=groups_per_slot, + MAX_LORAS=max_loras, + WIDTH=1 if group_ids is None else group_ids.shape[1], + HAS_GROUPS=group_ids is not None, + BLOCK_SIZE=block_size, + ) + return out + + +# Like CUDA alignment, the small builder places the sentinel bucket first. +# Pair order within each bucket is arbitrary. + + +@triton.jit +def _build_small_route_kernel( + group_ids_ptr, + token_slots_ptr, + sorted_pair_ids_ptr, + block_bucket_ids_ptr, + num_pairs_post_padded_ptr, + scratch_ptr, # int32 [2 * NUM_BINS]: bucket counters, then padded bucket starts + num_pairs, + num_route_buckets, + capacity, + num_blocks, + GROUPS_PER_SLOT: tl.constexpr, + MAX_LORAS: tl.constexpr, + WIDTH: tl.constexpr, + HAS_GROUPS: tl.constexpr, + BLOCK_SIZE: tl.constexpr, + LANES: tl.constexpr, + NUM_BINS: tl.constexpr, + FILL: tl.constexpr, +): + lane = tl.arange(0, LANES) + pair_mask = lane < num_pairs + bucket = route_bucket_ids( + group_ids_ptr, + token_slots_ptr, + lane, + pair_mask, + GROUPS_PER_SLOT=GROUPS_PER_SLOT, + MAX_LORAS=MAX_LORAS, + WIDTH=WIDTH, + HAS_GROUPS=HAS_GROUPS, + ) + # Bin 0 is the sentinel bucket of the dead rows; bucket b is bin b + 1. + bin_id = tl.where(bucket >= 0, bucket + 1, 0) + # The counters are cleared here, so a graph replay is self-contained. + for off in range(0, NUM_BINS, FILL): + idx = off + tl.arange(0, FILL) + tl.store( + scratch_ptr + idx, tl.zeros([FILL], dtype=tl.int32), mask=idx < NUM_BINS + ) + tl.debug_barrier() + rank = tl.atomic_add(scratch_ptr + bin_id, 1, mask=pair_mask) + tl.debug_barrier() + bins = tl.arange(0, NUM_BINS) + counts = tl.load( + scratch_ptr + bins, + mask=bins < num_route_buckets + 1, + other=0, + cache_modifier=".cg", + ) + padded = (counts + BLOCK_SIZE - 1) // BLOCK_SIZE * BLOCK_SIZE + starts = tl.cumsum(padded, axis=0) - padded + tl.store(scratch_ptr + NUM_BINS + bins, starts) + total = tl.sum(padded, axis=0) + for off in range(0, capacity, FILL): + idx = off + tl.arange(0, FILL) + tl.store( + sorted_pair_ids_ptr + idx, + tl.zeros([FILL], dtype=tl.int32) + num_pairs, + mask=idx < capacity, + ) + for off in range(0, num_blocks, FILL): + idx = off + tl.arange(0, FILL) + tl.store( + block_bucket_ids_ptr + idx, + tl.zeros([FILL], dtype=tl.int32) - 1, + mask=idx < num_blocks, + ) + tl.debug_barrier() + pos = tl.load(scratch_ptr + NUM_BINS + bin_id, cache_modifier=".cg") + rank + tl.store(sorted_pair_ids_ptr + pos, lane, mask=pair_mask) + tl.store(block_bucket_ids_ptr + pos // BLOCK_SIZE, bin_id - 1, mask=pair_mask) + tl.store(num_pairs_post_padded_ptr, total) + + +def _build_small_route( + token_slots: torch.Tensor, + group_ids: torch.Tensor | None, + *, + groups_per_slot: int, + max_loras: int, + block_size: int, + workspace: LoraWorkspace | None, + tensor_prefix: str | None, +) -> RouteView: + groups = token_slots if group_ids is None else group_ids # placeholder pointer + shape = (token_slots.numel(), 1) if group_ids is None else tuple(group_ids.shape) + num_pairs = shape[0] * shape[1] + num_route_buckets = groups_per_slot * max_loras + # The CUDA builder's capacity, so consumers size their grids the same way. + if num_pairs < num_route_buckets + 1: + capacity = num_pairs * block_size + else: + capacity = num_pairs + (num_route_buckets + 1) * (block_size - 1) + capacity = (capacity + 3) & ~3 + num_blocks = triton.cdiv(capacity, block_size) + lanes = max(16, triton.next_power_of_2(num_pairs)) + num_bins = max(16, triton.next_power_of_2(num_route_buckets + 1)) + device = token_slots.device + if workspace is not None: + prefix = f"{tensor_prefix}:small" + + def alloc(name: str, numel: int) -> torch.Tensor: + return workspace.tensor( + f"{prefix}:{name}", (numel,), dtype=torch.int32, device=device + ) + + else: + + def alloc(name: str, numel: int) -> torch.Tensor: + return torch.empty((numel,), dtype=torch.int32, device=device) + + sorted_pair_ids = alloc("sorted", capacity) + block_bucket_ids = alloc("block_bucket_ids", num_blocks) + num_pairs_post_padded = alloc("num_post", 1) + scratch = alloc("scratch", 2 * num_bins) + _build_small_route_kernel[(1,)]( + groups, + token_slots, + sorted_pair_ids, + block_bucket_ids, + num_pairs_post_padded, + scratch, + num_pairs, + num_route_buckets, + capacity, + num_blocks, + GROUPS_PER_SLOT=groups_per_slot, + MAX_LORAS=max_loras, + WIDTH=shape[1], + HAS_GROUPS=group_ids is not None, + BLOCK_SIZE=block_size, + LANES=lanes, + NUM_BINS=num_bins, + FILL=1024, + num_warps=8 if max(lanes, num_bins) >= 1024 else 4, + ) + return RouteView( + view=RouteViewKind.ALIGNED, + block_size=block_size, + token_slots=token_slots, + group_ids=group_ids, + groups_per_slot=groups_per_slot, + max_loras=max_loras, + maybe_sorted_pair_ids=sorted_pair_ids, + maybe_block_bucket_ids=block_bucket_ids, + maybe_num_pairs_post_padded=num_pairs_post_padded, + ) + + +def build_route( + token_slots: torch.Tensor, + *, + group_ids: torch.Tensor | None = None, + groups_per_slot: int = 1, + max_loras: int, + block_size: int, + view: RouteViewKind | str = RouteViewKind.ALIGNED, + workspace: LoraWorkspace | None = None, + tensor_prefix: str | None = None, + capacity: int | None = None, +) -> RouteView: + """Route tokens, or flattened ``group_ids`` [tokens, width] pairs. + + For ALIGNED views, ``capacity`` forces the large builder and reserves at + least that many rows, rounded up to a block. + """ + try: + view = RouteViewKind(view) + except (TypeError, ValueError): + raise ValueError( + f"unknown route view {view!r}; expected one of " + f"{tuple(kind.value for kind in RouteViewKind)}" + ) from None + if type(block_size) is not int or block_size <= 0: + raise ValueError("block_size must be a positive integer") + if capacity is not None and (type(capacity) is not int or capacity < 0): + raise ValueError("capacity must be a non-negative integer") + if groups_per_slot > 1 and group_ids is None: + raise ValueError("a route with more than one group per slot needs group_ids") + common = { + "view": view, + "block_size": block_size, + "token_slots": token_slots, + "group_ids": group_ids, + "groups_per_slot": groups_per_slot, + "max_loras": max_loras, + } + if view is RouteViewKind.RAW: + return RouteView(**common) + + shape = (token_slots.numel(), 1) if group_ids is None else tuple(group_ids.shape) + rows = shape[0] * shape[1] + num_route_buckets = groups_per_slot * max_loras + if ( + capacity is not None + or num_route_buckets >= _LARGE_ROUTE_MIN_BUCKETS + or rows >= _LARGE_ROUTE_MIN_PAIRS + ): + return _build_large_route( + token_slots, + group_ids, + groups_per_slot=groups_per_slot, + max_loras=max_loras, + block_size=block_size, + workspace=workspace, + tensor_prefix=tensor_prefix, + capacity=capacity, + ) + + small_max_pairs = _SMALL_ROUTE_MAX_PAIRS + if 0 < num_route_buckets <= _SMALL_ROUTE_LOW_BUCKET_MAX_BUCKETS: + small_max_pairs = _SMALL_ROUTE_LOW_BUCKET_MAX_PAIRS + if 0 < rows <= small_max_pairs: + return _build_small_route( + token_slots, + group_ids, + groups_per_slot=groups_per_slot, + max_loras=max_loras, + block_size=block_size, + workspace=workspace, + tensor_prefix=tensor_prefix, + ) + + # Use workspace storage to keep scratch out of the CUDA graph pool. + scratch = None + device = token_slots.device + if workspace is not None: + prefix = f"{tensor_prefix}:jit" + buckets_out = workspace.tensor( + f"{prefix}:bucket_ids", shape, dtype=torch.int32, device=device + ) + scratch = lambda numel: workspace.tensor( # noqa: E731 + f"{prefix}:scratch", (numel,), dtype=torch.int32, device=device + ) + else: + buckets_out = torch.empty(shape, dtype=torch.int32, device=device) + buckets = _build_route_bucket_ids( + token_slots, + group_ids, + groups_per_slot=groups_per_slot, + max_loras=max_loras, + out=buckets_out, + ) + sorted_pair_ids, block_bucket_ids, num_pairs_post_padded = _align_block_size_jit( + buckets, block_size, num_route_buckets, scratch=scratch + ) + return RouteView( + **common, + maybe_sorted_pair_ids=sorted_pair_ids, + maybe_block_bucket_ids=block_bucket_ids, + maybe_num_pairs_post_padded=num_pairs_post_padded, + ) diff --git a/python/sglang/kernels/ops/lora/dense/embedding_lora_a.py b/python/sglang/kernels/ops/lora/dense/embedding_lora_a.py index 1e21be50fd..03a3d91884 100644 --- a/python/sglang/kernels/ops/lora/dense/embedding_lora_a.py +++ b/python/sglang/kernels/ops/lora/dense/embedding_lora_a.py @@ -184,3 +184,112 @@ def embedding_lora_a_fwd( ) return output + + +@triton.jit +def _embedding_lora_a_tokens_kernel( + input_ids, + weights, + output, + extra_embeddings, + token_lora_mapping, # int32 [S]: adapter slot per token, -1 = none + lora_ranks, + vocab_size, + rank, + w_stride_0, + w_stride_1, + w_stride_2, + output_stride_0, + output_stride_1, + extra_emb_stride_0, + extra_emb_stride_1, + extra_emb_stride_2, + BLOCK_RANK: tl.constexpr, + HAS_EXTRA_EMBEDDINGS: tl.constexpr, +): + """One program per token; zero inactive rows and columns beyond live rank.""" + token = tl.program_id(axis=0) + slot = tl.load(token_lora_mapping + token) + has_adapter = slot >= 0 + w_index = tl.where(has_adapter, slot, 0) + rank_val = tl.where(has_adapter, tl.load(lora_ranks + w_index), 0) + token_id = tl.load(input_ids + token) + is_extra_token = token_id >= vocab_size + token_id_clamped = tl.minimum(token_id, vocab_size - 1) + extra_token_id = tl.maximum(token_id - vocab_size, 0) + for block_id in range(tl.cdiv(rank, BLOCK_RANK)): + rank_offset = tl.arange(0, BLOCK_RANK) + block_id * BLOCK_RANK + live = rank_offset < rank_val + if HAS_EXTRA_EMBEDDINGS and is_extra_token: + emb_values = tl.load( + extra_embeddings + + w_index * extra_emb_stride_0 + + extra_token_id * extra_emb_stride_1 + + rank_offset * extra_emb_stride_2, + mask=live, + other=0.0, + ) + else: + emb_values = tl.load( + weights + + w_index * w_stride_0 + + rank_offset * w_stride_1 + + token_id_clamped * w_stride_2, + mask=live, + other=0.0, + ) + tl.store( + output + token * output_stride_0 + rank_offset * output_stride_1, + emb_values, + mask=rank_offset < rank, + ) + + +def embedding_lora_a_tokens_fwd( + input_ids: torch.Tensor, + weights: torch.Tensor, + token_lora_mapping: torch.Tensor, + lora_ranks: torch.Tensor, + vocab_size: int, + extra_embeddings: torch.Tensor = None, +) -> torch.Tensor: + """Look up LoRA A by token slot (-1 = inactive), respecting per-slot ranks. + + The grid follows token count, not request count, including graph padding. + """ + assert input_ids.is_contiguous() and weights.is_contiguous() + assert input_ids.dim() == 1 and weights.dim() == 3 + S = input_ids.shape[0] + assert token_lora_mapping.shape[0] >= S, (token_lora_mapping.shape, S) + rank = weights.shape[1] + has_extra = extra_embeddings is not None + if has_extra: + assert extra_embeddings.is_contiguous() + extra_emb_stride = tuple(extra_embeddings.stride()) + else: + extra_embeddings = weights + extra_emb_stride = (1, 1, 1) + output = torch.empty((S, rank), device=input_ids.device, dtype=weights.dtype) + if S == 0: + return output + _embedding_lora_a_tokens_kernel[(S,)]( + input_ids, + weights, + output, + extra_embeddings, + token_lora_mapping, + lora_ranks, + vocab_size, + rank, + weights.stride(0), + weights.stride(1), + weights.stride(2), + output.stride(0), + output.stride(1), + extra_emb_stride[0], + extra_emb_stride[1], + extra_emb_stride[2], + BLOCK_RANK=128, + HAS_EXTRA_EMBEDDINGS=has_extra, + ) + return output diff --git a/python/sglang/kernels/ops/lora/moe/__init__.py b/python/sglang/kernels/ops/lora/moe/__init__.py index ec88850bfb..44b3d6feca 100644 --- a/python/sglang/kernels/ops/lora/moe/__init__.py +++ b/python/sglang/kernels/ops/lora/moe/__init__.py @@ -1,2 +1,3 @@ -"""Fused MoE-LoRA kernels: the fused shrink/expand Triton kernel, LoRA-aware -block alignment (JIT), and the merged virtual-expert path.""" +"""MoE-LoRA kernels: the legacy fused shrink/expand kernel, LoRA-aware block +alignment and virtual-expert path, and the engine's dispatch, activation, B, +finalize stages and CuTeDSL grouped GEMMs.""" diff --git a/python/sglang/kernels/ops/lora/moe/activation.py b/python/sglang/kernels/ops/lora/moe/activation.py new file mode 100644 index 0000000000..759511f103 --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/activation.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +from enum import Enum + + +class ActivationFn(str, Enum): + SILU = "silu" + RELU2 = "relu2" + + @classmethod + def parse(cls, name: str) -> ActivationFn: + try: + return cls(name) + except ValueError: + raise ValueError( + f"activation {name!r} is not one of {tuple(fn.value for fn in cls)}" + ) from None diff --git a/python/sglang/kernels/ops/lora/moe/activation_delta.py b/python/sglang/kernels/ops/lora/moe/activation_delta.py new file mode 100644 index 0000000000..91fb3817b4 --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/activation_delta.py @@ -0,0 +1,174 @@ +"""Add LoRA before activation and expose pair-major inputs for down-A. + +pair_to_row addresses either base row layout; invalid pair outputs are zero. +""" + +from __future__ import annotations + +import torch +import triton +import triton.language as tl + +from sglang.kernels.ops.lora.moe.activation import ActivationFn +from sglang.kernels.ops.lora.moe.fp8_quant import quantize_fp8_groups + + +@triton.jit +def apply_activation(x, ACTIVATION_TYPE: tl.constexpr): + if ACTIVATION_TYPE == "silu": + return x * tl.sigmoid(x) + elif ACTIVATION_TYPE == "relu2": + value = tl.maximum(x, 0.0) + return value * value + else: + raise ValueError(f"unsupported activation {ACTIVATION_TYPE}") + + +@triton.jit +def _act_delta_kernel( + gateup_ptr, # [rows, slices * inter] bf16, flat base rows + delta_ptr, # [num_tokens, top_k, slices * inter] [gate | up] + act_out_ptr, # [rows, inter] bf16, flat base rows + act_lora_in_ptr, # [num_tokens, top_k, inter] bf16 + act_q_ptr, # [rows, inter] fp8e4m3 (QUANT_GROUP > 0 only) + act_s_ptr, # [rows, inter // QUANT_GROUP] fp32 row-major + pair_to_row_ptr, # [num_tokens * top_k] int32 + topk_ids_ptr, # [num_tokens, top_k] (local ids; < 0 = invalid) + num_local_experts, + inter, + HAS_DELTA: tl.constexpr, + NUM_SLICES: tl.constexpr, + ACTIVATION_TYPE: tl.constexpr, + GATE_FIRST: tl.constexpr, + INTERLEAVED: tl.constexpr, + QUANT_GROUP: tl.constexpr, # 0 disables the additional FP8 output. + WHOLE_ROW: tl.constexpr, # Match upstream's whole-row rounding. + BLOCK_SIZE: tl.constexpr, +): + pair_idx_int32 = tl.program_id(0) + pair_idx = pair_idx_int32.to(tl.int64) + + expert_id = tl.load(topk_ids_ptr + pair_idx) + valid = (expert_id >= 0) & (expert_id < num_local_experts) + dst_row = tl.load(pair_to_row_ptr + pair_idx, mask=valid, other=0).to(tl.int64) + + total_inter = NUM_SLICES * inter + gateup_row = gateup_ptr + dst_row * total_inter + delta_row = delta_ptr + pair_idx * total_inter + act_out_row = act_out_ptr + dst_row * inter + lora_in_row = act_lora_in_ptr + pair_idx * inter + + vec = tl.arange(0, BLOCK_SIZE) + for start in tl.range(0, inter, BLOCK_SIZE): + offs = start + vec + mask = offs < inter + + if NUM_SLICES == 1: + gate_offs = offs + up_offs = offs + elif INTERLEAVED: + gate_offs = 2 * offs + up_offs = 2 * offs + 1 + else: + gate_offs = offs + up_offs = inter + offs + if not GATE_FIRST: + gate_offs, up_offs = up_offs, gate_offs + + g = tl.load(gateup_row + gate_offs, mask=mask & valid, other=0.0).to(tl.float32) + if HAS_DELTA: + # The delta is always contiguous [gate | up]. + dg = tl.load(delta_row + offs, mask=mask & valid, other=0.0).to(tl.float32) + g += dg + act = apply_activation(g, ACTIVATION_TYPE) + if NUM_SLICES == 2: + u = tl.load(gateup_row + up_offs, mask=mask & valid, other=0.0).to( + tl.float32 + ) + if HAS_DELTA: + du = tl.load( + delta_row + inter + offs, + mask=mask & valid, + other=0.0, + ).to(tl.float32) + u += du + act = act * u + act_bf16 = act.to(act_out_ptr.dtype.element_ty) + + tl.store(act_out_row + offs, act_bf16, mask=mask & valid) + lora_in = tl.where(valid, act, 0.0) + tl.store( + lora_in_row + offs, lora_in.to(act_lora_in_ptr.dtype.element_ty), mask=mask + ) + if QUANT_GROUP > 0: + # Quantize the BF16-rounded value, matching the unfused path. + # Admission ensures each quantization group is fully valid or masked. + QG: tl.constexpr = QUANT_GROUP if QUANT_GROUP > 0 else BLOCK_SIZE + grouped = tl.reshape( + tl.where(mask & valid, act_bf16.to(tl.float32), 0.0), + (BLOCK_SIZE // QG, QG), + ) + q, scale = quantize_fp8_groups(grouped, WHOLE_ROW) + tl.store( + act_q_ptr + dst_row * inter + offs, + tl.reshape(q, (BLOCK_SIZE,)).to(act_q_ptr.dtype.element_ty), + mask=mask & valid, + ) + gvec = tl.arange(0, BLOCK_SIZE // QG) + goffs = start // QG + gvec + n_groups = inter // QG + tl.store( + act_s_ptr + dst_row * n_groups + goffs, + scale, + mask=(goffs < n_groups) & valid, + ) + + +def act_delta( + gateup_rows: torch.Tensor, + gate_up_delta: torch.Tensor | None, # [num_tokens, top_k, slices * inter] + act_out_rows: torch.Tensor, + activation_lora_input: torch.Tensor, # [num_tokens, top_k, inter] bf16 + pair_to_row: torch.Tensor, # [num_tokens * top_k] int32 + topk_ids: torch.Tensor, # [num_tokens, top_k] + *, + num_local_experts: int, + gate_first: bool = True, + interleaved: bool = False, + activation: str = "silu", + act_quant: tuple[torch.Tensor, torch.Tensor, int] | None = None, +) -> None: + """Add pair-major LoRA deltas and activate either provider row layout.""" + ActivationFn.parse(activation) + num_pairs = topk_ids.numel() + if num_pairs == 0: + return + gateup_rows = gateup_rows.view(-1, gateup_rows.shape[-1]) + act_out_rows = act_out_rows.view(-1, act_out_rows.shape[-1]) + inter = act_out_rows.shape[-1] + num_slices = gateup_rows.shape[-1] // inter + if act_quant is not None: + act_q, act_s, group = act_quant + assert inter % group == 0 and 512 % group == 0 + else: + act_q, act_s, group = act_out_rows, act_out_rows, 0 + _act_delta_kernel[(num_pairs,)]( + gateup_rows, + gate_up_delta if gate_up_delta is not None else gateup_rows, + act_out_rows, + activation_lora_input, + act_q, + act_s, + pair_to_row, + topk_ids, + num_local_experts, + inter, + HAS_DELTA=gate_up_delta is not None, + NUM_SLICES=num_slices, + ACTIVATION_TYPE=activation, + GATE_FIRST=gate_first, + INTERLEAVED=interleaved, + QUANT_GROUP=group, + WHOLE_ROW=inter == group, + BLOCK_SIZE=512, + ) diff --git a/python/sglang/kernels/ops/lora/moe/align_rows.py b/python/sglang/kernels/ops/lora/moe/align_rows.py new file mode 100644 index 0000000000..6da79d80be --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/align_rows.py @@ -0,0 +1,99 @@ +"""Align routed pairs for Triton and Marlin, dropping negative expert IDs. + +Distinct top-k IDs allow a single-token fast path. pair_to_row maps pair p +to row p, or -1 for a pair without an expert. +""" + +from __future__ import annotations + +import torch +import triton +import triton.language as tl + + +@triton.jit +def _align_single_token_kernel( + topk_ids_ptr, # int32 [TOPK] + sorted_ids_ptr, # int32 [TOPK * BLOCK_SIZE] + expert_ids_ptr, # int32 [TOPK] + num_post_ptr, # int32 [1] + pair_to_row_ptr, # int32 [TOPK] out: pair p is row p, -1 without an expert + WRITE_PAIR_TO_ROW: tl.constexpr, + TOPK: tl.constexpr, + BLOCK_SIZE: tl.constexpr, + LANES: tl.constexpr, # next pow2 >= TOPK + SLOTS: tl.constexpr, # next pow2 >= TOPK * BLOCK_SIZE +): + lane = tl.arange(0, LANES) + in_range = lane < TOPK + ids = tl.load(topk_ids_ptr + lane, mask=in_range, other=-1) + valid = ids >= 0 + # Dropped lanes sort past every valid id; their ties break on lane. + key = tl.where(valid, ids, 2147483647) + before = (key[None, :] < key[:, None]) | ( + (key[None, :] == key[:, None]) & (lane[None, :] < lane[:, None]) + ) + rank = tl.sum(before.to(tl.int32), axis=1) + n_valid = tl.sum(valid.to(tl.int32), axis=0) + + # For one token, the lane is the flat pair index. + tl.store(expert_ids_ptr + rank, ids, mask=valid) + tl.store(sorted_ids_ptr + rank * BLOCK_SIZE, lane, mask=valid) + tl.store( + expert_ids_ptr + lane, + tl.full([LANES], -1, tl.int32), + mask=in_range & (lane >= n_valid), + ) + # Padding uses numel (= TOPK), matching the general alignment path. + slot = tl.arange(0, SLOTS) + pad = (slot < TOPK * BLOCK_SIZE) & ( + (slot % BLOCK_SIZE != 0) | (slot // BLOCK_SIZE >= n_valid) + ) + tl.store(sorted_ids_ptr + slot, tl.full([SLOTS], TOPK, tl.int32), mask=pad) + tl.store(num_post_ptr, n_valid * BLOCK_SIZE) + if WRITE_PAIR_TO_ROW: + tl.store(pair_to_row_ptr + lane, tl.where(valid, lane, -1), mask=in_range) + + +def moe_align_single_token( + topk_ids: torch.Tensor, block_size: int, pair_to_row: torch.Tensor | None = None +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Align distinct top-k IDs for one token; accepts int32 [1, topk], topk <= 32.""" + topk = topk_ids.shape[1] + device = topk_ids.device + sorted_ids = torch.empty((topk * block_size,), dtype=torch.int32, device=device) + expert_ids = torch.empty((topk,), dtype=torch.int32, device=device) + num_post = torch.empty((1,), dtype=torch.int32, device=device) + _align_single_token_kernel[(1,)]( + topk_ids, + sorted_ids, + expert_ids, + num_post, + topk_ids if pair_to_row is None else pair_to_row, + WRITE_PAIR_TO_ROW=pair_to_row is not None, + TOPK=topk, + BLOCK_SIZE=block_size, + LANES=triton.next_power_of_2(topk), + SLOTS=triton.next_power_of_2(topk * block_size), + num_warps=1, + ) + return sorted_ids, expert_ids, num_post + + +@triton.jit +def _pair_to_row_kernel(topk_ids_ptr, out_ptr, n, BLOCK: tl.constexpr): + offs = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK) + mask = offs < n + ids = tl.load(topk_ids_ptr + offs, mask=mask, other=-1) + tl.store(out_ptr + offs, tl.where(ids >= 0, offs, -1).to(tl.int32), mask=mask) + + +def pair_to_row_map(topk_ids: torch.Tensor, out: torch.Tensor) -> torch.Tensor: + """Write out[p] = p for routed pairs, else -1; finalize gates on this map.""" + flat = topk_ids.reshape(-1) + n = flat.numel() + block = 1024 + _pair_to_row_kernel[(triton.cdiv(n, block),)]( + flat, out, n, BLOCK=block, num_warps=4 + ) + return out diff --git a/python/sglang/kernels/ops/lora/moe/cutedsl/__init__.py b/python/sglang/kernels/ops/lora/moe/cutedsl/__init__.py new file mode 100644 index 0000000000..57a99c20c6 --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/cutedsl/__init__.py @@ -0,0 +1,4 @@ +"""SM90/SM100 grouped GEMMs for BF16 and FP8, with masked or contiguous rows. + +Mainloops derive from the CUTLASS dense persistent examples (NVIDIA BSD-3). +""" diff --git a/python/sglang/kernels/ops/lora/moe/cutedsl/api.py b/python/sglang/kernels/ops/lora/moe/cutedsl/api.py new file mode 100644 index 0000000000..41349bb395 --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/cutedsl/api.py @@ -0,0 +1,367 @@ +# Copyright (c) 2025 - 2026 NVIDIA CORPORATION & AFFILIATES. +# SPDX-License-Identifier: BSD-3-Clause + +"""Compile grouped GEMMs with dynamic row counts; providers cache the code.""" + +from typing import Any, Tuple + +import cuda.bindings.driver as cuda +import cutlass +import cutlass.cute as cute +import cutlass.cute.testing as testing +import cutlass.utils as utils +import msgspec +import torch +from cutlass.cute.runtime import from_dlpack + +from sglang.kernels.ops.lora.moe.cutedsl.kernel_sm100_bf16 import ( + GroupedGemmKernelSm100Bf16, +) + + +@cute.jit +def _grouped_gemm_bf16_swap_ab( + gemm_op: cutlass.Constexpr, + a: cute.Tensor, # physical routed input (expert, m_max, k) + b: cute.Tensor, # physical weight (expert, n_out, k) + c: cute.Tensor, # physical output (expert, m_max, n_out) + group_m: cute.Tensor, + direct_schedule: cute.Tensor, + schedule_tiles: cute.Tensor, + max_active_clusters: cutlass.Constexpr, + stream: cuda.CUstream, + epilogue_op: cutlass.Constexpr = lambda x: x, +): + # W @ X.T puts tokens on N for 8-wide tiles; C uses the transposed layout. + weight_mke = cute.make_tensor(b.iterator, cute.select(b.layout, mode=[1, 2, 0])) + token_nke = cute.make_tensor(a.iterator, cute.select(a.layout, mode=[1, 2, 0])) + output_mne = cute.make_tensor(c.iterator, cute.select(c.layout, mode=[2, 1, 0])) + gemm_op( + weight_mke, + token_nke, + output_mne, + group_m, + direct_schedule, + schedule_tiles, + max_active_clusters, + stream, + epilogue_op, + ) + + +def _bf16_kernel_class_for(device: torch.device): + major, _minor = torch.cuda.get_device_capability(device) + if major >= 10: + return GroupedGemmKernelSm100Bf16 + if major == 9: + from sglang.kernels.ops.lora.moe.cutedsl.kernel_sm90_bf16 import ( + GroupedGemmKernelSm90Bf16, + ) + + return GroupedGemmKernelSm90Bf16 + raise NotImplementedError( + f"the BF16 grouped GEMM needs SM90+; device is sm{major}x" + ) + + +@cute.jit +def _grouped_gemm_fp8_swap_ab( + gemm_op: cutlass.Constexpr, + a: cute.Tensor, # physical routed input (expert, m_max, k) e4m3 + b: cute.Tensor, # physical weight (expert, n_out, k) e4m3 + sf_tokens: cute.Tensor, # physical (expert, rows, k/128) fp32 + sf_weights: cute.Tensor, # physical (expert, n/128, k/128) fp32 + c: cute.Tensor, # physical output (expert, m_max, n_out) bf16 + group_m: cute.Tensor, + direct_schedule: cute.Tensor, + schedule_tiles: cute.Tensor, + max_active_clusters: cutlass.Constexpr, + stream: cuda.CUstream, + epilogue_op: cutlass.Constexpr = lambda x: x, +): + # SFA follows weights (kernel A); SFB follows tokens (kernel B). + weight_mke = cute.make_tensor(b.iterator, cute.select(b.layout, mode=[1, 2, 0])) + token_nke = cute.make_tensor(a.iterator, cute.select(a.layout, mode=[1, 2, 0])) + output_mne = cute.make_tensor(c.iterator, cute.select(c.layout, mode=[2, 1, 0])) + sfa_weights = cute.make_tensor( + sf_weights.iterator, cute.select(sf_weights.layout, mode=[1, 2, 0]) + ) + sfb_tokens = cute.make_tensor( + sf_tokens.iterator, cute.select(sf_tokens.layout, mode=[1, 2, 0]) + ) + gemm_op( + weight_mke, + token_nke, + sfa_weights, + sfb_tokens, + output_mne, + group_m, + direct_schedule, + schedule_tiles, + max_active_clusters, + stream, + epilogue_op, + ) + + +def _fp8_kernel_class_for(device: torch.device): + major, _minor = torch.cuda.get_device_capability(device) + if major >= 10: + from sglang.kernels.ops.lora.moe.cutedsl.kernel_sm100_fp8 import ( + GroupedGemmKernelSm100Fp8, + ) + + return GroupedGemmKernelSm100Fp8 + if major == 9: + from sglang.kernels.ops.lora.moe.cutedsl.kernel_sm90_fp8 import ( + GroupedGemmKernelSm90Fp8, + ) + + return GroupedGemmKernelSm90Fp8 + raise NotImplementedError(f"the FP8 grouped GEMM needs SM90+; device is sm{major}x") + + +class GroupedGemmConfig(msgspec.Struct, frozen=True, kw_only=True): + mma_tiler_mn: Tuple[int, int] = (64, 128) + cluster_shape_mn: Tuple[int, int] = (1, 1) + use_2cta_instrs: bool = False + occupancy: int = 1 + mma_inst_tile_k: int = 4 + persistent_clusters: int | None = None + + +class PreparedGroupedGemm(msgspec.Struct, kw_only=True): + """Bound arguments retain the tensors backing their DLPack views.""" + + compiled_fn: Any + operand_args: tuple # the wrapper's tensor operands, in its order + group_m_arg: cute.Tensor + direct_schedule_arg: cute.Tensor + schedule_tiles_arg: cute.Tensor + direct_schedule_owner: torch.Tensor + schedule_tiles_owner: torch.Tensor + stream: cuda.CUstream + + def launch(self) -> None: + self.compiled_fn( + *self.operand_args, + self.group_m_arg, + self.direct_schedule_arg, + self.schedule_tiles_arg, + self.stream, + ) + + +def as_dynamic_cute_tensor(tensor: torch.Tensor, *, leading_dim: int) -> cute.Tensor: + """Compile-time and runtime calls must use identical layout wrapping.""" + return from_dlpack(tensor, assumed_align=16).mark_layout_dynamic( + leading_dim=leading_dim + ) + + +def _compile_prepared( + *, + kernel_cls, + wrapper, + ab_dtype, + config: GroupedGemmConfig, + contiguous_segments: bool, + problem_shape: Tuple[int, int, int, int], + operand_args: tuple, + group_m_arg: cute.Tensor, + direct_schedule: torch.Tensor | None, + schedule_tiles: torch.Tensor | None, + device: torch.device, +) -> PreparedGroupedGemm: + if direct_schedule is None: + direct_schedule = torch.zeros((1,), device=device, dtype=torch.int64) + if schedule_tiles is None: + schedule_tiles = torch.zeros((1,), device=device, dtype=torch.int32) + direct_schedule_arg = as_dynamic_cute_tensor(direct_schedule, leading_dim=0) + schedule_tiles_arg = as_dynamic_cute_tensor(schedule_tiles, leading_dim=0) + + kernel_kwargs = {} + if getattr(kernel_cls, "SUPPORTS_SINGLE_K_PIPELINE", False): + # Compile the rolling pipeline only for single-K tiles to save registers. + cta_tile_k = 32 * config.mma_inst_tile_k + kernel_kwargs["single_k_pipeline"] = problem_shape[2] <= cta_tile_k + gemm = kernel_cls( + acc_dtype=cutlass.Float32, + use_2cta_instrs=config.use_2cta_instrs, + mma_tiler_mn=config.mma_tiler_mn, + cluster_shape_mn=config.cluster_shape_mn, + mma_inst_tile_k=config.mma_inst_tile_k, + persistent_clusters=config.persistent_clusters, + swap_ab=True, + contiguous_segments=contiguous_segments, + **kernel_kwargs, + ) + gemm.occupancy = config.occupancy + if not gemm.can_implement( + problem_shape, ab_dtype, ab_dtype, cutlass.BFloat16, "k", "k", "m" + ): + raise testing.CantImplementError( + f"unsupported {getattr(ab_dtype, '__name__', ab_dtype)} " + f"config={config} for logical MNKL={problem_shape}" + ) + + max_active_clusters = utils.HardwareInfo().get_max_active_clusters( + config.cluster_shape_mn[0] * config.cluster_shape_mn[1] + ) + stream = cuda.CUstream(torch.cuda.current_stream(device).cuda_stream) + compiled_fn = cute.compile( + wrapper, + gemm, + *operand_args, + group_m_arg, + direct_schedule_arg, + schedule_tiles_arg, + max_active_clusters, + stream, + lambda x: x, + ) + return PreparedGroupedGemm( + compiled_fn=compiled_fn, + operand_args=operand_args, + group_m_arg=group_m_arg, + direct_schedule_arg=direct_schedule_arg, + schedule_tiles_arg=schedule_tiles_arg, + direct_schedule_owner=direct_schedule, + schedule_tiles_owner=schedule_tiles, + stream=stream, + ) + + +def prepare_masked_bf16( + a: torch.Tensor, + b: torch.Tensor, + c: torch.Tensor, + masked_m: torch.Tensor, + *, + config: GroupedGemmConfig, + direct_schedule: torch.Tensor | None = None, + schedule_tiles: torch.Tensor | None = None, +) -> PreparedGroupedGemm: + experts, m_max, k = a.shape + n = b.shape[1] + return _compile_prepared( + kernel_cls=_bf16_kernel_class_for(a.device), + wrapper=_grouped_gemm_bf16_swap_ab, + ab_dtype=cutlass.BFloat16, + config=config, + contiguous_segments=False, + problem_shape=(n, m_max, k, experts), + operand_args=( + as_dynamic_cute_tensor(a, leading_dim=2), + as_dynamic_cute_tensor(b, leading_dim=2), + as_dynamic_cute_tensor(c, leading_dim=2), + ), + group_m_arg=as_dynamic_cute_tensor(masked_m, leading_dim=0), + direct_schedule=direct_schedule, + schedule_tiles=schedule_tiles, + device=a.device, + ) + + +def prepare_contiguous_bf16( + a: torch.Tensor, + b: torch.Tensor, + c: torch.Tensor, + seg_offsets: torch.Tensor, + *, + config: GroupedGemmConfig, + direct_schedule: torch.Tensor | None = None, + schedule_tiles: torch.Tensor | None = None, +) -> PreparedGroupedGemm: + """Use seg_offsets in the group_m slot to address flat expert segments.""" + m_ceil, k = a.shape + experts, n, _ = b.shape + return _compile_prepared( + kernel_cls=_bf16_kernel_class_for(a.device), + wrapper=_grouped_gemm_bf16_swap_ab, + ab_dtype=cutlass.BFloat16, + config=config, + contiguous_segments=True, + problem_shape=(n, m_ceil, k, experts), + operand_args=( + as_dynamic_cute_tensor(a.unsqueeze(0), leading_dim=2), + as_dynamic_cute_tensor(b, leading_dim=2), + as_dynamic_cute_tensor(c.unsqueeze(0), leading_dim=2), + ), + group_m_arg=as_dynamic_cute_tensor(seg_offsets, leading_dim=0), + direct_schedule=direct_schedule, + schedule_tiles=schedule_tiles, + device=a.device, + ) + + +def prepare_masked_fp8( + a: torch.Tensor, + b: torch.Tensor, + sf_tokens: torch.Tensor, # fp32 [E, m_max, K // 128] + sf_weights: torch.Tensor, # fp32 [E, N // 128, K // 128] (checkpoint form) + c: torch.Tensor, + masked_m: torch.Tensor, + *, + config: GroupedGemmConfig, + direct_schedule: torch.Tensor | None = None, + schedule_tiles: torch.Tensor | None = None, +) -> PreparedGroupedGemm: + assert sf_tokens.dtype == torch.float32 and sf_weights.dtype == torch.float32 + experts, m_max, k = a.shape + n = b.shape[1] + return _compile_prepared( + kernel_cls=_fp8_kernel_class_for(a.device), + wrapper=_grouped_gemm_fp8_swap_ab, + ab_dtype=cutlass.Float8E4M3FN, + config=config, + contiguous_segments=False, + problem_shape=(n, m_max, k, experts), + operand_args=( + as_dynamic_cute_tensor(a, leading_dim=2), + as_dynamic_cute_tensor(b, leading_dim=2), + as_dynamic_cute_tensor(sf_tokens, leading_dim=2), + as_dynamic_cute_tensor(sf_weights, leading_dim=2), + as_dynamic_cute_tensor(c, leading_dim=2), + ), + group_m_arg=as_dynamic_cute_tensor(masked_m, leading_dim=0), + direct_schedule=direct_schedule, + schedule_tiles=schedule_tiles, + device=a.device, + ) + + +def prepare_contiguous_fp8( + a: torch.Tensor, + b: torch.Tensor, + sf_tokens: torch.Tensor, # fp32 [1, M, K // 128] + sf_weights: torch.Tensor, # fp32 [E, N // 128, K // 128] (checkpoint form) + c: torch.Tensor, + seg_offsets: torch.Tensor, + *, + config: GroupedGemmConfig, + direct_schedule: torch.Tensor | None = None, + schedule_tiles: torch.Tensor | None = None, +) -> PreparedGroupedGemm: + assert sf_tokens.dtype == torch.float32 and sf_weights.dtype == torch.float32 + m_ceil, k = a.shape + experts, n, _ = b.shape + return _compile_prepared( + kernel_cls=_fp8_kernel_class_for(a.device), + wrapper=_grouped_gemm_fp8_swap_ab, + ab_dtype=cutlass.Float8E4M3FN, + config=config, + contiguous_segments=True, + problem_shape=(n, m_ceil, k, experts), + operand_args=( + as_dynamic_cute_tensor(a.unsqueeze(0), leading_dim=2), + as_dynamic_cute_tensor(b, leading_dim=2), + as_dynamic_cute_tensor(sf_tokens, leading_dim=2), + as_dynamic_cute_tensor(sf_weights, leading_dim=2), + as_dynamic_cute_tensor(c.unsqueeze(0), leading_dim=2), + ), + group_m_arg=as_dynamic_cute_tensor(seg_offsets, leading_dim=0), + direct_schedule=direct_schedule, + schedule_tiles=schedule_tiles, + device=a.device, + ) diff --git a/python/sglang/kernels/ops/lora/moe/cutedsl/kernel_sm100_bf16.py b/python/sglang/kernels/ops/lora/moe/cutedsl/kernel_sm100_bf16.py new file mode 100644 index 0000000000..15e00f7e00 --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/cutedsl/kernel_sm100_bf16.py @@ -0,0 +1,799 @@ +# Copyright (c) 2025 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: BSD-3-Clause + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# 3. Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Persistent BF16 GEMM for masked slabs or aligned flat expert segments. + +Physical tensors are A [E, M, K], B [E, N, K], and C [E, M, N]. Masked output +is defined only below group_m[e]; partial tiles may write padding, but none +starts beyond an expert's rows. For flat segments, group_m holds seg_offsets +and token tiles divide the segment alignment, keeping tails within their segment. + +Mainloop and epilogue derive from CUTLASS v4.6.1 +blackwell/kernel/dense_gemm/dense_gemm_persistent.py. +""" + +from typing import Tuple, Type + +import cuda.bindings.driver as cuda +import cutlass +import cutlass.cute as cute +import cutlass.cute.testing as testing +import cutlass.pipeline as pipeline +import cutlass.utils as utils +from cutlass.cute.nvgpu import cpasync, tcgen05 +from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait + +from sglang.kernels.ops.lora.moe.cutedsl.scheduler import ( + MoESchedulerParams, + create_moe_tile_scheduler, + resolve_scheduler_params_and_grid, +) + + +class GroupedGemmKernelSm100Bf16: + def __init__( + self, + acc_dtype: Type[cutlass.Numeric], + use_2cta_instrs: bool, + mma_tiler_mn: Tuple[int, int], + cluster_shape_mn: Tuple[int, int], + mma_inst_tile_k: int = 4, + persistent_clusters: int | None = None, + swap_ab: bool = False, + contiguous_segments: bool = False, + ): + self.acc_dtype: Type[cutlass.Numeric] = acc_dtype + self.use_2cta_instrs = use_2cta_instrs + self.cluster_shape_mn = cluster_shape_mn + # The K extent here is a placeholder. _setup_attributes computes it. + self.mma_tiler_mn = mma_tiler_mn + self.mma_tiler = (*mma_tiler_mn, 1) + self.mma_inst_tile_k = mma_inst_tile_k + self.persistent_clusters = persistent_clusters + self.swap_ab = swap_ab + self.contiguous_segments = contiguous_segments + if contiguous_segments and not swap_ab: + raise ValueError("contiguous_segments requires swap_ab") + if contiguous_segments and cluster_shape_mn != (1, 1): + raise ValueError("contiguous_segments requires a (1, 1) cluster") + self.arch = "sm_100" + + self.cta_group = ( + tcgen05.CtaGroup.TWO if use_2cta_instrs else tcgen05.CtaGroup.ONE + ) + + self.occupancy = 1 + self.epilogue_warp_id = (0, 1, 2, 3) + self.mma_warp_id = 4 + self.tma_warp_id = 5 + self.threads_per_cta = 32 * len( + (self.mma_warp_id, self.tma_warp_id, *self.epilogue_warp_id) + ) + self.epilog_sync_bar_id = 1 + self.tmem_alloc_sync_bar_id = 2 + + def _create_tiled_mma(self): + return utils.sm100.make_trivial_tiled_mma( + self.a_dtype, + self.a_major_mode, + self.b_major_mode, + self.acc_dtype, + self.cta_group, + self.mma_tiler[:2], + ) + + def _setup_attributes(self): + tiled_mma = self._create_tiled_mma() + + mma_inst_shape_k = cute.size(tiled_mma.shape_mnk, mode=[2]) + self.mma_tiler = ( + self.mma_tiler[0], + self.mma_tiler[1], + mma_inst_shape_k * self.mma_inst_tile_k, + ) + self.cta_tile_shape_mnk = ( + self.mma_tiler[0] // cute.size(tiled_mma.thr_id.shape), + self.mma_tiler[1], + self.mma_tiler[2], + ) + + self.cluster_layout_vmnk = cute.tiled_divide( + cute.make_layout((*self.cluster_shape_mn, 1)), + (tiled_mma.thr_id.shape,), + ) + + self.num_mcast_ctas_a = cute.size(self.cluster_layout_vmnk.shape[2]) + self.num_mcast_ctas_b = cute.size(self.cluster_layout_vmnk.shape[1]) + self.is_a_mcast = self.num_mcast_ctas_a > 1 + self.is_b_mcast = self.num_mcast_ctas_b > 1 + + self.epi_tile = utils.sm100.compute_epilogue_tile_shape( + self.cta_tile_shape_mnk, + self.use_2cta_instrs, + self.c_layout, + self.c_dtype, + ) + + c_smem_layout = utils.sm100.make_smem_layout_epi( + self.c_dtype, self.c_layout, self.epi_tile, 1 + ) + + self.smem_capacity = utils.get_smem_capacity_in_bytes() + + self.num_acc_stage, self.num_ab_stage, self.num_c_stage = self._compute_stages( + tiled_mma, + self.mma_tiler, + self.a_dtype, + self.b_dtype, + self.c_dtype, + self.smem_capacity, + self.occupancy, + c_smem_layout, + ) + + self.a_smem_layout_staged = utils.sm100.make_smem_layout_a( + tiled_mma, self.mma_tiler, self.a_dtype, self.num_ab_stage + ) + self.b_smem_layout_staged = utils.sm100.make_smem_layout_b( + tiled_mma, self.mma_tiler, self.b_dtype, self.num_ab_stage + ) + + self.c_smem_layout_staged = utils.sm100.make_smem_layout_epi( + self.c_dtype, self.c_layout, self.epi_tile, self.num_c_stage + ) + + acc_shape = tiled_mma.partition_shape_C(self.mma_tiler[:2]) + tCtAcc_fake = tiled_mma.make_fragment_C( + cute.append(acc_shape, self.num_acc_stage) + ) + self.num_tmem_alloc_cols = utils.get_num_tmem_alloc_cols( + tCtAcc_fake, arch=self.arch + ) + + @cute.jit + def __call__( + self, + a: cute.Tensor, + b: cute.Tensor, + c: cute.Tensor, + group_m: cute.Tensor, + direct_schedule: cute.Tensor, + schedule_tiles: cute.Tensor, + max_active_clusters: cutlass.Constexpr, + stream: cuda.CUstream, + epilogue_op: cutlass.Constexpr = lambda x: x, + ): + self.a_dtype: Type[cutlass.Numeric] = a.element_type + self.b_dtype: Type[cutlass.Numeric] = b.element_type + self.c_dtype: Type[cutlass.Numeric] = c.element_type + self.a_major_mode = utils.LayoutEnum.from_tensor(a).mma_major_mode() + self.b_major_mode = utils.LayoutEnum.from_tensor(b).mma_major_mode() + self.c_layout = utils.LayoutEnum.from_tensor(c) + + if cutlass.const_expr(self.a_dtype != self.b_dtype): + raise TypeError(f"Type must match: {self.a_dtype} != {self.b_dtype}") + + tiled_mma = self._create_tiled_mma() + + self._setup_attributes() + + atom_thr_size = cute.size(tiled_mma.thr_id.shape) + + a_op = utils.sm100.cluster_shape_to_tma_atom_A( + self.cluster_shape_mn, tiled_mma.thr_id + ) + a_smem_layout = cute.slice_(self.a_smem_layout_staged, (None, None, None, 0)) + tma_atom_a, tma_tensor_a = cute.nvgpu.make_tiled_tma_atom_A( + a_op, + a, + a_smem_layout, + self.mma_tiler, + tiled_mma, + self.cluster_layout_vmnk.shape, + internal_type=( + cutlass.TFloat32 if a.element_type is cutlass.Float32 else None + ), + ) + + b_op = utils.sm100.cluster_shape_to_tma_atom_B( + self.cluster_shape_mn, tiled_mma.thr_id + ) + b_smem_layout = cute.slice_(self.b_smem_layout_staged, (None, None, None, 0)) + tma_atom_b, tma_tensor_b = cute.nvgpu.make_tiled_tma_atom_B( + b_op, + b, + b_smem_layout, + self.mma_tiler, + tiled_mma, + self.cluster_layout_vmnk.shape, + internal_type=( + cutlass.TFloat32 if b.element_type is cutlass.Float32 else None + ), + ) + + a_copy_size = cute.size_in_bytes(self.a_dtype, a_smem_layout) + b_copy_size = cute.size_in_bytes(self.b_dtype, b_smem_layout) + self.num_tma_load_bytes = (a_copy_size + b_copy_size) * atom_thr_size + + epi_smem_layout = cute.select(self.c_smem_layout_staged, mode=[0, 1]) + tma_atom_c, tma_tensor_c = cpasync.make_tiled_tma_atom( + cpasync.CopyBulkTensorTileS2GOp(), c, epi_smem_layout, self.epi_tile + ) + + self.tile_sched_params, grid = resolve_scheduler_params_and_grid( + a=a, + cta_tile_k=self.cta_tile_shape_mnk[2], + cluster_shape_mn=self.cluster_shape_mn, + swap_ab=self.swap_ab, + persistent_clusters=self.persistent_clusters, + max_active_clusters=max_active_clusters, + ) + + self.kernel( + tiled_mma, + tma_atom_a, + tma_tensor_a, + tma_atom_b, + tma_tensor_b, + tma_atom_c, + tma_tensor_c, + group_m, + direct_schedule, + schedule_tiles, + self.cluster_layout_vmnk, + self.a_smem_layout_staged, + self.b_smem_layout_staged, + self.c_smem_layout_staged, + self.epi_tile, + self.tile_sched_params, + epilogue_op, + ).launch( + grid=grid, + block=[self.threads_per_cta, 1, 1], + cluster=(*self.cluster_shape_mn, 1), + stream=stream, + ) + return + + @cute.kernel + def kernel( + self, + tiled_mma: cute.TiledMma, + tma_atom_a: cute.CopyAtom, + mA_mkl: cute.Tensor, + tma_atom_b: cute.CopyAtom, + mB_nkl: cute.Tensor, + tma_atom_c: cute.CopyAtom, + mC_mnl: cute.Tensor, + group_m: cute.Tensor, + direct_schedule: cute.Tensor, + schedule_tiles: cute.Tensor, + cluster_layout_vmnk: cute.Layout, + a_smem_layout_staged: cute.ComposedLayout, + b_smem_layout_staged: cute.ComposedLayout, + c_smem_layout_staged: cute.ComposedLayout, + epi_tile: cute.Tile, + tile_sched_params: MoESchedulerParams, + epilogue_op: cutlass.Constexpr, + ): + warp_idx = cute.arch.warp_idx() + warp_idx = cute.arch.make_warp_uniform(warp_idx) + + if warp_idx == self.tma_warp_id: + cpasync.prefetch_descriptor(tma_atom_a) + cpasync.prefetch_descriptor(tma_atom_b) + cpasync.prefetch_descriptor(tma_atom_c) + + use_2cta_instrs = cute.size(tiled_mma.thr_id.shape) == 2 + + bidx, bidy, bidz = cute.arch.block_idx() + mma_tile_coord_v = bidx % cute.size(tiled_mma.thr_id.shape) + is_leader_cta = mma_tile_coord_v == 0 + cta_rank_in_cluster = cute.arch.make_warp_uniform( + cute.arch.block_idx_in_cluster() + ) + block_in_cluster_coord_vmnk = cluster_layout_vmnk.get_flat_coord( + cta_rank_in_cluster + ) + tidx, _, _ = cute.arch.thread_idx() + + @cute.struct + class SharedStorage: + ab_full_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_ab_stage * 2] + acc_full_mbar_ptr: cute.struct.MemRange[ + cutlass.Int64, self.num_acc_stage * 2 + ] + tmem_dealloc_mbar: cutlass.Int64 + tmem_holding_buf: cutlass.Int32 + + smem = utils.SmemAllocator() + storage = smem.allocate(SharedStorage) + + ab_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread) + num_tma_producer = self.num_mcast_ctas_a + self.num_mcast_ctas_b - 1 + ab_pipeline_consumer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, num_tma_producer + ) + ab_producer, ab_consumer = pipeline.PipelineTmaUmma.create( + barrier_storage=storage.ab_full_mbar_ptr.data_ptr(), + num_stages=self.num_ab_stage, + producer_group=ab_pipeline_producer_group, + consumer_group=ab_pipeline_consumer_group, + tx_count=self.num_tma_load_bytes, + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ).make_participants() + + acc_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread) + num_acc_consumer_threads = len(self.epilogue_warp_id) * ( + 2 if use_2cta_instrs else 1 + ) + acc_pipeline_consumer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, num_acc_consumer_threads + ) + acc_pipeline = pipeline.PipelineUmmaAsync.create( + barrier_storage=storage.acc_full_mbar_ptr.data_ptr(), + num_stages=self.num_acc_stage, + producer_group=acc_pipeline_producer_group, + consumer_group=acc_pipeline_consumer_group, + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + + tmem_alloc_barrier = pipeline.NamedBarrier( + barrier_id=self.tmem_alloc_sync_bar_id, + num_threads=32 * len((self.mma_warp_id, *self.epilogue_warp_id)), + ) + tmem = utils.TmemAllocator( + storage.tmem_holding_buf.ptr, + barrier_for_retrieve=tmem_alloc_barrier, + allocator_warp_id=self.epilogue_warp_id[0], + is_two_cta=use_2cta_instrs, + two_cta_tmem_dealloc_mbar_ptr=storage.tmem_dealloc_mbar.ptr, + ) + + pipeline_init_arrive(cluster_shape_mn=cluster_layout_vmnk, is_relaxed=True) + + # (MMA, MMA_M, MMA_K, STAGE) + sA = smem.allocate_tensor( + element_type=self.a_dtype, + layout=a_smem_layout_staged.outer, + byte_alignment=128, + swizzle=a_smem_layout_staged.inner, + ) + # (MMA, MMA_N, MMA_K, STAGE) + sB = smem.allocate_tensor( + element_type=self.b_dtype, + layout=b_smem_layout_staged.outer, + byte_alignment=128, + swizzle=b_smem_layout_staged.inner, + ) + + a_full_mcast_mask = None + b_full_mcast_mask = None + if cutlass.const_expr(self.is_a_mcast or self.is_b_mcast or use_2cta_instrs): + a_full_mcast_mask = cpasync.create_tma_multicast_mask( + cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=2 + ) + b_full_mcast_mask = cpasync.create_tma_multicast_mask( + cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=1 + ) + + # (bM, bK, RestM, RestK, RestL) + gA_mkl = cute.local_tile( + mA_mkl, cute.slice_(self.mma_tiler, (None, 0, None)), (None, None, None) + ) + # (bN, bK, RestN, RestK, RestL) + gB_nkl = cute.local_tile( + mB_nkl, cute.slice_(self.mma_tiler, (0, None, None)), (None, None, None) + ) + # (bM, bN, RestM, RestN, RestL) + gC_mnl = cute.local_tile( + mC_mnl, cute.slice_(self.mma_tiler, (None, None, 0)), (None, None, None) + ) + thr_mma = tiled_mma.get_slice(mma_tile_coord_v) + # (MMA, MMA_M, MMA_K, RestM, RestK, RestL) + tCgA = thr_mma.partition_A(gA_mkl) + # (MMA, MMA_N, MMA_K, RestN, RestK, RestL) + tCgB = thr_mma.partition_B(gB_nkl) + # (MMA, MMA_M, MMA_N, RestM, RestN, RestL) + tCgC = thr_mma.partition_C(gC_mnl) + + a_cta_layout = cute.make_layout( + cute.slice_(cluster_layout_vmnk, (0, 0, None, 0)).shape + ) + # ((atom_v, rest_v), STAGE) + # ((atom_v, rest_v), RestM, RestK, RestL) + tAsA, tAgA = cpasync.tma_partition( + tma_atom_a, + block_in_cluster_coord_vmnk[2], + a_cta_layout, + cute.group_modes(sA, 0, 3), + cute.group_modes(tCgA, 0, 3), + ) + b_cta_layout = cute.make_layout( + cute.slice_(cluster_layout_vmnk, (0, None, 0, 0)).shape + ) + # ((atom_v, rest_v), STAGE) + # ((atom_v, rest_v), RestM, RestK, RestL) + tBsB, tBgB = cpasync.tma_partition( + tma_atom_b, + block_in_cluster_coord_vmnk[1], + b_cta_layout, + cute.group_modes(sB, 0, 3), + cute.group_modes(tCgB, 0, 3), + ) + + # (MMA, MMA_M, MMA_K, STAGE) + tCrA = tiled_mma.make_fragment_A(sA) + # (MMA, MMA_N, MMA_K, STAGE) + tCrB = tiled_mma.make_fragment_B(sB) + # (MMA, MMA_M, MMA_N) + acc_shape = tiled_mma.partition_shape_C(self.mma_tiler[:2]) + # (MMA, MMA_M, MMA_N, STAGE) + tCtAcc_fake = tiled_mma.make_fragment_C( + cute.append(acc_shape, self.num_acc_stage) + ) + + pipeline_init_wait(cluster_shape_mn=cluster_layout_vmnk) + + tile_sched = create_moe_tile_scheduler( + tile_sched_params=tile_sched_params, + direct_schedule=direct_schedule, + schedule_tiles=schedule_tiles, + swap_ab=self.swap_ab, + ) + work_tile = tile_sched.initial_work_tile_info() + + if warp_idx == self.tma_warp_id: + while work_tile.is_valid_tile: + mma_tile_coord_mnl = ( + work_tile.tile_m_idx // cute.size(tiled_mma.thr_id.shape), + work_tile.tile_n_idx, + work_tile.expert_idx, + ) + if cutlass.const_expr(self.swap_ab): + mma_tile_coord_mnl = ( + work_tile.tile_n_idx // cute.size(tiled_mma.thr_id.shape), + work_tile.tile_m_idx, + work_tile.expert_idx, + ) + a_rest_l_coord = mma_tile_coord_mnl[2] + if cutlass.const_expr(self.contiguous_segments): + # Flat rows use slot 0 plus seg_offsets; weights keep the expert. + seg_base_tile = ( + group_m[work_tile.expert_idx] // self.cta_tile_shape_mnk[1] + ) + mma_tile_coord_mnl = ( + mma_tile_coord_mnl[0], + seg_base_tile + mma_tile_coord_mnl[1], + cutlass.Int32(0), + ) + a_rest_l_coord = work_tile.expert_idx + + # ((atom_v, rest_v), RestK) + tAgA_slice = tAgA[(None, mma_tile_coord_mnl[0], None, a_rest_l_coord)] + # ((atom_v, rest_v), RestK) + tBgB_slice = tBgB[ + (None, mma_tile_coord_mnl[1], None, mma_tile_coord_mnl[2]) + ] + + ab_producer.reset() + peek_ab_empty_status = ab_producer.try_acquire() + + for k_tile in cutlass.range(0, work_tile.k_tile_cnt, 1, unroll=1): + handle = ab_producer.acquire_and_advance(peek_ab_empty_status) + + cute.copy( + tma_atom_a, + tAgA_slice[(None, handle.count)], + tAsA[(None, handle.index)], + tma_bar_ptr=handle.barrier, + mcast_mask=a_full_mcast_mask, + ) + cute.copy( + tma_atom_b, + tBgB_slice[(None, handle.count)], + tBsB[(None, handle.index)], + tma_bar_ptr=handle.barrier, + mcast_mask=b_full_mcast_mask, + ) + + peek_ab_empty_status = cutlass.Boolean(1) + if handle.count + 1 < work_tile.k_tile_cnt: + peek_ab_empty_status = ab_producer.try_acquire() + + work_tile = tile_sched.advance_to_next_work() + + ab_producer.tail() + + if warp_idx == self.mma_warp_id: + tmem.wait_for_alloc() + tmem_ptr = tmem.retrieve_ptr(self.acc_dtype) + # (MMA, MMA_M, MMA_N, STAGE) + tCtAcc_base = cute.make_tensor(tmem_ptr, tCtAcc_fake.layout) + + acc_producer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.num_acc_stage + ) + + while work_tile.is_valid_tile: + # (MMA, MMA_M, MMA_N) + tCtAcc = tCtAcc_base[(None, None, None, acc_producer_state.index)] + + ab_consumer.reset() + peek_ab_full_status = cutlass.Boolean(1) + if is_leader_cta: + peek_ab_full_status = ab_consumer.try_wait() + + if is_leader_cta: + acc_pipeline.producer_acquire(acc_producer_state) + + tiled_mma.set(tcgen05.Field.ACCUMULATE, False) + + for k_tile in range(work_tile.k_tile_cnt): + if is_leader_cta: + handle = ab_consumer.wait_and_advance(peek_ab_full_status) + + num_kblocks = cute.size(tCrA, mode=[2]) + for kblk_idx in cutlass.range(num_kblocks, unroll_full=True): + kblk_crd = (None, None, kblk_idx, handle.index) + + cute.gemm( + tiled_mma, + tCtAcc, + tCrA[kblk_crd], + tCrB[kblk_crd], + tCtAcc, + ) + tiled_mma.set(tcgen05.Field.ACCUMULATE, True) + + handle.release() + + peek_ab_full_status = cutlass.Boolean(1) + if handle.count + 1 < work_tile.k_tile_cnt: + peek_ab_full_status = ab_consumer.try_wait() + + if is_leader_cta: + acc_pipeline.producer_commit(acc_producer_state) + acc_producer_state.advance() + + work_tile = tile_sched.advance_to_next_work() + + acc_pipeline.producer_tail(acc_producer_state) + + # (EPI_TILE_M, EPI_TILE_N, STAGE) + sC = smem.allocate_tensor( + element_type=self.c_dtype, + layout=c_smem_layout_staged.outer, + byte_alignment=128, + swizzle=c_smem_layout_staged.inner, + ) + + if warp_idx < self.mma_warp_id: + tmem.allocate(self.num_tmem_alloc_cols) + + tmem.wait_for_alloc() + tmem_ptr = tmem.retrieve_ptr(self.acc_dtype) + # (MMA, MMA_M, MMA_N, STAGE) + tCtAcc_base = cute.make_tensor(tmem_ptr, tCtAcc_fake.layout) + + acc_consumer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_acc_stage + ) + + c_producer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, + 32 * len(self.epilogue_warp_id), + ) + c_pipeline = pipeline.PipelineTmaStore.create( + num_stages=self.num_c_stage, producer_group=c_producer_group + ) + while work_tile.is_valid_tile: + mma_tile_coord_mnl = ( + work_tile.tile_m_idx // cute.size(tiled_mma.thr_id.shape), + work_tile.tile_n_idx, + work_tile.expert_idx, + ) + if cutlass.const_expr(self.swap_ab): + mma_tile_coord_mnl = ( + work_tile.tile_n_idx // cute.size(tiled_mma.thr_id.shape), + work_tile.tile_m_idx, + work_tile.expert_idx, + ) + if cutlass.const_expr(self.contiguous_segments): + # Same segment base as the TMA warp. + seg_base_tile = ( + group_m[work_tile.expert_idx] // self.cta_tile_shape_mnk[1] + ) + mma_tile_coord_mnl = ( + mma_tile_coord_mnl[0], + seg_base_tile + mma_tile_coord_mnl[1], + cutlass.Int32(0), + ) + work_tile = tile_sched.advance_to_next_work() + + # Valid tiles only: pipeline count also counts executed tiles. + num_tiles_executed = acc_consumer_state.count + acc_consumer_state = utils.gemm.sm100.epilogue_tma_store( + self, + tidx, + warp_idx, + tma_atom_c, + tCtAcc_base, + sC, + tCgC, + epi_tile, + num_tiles_executed, + epilogue_op, + mma_tile_coord_mnl, + acc_consumer_state, + acc_pipeline, + c_pipeline, + ) + + c_pipeline.producer_tail() + + tmem.relinquish_alloc_permit() + tmem.free(tmem_ptr) + + @staticmethod + def _compute_stages( + tiled_mma: cute.TiledMma, + mma_tiler_mnk: Tuple[int, int, int], + a_dtype: Type[cutlass.Numeric], + b_dtype: Type[cutlass.Numeric], + c_dtype: Type[cutlass.Numeric], + smem_capacity: int, + occupancy: int, + c_smem_layout: cute.Layout, + ) -> Tuple[int, int, int]: + num_acc_stage = 2 + num_c_stage = 2 + + a_smem_layout_stage_one = utils.sm100.make_smem_layout_a( + tiled_mma, mma_tiler_mnk, a_dtype, 1 + ) + b_smem_layout_staged_one = utils.sm100.make_smem_layout_b( + tiled_mma, mma_tiler_mnk, b_dtype, 1 + ) + + ab_bytes_per_stage = cute.size_in_bytes( + a_dtype, a_smem_layout_stage_one + ) + cute.size_in_bytes(b_dtype, b_smem_layout_staged_one) + mbar_helpers_bytes = 1024 + + c_bytes_per_stage = cute.size_in_bytes(c_dtype, c_smem_layout) + c_bytes = c_bytes_per_stage * num_c_stage + + num_ab_stage = ( + smem_capacity // occupancy - (mbar_helpers_bytes + c_bytes) + ) // ab_bytes_per_stage + + num_c_stage += ( + smem_capacity + - occupancy * ab_bytes_per_stage * num_ab_stage + - occupancy * (mbar_helpers_bytes + c_bytes) + ) // (occupancy * c_bytes_per_stage) + return num_acc_stage, num_ab_stage, num_c_stage + + def check_supported_dtypes( + self, + a_dtype: Type[cutlass.Numeric], + b_dtype: Type[cutlass.Numeric], + c_dtype: Type[cutlass.Numeric], + ): + if a_dtype is not cutlass.BFloat16 or b_dtype is not cutlass.BFloat16: + raise testing.CantImplementError( + f"the BF16 grouped GEMM takes BF16 A/B; got {a_dtype}, {b_dtype}" + ) + if c_dtype is not cutlass.BFloat16: + raise testing.CantImplementError(f"C must be BF16; got {c_dtype}") + if self.acc_dtype is not cutlass.Float32: + raise testing.CantImplementError( + f"the accumulator must be FP32; got {self.acc_dtype}" + ) + + def check_mma_tiler_and_cluster_shape(self): + if not ( + (not self.use_2cta_instrs and self.mma_tiler_mn[0] in [64, 128]) + or (self.use_2cta_instrs and self.mma_tiler_mn[0] in [128, 256]) + ): + raise testing.CantImplementError( + f"Invalid mma tiler & use_2cta_instrs: {self.mma_tiler_mn}, {self.use_2cta_instrs}" + ) + valid_n_tiles = range(8, 257, 8) if self.swap_ab else range(32, 257, 32) + if self.mma_tiler_mn[1] not in valid_n_tiles: + raise testing.CantImplementError( + f"Invalid mma tiler N: {self.mma_tiler_mn[1]}" + ) + if self.cluster_shape_mn[0] % (2 if self.use_2cta_instrs else 1) != 0: + raise testing.CantImplementError( + f"Invalid cluster shape M: {self.cluster_shape_mn[0]}" + ) + is_power_of_2 = lambda x: x > 0 and (x & (x - 1)) == 0 + if ( + self.cluster_shape_mn[0] * self.cluster_shape_mn[1] > 16 + or self.cluster_shape_mn[0] <= 0 + or self.cluster_shape_mn[1] <= 0 + or not is_power_of_2(self.cluster_shape_mn[0]) + or not is_power_of_2(self.cluster_shape_mn[1]) + ): + raise testing.CantImplementError( + f"Invalid cluster shape: {self.cluster_shape_mn}" + ) + + def check_tensor_alignment( + self, + m: int, + n: int, + k: int, + l: int, + a_dtype: Type[cutlass.Numeric], + b_dtype: Type[cutlass.Numeric], + c_dtype: Type[cutlass.Numeric], + a_major: str, + b_major: str, + c_major: str, + ): + def check_contiguous_16B_alignment(dtype, is_mode0_major, tensor_shape): + major_mode_idx = 0 if is_mode0_major else 1 + num_major_elements = tensor_shape[major_mode_idx] + num_contiguous_elements = 16 * 8 // dtype.width + return num_major_elements % num_contiguous_elements == 0 + + if ( + not check_contiguous_16B_alignment(a_dtype, a_major == "m", (m, k, l)) + or not check_contiguous_16B_alignment(b_dtype, b_major == "n", (n, k, l)) + or not check_contiguous_16B_alignment(c_dtype, c_major == "m", (m, n, l)) + ): + raise testing.CantImplementError( + f"Invalid tensor alignment: {m}, {n}, {k}, {l}, {a_dtype}, {b_dtype}, {c_dtype}, {a_major}, {b_major}, {c_major}" + ) + + def can_implement( + self, + mnkl: Tuple[int, int, int, int], + a_dtype: Type[cutlass.Numeric], + b_dtype: Type[cutlass.Numeric], + c_dtype: Type[cutlass.Numeric], + a_major: str, + b_major: str, + c_major: str, + ) -> bool: + try: + self.check_supported_dtypes(a_dtype, b_dtype, c_dtype) + self.check_mma_tiler_and_cluster_shape() + + m, n, k, l = mnkl + self.check_tensor_alignment( + m, n, k, l, a_dtype, b_dtype, c_dtype, a_major, b_major, c_major + ) + except testing.CantImplementError: + return False + return True diff --git a/python/sglang/kernels/ops/lora/moe/cutedsl/kernel_sm100_fp8.py b/python/sglang/kernels/ops/lora/moe/cutedsl/kernel_sm100_fp8.py new file mode 100644 index 0000000000..7fb29513c4 --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/cutedsl/kernel_sm100_fp8.py @@ -0,0 +1,574 @@ +# SPDX-License-Identifier: BSD-3-Clause +"""SM100 FP8 GEMM derived from kernel_sm100_bf16.py. + +Each 128-element K partial is drained from tensor memory, scaled in FP32, +and accumulated in registers. Software scaling preserves checkpoint values +and permits 8-wide token tiles. + +Scale layouts after swap_ab: weights [N/128, K/128, E], tokens [M, K/128, E|1]. +""" + +from typing import Type + +import cuda.bindings.driver as cuda +import cutlass +import cutlass.cute as cute +import cutlass.cute.testing as testing +import cutlass.pipeline as pipeline +import cutlass.utils as utils +from cutlass.cute.nvgpu import cpasync, tcgen05 +from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait + +from sglang.kernels.ops.lora.moe.cutedsl.kernel_sm100_bf16 import ( + GroupedGemmKernelSm100Bf16, +) +from sglang.kernels.ops.lora.moe.cutedsl.scheduler import ( + create_moe_tile_scheduler, + resolve_scheduler_params_and_grid, +) + + +class GroupedGemmKernelSm100Fp8(GroupedGemmKernelSm100Bf16): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not self.swap_ab: + raise ValueError("the software-scaled FP8 kernel ships swap_ab only") + if self.use_2cta_instrs or self.cluster_shape_mn != (1, 1): + raise ValueError( + "the software-scaled FP8 kernel ships (1, 1) single-CTA only" + ) + if self.mma_tiler_mn[0] != 128 or self.mma_tiler_mn[1] > 128: + raise ValueError( + "the software-scaled FP8 kernel indexes weight scales per 128-wide " + "output tile and stages one column scale per epilogue thread, so " + f"mma_tiler_mn must be (128, <=128); got {self.mma_tiler_mn}" + ) + + def check_supported_dtypes( + self, + a_dtype: Type[cutlass.Numeric], + b_dtype: Type[cutlass.Numeric], + c_dtype: Type[cutlass.Numeric], + ): + if a_dtype is not cutlass.Float8E4M3FN or b_dtype is not cutlass.Float8E4M3FN: + raise testing.CantImplementError( + f"the software-scaled GEMM takes e4m3 A/B; got {a_dtype}, {b_dtype}" + ) + if c_dtype is not cutlass.BFloat16: + raise testing.CantImplementError(f"C must be BF16; got {c_dtype}") + if self.acc_dtype is not cutlass.Float32: + raise testing.CantImplementError( + f"the accumulator must be FP32; got {self.acc_dtype}" + ) + + @cute.jit + def __call__( + self, + a: cute.Tensor, + b: cute.Tensor, + sf_a: cute.Tensor, # weight scales [NT, KT, E] fp32 + sf_b: cute.Tensor, # token scales [M, KT, E|1] fp32 + c: cute.Tensor, + group_m: cute.Tensor, + direct_schedule: cute.Tensor, + schedule_tiles: cute.Tensor, + max_active_clusters: cutlass.Constexpr, + stream: cuda.CUstream, + epilogue_op: cutlass.Constexpr = lambda x: x, + ): + self.a_dtype: Type[cutlass.Numeric] = a.element_type + self.b_dtype: Type[cutlass.Numeric] = b.element_type + self.c_dtype: Type[cutlass.Numeric] = c.element_type + self.a_major_mode = utils.LayoutEnum.from_tensor(a).mma_major_mode() + self.b_major_mode = utils.LayoutEnum.from_tensor(b).mma_major_mode() + self.c_layout = utils.LayoutEnum.from_tensor(c) + + tiled_mma = self._create_tiled_mma() + self._setup_attributes() + # One k_tile must cover exactly one 128-element scale group. + if cutlass.const_expr(self.mma_tiler[2] != 128): + raise ValueError( + f"k_tile must equal the 128-element scale group; got " + f"{self.mma_tiler[2]} (mma_inst_tile_k={self.mma_inst_tile_k})" + ) + + a_op = utils.sm100.cluster_shape_to_tma_atom_A( + self.cluster_shape_mn, tiled_mma.thr_id + ) + a_smem_layout = cute.slice_(self.a_smem_layout_staged, (None, None, None, 0)) + tma_atom_a, tma_tensor_a = cute.nvgpu.make_tiled_tma_atom_A( + a_op, + a, + a_smem_layout, + self.mma_tiler, + tiled_mma, + self.cluster_layout_vmnk.shape, + ) + + b_op = utils.sm100.cluster_shape_to_tma_atom_B( + self.cluster_shape_mn, tiled_mma.thr_id + ) + b_smem_layout = cute.slice_(self.b_smem_layout_staged, (None, None, None, 0)) + tma_atom_b, tma_tensor_b = cute.nvgpu.make_tiled_tma_atom_B( + b_op, + b, + b_smem_layout, + self.mma_tiler, + tiled_mma, + self.cluster_layout_vmnk.shape, + ) + + a_copy_size = cute.size_in_bytes(self.a_dtype, a_smem_layout) + b_copy_size = cute.size_in_bytes(self.b_dtype, b_smem_layout) + self.num_tma_load_bytes = a_copy_size + b_copy_size + + epi_smem_layout = cute.select(self.c_smem_layout_staged, mode=[0, 1]) + tma_atom_c, tma_tensor_c = cpasync.make_tiled_tma_atom( + cpasync.CopyBulkTensorTileS2GOp(), c, epi_smem_layout, self.epi_tile + ) + + self.tile_sched_params, grid = resolve_scheduler_params_and_grid( + a=a, + cta_tile_k=self.cta_tile_shape_mnk[2], + cluster_shape_mn=self.cluster_shape_mn, + swap_ab=self.swap_ab, + persistent_clusters=self.persistent_clusters, + max_active_clusters=max_active_clusters, + ) + + self.kernel( + tiled_mma, + tma_atom_a, + tma_tensor_a, + tma_atom_b, + tma_tensor_b, + tma_atom_c, + tma_tensor_c, + sf_a, + sf_b, + group_m, + direct_schedule, + schedule_tiles, + self.cluster_layout_vmnk, + self.a_smem_layout_staged, + self.b_smem_layout_staged, + self.c_smem_layout_staged, + self.epi_tile, + self.tile_sched_params, + epilogue_op, + ).launch( + grid=grid, + block=[self.threads_per_cta, 1, 1], + cluster=(*self.cluster_shape_mn, 1), + stream=stream, + ) + return + + @cute.kernel + def kernel( + self, + tiled_mma: cute.TiledMma, + tma_atom_a: cute.CopyAtom, + mA_mkl: cute.Tensor, + tma_atom_b: cute.CopyAtom, + mB_nkl: cute.Tensor, + tma_atom_c: cute.CopyAtom, + mC_mnl: cute.Tensor, + sf_a: cute.Tensor, + sf_b: cute.Tensor, + group_m: cute.Tensor, + direct_schedule: cute.Tensor, + schedule_tiles: cute.Tensor, + cluster_layout_vmnk: cute.Layout, + a_smem_layout_staged: cute.ComposedLayout, + b_smem_layout_staged: cute.ComposedLayout, + c_smem_layout_staged: cute.ComposedLayout, + epi_tile: cute.Tile, + tile_sched_params, + epilogue_op: cutlass.Constexpr, + ): + warp_idx = cute.arch.warp_idx() + warp_idx = cute.arch.make_warp_uniform(warp_idx) + + if warp_idx == self.tma_warp_id: + cpasync.prefetch_descriptor(tma_atom_a) + cpasync.prefetch_descriptor(tma_atom_b) + cpasync.prefetch_descriptor(tma_atom_c) + + tidx, _, _ = cute.arch.thread_idx() + cta_n = self.cta_tile_shape_mnk[1] + + @cute.struct + class SharedStorage: + ab_full_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_ab_stage * 2] + acc_full_mbar_ptr: cute.struct.MemRange[ + cutlass.Int64, self.num_acc_stage * 2 + ] + col_scale: cute.struct.MemRange[cutlass.Float32, self.cta_tile_shape_mnk[1]] + tmem_dealloc_mbar: cutlass.Int64 + tmem_holding_buf: cutlass.Int32 + + smem = utils.SmemAllocator() + storage = smem.allocate(SharedStorage) + + ab_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread) + ab_pipeline_consumer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread, 1) + ab_producer, ab_consumer = pipeline.PipelineTmaUmma.create( + barrier_storage=storage.ab_full_mbar_ptr.data_ptr(), + num_stages=self.num_ab_stage, + producer_group=ab_pipeline_producer_group, + consumer_group=ab_pipeline_consumer_group, + tx_count=self.num_tma_load_bytes, + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ).make_participants() + + acc_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread) + acc_pipeline_consumer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, len(self.epilogue_warp_id) + ) + acc_pipeline = pipeline.PipelineUmmaAsync.create( + barrier_storage=storage.acc_full_mbar_ptr.data_ptr(), + num_stages=self.num_acc_stage, + producer_group=acc_pipeline_producer_group, + consumer_group=acc_pipeline_consumer_group, + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + + tmem_alloc_barrier = pipeline.NamedBarrier( + barrier_id=self.tmem_alloc_sync_bar_id, + num_threads=32 * len((self.mma_warp_id, *self.epilogue_warp_id)), + ) + tmem = utils.TmemAllocator( + storage.tmem_holding_buf.ptr, + barrier_for_retrieve=tmem_alloc_barrier, + allocator_warp_id=self.epilogue_warp_id[0], + is_two_cta=False, + two_cta_tmem_dealloc_mbar_ptr=storage.tmem_dealloc_mbar.ptr, + ) + + pipeline_init_arrive(cluster_shape_mn=cluster_layout_vmnk, is_relaxed=True) + + sA = smem.allocate_tensor( + element_type=self.a_dtype, + layout=a_smem_layout_staged.outer, + byte_alignment=128, + swizzle=a_smem_layout_staged.inner, + ) + sB = smem.allocate_tensor( + element_type=self.b_dtype, + layout=b_smem_layout_staged.outer, + byte_alignment=128, + swizzle=b_smem_layout_staged.inner, + ) + sColScale = cute.make_tensor( + storage.col_scale.data_ptr(), cute.make_layout(cta_n) + ) + + gA_mkl = cute.local_tile( + mA_mkl, cute.slice_(self.mma_tiler, (None, 0, None)), (None, None, None) + ) + gB_nkl = cute.local_tile( + mB_nkl, cute.slice_(self.mma_tiler, (0, None, None)), (None, None, None) + ) + gC_mnl = cute.local_tile( + mC_mnl, cute.slice_(self.mma_tiler, (None, None, 0)), (None, None, None) + ) + + thr_mma = tiled_mma.get_slice(0) + tCgA = thr_mma.partition_A(gA_mkl) + tCgB = thr_mma.partition_B(gB_nkl) + tCgC = thr_mma.partition_C(gC_mnl) + + a_cta_layout = cute.make_layout( + cute.slice_(cluster_layout_vmnk, (0, 0, None, 0)).shape + ) + tAsA, tAgA = cpasync.tma_partition( + tma_atom_a, + 0, + a_cta_layout, + cute.group_modes(sA, 0, 3), + cute.group_modes(tCgA, 0, 3), + ) + b_cta_layout = cute.make_layout( + cute.slice_(cluster_layout_vmnk, (0, None, 0, 0)).shape + ) + tBsB, tBgB = cpasync.tma_partition( + tma_atom_b, + 0, + b_cta_layout, + cute.group_modes(sB, 0, 3), + cute.group_modes(tCgB, 0, 3), + ) + + tCrA = tiled_mma.make_fragment_A(sA) + tCrB = tiled_mma.make_fragment_B(sB) + acc_shape = tiled_mma.partition_shape_C(self.mma_tiler[:2]) + tCtAcc_fake = tiled_mma.make_fragment_C( + cute.append(acc_shape, self.num_acc_stage) + ) + + pipeline_init_wait(cluster_shape_mn=cluster_layout_vmnk) + + tile_sched = create_moe_tile_scheduler( + tile_sched_params=tile_sched_params, + direct_schedule=direct_schedule, + schedule_tiles=schedule_tiles, + swap_ab=self.swap_ab, + ) + work_tile = tile_sched.initial_work_tile_info() + + if warp_idx == self.tma_warp_id: + while work_tile.is_valid_tile: + mma_tile_coord_mnl = ( + work_tile.tile_n_idx, + work_tile.tile_m_idx, + work_tile.expert_idx, + ) + a_rest_l_coord = mma_tile_coord_mnl[2] + if cutlass.const_expr(self.contiguous_segments): + seg_base_tile = ( + group_m[work_tile.expert_idx] // self.cta_tile_shape_mnk[1] + ) + mma_tile_coord_mnl = ( + mma_tile_coord_mnl[0], + seg_base_tile + mma_tile_coord_mnl[1], + cutlass.Int32(0), + ) + a_rest_l_coord = work_tile.expert_idx + + tAgA_slice = tAgA[(None, mma_tile_coord_mnl[0], None, a_rest_l_coord)] + tBgB_slice = tBgB[ + (None, mma_tile_coord_mnl[1], None, mma_tile_coord_mnl[2]) + ] + + ab_producer.reset() + peek_ab_empty_status = ab_producer.try_acquire() + + for k_tile in cutlass.range(0, work_tile.k_tile_cnt, 1, unroll=1): + handle = ab_producer.acquire_and_advance(peek_ab_empty_status) + cute.copy( + tma_atom_a, + tAgA_slice[(None, handle.count)], + tAsA[(None, handle.index)], + tma_bar_ptr=handle.barrier, + ) + cute.copy( + tma_atom_b, + tBgB_slice[(None, handle.count)], + tBsB[(None, handle.index)], + tma_bar_ptr=handle.barrier, + ) + peek_ab_empty_status = cutlass.Boolean(1) + if handle.count + 1 < work_tile.k_tile_cnt: + peek_ab_empty_status = ab_producer.try_acquire() + + work_tile = tile_sched.advance_to_next_work() + + ab_producer.tail() + + if warp_idx == self.mma_warp_id: + tmem.wait_for_alloc() + tmem_ptr = tmem.retrieve_ptr(self.acc_dtype) + tCtAcc_base = cute.make_tensor(tmem_ptr, tCtAcc_fake.layout) + + acc_producer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.num_acc_stage + ) + + while work_tile.is_valid_tile: + ab_consumer.reset() + peek_ab_full_status = ab_consumer.try_wait() + + # Hand each 128-K partial to the epilogue warps for scaling. + for k_tile in range(work_tile.k_tile_cnt): + tCtAcc = tCtAcc_base[(None, None, None, acc_producer_state.index)] + acc_pipeline.producer_acquire(acc_producer_state) + + handle = ab_consumer.wait_and_advance(peek_ab_full_status) + tiled_mma.set(tcgen05.Field.ACCUMULATE, False) + num_kblocks = cute.size(tCrA, mode=[2]) + for kblk_idx in cutlass.range(num_kblocks, unroll_full=True): + kblk_crd = (None, None, kblk_idx, handle.index) + cute.gemm( + tiled_mma, + tCtAcc, + tCrA[kblk_crd], + tCrB[kblk_crd], + tCtAcc, + ) + tiled_mma.set(tcgen05.Field.ACCUMULATE, True) + handle.release() + + peek_ab_full_status = cutlass.Boolean(1) + if handle.count + 1 < work_tile.k_tile_cnt: + peek_ab_full_status = ab_consumer.try_wait() + + acc_pipeline.producer_commit(acc_producer_state) + acc_producer_state.advance() + + work_tile = tile_sched.advance_to_next_work() + + acc_pipeline.producer_tail(acc_producer_state) + + sC = smem.allocate_tensor( + element_type=self.c_dtype, + layout=c_smem_layout_staged.outer, + byte_alignment=128, + swizzle=c_smem_layout_staged.inner, + ) + + if warp_idx < self.mma_warp_id: + tmem.allocate(self.num_tmem_alloc_cols) + tmem.wait_for_alloc() + tmem_ptr = tmem.retrieve_ptr(self.acc_dtype) + tCtAcc_base = cute.make_tensor(tmem_ptr, tCtAcc_fake.layout) + + acc_consumer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_acc_stage + ) + + c_producer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, + 32 * len(self.epilogue_warp_id), + ) + c_pipeline = pipeline.PipelineTmaStore.create( + num_stages=self.num_c_stage, producer_group=c_producer_group + ) + + epilog_sync_barrier = pipeline.NamedBarrier( + barrier_id=self.epilog_sync_bar_id, + num_threads=32 * len(self.epilogue_warp_id), + ) + + # Match accumulator elements to token columns for scale lookup. + tCgC_t = utils.gemm.sm100.transform_partitioned_tensor_layout(tCgC) + tCtAcc_t = utils.gemm.sm100.transform_partitioned_tensor_layout(tCtAcc_base) + tiled_copy_t2r, tTR_tAcc_base, tTR_rAcc = ( + utils.gemm.sm100.epilogue_tmem_copy_and_partition( + self, tidx, tCtAcc_t, tCgC_t, epi_tile, False + ) + ) + thr_copy_t2r = tiled_copy_t2r.get_slice(tidx) + cC = cute.make_identity_tensor( + (self.cta_tile_shape_mnk[0], self.cta_tile_shape_mnk[1]) + ) + cC_epi = cute.flat_divide(cC, epi_tile) + tTR_cC_epi = thr_copy_t2r.partition_D(cC_epi) + # ((frag), (subtile)): linear element and subtile indices. + tTR_cC = cute.group_modes( + cute.group_modes(tTR_cC_epi, 3, cute.rank(tTR_cC_epi)), 0, 3 + ) + + tTR_rC = cute.make_rmem_tensor(tTR_rAcc.shape, self.c_dtype) + tiled_copy_r2s, tRS_rC, tRS_sC = ( + utils.gemm.sm100.epilogue_smem_copy_and_partition( + self, tiled_copy_t2r, tTR_rC, tidx, sC + ) + ) + + tCgC_epi = cute.flat_divide(tCgC_t, epi_tile) + bSG_sC, bSG_gC_partitioned = cpasync.tma_partition( + tma_atom_c, + 0, + cute.make_layout(1), + cute.group_modes(sC, 0, 2), + cute.group_modes(tCgC_epi, 0, 2), + ) + + subtile_cnt = cute.size(tTR_cC.shape, mode=[1]) + frag_size = cute.size(tTR_rAcc.shape) + tTR_rAcc_flat = cute.group_modes(tTR_rAcc, 0, cute.rank(tTR_rAcc)) + tTR_rTotal = cute.make_rmem_tensor( + cute.make_layout((frag_size, subtile_cnt)), cutlass.Float32 + ) + + num_tiles_executed = cutlass.Int32(0) + while work_tile.is_valid_tile: + mma_tile_coord_mnl = ( + work_tile.tile_n_idx, + work_tile.tile_m_idx, + work_tile.expert_idx, + ) + weight_expert = work_tile.expert_idx + if cutlass.const_expr(self.contiguous_segments): + seg_base_tile = ( + group_m[work_tile.expert_idx] // self.cta_tile_shape_mnk[1] + ) + mma_tile_coord_mnl = ( + mma_tile_coord_mnl[0], + seg_base_tile + mma_tile_coord_mnl[1], + cutlass.Int32(0), + ) + k_tile_cnt = work_tile.k_tile_cnt + nt_idx = mma_tile_coord_mnl[0] + token_base = mma_tile_coord_mnl[1] * cta_n + token_rest_l = mma_tile_coord_mnl[2] + work_tile = tile_sched.advance_to_next_work() + + for i in cutlass.range_constexpr(frag_size): + for st in cutlass.range_constexpr(subtile_cnt): + tTR_rTotal[(i, st)] = cutlass.Float32(0.0) + + for k_tile in range(k_tile_cnt): + sw = sf_a[(nt_idx, k_tile, weight_expert)] + if tidx < cta_n: + sColScale[tidx] = ( + sw * sf_b[(token_base + tidx, k_tile, token_rest_l)] + ) + epilog_sync_barrier.arrive_and_wait() + + acc_pipeline.consumer_wait(acc_consumer_state) + tTR_tAcc = tTR_tAcc_base[ + (None, None, None, None, None, acc_consumer_state.index) + ] + tTR_tAcc = cute.group_modes(tTR_tAcc, 3, cute.rank(tTR_tAcc)) + for st in cutlass.range_constexpr(subtile_cnt): + cute.copy( + tiled_copy_t2r, + tTR_tAcc[(None, None, None, st)], + tTR_rAcc, + ) + for i in cutlass.range_constexpr(frag_size): + col = tTR_cC[(i, st)][1] + tTR_rTotal[(i, st)] = ( + tTR_rTotal[(i, st)] + tTR_rAcc_flat[i] * sColScale[col] + ) + with cute.arch.elect_one(): + acc_pipeline.consumer_release(acc_consumer_state) + acc_consumer_state.advance() + epilog_sync_barrier.arrive_and_wait() + + num_prev_subtiles = num_tiles_executed * subtile_cnt + bSG_gC = bSG_gC_partitioned[(None, None, None, *mma_tile_coord_mnl)] + bSG_gC = cute.group_modes(bSG_gC, 1, cute.rank(bSG_gC)) + for st in cutlass.range_constexpr(subtile_cnt): + for i in cutlass.range_constexpr(frag_size): + tTR_rAcc_flat[i] = tTR_rTotal[(i, st)] + acc_vec = tiled_copy_r2s.retile(tTR_rAcc).load() + acc_vec = epilogue_op(acc_vec.to(self.c_dtype)) + tRS_rC.store(acc_vec) + + c_buffer = (num_prev_subtiles + st) % self.num_c_stage + cute.copy( + tiled_copy_r2s, + tRS_rC, + tRS_sC[(None, None, None, c_buffer)], + ) + cute.arch.fence_proxy("async.shared", space="cta") + epilog_sync_barrier.arrive_and_wait() + if warp_idx == self.epilogue_warp_id[0]: + cute.copy( + tma_atom_c, + bSG_sC[(None, c_buffer)], + bSG_gC[(None, st)], + ) + c_pipeline.producer_commit() + c_pipeline.producer_acquire() + epilog_sync_barrier.arrive_and_wait() + num_tiles_executed = num_tiles_executed + 1 + + c_pipeline.producer_tail() + tmem.relinquish_alloc_permit() + tmem.free(tmem_ptr) diff --git a/python/sglang/kernels/ops/lora/moe/cutedsl/kernel_sm90_bf16.py b/python/sglang/kernels/ops/lora/moe/cutedsl/kernel_sm90_bf16.py new file mode 100644 index 0000000000..5cb6b85402 --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/cutedsl/kernel_sm90_bf16.py @@ -0,0 +1,802 @@ +# Copyright (c) 2025 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: BSD-3-Clause + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# 3. Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import math +from typing import Optional, Tuple, Type + +import cuda.bindings.driver as cuda +import cutlass +import cutlass.cute as cute +import cutlass.utils as utils +import cutlass.utils.hopper_helpers as sm90_utils +from cutlass import pipeline +from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait + +from sglang.kernels.ops.lora.moe.cutedsl.scheduler import ( + MoESchedulerParams, + create_moe_tile_scheduler, + resolve_scheduler_params_and_grid, +) + + +class GroupedGemmKernelSm90Bf16: + """Hopper grouped GEMM with the same config interface as SM100.""" + + def __init__( + self, + acc_dtype: Type[cutlass.Numeric], + use_2cta_instrs: bool, + mma_tiler_mn: Tuple[int, int], + cluster_shape_mn: Tuple[int, int], + mma_inst_tile_k: int = 4, + persistent_clusters: Optional[int] = None, + swap_ab: bool = False, + contiguous_segments: bool = False, + ): + if use_2cta_instrs: + raise ValueError("2-CTA MMA is a tcgen05 feature; SM90 has none") + self.acc_dtype = acc_dtype + self.cluster_shape_mn = cluster_shape_mn + self.mma_inst_tile_k = mma_inst_tile_k + self.persistent_clusters = persistent_clusters + self.swap_ab = swap_ab + self.contiguous_segments = contiguous_segments + if contiguous_segments and not swap_ab: + raise ValueError("contiguous_segments requires swap_ab") + if contiguous_segments and cluster_shape_mn != (1, 1): + raise ValueError("contiguous_segments requires a (1, 1) cluster") + + # The K extent here is a placeholder. _setup_attributes computes it. + self.tile_shape_mnk = (*mma_tiler_mn, 1) + # Upstream uses a second math warp group only for large tiles. + self.atom_layout_mnk = ( + (2, 1, 1) + if self.tile_shape_mnk[0] > 64 and self.tile_shape_mnk[1] > 128 + else (1, 1, 1) + ) + + self.occupancy = 1 + self.num_dma_warp_groups = 1 + self.num_mma_warp_groups = math.prod(self.atom_layout_mnk) + self.num_threads_per_warp_group = 128 + self.threads_per_cta = ( + self.num_dma_warp_groups + self.num_mma_warp_groups + ) * self.num_threads_per_warp_group + self.load_warp_id = 0 + self.epi_store_warp_id = self.num_dma_warp_groups * 4 + self.load_register_requirement = 40 + self.mma_register_requirement = 232 + self.smem_capacity = utils.get_smem_capacity_in_bytes("sm_90") + self.num_mma_threads = ( + self.num_mma_warp_groups * self.num_threads_per_warp_group + ) + self.epilog_sync_barrier = pipeline.NamedBarrier( + barrier_id=1, num_threads=self.num_mma_threads + ) + self.buffer_align_bytes = 1024 + + self.tiled_mma = None + self.ab_stage = None + self.epi_stage = None + self.a_smem_layout_staged = None + self.b_smem_layout_staged = None + self.epi_smem_layout_staged = None + self.epi_tile = None + self.shared_storage = None + + def _setup_attributes(self): + self.tiled_mma = sm90_utils.make_trivial_tiled_mma( + self.a_dtype, + self.b_dtype, + self.a_layout.sm90_mma_major_mode(), + self.b_layout.sm90_mma_major_mode(), + self.acc_dtype, + self.atom_layout_mnk, + tiler_mn=(64, self.tile_shape_mnk[1]), + ) + mma_inst_shape_k = cute.size(self.tiled_mma.shape_mnk, mode=[2]) + self.tile_shape_mnk = ( + self.tile_shape_mnk[0], + self.tile_shape_mnk[1], + mma_inst_shape_k * self.mma_inst_tile_k, + ) + + self.cta_layout_mnk = cute.make_layout((*self.cluster_shape_mn, 1)) + self.num_mcast_ctas_a = self.cluster_shape_mn[1] + self.num_mcast_ctas_b = self.cluster_shape_mn[0] + self.is_a_mcast = self.num_mcast_ctas_a > 1 + self.is_b_mcast = self.num_mcast_ctas_b > 1 + + is_cooperative = self.atom_layout_mnk == (2, 1, 1) + self.epi_tile = ( + min(128 if is_cooperative else 64, self.tile_shape_mnk[0]), + min(32, self.tile_shape_mnk[1]), + ) + self.ab_stage, self.epi_stage = self._compute_stages( + self.tile_shape_mnk, + self.a_dtype, + self.b_dtype, + self.epi_tile, + self.c_dtype, + self.smem_capacity, + self.occupancy, + ) + ( + self.a_smem_layout_staged, + self.b_smem_layout_staged, + self.epi_smem_layout_staged, + ) = self._make_smem_layouts( + self.tile_shape_mnk, + self.epi_tile, + self.a_dtype, + self.a_layout, + self.b_dtype, + self.b_layout, + self.ab_stage, + self.c_dtype, + self.c_layout, + self.epi_stage, + ) + + @cute.jit + def __call__( + self, + a: cute.Tensor, + b: cute.Tensor, + c: cute.Tensor, + group_m: cute.Tensor, + direct_schedule: cute.Tensor, + schedule_tiles: cute.Tensor, + max_active_clusters: cutlass.Constexpr, + stream: cuda.CUstream, + epilogue_op: cutlass.Constexpr = lambda x: x, + ): + self.a_dtype = a.element_type + self.b_dtype = b.element_type + self.c_dtype = c.element_type + self.a_layout = utils.LayoutEnum.from_tensor(a) + self.b_layout = utils.LayoutEnum.from_tensor(b) + self.c_layout = utils.LayoutEnum.from_tensor(c) + if cutlass.const_expr(self.a_dtype != self.b_dtype): + raise TypeError(f"Type mismatch: {self.a_dtype} != {self.b_dtype}") + + self._setup_attributes() + + tma_atom_a, tma_tensor_a = self._make_tma_atoms_and_tensors( + a, + self.a_smem_layout_staged, + (self.tile_shape_mnk[0], self.tile_shape_mnk[2]), + self.cluster_shape_mn[1], + ) + tma_atom_b, tma_tensor_b = self._make_tma_atoms_and_tensors( + b, + self.b_smem_layout_staged, + (self.tile_shape_mnk[1], self.tile_shape_mnk[2]), + self.cluster_shape_mn[0], + ) + tma_atom_c, tma_tensor_c = self._make_tma_store_atoms_and_tensors( + c, self.epi_smem_layout_staged, self.epi_tile + ) + + self.tile_sched_params, grid = resolve_scheduler_params_and_grid( + a=a, + cta_tile_k=self.tile_shape_mnk[2], + cluster_shape_mn=self.cluster_shape_mn, + swap_ab=self.swap_ab, + persistent_clusters=self.persistent_clusters, + max_active_clusters=max_active_clusters, + ) + + @cute.struct + class SharedStorage: + mainloop_pipeline_array_ptr: cute.struct.MemRange[ + cutlass.Int64, self.ab_stage * 2 + ] + sA: cute.struct.Align[ + cute.struct.MemRange[ + self.a_dtype, cute.cosize(self.a_smem_layout_staged) + ], + self.buffer_align_bytes, + ] + sB: cute.struct.Align[ + cute.struct.MemRange[ + self.b_dtype, cute.cosize(self.b_smem_layout_staged) + ], + self.buffer_align_bytes, + ] + sC: cute.struct.Align[ + cute.struct.MemRange[ + self.c_dtype, cute.cosize(self.epi_smem_layout_staged) + ], + self.buffer_align_bytes, + ] + + self.shared_storage = SharedStorage + + self.kernel( + tma_atom_a, + tma_tensor_a, + tma_atom_b, + tma_tensor_b, + tma_atom_c, + tma_tensor_c, + group_m, + direct_schedule, + schedule_tiles, + self.tiled_mma, + self.cta_layout_mnk, + self.a_smem_layout_staged, + self.b_smem_layout_staged, + self.epi_smem_layout_staged, + self.tile_sched_params, + epilogue_op, + ).launch( + grid=grid, + block=[self.threads_per_cta, 1, 1], + cluster=(*self.cluster_shape_mn, 1), + min_blocks_per_mp=1, + stream=stream, + ) + return + + @cute.kernel + def kernel( + self, + tma_atom_a: cute.CopyAtom, + mA_mkl: cute.Tensor, + tma_atom_b: cute.CopyAtom, + mB_nkl: cute.Tensor, + tma_atom_c: cute.CopyAtom, + mC_mnl: cute.Tensor, + group_m: cute.Tensor, + direct_schedule: cute.Tensor, + schedule_tiles: cute.Tensor, + tiled_mma: cute.TiledMma, + cta_layout_mnk: cute.Layout, + a_smem_layout_staged: cute.ComposedLayout, + b_smem_layout_staged: cute.ComposedLayout, + epi_smem_layout_staged: cute.ComposedLayout, + tile_sched_params: MoESchedulerParams, + epilogue_op: cutlass.Constexpr, + ): + tidx, _, _ = cute.arch.thread_idx() + warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + + if warp_idx == 0: + cute.nvgpu.cpasync.prefetch_descriptor(tma_atom_a) + cute.nvgpu.cpasync.prefetch_descriptor(tma_atom_b) + cute.nvgpu.cpasync.prefetch_descriptor(tma_atom_c) + + cta_rank_in_cluster = cute.arch.make_warp_uniform( + cute.arch.block_idx_in_cluster() + ) + cluster_coord_mnk = cta_layout_mnk.get_flat_coord(cta_rank_in_cluster) + a_mcast_mask = cute.make_layout_image_mask( + cta_layout_mnk, cluster_coord_mnk, mode=1 + ) + b_mcast_mask = cute.make_layout_image_mask( + cta_layout_mnk, cluster_coord_mnk, mode=0 + ) + a_mcast_mask = a_mcast_mask if self.is_a_mcast else 0 + b_mcast_mask = b_mcast_mask if self.is_b_mcast else 0 + + a_smem_layout = cute.slice_(a_smem_layout_staged, (None, None, 0)) + b_smem_layout = cute.slice_(b_smem_layout_staged, (None, None, 0)) + tma_copy_bytes = cute.size_in_bytes( + self.a_dtype, a_smem_layout + ) + cute.size_in_bytes(self.b_dtype, b_smem_layout) + + smem = utils.SmemAllocator() + storage = smem.allocate(self.shared_storage) + + mainloop_pipeline_producer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread + ) + mcast_size = self.num_mcast_ctas_a + self.num_mcast_ctas_b - 1 + consumer_arrive_cnt = mcast_size * self.num_mma_warp_groups * 4 + mainloop_pipeline_consumer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, consumer_arrive_cnt + ) + mainloop_pipeline = pipeline.PipelineTmaAsync.create( + barrier_storage=storage.mainloop_pipeline_array_ptr.data_ptr(), + num_stages=self.ab_stage, + producer_group=mainloop_pipeline_producer_group, + consumer_group=mainloop_pipeline_consumer_group, + tx_count=tma_copy_bytes, + cta_layout_vmnk=cute.make_layout((1, *cta_layout_mnk.shape)), + defer_sync=True, + ) + pipeline_init_arrive(cluster_shape_mn=self.cluster_shape_mn, is_relaxed=True) + + sA = storage.sA.get_tensor( + a_smem_layout_staged.outer, swizzle=a_smem_layout_staged.inner + ) + sB = storage.sB.get_tensor( + b_smem_layout_staged.outer, swizzle=b_smem_layout_staged.inner + ) + sC = storage.sC.get_tensor( + epi_smem_layout_staged.outer, swizzle=epi_smem_layout_staged.inner + ) + + # (bM, bK, RestM, RestK, RestL). The L mode is the expert index. + gA_mkl = cute.local_tile( + mA_mkl, + cute.slice_(self.tile_shape_mnk, (None, 0, None)), + (None, None, None), + ) + gB_nkl = cute.local_tile( + mB_nkl, + cute.slice_(self.tile_shape_mnk, (0, None, None)), + (None, None, None), + ) + gC_mnl = cute.local_tile( + mC_mnl, + cute.slice_(self.tile_shape_mnk, (None, None, 0)), + (None, None, None), + ) + + a_cta_layout = cute.make_layout(cute.slice_(cta_layout_mnk, (0, None, 0)).shape) + tAsA, tAgA = cute.nvgpu.cpasync.tma_partition( + tma_atom_a, + cluster_coord_mnk[1], + a_cta_layout, + cute.group_modes(sA, 0, 2), + cute.group_modes(gA_mkl, 0, 2), + ) + b_cta_layout = cute.make_layout(cute.slice_(cta_layout_mnk, (None, 0, 0)).shape) + tBsB, tBgB = cute.nvgpu.cpasync.tma_partition( + tma_atom_b, + cluster_coord_mnk[0], + b_cta_layout, + cute.group_modes(sB, 0, 2), + cute.group_modes(gB_nkl, 0, 2), + ) + + warp_group_idx = cute.arch.make_warp_uniform( + tidx // self.num_threads_per_warp_group + ) + mma_warp_group_thread_layout = cute.make_layout( + self.num_mma_warp_groups, stride=self.num_threads_per_warp_group + ) + thr_mma = tiled_mma.get_slice( + mma_warp_group_thread_layout(warp_group_idx - self.num_dma_warp_groups) + ) + + tCsA = thr_mma.partition_A(sA) + tCsB = thr_mma.partition_B(sB) + tCrA = tiled_mma.make_fragment_A(tCsA) + tCrB = tiled_mma.make_fragment_B(tCsB) + tCgC = thr_mma.partition_C(gC_mnl) + accumulators = cute.make_rmem_tensor(tCgC.shape[:3], self.acc_dtype) + + pipeline_init_wait(cluster_shape_mn=self.cluster_shape_mn) + + tile_sched = create_moe_tile_scheduler( + tile_sched_params=tile_sched_params, + direct_schedule=direct_schedule, + schedule_tiles=schedule_tiles, + swap_ab=self.swap_ab, + ) + work_tile = tile_sched.initial_work_tile_info() + + is_dma_warp_group = warp_group_idx < self.num_dma_warp_groups + if is_dma_warp_group: + cute.arch.setmaxregister_decrease(self.load_register_requirement) + + if warp_idx == self.load_warp_id: + mainloop_producer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.ab_stage + ) + while work_tile.is_valid_tile: + mma_tile_coord_mnl = ( + work_tile.tile_m_idx, + work_tile.tile_n_idx, + work_tile.expert_idx, + ) + if cutlass.const_expr(self.swap_ab): + mma_tile_coord_mnl = ( + work_tile.tile_n_idx, + work_tile.tile_m_idx, + work_tile.expert_idx, + ) + a_rest_l_coord = mma_tile_coord_mnl[2] + if cutlass.const_expr(self.contiguous_segments): + # Flat rows use slot 0 plus seg_offsets; weights keep the expert. + seg_base_tile = ( + group_m[work_tile.expert_idx] // self.tile_shape_mnk[1] + ) + mma_tile_coord_mnl = ( + mma_tile_coord_mnl[0], + seg_base_tile + mma_tile_coord_mnl[1], + cutlass.Int32(0), + ) + a_rest_l_coord = work_tile.expert_idx + tAgA_mkl = tAgA[(None, mma_tile_coord_mnl[0], None, a_rest_l_coord)] + tBgB_nkl = tBgB[ + (None, mma_tile_coord_mnl[1], None, mma_tile_coord_mnl[2]) + ] + + mainloop_producer_state.reset_count() + for k_tile in cutlass.range(0, work_tile.k_tile_cnt, 1, unroll=1): + mainloop_pipeline.producer_acquire(mainloop_producer_state) + cute.copy( + tma_atom_a, + tAgA_mkl[(None, mainloop_producer_state.count)], + tAsA[(None, mainloop_producer_state.index)], + tma_bar_ptr=mainloop_pipeline.producer_get_barrier( + mainloop_producer_state + ), + mcast_mask=a_mcast_mask, + ) + cute.copy( + tma_atom_b, + tBgB_nkl[(None, mainloop_producer_state.count)], + tBsB[(None, mainloop_producer_state.index)], + tma_bar_ptr=mainloop_pipeline.producer_get_barrier( + mainloop_producer_state + ), + mcast_mask=b_mcast_mask, + ) + mainloop_pipeline.producer_commit(mainloop_producer_state) + mainloop_producer_state.advance() + + work_tile = tile_sched.advance_to_next_work() + mainloop_pipeline.producer_tail(mainloop_producer_state) + + if not is_dma_warp_group: + cute.arch.setmaxregister_increase(self.mma_register_requirement) + + mainloop_consumer_read_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.ab_stage + ) + mainloop_consumer_release_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.ab_stage + ) + num_k_blocks = cute.size(tCrA, mode=[2]) + + # N=8 has only four values/thread; the helper's fixed st.matrix x4 + # needs eight. Scale the matrix count with the tile instead. + num_store_matrices = min(4, max(1, self.tile_shape_mnk[1] // 4)) + if cutlass.const_expr(self.c_dtype.width == 16): + copy_atom_r2s = cute.make_copy_atom( + cute.nvgpu.warp.StMatrix8x8x16bOp( + self.c_layout.is_m_major_c(), num_store_matrices + ), + self.c_dtype, + ) + else: + copy_atom_r2s = sm90_utils.sm90_get_smem_store_op( + self.c_layout, elem_ty_d=self.c_dtype, elem_ty_acc=self.acc_dtype + ) + copy_atom_C = cute.make_copy_atom( + cute.nvgpu.warp.StMatrix8x8x16bOp( + self.c_layout.is_m_major_c(), num_store_matrices + ), + self.c_dtype, + ) + tiled_copy_C_Atom = cute.make_tiled_copy_C_atom(copy_atom_C, tiled_mma) + tiled_copy_r2s = cute.make_tiled_copy_S(copy_atom_r2s, tiled_copy_C_Atom) + thr_copy_r2s = tiled_copy_r2s.get_slice( + tidx - self.num_dma_warp_groups * self.num_threads_per_warp_group + ) + tRS_sD = thr_copy_r2s.partition_D(sC) + tRS_rAcc = tiled_copy_r2s.retile(accumulators) + rD_shape = cute.shape(thr_copy_r2s.partition_S(sC)) + tRS_rD_layout = cute.make_layout(rD_shape[:3]) + tRS_rD = cute.make_rmem_tensor(tRS_rD_layout.shape, self.acc_dtype) + tRS_rD_out = cute.make_rmem_tensor(tRS_rD_layout.shape, self.c_dtype) + size_tRS_rD = cute.size(tRS_rD) + + tma_store_producer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, self.num_mma_threads + ) + tma_store_pipeline = pipeline.PipelineTmaStore.create( + num_stages=self.epi_stage, + producer_group=tma_store_producer_group, + ) + + # Rotate epilogue buffers by executed tiles, not global work index. + num_tiles_executed = cutlass.Int32(0) + + while work_tile.is_valid_tile: + mma_tile_coord_mnl = ( + work_tile.tile_m_idx, + work_tile.tile_n_idx, + work_tile.expert_idx, + ) + if cutlass.const_expr(self.swap_ab): + mma_tile_coord_mnl = ( + work_tile.tile_n_idx, + work_tile.tile_m_idx, + work_tile.expert_idx, + ) + if cutlass.const_expr(self.contiguous_segments): + # Use the same flat segment offset as the DMA warp. + seg_base_tile = ( + group_m[work_tile.expert_idx] // self.tile_shape_mnk[1] + ) + mma_tile_coord_mnl = ( + mma_tile_coord_mnl[0], + seg_base_tile + mma_tile_coord_mnl[1], + cutlass.Int32(0), + ) + gC_mnl_slice = gC_mnl[(None, None, *mma_tile_coord_mnl)] + + mainloop_consumer_read_state.reset_count() + mainloop_consumer_release_state.reset_count() + accumulators.fill(0.0) + tiled_mma.set(cute.nvgpu.warpgroup.Field.ACCUMULATE, True) + cute.nvgpu.warpgroup.fence() + + # Positive, aligned K guarantees one prologue tile. + k_pipe_mmas = 1 + for k_tile in cutlass.range(0, k_pipe_mmas, 1, unroll=1): + mainloop_pipeline.consumer_wait(mainloop_consumer_read_state) + for k_block_idx in cutlass.range_constexpr(num_k_blocks): + k_block_coord = ( + None, + None, + k_block_idx, + mainloop_consumer_read_state.index, + ) + cute.gemm( + tiled_mma, + accumulators, + tCrA[k_block_coord], + tCrB[k_block_coord], + accumulators, + ) + cute.nvgpu.warpgroup.commit_group() + mainloop_consumer_read_state.advance() + + for k_tile in cutlass.range( + k_pipe_mmas, work_tile.k_tile_cnt, 1, unroll=1 + ): + mainloop_pipeline.consumer_wait(mainloop_consumer_read_state) + for k_block_idx in cutlass.range_constexpr(num_k_blocks): + k_block_coord = ( + None, + None, + k_block_idx, + mainloop_consumer_read_state.index, + ) + cute.gemm( + tiled_mma, + accumulators, + tCrA[k_block_coord], + tCrB[k_block_coord], + accumulators, + ) + cute.nvgpu.warpgroup.commit_group() + cute.nvgpu.warpgroup.wait_group(k_pipe_mmas) + mainloop_pipeline.consumer_release(mainloop_consumer_release_state) + mainloop_consumer_release_state.advance() + mainloop_consumer_read_state.advance() + + cute.nvgpu.warpgroup.wait_group(0) + for k_tile in cutlass.range(0, k_pipe_mmas, 1, unroll=1): + mainloop_pipeline.consumer_release(mainloop_consumer_release_state) + mainloop_consumer_release_state.advance() + + tCgC_for_tma_partition = cute.zipped_divide(gC_mnl_slice, self.epi_tile) + bSG_sD, bSG_gD = cute.nvgpu.cpasync.tma_partition( + tma_atom_c, + 0, + cute.make_layout(1), + cute.group_modes(sC, 0, 2), + tCgC_for_tma_partition, + ) + epi_tile_num = cute.size(tCgC_for_tma_partition, mode=[1]) + epi_tile_shape = tCgC_for_tma_partition.shape[1] + epi_tile_layout = cute.make_layout( + epi_tile_shape, stride=(epi_tile_shape[1], 1) + ) + num_prev_epi_tiles = num_tiles_executed * epi_tile_num + + for epi_idx in cutlass.range_constexpr(epi_tile_num): + for epi_v in cutlass.range_constexpr(size_tRS_rD): + tRS_rD[epi_v] = tRS_rAcc[epi_idx * size_tRS_rD + epi_v] + acc_vec = epilogue_op(tRS_rD.load()) + tRS_rD_out.store(acc_vec.to(self.c_dtype)) + + epi_buffer = (num_prev_epi_tiles + epi_idx) % cute.size( + tRS_sD, mode=[3] + ) + cute.copy( + tiled_copy_r2s, + tRS_rD_out, + tRS_sD[(None, None, None, epi_buffer)], + ) + cute.arch.fence_proxy("async.shared", space="cta") + self.epilog_sync_barrier.arrive_and_wait() + + gmem_coord = epi_tile_layout.get_hier_coord(epi_idx) + if warp_idx == self.epi_store_warp_id: + cute.copy( + tma_atom_c, + bSG_sD[(None, epi_buffer)], + bSG_gD[(None, gmem_coord)], + ) + tma_store_pipeline.producer_commit() + tma_store_pipeline.producer_acquire() + self.epilog_sync_barrier.arrive_and_wait() + + num_tiles_executed += cutlass.Int32(1) + work_tile = tile_sched.advance_to_next_work() + + tma_store_pipeline.producer_tail() + + # The host helpers below come from the upstream Hopper persistent example. + + @staticmethod + def _compute_stages( + tile_shape_mnk, + a_dtype, + b_dtype, + epi_tile, + c_dtype, + smem_capacity, + occupancy, + ): + a_shape = cute.slice_(tile_shape_mnk, (None, 0, None)) + b_shape = cute.slice_(tile_shape_mnk, (0, None, None)) + ab_bytes_per_stage = ( + cute.size(a_shape) * a_dtype.width // 8 + + cute.size(b_shape) * b_dtype.width // 8 + ) + c_bytes_per_stage = cute.size(epi_tile) * c_dtype.width // 8 + epi_stage = 4 + epi_bytes = c_bytes_per_stage * epi_stage + mbar_helpers_bytes = 1024 + ab_stage = ( + smem_capacity // occupancy - (mbar_helpers_bytes + epi_bytes) + ) // ab_bytes_per_stage + return ab_stage, epi_stage + + @staticmethod + def _make_smem_layouts( + tile_shape_mnk, + epi_tile, + a_dtype, + a_layout, + b_dtype, + b_layout, + ab_stage, + c_dtype, + c_layout, + epi_stage, + ): + a_smem_shape = cute.slice_(tile_shape_mnk, (None, 0, None)) + a_is_k_major = ( + a_layout.sm90_mma_major_mode() == cute.nvgpu.warpgroup.OperandMajorMode.K + ) + b_is_k_major = ( + b_layout.sm90_mma_major_mode() == cute.nvgpu.warpgroup.OperandMajorMode.K + ) + a_major_mode_size = tile_shape_mnk[2 if a_is_k_major else 0] + a_smem_layout_atom = cute.nvgpu.warpgroup.make_smem_layout_atom( + sm90_utils.get_smem_layout_atom(a_layout, a_dtype, a_major_mode_size), + a_dtype, + ) + a_smem_layout_staged = cute.tile_to_shape( + a_smem_layout_atom, + cute.append(a_smem_shape, ab_stage), + order=(0, 1, 2) if a_is_k_major else (1, 0, 2), + ) + + b_smem_shape = cute.slice_(tile_shape_mnk, (0, None, None)) + b_major_mode_size = tile_shape_mnk[2 if b_is_k_major else 1] + b_smem_layout_atom = cute.nvgpu.warpgroup.make_smem_layout_atom( + sm90_utils.get_smem_layout_atom(b_layout, b_dtype, b_major_mode_size), + b_dtype, + ) + b_smem_layout_staged = cute.tile_to_shape( + b_smem_layout_atom, + cute.append(b_smem_shape, ab_stage), + order=(0, 1, 2) if b_is_k_major else (1, 0, 2), + ) + + c_smem_shape = epi_tile + c_major_mode_size = epi_tile[1] if c_layout.is_n_major_c() else epi_tile[0] + c_smem_layout_atom = cute.nvgpu.warpgroup.make_smem_layout_atom( + sm90_utils.get_smem_layout_atom(c_layout, c_dtype, c_major_mode_size), + c_dtype, + ) + epi_smem_layout_staged = cute.tile_to_shape( + c_smem_layout_atom, + cute.append(c_smem_shape, epi_stage), + order=(1, 0, 2) if c_layout.is_m_major_c() else (0, 1, 2), + ) + return a_smem_layout_staged, b_smem_layout_staged, epi_smem_layout_staged + + @staticmethod + def _make_tma_store_atoms_and_tensors(tensor_c, epi_smem_layout_staged, epi_tile): + epi_smem_layout = cute.slice_(epi_smem_layout_staged, (None, None, 0)) + return cute.nvgpu.cpasync.make_tiled_tma_atom( + cute.nvgpu.cpasync.CopyBulkTensorTileS2GOp(), + tensor_c, + epi_smem_layout, + epi_tile, + ) + + @staticmethod + def _make_tma_atoms_and_tensors(tensor, smem_layout_staged, smem_tile, mcast_dim): + op = ( + cute.nvgpu.cpasync.CopyBulkTensorTileG2SOp() + if mcast_dim == 1 + else cute.nvgpu.cpasync.CopyBulkTensorTileG2SMulticastOp() + ) + smem_layout = cute.slice_(smem_layout_staged, (None, None, 0)) + return cute.nvgpu.cpasync.make_tiled_tma_atom( + op, tensor, smem_layout, smem_tile, num_multicast=mcast_dim + ) + + def check_supported_dtypes(self, a_dtype, b_dtype, c_dtype): + if a_dtype not in (cutlass.Float16, cutlass.BFloat16): + raise TypeError(f"SM90 port supports F16/BF16 A/B; got {a_dtype}") + if a_dtype != b_dtype: + raise TypeError(f"A/B dtype mismatch: {a_dtype} vs {b_dtype}") + if c_dtype not in (cutlass.Float16, cutlass.BFloat16, cutlass.Float32): + raise TypeError(f"unsupported C dtype {c_dtype}") + + def check_mma_tiler_and_cluster_shape(self): + if self.tile_shape_mnk[0] not in (64, 128): + raise ValueError("SM90 CTA tile M must be 64/128") + if self.tile_shape_mnk[1] not in (8, 16, 32, 64, 128, 256): + raise ValueError( + "this port validates CTA tile N in {8, 16, 32, 64, 128, " + "256}; WGMMA itself accepts 8..256 step 8 -- extend the " + "validated set before requesting other widths" + ) + if math.prod(self.cluster_shape_mn) > 4: + raise ValueError("SM90 cluster size must be <= 4") + for extent in self.cluster_shape_mn: + if extent <= 0 or extent & (extent - 1): + raise ValueError( + "cluster extents must be positive powers of two; got " + f"{self.cluster_shape_mn}" + ) + + def check_tensor_alignment(self, problem_shape, a_major, b_major, c_major): + if a_major != "k" or b_major != "k": + raise ValueError("SM90 port requires K-major A and B") + m, n, k, _length = problem_shape + for extent, name in ((m, "M"), (n, "N"), (k, "K")): + if extent % 8: + raise ValueError(f"{name}={extent} breaks 16-byte TMA alignment") + + def can_implement( + self, problem_shape, a_dtype, b_dtype, c_dtype, a_major, b_major, c_major + ) -> bool: + try: + self.check_supported_dtypes(a_dtype, b_dtype, c_dtype) + self.check_mma_tiler_and_cluster_shape() + self.check_tensor_alignment(problem_shape, a_major, b_major, c_major) + except (TypeError, ValueError): + return False + return True diff --git a/python/sglang/kernels/ops/lora/moe/cutedsl/kernel_sm90_fp8.py b/python/sglang/kernels/ops/lora/moe/cutedsl/kernel_sm90_fp8.py new file mode 100644 index 0000000000..08afb18d7a --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/cutedsl/kernel_sm90_fp8.py @@ -0,0 +1,1044 @@ +# Copyright (c) 2025 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: BSD-3-Clause + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# 3. Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import math +from typing import Optional, Tuple, Type + +import cuda.bindings.driver as cuda +import cutlass +import cutlass.cute as cute +import cutlass.utils as utils +import cutlass.utils.hopper_helpers as sm90_utils +from cutlass import pipeline +from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait + +from sglang.kernels.ops.lora.moe.cutedsl.scheduler import ( + MoESchedulerParams, + create_moe_tile_scheduler, + resolve_scheduler_params_and_grid, +) + + +class GroupedGemmKernelSm90Fp8: + """Hopper FP8 GEMM with software FP32 scale promotion per 128-K tile. + + swap_ab puts weights on M, giving one weight scale per tile and one + activation scale per token. Partial sums are scaled before accumulation. + """ + + SUPPORTS_SINGLE_K_PIPELINE = True + + def __init__( + self, + acc_dtype: Type[cutlass.Numeric], + use_2cta_instrs: bool, + mma_tiler_mn: Tuple[int, int], + cluster_shape_mn: Tuple[int, int], + mma_inst_tile_k: int = 4, + persistent_clusters: Optional[int] = None, + swap_ab: bool = False, + contiguous_segments: bool = False, + single_k_pipeline: bool = False, + ): + if use_2cta_instrs: + raise ValueError("2-CTA MMA is a tcgen05 feature; SM90 has none") + if not swap_ab: + raise ValueError("the FP8 grouped GEMM implements swap_ab only") + if mma_inst_tile_k != 4: + # 4 x k32 FP8 WGMMA steps = one 128-element scale group per tile. + raise ValueError("FP8 promotion pins mma_inst_tile_k to 4") + self.acc_dtype = acc_dtype + self.single_k_pipeline = single_k_pipeline + self.cluster_shape_mn = cluster_shape_mn + self.mma_inst_tile_k = mma_inst_tile_k + self.persistent_clusters = persistent_clusters + self.swap_ab = swap_ab + self.contiguous_segments = contiguous_segments + if contiguous_segments and cluster_shape_mn != (1, 1): + raise ValueError("contiguous_segments requires a (1, 1) cluster") + + # The K extent here is a placeholder. _setup_attributes computes it. + self.tile_shape_mnk = (*mma_tiler_mn, 1) + # Upstream uses a second math warp group only for large tiles. + self.atom_layout_mnk = ( + (2, 1, 1) + if self.tile_shape_mnk[0] > 64 and self.tile_shape_mnk[1] > 128 + else (1, 1, 1) + ) + + self.occupancy = 1 + self.num_dma_warp_groups = 1 + self.num_mma_warp_groups = math.prod(self.atom_layout_mnk) + self.num_threads_per_warp_group = 128 + self.threads_per_cta = ( + self.num_dma_warp_groups + self.num_mma_warp_groups + ) * self.num_threads_per_warp_group + self.load_warp_id = 0 + self.epi_store_warp_id = self.num_dma_warp_groups * 4 + self.load_register_requirement = 40 + self.mma_register_requirement = 232 + self.smem_capacity = utils.get_smem_capacity_in_bytes("sm_90") + self.num_mma_threads = ( + self.num_mma_warp_groups * self.num_threads_per_warp_group + ) + self.epilog_sync_barrier = pipeline.NamedBarrier( + barrier_id=1, num_threads=self.num_mma_threads + ) + self.buffer_align_bytes = 1024 + + self.tiled_mma = None + self.ab_stage = None + self.epi_stage = None + self.a_smem_layout_staged = None + self.b_smem_layout_staged = None + self.epi_smem_layout_staged = None + self.epi_tile = None + self.shared_storage = None + + def _setup_attributes(self): + self.tiled_mma = sm90_utils.make_trivial_tiled_mma( + self.a_dtype, + self.b_dtype, + self.a_layout.sm90_mma_major_mode(), + self.b_layout.sm90_mma_major_mode(), + self.acc_dtype, + self.atom_layout_mnk, + tiler_mn=(64, self.tile_shape_mnk[1]), + ) + mma_inst_shape_k = cute.size(self.tiled_mma.shape_mnk, mode=[2]) + self.tile_shape_mnk = ( + self.tile_shape_mnk[0], + self.tile_shape_mnk[1], + mma_inst_shape_k * self.mma_inst_tile_k, + ) + + self.cta_layout_mnk = cute.make_layout((*self.cluster_shape_mn, 1)) + self.num_mcast_ctas_a = self.cluster_shape_mn[1] + self.num_mcast_ctas_b = self.cluster_shape_mn[0] + self.is_a_mcast = self.num_mcast_ctas_a > 1 + self.is_b_mcast = self.num_mcast_ctas_b > 1 + + is_cooperative = self.atom_layout_mnk == (2, 1, 1) + self.epi_tile = ( + min(128 if is_cooperative else 64, self.tile_shape_mnk[0]), + min(32, self.tile_shape_mnk[1]), + ) + self.ab_stage, self.epi_stage = self._compute_stages( + self.tile_shape_mnk, + self.a_dtype, + self.b_dtype, + self.epi_tile, + self.c_dtype, + self.smem_capacity, + self.occupancy, + ) + ( + self.a_smem_layout_staged, + self.b_smem_layout_staged, + self.epi_smem_layout_staged, + ) = self._make_smem_layouts( + self.tile_shape_mnk, + self.epi_tile, + self.a_dtype, + self.a_layout, + self.b_dtype, + self.b_layout, + self.ab_stage, + self.c_dtype, + self.c_layout, + self.epi_stage, + ) + + @cute.jit + def __call__( + self, + a: cute.Tensor, + b: cute.Tensor, + sfa: cute.Tensor, + sfb: cute.Tensor, + c: cute.Tensor, + group_m: cute.Tensor, + direct_schedule: cute.Tensor, + schedule_tiles: cute.Tensor, + max_active_clusters: cutlass.Constexpr, + stream: cuda.CUstream, + epilogue_op: cutlass.Constexpr = lambda x: x, + ): + self.a_dtype = a.element_type + self.b_dtype = b.element_type + self.c_dtype = c.element_type + self.a_layout = utils.LayoutEnum.from_tensor(a) + self.b_layout = utils.LayoutEnum.from_tensor(b) + self.c_layout = utils.LayoutEnum.from_tensor(c) + if cutlass.const_expr(self.a_dtype != self.b_dtype): + raise TypeError(f"Type mismatch: {self.a_dtype} != {self.b_dtype}") + + self._setup_attributes() + + tma_atom_a, tma_tensor_a = self._make_tma_atoms_and_tensors( + a, + self.a_smem_layout_staged, + (self.tile_shape_mnk[0], self.tile_shape_mnk[2]), + self.cluster_shape_mn[1], + ) + tma_atom_b, tma_tensor_b = self._make_tma_atoms_and_tensors( + b, + self.b_smem_layout_staged, + (self.tile_shape_mnk[1], self.tile_shape_mnk[2]), + self.cluster_shape_mn[0], + ) + tma_atom_c, tma_tensor_c = self._make_tma_store_atoms_and_tensors( + c, self.epi_smem_layout_staged, self.epi_tile + ) + + self.tile_sched_params, grid = resolve_scheduler_params_and_grid( + a=a, + cta_tile_k=self.tile_shape_mnk[2], + cluster_shape_mn=self.cluster_shape_mn, + swap_ab=self.swap_ab, + persistent_clusters=self.persistent_clusters, + max_active_clusters=max_active_clusters, + ) + + @cute.struct + class SharedStorage: + mainloop_pipeline_array_ptr: cute.struct.MemRange[ + cutlass.Int64, self.ab_stage * 2 + ] + sA: cute.struct.Align[ + cute.struct.MemRange[ + self.a_dtype, cute.cosize(self.a_smem_layout_staged) + ], + self.buffer_align_bytes, + ] + sB: cute.struct.Align[ + cute.struct.MemRange[ + self.b_dtype, cute.cosize(self.b_smem_layout_staged) + ], + self.buffer_align_bytes, + ] + sC: cute.struct.Align[ + cute.struct.MemRange[ + self.c_dtype, cute.cosize(self.epi_smem_layout_staged) + ], + self.buffer_align_bytes, + ] + + self.shared_storage = SharedStorage + + self.kernel( + tma_atom_a, + tma_tensor_a, + tma_atom_b, + tma_tensor_b, + tma_atom_c, + tma_tensor_c, + sfa, + sfb, + group_m, + direct_schedule, + schedule_tiles, + self.tiled_mma, + self.cta_layout_mnk, + self.a_smem_layout_staged, + self.b_smem_layout_staged, + self.epi_smem_layout_staged, + self.tile_sched_params, + epilogue_op, + ).launch( + grid=grid, + block=[self.threads_per_cta, 1, 1], + cluster=(*self.cluster_shape_mn, 1), + min_blocks_per_mp=1, + stream=stream, + ) + return + + @cute.kernel + def kernel( + self, + tma_atom_a: cute.CopyAtom, + mA_mkl: cute.Tensor, + tma_atom_b: cute.CopyAtom, + mB_nkl: cute.Tensor, + tma_atom_c: cute.CopyAtom, + mC_mnl: cute.Tensor, + mSFA_mkl: cute.Tensor, + mSFB_nkl: cute.Tensor, + group_m: cute.Tensor, + direct_schedule: cute.Tensor, + schedule_tiles: cute.Tensor, + tiled_mma: cute.TiledMma, + cta_layout_mnk: cute.Layout, + a_smem_layout_staged: cute.ComposedLayout, + b_smem_layout_staged: cute.ComposedLayout, + epi_smem_layout_staged: cute.ComposedLayout, + tile_sched_params: MoESchedulerParams, + epilogue_op: cutlass.Constexpr, + ): + tidx, _, _ = cute.arch.thread_idx() + warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + + if warp_idx == 0: + cute.nvgpu.cpasync.prefetch_descriptor(tma_atom_a) + cute.nvgpu.cpasync.prefetch_descriptor(tma_atom_b) + cute.nvgpu.cpasync.prefetch_descriptor(tma_atom_c) + + cta_rank_in_cluster = cute.arch.make_warp_uniform( + cute.arch.block_idx_in_cluster() + ) + cluster_coord_mnk = cta_layout_mnk.get_flat_coord(cta_rank_in_cluster) + a_mcast_mask = cute.make_layout_image_mask( + cta_layout_mnk, cluster_coord_mnk, mode=1 + ) + b_mcast_mask = cute.make_layout_image_mask( + cta_layout_mnk, cluster_coord_mnk, mode=0 + ) + a_mcast_mask = a_mcast_mask if self.is_a_mcast else 0 + b_mcast_mask = b_mcast_mask if self.is_b_mcast else 0 + + a_smem_layout = cute.slice_(a_smem_layout_staged, (None, None, 0)) + b_smem_layout = cute.slice_(b_smem_layout_staged, (None, None, 0)) + tma_copy_bytes = cute.size_in_bytes( + self.a_dtype, a_smem_layout + ) + cute.size_in_bytes(self.b_dtype, b_smem_layout) + + smem = utils.SmemAllocator() + storage = smem.allocate(self.shared_storage) + + mainloop_pipeline_producer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread + ) + mcast_size = self.num_mcast_ctas_a + self.num_mcast_ctas_b - 1 + consumer_arrive_cnt = mcast_size * self.num_mma_warp_groups * 4 + mainloop_pipeline_consumer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, consumer_arrive_cnt + ) + mainloop_pipeline = pipeline.PipelineTmaAsync.create( + barrier_storage=storage.mainloop_pipeline_array_ptr.data_ptr(), + num_stages=self.ab_stage, + producer_group=mainloop_pipeline_producer_group, + consumer_group=mainloop_pipeline_consumer_group, + tx_count=tma_copy_bytes, + cta_layout_vmnk=cute.make_layout((1, *cta_layout_mnk.shape)), + defer_sync=True, + ) + pipeline_init_arrive(cluster_shape_mn=self.cluster_shape_mn, is_relaxed=True) + + sA = storage.sA.get_tensor( + a_smem_layout_staged.outer, swizzle=a_smem_layout_staged.inner + ) + sB = storage.sB.get_tensor( + b_smem_layout_staged.outer, swizzle=b_smem_layout_staged.inner + ) + sC = storage.sC.get_tensor( + epi_smem_layout_staged.outer, swizzle=epi_smem_layout_staged.inner + ) + + # (bM, bK, RestM, RestK, RestL). The L mode is the expert index. + gA_mkl = cute.local_tile( + mA_mkl, + cute.slice_(self.tile_shape_mnk, (None, 0, None)), + (None, None, None), + ) + gB_nkl = cute.local_tile( + mB_nkl, + cute.slice_(self.tile_shape_mnk, (0, None, None)), + (None, None, None), + ) + gC_mnl = cute.local_tile( + mC_mnl, + cute.slice_(self.tile_shape_mnk, (None, None, 0)), + (None, None, None), + ) + + a_cta_layout = cute.make_layout(cute.slice_(cta_layout_mnk, (0, None, 0)).shape) + tAsA, tAgA = cute.nvgpu.cpasync.tma_partition( + tma_atom_a, + cluster_coord_mnk[1], + a_cta_layout, + cute.group_modes(sA, 0, 2), + cute.group_modes(gA_mkl, 0, 2), + ) + b_cta_layout = cute.make_layout(cute.slice_(cta_layout_mnk, (None, 0, 0)).shape) + tBsB, tBgB = cute.nvgpu.cpasync.tma_partition( + tma_atom_b, + cluster_coord_mnk[0], + b_cta_layout, + cute.group_modes(sB, 0, 2), + cute.group_modes(gB_nkl, 0, 2), + ) + + warp_group_idx = cute.arch.make_warp_uniform( + tidx // self.num_threads_per_warp_group + ) + mma_warp_group_thread_layout = cute.make_layout( + self.num_mma_warp_groups, stride=self.num_threads_per_warp_group + ) + thr_mma = tiled_mma.get_slice( + mma_warp_group_thread_layout(warp_group_idx - self.num_dma_warp_groups) + ) + + tCsA = thr_mma.partition_A(sA) + tCsB = thr_mma.partition_B(sB) + tCrA = tiled_mma.make_fragment_A(tCsA) + tCrB = tiled_mma.make_fragment_B(tCsB) + tCgC = thr_mma.partition_C(gC_mnl) + accumulators = cute.make_rmem_tensor(tCgC.shape[:3], self.acc_dtype) + acc_partial = cute.make_rmem_tensor(tCgC.shape[:3], self.acc_dtype) + # Match accumulator elements to token columns for scale lookup. + idC = cute.make_identity_tensor( + (self.tile_shape_mnk[0], self.tile_shape_mnk[1]) + ) + tCcC = thr_mma.partition_C(idC) + + pipeline_init_wait(cluster_shape_mn=self.cluster_shape_mn) + + tile_sched = create_moe_tile_scheduler( + tile_sched_params=tile_sched_params, + direct_schedule=direct_schedule, + schedule_tiles=schedule_tiles, + swap_ab=self.swap_ab, + ) + work_tile = tile_sched.initial_work_tile_info() + + is_dma_warp_group = warp_group_idx < self.num_dma_warp_groups + if is_dma_warp_group: + cute.arch.setmaxregister_decrease(self.load_register_requirement) + + if warp_idx == self.load_warp_id: + mainloop_producer_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.ab_stage + ) + while work_tile.is_valid_tile: + mma_tile_coord_mnl = ( + work_tile.tile_n_idx, + work_tile.tile_m_idx, + work_tile.expert_idx, + ) + a_rest_l_coord = mma_tile_coord_mnl[2] + if cutlass.const_expr(self.contiguous_segments): + # Flat rows use slot 0 plus seg_offsets; weights keep the expert. + seg_base_tile = ( + group_m[work_tile.expert_idx] // self.tile_shape_mnk[1] + ) + mma_tile_coord_mnl = ( + mma_tile_coord_mnl[0], + seg_base_tile + mma_tile_coord_mnl[1], + cutlass.Int32(0), + ) + a_rest_l_coord = work_tile.expert_idx + tAgA_mkl = tAgA[(None, mma_tile_coord_mnl[0], None, a_rest_l_coord)] + tBgB_nkl = tBgB[ + (None, mma_tile_coord_mnl[1], None, mma_tile_coord_mnl[2]) + ] + + mainloop_producer_state.reset_count() + for k_tile in cutlass.range(0, work_tile.k_tile_cnt, 1, unroll=1): + mainloop_pipeline.producer_acquire(mainloop_producer_state) + cute.copy( + tma_atom_a, + tAgA_mkl[(None, mainloop_producer_state.count)], + tAsA[(None, mainloop_producer_state.index)], + tma_bar_ptr=mainloop_pipeline.producer_get_barrier( + mainloop_producer_state + ), + mcast_mask=a_mcast_mask, + ) + cute.copy( + tma_atom_b, + tBgB_nkl[(None, mainloop_producer_state.count)], + tBsB[(None, mainloop_producer_state.index)], + tma_bar_ptr=mainloop_pipeline.producer_get_barrier( + mainloop_producer_state + ), + mcast_mask=b_mcast_mask, + ) + mainloop_pipeline.producer_commit(mainloop_producer_state) + mainloop_producer_state.advance() + + work_tile = tile_sched.advance_to_next_work() + mainloop_pipeline.producer_tail(mainloop_producer_state) + + if not is_dma_warp_group: + cute.arch.setmaxregister_increase(self.mma_register_requirement) + + mainloop_consumer_read_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.ab_stage + ) + mainloop_consumer_release_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.ab_stage + ) + num_k_blocks = cute.size(tCrA, mode=[2]) + + # N=8 has only four values/thread; the helper's fixed st.matrix x4 + # needs eight. Scale the matrix count with the tile instead. + num_store_matrices = min(4, max(1, self.tile_shape_mnk[1] // 4)) + copy_atom_r2s = cute.make_copy_atom( + cute.nvgpu.warp.StMatrix8x8x16bOp( + self.c_layout.is_m_major_c(), num_store_matrices + ), + self.c_dtype, + ) + copy_atom_C = cute.make_copy_atom( + cute.nvgpu.warp.StMatrix8x8x16bOp( + self.c_layout.is_m_major_c(), num_store_matrices + ), + self.c_dtype, + ) + tiled_copy_C_Atom = cute.make_tiled_copy_C_atom(copy_atom_C, tiled_mma) + tiled_copy_r2s = cute.make_tiled_copy_S(copy_atom_r2s, tiled_copy_C_Atom) + thr_copy_r2s = tiled_copy_r2s.get_slice( + tidx - self.num_dma_warp_groups * self.num_threads_per_warp_group + ) + tRS_sD = thr_copy_r2s.partition_D(sC) + tRS_rAcc = tiled_copy_r2s.retile(accumulators) + rD_shape = cute.shape(thr_copy_r2s.partition_S(sC)) + tRS_rD_layout = cute.make_layout(rD_shape[:3]) + tRS_rD = cute.make_rmem_tensor(tRS_rD_layout.shape, self.acc_dtype) + tRS_rD_out = cute.make_rmem_tensor(tRS_rD_layout.shape, self.c_dtype) + size_tRS_rD = cute.size(tRS_rD) + + tma_store_producer_group = pipeline.CooperativeGroup( + pipeline.Agent.Thread, self.num_mma_threads + ) + tma_store_pipeline = pipeline.PipelineTmaStore.create( + num_stages=self.epi_stage, + producer_group=tma_store_producer_group, + ) + + # Rotate epilogue buffers by executed tiles, not global work index. + num_tiles_executed = cutlass.Int32(0) + + # These helpers inline at trace time. + + def _tile_ctx(self, work, gC_mnl, group_m): + coord = (work.tile_n_idx, work.tile_m_idx, work.expert_idx) + rest_l = coord[2] + if cutlass.const_expr(self.contiguous_segments): + # Use the same flat segment offset as the DMA warp. + seg_base_tile = group_m[work.expert_idx] // self.tile_shape_mnk[1] + coord = (coord[0], seg_base_tile + coord[1], cutlass.Int32(0)) + rest_l = work.expert_idx + gC_slice = gC_mnl[(None, None, *coord)] + sfa_row_blk = (coord[0] * self.tile_shape_mnk[0]) // 128 + token_base = coord[1] * self.tile_shape_mnk[1] + return gC_slice, sfa_row_blk, token_base, rest_l, coord[2] + + # Add each lane's column offset to the warpgroup partition. + lane_col_base = (tidx % 32) % 4 * 2 + + def _load_scales( + sfa_row_blk, + token_base, + sfa_l, + sfb_l, + k_tile, + sfb_frag, + mSFA_mkl, + mSFB_nkl, + tCcC, + lane_col_base, + ): + sfa_s = mSFA_mkl[(sfa_row_blk, k_tile, sfa_l)] + for v in cutlass.range_constexpr(cute.size(sfb_frag, mode=[0])): + for im in cutlass.range_constexpr(cute.size(sfb_frag, mode=[1])): + for in_ in cutlass.range_constexpr( + cute.size(sfb_frag, mode=[2]) + ): + crd = (v, im, in_) + sfb_frag[crd] = mSFB_nkl[ + ( + token_base + lane_col_base + tCcC[crd][1], + k_tile, + sfb_l, + ) + ] + return sfa_s + + def _issue_mma( + acc_frag, + mainloop_pipeline, + read_state, + tiled_mma, + tCrA, + tCrB, + num_k_blocks, + ): + """Issue one K tile without draining its WGMMA group.""" + mainloop_pipeline.consumer_wait(read_state) + acc_frag.fill(0.0) + cute.nvgpu.warpgroup.fence() + for k_block_idx in cutlass.range_constexpr(num_k_blocks): + k_block_coord = ( + None, + None, + k_block_idx, + read_state.index, + ) + cute.gemm( + tiled_mma, + acc_frag, + tCrA[k_block_coord], + tCrB[k_block_coord], + acc_frag, + ) + cute.nvgpu.warpgroup.commit_group() + read_state.advance() + return read_state + + def _release_stage(mainloop_pipeline, release_state): + mainloop_pipeline.consumer_release(release_state) + release_state.advance() + return release_state + + def _promote(acc_frag, sfa_s, sfb_frag, accumulators): + # Nested coordinates pair layouts correctly; flat iteration does not. + # Single-K promotion overwrites the total. + for v in cutlass.range_constexpr(cute.size(accumulators, mode=[0])): + for im in cutlass.range_constexpr( + cute.size(accumulators, mode=[1]) + ): + for in_ in cutlass.range_constexpr( + cute.size(accumulators, mode=[2]) + ): + crd = (v, im, in_) + accumulators[crd] = acc_frag[crd] * (sfa_s * sfb_frag[crd]) + + def _epilogue( + self, + gC_slice, + tiles_executed, + tma_atom_c, + sC, + tRS_sD, + tRS_rAcc, + tRS_rD, + tRS_rD_out, + tiled_copy_r2s, + tma_store_pipeline, + warp_idx, + size_tRS_rD, + epilogue_op, + ): + tCgC_for_tma_partition = cute.zipped_divide(gC_slice, self.epi_tile) + bSG_sD, bSG_gD = cute.nvgpu.cpasync.tma_partition( + tma_atom_c, + 0, + cute.make_layout(1), + cute.group_modes(sC, 0, 2), + tCgC_for_tma_partition, + ) + epi_tile_num = cute.size(tCgC_for_tma_partition, mode=[1]) + epi_tile_shape = tCgC_for_tma_partition.shape[1] + epi_tile_layout = cute.make_layout( + epi_tile_shape, stride=(epi_tile_shape[1], 1) + ) + num_prev_epi_tiles = tiles_executed * epi_tile_num + + for epi_idx in cutlass.range_constexpr(epi_tile_num): + for epi_v in cutlass.range_constexpr(size_tRS_rD): + tRS_rD[epi_v] = tRS_rAcc[epi_idx * size_tRS_rD + epi_v] + acc_vec = epilogue_op(tRS_rD.load()) + tRS_rD_out.store(acc_vec.to(self.c_dtype)) + + epi_buffer = (num_prev_epi_tiles + epi_idx) % cute.size( + tRS_sD, mode=[3] + ) + cute.copy( + tiled_copy_r2s, + tRS_rD_out, + tRS_sD[(None, None, None, epi_buffer)], + ) + cute.arch.fence_proxy("async.shared", space="cta") + self.epilog_sync_barrier.arrive_and_wait() + + gmem_coord = epi_tile_layout.get_hier_coord(epi_idx) + if warp_idx == self.epi_store_warp_id: + cute.copy( + tma_atom_c, + bSG_sD[(None, epi_buffer)], + bSG_gD[(None, gmem_coord)], + ) + tma_store_pipeline.producer_commit() + tma_store_pipeline.producer_acquire() + self.epilog_sync_barrier.arrive_and_wait() + + # Set outside helpers: handle updates cannot cross staged regions. + tiled_mma.set(cute.nvgpu.warpgroup.Field.ACCUMULATE, True) + + if cutlass.const_expr(self.single_k_pipeline): + # Keep these buffers out of the multi-K path's register live ranges. + acc_partial2 = cute.make_fragment_like(acc_partial) + sfb_frag = cute.make_fragment_like(acc_partial) + sfb_frag2 = cute.make_fragment_like(acc_partial) + # Promote/store t-1 while tile t's WGMMA drains. Fixed fragment + # sets plus parity avoid spilling memrefs through the loop. + have_pending = cutlass.Boolean(False) + parity = cutlass.Boolean(False) + pend_sfa = cutlass.Float32(0.0) + pend_gC = gC_mnl[ + (None, None, cutlass.Int32(0), cutlass.Int32(0), cutlass.Int32(0)) + ] + while work_tile.is_valid_tile: + pend2_gC, sfa_blk0, tok0, sfal0, sfbl0 = _tile_ctx( + self, work_tile, gC_mnl, group_m + ) + pend2_sfa = cutlass.Float32(0.0) + mainloop_consumer_read_state.reset_count() + mainloop_consumer_release_state.reset_count() + if parity: + pend2_sfa = _load_scales( + sfa_blk0, + tok0, + sfal0, + sfbl0, + 0, + sfb_frag2, + mSFA_mkl, + mSFB_nkl, + tCcC, + lane_col_base, + ) + mainloop_consumer_read_state = _issue_mma( + acc_partial2, + mainloop_pipeline, + mainloop_consumer_read_state, + tiled_mma, + tCrA, + tCrB, + num_k_blocks, + ) + else: + pend2_sfa = _load_scales( + sfa_blk0, + tok0, + sfal0, + sfbl0, + 0, + sfb_frag, + mSFA_mkl, + mSFB_nkl, + tCcC, + lane_col_base, + ) + mainloop_consumer_read_state = _issue_mma( + acc_partial, + mainloop_pipeline, + mainloop_consumer_read_state, + tiled_mma, + tCrA, + tCrB, + num_k_blocks, + ) + if have_pending: + # Leave only the just-issued WGMMA group outstanding. + cute.nvgpu.warpgroup.wait_group(1) + mainloop_consumer_release_state = _release_stage( + mainloop_pipeline, mainloop_consumer_release_state + ) + if parity: + _promote(acc_partial, pend_sfa, sfb_frag, accumulators) + else: + _promote(acc_partial2, pend_sfa, sfb_frag2, accumulators) + _epilogue( + self, + pend_gC, + num_tiles_executed, + tma_atom_c, + sC, + tRS_sD, + tRS_rAcc, + tRS_rD, + tRS_rD_out, + tiled_copy_r2s, + tma_store_pipeline, + warp_idx, + size_tRS_rD, + epilogue_op, + ) + num_tiles_executed += cutlass.Int32(1) + pend_sfa = pend2_sfa + pend_gC = pend2_gC + have_pending = cutlass.Boolean(True) + parity = ~parity + work_tile = tile_sched.advance_to_next_work() + if have_pending: + cute.nvgpu.warpgroup.wait_group(0) + mainloop_consumer_release_state = _release_stage( + mainloop_pipeline, mainloop_consumer_release_state + ) + # Drain the buffer selected before the final parity flip. + if parity: + _promote(acc_partial, pend_sfa, sfb_frag, accumulators) + else: + _promote(acc_partial2, pend_sfa, sfb_frag2, accumulators) + _epilogue( + self, + pend_gC, + num_tiles_executed, + tma_atom_c, + sC, + tRS_sD, + tRS_rAcc, + tRS_rD, + tRS_rD_out, + tiled_copy_r2s, + tma_store_pipeline, + warp_idx, + size_tRS_rD, + epilogue_op, + ) + num_tiles_executed += cutlass.Int32(1) + else: + while work_tile.is_valid_tile: + gC_mnl_slice, sfa_row_blk, token_base, sfa_l, sfb_l = _tile_ctx( + self, work_tile, gC_mnl, group_m + ) + mainloop_consumer_read_state.reset_count() + mainloop_consumer_release_state.reset_count() + accumulators.fill(0.0) + + # Hoisting scale loads ahead of the wait regresses multi-K tiles. + for k_tile in cutlass.range(0, work_tile.k_tile_cnt, 1, unroll=1): + mainloop_pipeline.consumer_wait(mainloop_consumer_read_state) + acc_partial.fill(0.0) + cute.nvgpu.warpgroup.fence() + for k_block_idx in cutlass.range_constexpr(num_k_blocks): + k_block_coord = ( + None, + None, + k_block_idx, + mainloop_consumer_read_state.index, + ) + cute.gemm( + tiled_mma, + acc_partial, + tCrA[k_block_coord], + tCrB[k_block_coord], + acc_partial, + ) + cute.nvgpu.warpgroup.commit_group() + cute.nvgpu.warpgroup.wait_group(0) + mainloop_pipeline.consumer_release( + mainloop_consumer_release_state + ) + mainloop_consumer_release_state.advance() + mainloop_consumer_read_state.advance() + + sfa_s = mSFA_mkl[(sfa_row_blk, k_tile, sfa_l)] + # Nested coordinates pair layouts correctly; flat iteration does not. + for v in cutlass.range_constexpr( + cute.size(accumulators, mode=[0]) + ): + for im in cutlass.range_constexpr( + cute.size(accumulators, mode=[1]) + ): + for in_ in cutlass.range_constexpr( + cute.size(accumulators, mode=[2]) + ): + crd = (v, im, in_) + sfb_s = mSFB_nkl[ + ( + token_base + lane_col_base + tCcC[crd][1], + k_tile, + sfb_l, + ) + ] + accumulators[crd] += acc_partial[crd] * ( + sfa_s * sfb_s + ) + + _epilogue( + self, + gC_mnl_slice, + num_tiles_executed, + tma_atom_c, + sC, + tRS_sD, + tRS_rAcc, + tRS_rD, + tRS_rD_out, + tiled_copy_r2s, + tma_store_pipeline, + warp_idx, + size_tRS_rD, + epilogue_op, + ) + num_tiles_executed += cutlass.Int32(1) + work_tile = tile_sched.advance_to_next_work() + + tma_store_pipeline.producer_tail() + + # The host helpers below come from the upstream Hopper persistent example. + + @staticmethod + def _compute_stages( + tile_shape_mnk, + a_dtype, + b_dtype, + epi_tile, + c_dtype, + smem_capacity, + occupancy, + ): + a_shape = cute.slice_(tile_shape_mnk, (None, 0, None)) + b_shape = cute.slice_(tile_shape_mnk, (0, None, None)) + ab_bytes_per_stage = ( + cute.size(a_shape) * a_dtype.width // 8 + + cute.size(b_shape) * b_dtype.width // 8 + ) + c_bytes_per_stage = cute.size(epi_tile) * c_dtype.width // 8 + epi_stage = 4 + epi_bytes = c_bytes_per_stage * epi_stage + mbar_helpers_bytes = 1024 + ab_stage = ( + smem_capacity // occupancy - (mbar_helpers_bytes + epi_bytes) + ) // ab_bytes_per_stage + return ab_stage, epi_stage + + @staticmethod + def _make_smem_layouts( + tile_shape_mnk, + epi_tile, + a_dtype, + a_layout, + b_dtype, + b_layout, + ab_stage, + c_dtype, + c_layout, + epi_stage, + ): + a_smem_shape = cute.slice_(tile_shape_mnk, (None, 0, None)) + a_is_k_major = ( + a_layout.sm90_mma_major_mode() == cute.nvgpu.warpgroup.OperandMajorMode.K + ) + b_is_k_major = ( + b_layout.sm90_mma_major_mode() == cute.nvgpu.warpgroup.OperandMajorMode.K + ) + a_major_mode_size = tile_shape_mnk[2 if a_is_k_major else 0] + a_smem_layout_atom = cute.nvgpu.warpgroup.make_smem_layout_atom( + sm90_utils.get_smem_layout_atom(a_layout, a_dtype, a_major_mode_size), + a_dtype, + ) + a_smem_layout_staged = cute.tile_to_shape( + a_smem_layout_atom, + cute.append(a_smem_shape, ab_stage), + order=(0, 1, 2) if a_is_k_major else (1, 0, 2), + ) + + b_smem_shape = cute.slice_(tile_shape_mnk, (0, None, None)) + b_major_mode_size = tile_shape_mnk[2 if b_is_k_major else 1] + b_smem_layout_atom = cute.nvgpu.warpgroup.make_smem_layout_atom( + sm90_utils.get_smem_layout_atom(b_layout, b_dtype, b_major_mode_size), + b_dtype, + ) + b_smem_layout_staged = cute.tile_to_shape( + b_smem_layout_atom, + cute.append(b_smem_shape, ab_stage), + order=(0, 1, 2) if b_is_k_major else (1, 0, 2), + ) + + c_smem_shape = epi_tile + c_major_mode_size = epi_tile[1] if c_layout.is_n_major_c() else epi_tile[0] + c_smem_layout_atom = cute.nvgpu.warpgroup.make_smem_layout_atom( + sm90_utils.get_smem_layout_atom(c_layout, c_dtype, c_major_mode_size), + c_dtype, + ) + epi_smem_layout_staged = cute.tile_to_shape( + c_smem_layout_atom, + cute.append(c_smem_shape, epi_stage), + order=(1, 0, 2) if c_layout.is_m_major_c() else (0, 1, 2), + ) + return a_smem_layout_staged, b_smem_layout_staged, epi_smem_layout_staged + + @staticmethod + def _make_tma_store_atoms_and_tensors(tensor_c, epi_smem_layout_staged, epi_tile): + epi_smem_layout = cute.slice_(epi_smem_layout_staged, (None, None, 0)) + return cute.nvgpu.cpasync.make_tiled_tma_atom( + cute.nvgpu.cpasync.CopyBulkTensorTileS2GOp(), + tensor_c, + epi_smem_layout, + epi_tile, + ) + + @staticmethod + def _make_tma_atoms_and_tensors(tensor, smem_layout_staged, smem_tile, mcast_dim): + op = ( + cute.nvgpu.cpasync.CopyBulkTensorTileG2SOp() + if mcast_dim == 1 + else cute.nvgpu.cpasync.CopyBulkTensorTileG2SMulticastOp() + ) + smem_layout = cute.slice_(smem_layout_staged, (None, None, 0)) + return cute.nvgpu.cpasync.make_tiled_tma_atom( + op, tensor, smem_layout, smem_tile, num_multicast=mcast_dim + ) + + def check_supported_dtypes(self, a_dtype, b_dtype, c_dtype): + if a_dtype is not cutlass.Float8E4M3FN or b_dtype is not cutlass.Float8E4M3FN: + raise TypeError(f"the FP8 grouped GEMM takes e4m3 A/B; got {a_dtype}") + if c_dtype is not cutlass.BFloat16: + raise TypeError(f"C must be BF16; got {c_dtype}") + + def check_mma_tiler_and_cluster_shape(self): + if self.tile_shape_mnk[0] not in (64, 128): + raise ValueError("SM90 CTA tile M must be 64/128") + if self.tile_shape_mnk[1] not in (8, 16, 32, 64, 128, 256): + raise ValueError( + "this port validates CTA tile N in {8, 16, 32, 64, 128, " + "256}; WGMMA itself accepts 8..256 step 8 -- extend the " + "validated set before requesting other widths" + ) + if math.prod(self.cluster_shape_mn) > 4: + raise ValueError("SM90 cluster size must be <= 4") + for extent in self.cluster_shape_mn: + if extent <= 0 or extent & (extent - 1): + raise ValueError( + "cluster extents must be positive powers of two; got " + f"{self.cluster_shape_mn}" + ) + + def check_tensor_alignment(self, problem_shape, a_major, b_major, c_major): + if a_major != "k" or b_major != "k": + raise ValueError("SM90 port requires K-major A and B") + m, n, k, _length = problem_shape + for extent, name in ((m, "M"), (n, "N"), (k, "K")): + if extent % 8: + raise ValueError(f"{name}={extent} breaks 16-byte TMA alignment") + + def can_implement( + self, problem_shape, a_dtype, b_dtype, c_dtype, a_major, b_major, c_major + ) -> bool: + try: + self.check_supported_dtypes(a_dtype, b_dtype, c_dtype) + self.check_mma_tiler_and_cluster_shape() + self.check_tensor_alignment(problem_shape, a_major, b_major, c_major) + except (TypeError, ValueError): + return False + return True diff --git a/python/sglang/kernels/ops/lora/moe/cutedsl/schedule_builder.py b/python/sglang/kernels/ops/lora/moe/cutedsl/schedule_builder.py new file mode 100644 index 0000000000..f7ddf03537 --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/cutedsl/schedule_builder.py @@ -0,0 +1,335 @@ +"""Build both GEMM schedules from the dispatcher's row counts in one launch.""" + +from __future__ import annotations + +import torch +import triton +import triton.language as tl + +# Shared with scheduler.py: one signed int64 per tile, leaving bit 63 clear. + +EXPERT_SHIFT = 0 +EXPERT_BITS = 20 +EXPERT_MASK = (1 << EXPERT_BITS) - 1 + +TOKEN_CLUSTER_SHIFT = EXPERT_SHIFT + EXPERT_BITS +TOKEN_CLUSTER_BITS = 22 +TOKEN_CLUSTER_MASK = (1 << TOKEN_CLUSTER_BITS) - 1 + +OUTPUT_CLUSTER_SHIFT = TOKEN_CLUSTER_SHIFT + TOKEN_CLUSTER_BITS +OUTPUT_CLUSTER_BITS = 21 +OUTPUT_CLUSTER_MASK = (1 << OUTPUT_CLUSTER_BITS) - 1 + +PACKED_BITS = OUTPUT_CLUSTER_SHIFT + OUTPUT_CLUSTER_BITS +assert PACKED_BITS == 63, PACKED_BITS + +MAX_EXPERTS = 1 << EXPERT_BITS +MAX_TOKEN_CLUSTERS = 1 << TOKEN_CLUSTER_BITS +MAX_OUTPUT_CLUSTERS = 1 << OUTPUT_CLUSTER_BITS + + +@triton.jit +def _dual_schedule_kernel( + masked_m_ptr, + schedule1_ptr, + tiles1_ptr, + schedule2_ptr, + tiles2_ptr, + token_width, + out_clusters1, + out_clusters2, + EXPERTS: tl.constexpr, + BLOCK_EXPERTS: tl.constexpr, + ENTRY_BLOCK: tl.constexpr, + TOKEN_SHIFT: tl.constexpr, + OUTPUT_SHIFT: tl.constexpr, +): + expert = tl.program_id(0) + stage = tl.program_id(1) + out_clusters = tl.where(stage == 0, out_clusters1, out_clusters2) + + offs = tl.arange(0, BLOCK_EXPERTS) + all_rows = tl.load(masked_m_ptr + offs, mask=offs < EXPERTS, other=0) + all_entries = tl.cdiv(all_rows, token_width) * out_clusters + begin = tl.sum(tl.where(offs < expert, all_entries, 0)) + if expert == 0: + total = tl.sum(tl.where(offs < EXPERTS, all_entries, 0)) + if stage == 0: + tl.store(tiles1_ptr, total) + else: + tl.store(tiles2_ptr, total) + + rows = tl.load(masked_m_ptr + expert) + token_clusters = tl.cdiv(rows, token_width) + safe_tc = tl.maximum(token_clusters, 1) + entries = token_clusters * out_clusters + token_major = token_clusters > out_clusters + for base in range(0, entries, ENTRY_BLOCK): + local = base + tl.arange(0, ENTRY_BLOCK) + valid = local < entries + oc_a = local // safe_tc + tc_a = local - oc_a * safe_tc + tc_b = local // out_clusters + oc_b = local - tc_b * out_clusters + tc_i = tl.where(token_major, tc_b, tc_a) + oc_i = tl.where(token_major, oc_b, oc_a) + # Widen before shifting to preserve the upper fields. + packed = ( + expert.to(tl.int64) + | (tc_i.to(tl.int64) << TOKEN_SHIFT) + | (oc_i.to(tl.int64) << OUTPUT_SHIFT) + ) + if stage == 0: + tl.store(schedule1_ptr + begin + local, packed, mask=valid) + else: + tl.store(schedule2_ptr + begin + local, packed, mask=valid) + + +def dual_stage_schedule_capacities_masked( + *, + num_experts: int, + m_max: int, + token_width: int, + n_gemm1: int, + n_gemm2: int, + output_width: int, + cluster_shape_mn: tuple[int, int] = (1, 1), + use_2cta_instrs: bool = False, +) -> tuple[int, int]: + """CTA-tile entries require 1x1 clusters and 1-CTA MMA.""" + if tuple(cluster_shape_mn) != (1, 1) or use_2cta_instrs: + raise ValueError( + "packed schedules require a (1, 1) cluster and 1-CTA MMA; got " + f"cluster_shape_mn={tuple(cluster_shape_mn)}, " + f"use_2cta_instrs={use_2cta_instrs}" + ) + out_clusters1 = (n_gemm1 + output_width - 1) // output_width + out_clusters2 = (n_gemm2 + output_width - 1) // output_width + max_token_clusters = (m_max + token_width - 1) // token_width + if num_experts > MAX_EXPERTS: + raise ValueError( + f"direct schedule packs expert INDICES in " + f"{MAX_EXPERTS.bit_length() - 1} bits (counts up to " + f"{MAX_EXPERTS}); got {num_experts}" + ) + if max_token_clusters > MAX_TOKEN_CLUSTERS: + raise ValueError( + f"m_max={m_max} at token width {token_width} needs " + f"{max_token_clusters} token clusters; the packing holds " + f"{MAX_TOKEN_CLUSTERS}. Admission must pick a wider tile." + ) + if max(out_clusters1, out_clusters2) > MAX_OUTPUT_CLUSTERS: + raise ValueError( + f"{max(out_clusters1, out_clusters2)} output clusters exceed the " + f"{MAX_OUTPUT_CLUSTERS} the non-negative-word config allows" + ) + # Individually valid fields can still overflow the int32 prefix sum. + capacity = num_experts * max_token_clusters * max(out_clusters1, out_clusters2) + if capacity > 2**31 - 1: + raise ValueError( + f"worst-case schedule capacity {capacity} overflows the builder's " + "int32 prefix arithmetic" + ) + return ( + num_experts * max_token_clusters * out_clusters1, + num_experts * max_token_clusters * out_clusters2, + ) + + +def validate_tile_geometry_contiguous(token_width: int, m_alignment: int) -> None: + """Require exact segment-base division and keep partial tiles in bounds.""" + if not isinstance(token_width, int) or token_width < 1: + raise ValueError(f"token_width must be a positive int, got {token_width!r}") + if not isinstance(m_alignment, int) or m_alignment < 1: + raise ValueError(f"m_alignment must be a positive int, got {m_alignment!r}") + if m_alignment % token_width: + raise ValueError( + f"token tile {token_width} does not divide the segment alignment " + f"{m_alignment}: a partial tile could cross into the next " + "expert's rows" + ) + + +def dual_stage_schedule_capacities_contiguous( + *, + num_experts: int, + m_pad_ceiling: int, + max_expert_rows: int, + m_alignment: int, + token_width: int, + n_gemm1: int, + n_gemm2: int, + output_width: int, + cluster_shape_mn: tuple[int, int] = (1, 1), + use_2cta_instrs: bool = False, +) -> tuple[int, int]: + """Bound capacity by total padded rows instead of per-expert slabs.""" + dual_stage_schedule_capacities_masked( + num_experts=num_experts, + m_max=max_expert_rows, + token_width=token_width, + n_gemm1=n_gemm1, + n_gemm2=n_gemm2, + output_width=output_width, + cluster_shape_mn=cluster_shape_mn, + use_2cta_instrs=use_2cta_instrs, + ) + validate_tile_geometry_contiguous(token_width, m_alignment) + if m_pad_ceiling < 0 or m_pad_ceiling % m_alignment: + raise ValueError( + f"m_pad_ceiling={m_pad_ceiling} must be a non-negative multiple " + f"of the segment alignment {m_alignment}" + ) + total_clusters = m_pad_ceiling // token_width + out_clusters1 = (n_gemm1 + output_width - 1) // output_width + out_clusters2 = (n_gemm2 + output_width - 1) // output_width + capacity = total_clusters * max(out_clusters1, out_clusters2) + if capacity > 2**31 - 1: + raise ValueError( + f"worst-case contiguous schedule capacity {capacity} overflows " + "the builder's int32 prefix arithmetic" + ) + return ( + max(total_clusters * out_clusters1, 1), + max(total_clusters * out_clusters2, 1), + ) + + +def build_dual_stage_schedules_contiguous( + seg_counts: torch.Tensor, + *, + m_pad_ceiling: int, + max_expert_rows: int, + m_alignment: int, + token_width: int, + n_gemm1: int, + n_gemm2: int, + output_width: int, + cluster_shape_mn: tuple[int, int] = (1, 1), + use_2cta_instrs: bool = False, + schedule1_out: torch.Tensor | None = None, + tiles1_out: torch.Tensor | None = None, + schedule2_out: torch.Tensor | None = None, + tiles2_out: torch.Tensor | None = None, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + capacities = dual_stage_schedule_capacities_contiguous( + num_experts=seg_counts.numel(), + m_pad_ceiling=m_pad_ceiling, + max_expert_rows=max_expert_rows, + m_alignment=m_alignment, + token_width=token_width, + n_gemm1=n_gemm1, + n_gemm2=n_gemm2, + output_width=output_width, + cluster_shape_mn=cluster_shape_mn, + use_2cta_instrs=use_2cta_instrs, + ) + return _emit_dual_stage_schedules( + seg_counts, + capacities=capacities, + token_width=token_width, + n_gemm1=n_gemm1, + n_gemm2=n_gemm2, + output_width=output_width, + schedule1_out=schedule1_out, + tiles1_out=tiles1_out, + schedule2_out=schedule2_out, + tiles2_out=tiles2_out, + ) + + +def _schedule_output( + output: torch.Tensor | None, *, elements: int, device: torch.device +) -> torch.Tensor: + if output is None: + return torch.empty(elements, dtype=torch.int64, device=device) + return output + + +def _tile_count_output( + output: torch.Tensor | None, *, device: torch.device +) -> torch.Tensor: + # int32: the device compares it to an Int32 work index. + if output is None: + return torch.empty(1, dtype=torch.int32, device=device) + return output + + +def build_dual_stage_schedules_masked( + masked_m: torch.Tensor, + *, + m_max: int, + token_width: int, + n_gemm1: int, + n_gemm2: int, + output_width: int, + cluster_shape_mn: tuple[int, int] = (1, 1), + use_2cta_instrs: bool = False, + schedule1_out: torch.Tensor | None = None, + tiles1_out: torch.Tensor | None = None, + schedule2_out: torch.Tensor | None = None, + tiles2_out: torch.Tensor | None = None, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + capacities = dual_stage_schedule_capacities_masked( + num_experts=masked_m.numel(), + m_max=m_max, + token_width=token_width, + n_gemm1=n_gemm1, + n_gemm2=n_gemm2, + output_width=output_width, + cluster_shape_mn=cluster_shape_mn, + use_2cta_instrs=use_2cta_instrs, + ) + return _emit_dual_stage_schedules( + masked_m, + capacities=capacities, + token_width=token_width, + n_gemm1=n_gemm1, + n_gemm2=n_gemm2, + output_width=output_width, + schedule1_out=schedule1_out, + tiles1_out=tiles1_out, + schedule2_out=schedule2_out, + tiles2_out=tiles2_out, + ) + + +def _emit_dual_stage_schedules( + row_counts: torch.Tensor, + *, + capacities: tuple[int, int], + token_width: int, + n_gemm1: int, + n_gemm2: int, + output_width: int, + schedule1_out: torch.Tensor | None, + tiles1_out: torch.Tensor | None, + schedule2_out: torch.Tensor | None, + tiles2_out: torch.Tensor | None, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + capacity1, capacity2 = capacities + out_clusters1 = (n_gemm1 + output_width - 1) // output_width + out_clusters2 = (n_gemm2 + output_width - 1) // output_width + + num_experts = row_counts.numel() + device = row_counts.device + schedule1 = _schedule_output(schedule1_out, elements=capacity1, device=device) + schedule2 = _schedule_output(schedule2_out, elements=capacity2, device=device) + tiles1 = _tile_count_output(tiles1_out, device=device) + tiles2 = _tile_count_output(tiles2_out, device=device) + _dual_schedule_kernel[(num_experts, 2)]( + row_counts, + schedule1, + tiles1, + schedule2, + tiles2, + token_width, + out_clusters1, + out_clusters2, + EXPERTS=num_experts, + BLOCK_EXPERTS=max(triton.next_power_of_2(num_experts), 2), + ENTRY_BLOCK=128, + TOKEN_SHIFT=TOKEN_CLUSTER_SHIFT, + OUTPUT_SHIFT=OUTPUT_CLUSTER_SHIFT, + ) + return schedule1, tiles1, schedule2, tiles2 diff --git a/python/sglang/kernels/ops/lora/moe/cutedsl/scheduler.py b/python/sglang/kernels/ops/lora/moe/cutedsl/scheduler.py new file mode 100644 index 0000000000..eaaf533bcd --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/cutedsl/scheduler.py @@ -0,0 +1,294 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: BSD-3-Clause + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# 3. Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Persistent scheduler for the packed work list from schedule_builder.""" + +from typing import List, Tuple + +import cutlass.cute as cute +from cutlass._mlir import ir +from cutlass.cutlass_dsl import ( + Boolean, + Int32, + Int64, + Integer, + dsl_user_op, + extract_mlir_values, + new_from_mlir_values, +) + +from sglang.kernels.ops.lora.moe.cutedsl.schedule_builder import ( + EXPERT_MASK, + OUTPUT_CLUSTER_MASK, + OUTPUT_CLUSTER_SHIFT, + TOKEN_CLUSTER_MASK, + TOKEN_CLUSTER_SHIFT, +) + + +class MoEWorkTileInfo: + def __init__( + self, + expert_idx: Int32, # -1 means invalid tile + tile_m_idx: Int32, + tile_n_idx: Int32, + k_tile_cnt: Int32, + ): + self.expert_idx = expert_idx + self.tile_m_idx = tile_m_idx + self.tile_n_idx = tile_n_idx + self.k_tile_cnt = k_tile_cnt + + @property + def is_valid_tile(self) -> Boolean: + return self.expert_idx >= Int32(0) + + def __extract_mlir_values__(self) -> List[ir.Value]: + values = extract_mlir_values(self.expert_idx) + values.extend(extract_mlir_values(self.tile_m_idx)) + values.extend(extract_mlir_values(self.tile_n_idx)) + values.extend(extract_mlir_values(self.k_tile_cnt)) + return values + + def __new_from_mlir_values__(self, values: List[ir.Value]) -> "MoEWorkTileInfo": + assert len(values) == 4 + return MoEWorkTileInfo( + expert_idx=new_from_mlir_values(self.expert_idx, [values[0]]), + tile_m_idx=new_from_mlir_values(self.tile_m_idx, [values[1]]), + tile_n_idx=new_from_mlir_values(self.tile_n_idx, [values[2]]), + k_tile_cnt=new_from_mlir_values(self.k_tile_cnt, [values[3]]), + ) + + +class MoESchedulerParams: + def __init__( + self, + hidden: int | Int32, + cta_tile_k: int, + cluster_shape_mn: Tuple[int, int], + ): + self.hidden = hidden if isinstance(hidden, Int32) else Int32(hidden) + self.cta_tile_k = cta_tile_k + self.cluster_shape_mn = cluster_shape_mn + + def __extract_mlir_values__(self) -> List[ir.Value]: + return extract_mlir_values(self.hidden) + + def __new_from_mlir_values__(self, values: List[ir.Value]) -> "MoESchedulerParams": + assert len(values) == 1 + return MoESchedulerParams( + hidden=new_from_mlir_values(self.hidden, values), + cta_tile_k=self.cta_tile_k, + cluster_shape_mn=self.cluster_shape_mn, + ) + + +class MoEDirectPersistentTileScheduler: + """Decode (expert, cluster_m, cluster_n) from one int64 per tile.""" + + def __init__( + self, + params: MoESchedulerParams, + schedule: cute.Tensor, + schedule_tiles: cute.Tensor, + num_persistent_clusters: Int32, + current_work_linear_idx: Int32, + cta_id_in_cluster: cute.Coord, + ): + self.params = params + self.schedule = schedule + self.schedule_tiles = schedule_tiles + self.num_persistent_clusters = num_persistent_clusters + self._current_work_linear_idx = current_work_linear_idx + self.cta_id_in_cluster = cta_id_in_cluster + + def __extract_mlir_values__(self) -> List[ir.Value]: + values = [] + values.extend(extract_mlir_values(self.params)) + values.extend(extract_mlir_values(self.schedule)) + values.extend(extract_mlir_values(self.schedule_tiles)) + values.extend(extract_mlir_values(self.num_persistent_clusters)) + values.extend(extract_mlir_values(self._current_work_linear_idx)) + values.extend(extract_mlir_values(self.cta_id_in_cluster)) + return values + + def __new_from_mlir_values__( + self, values: List[ir.Value] + ) -> "MoEDirectPersistentTileScheduler": + idx = 0 + new_params = new_from_mlir_values(self.params, values[idx : idx + 1]) + idx += 1 + schedule_len = len(extract_mlir_values(self.schedule)) + new_schedule = new_from_mlir_values( + self.schedule, values[idx : idx + schedule_len] + ) + idx += schedule_len + tiles_len = len(extract_mlir_values(self.schedule_tiles)) + new_schedule_tiles = new_from_mlir_values( + self.schedule_tiles, values[idx : idx + tiles_len] + ) + idx += tiles_len + new_num_clusters = new_from_mlir_values( + self.num_persistent_clusters, [values[idx]] + ) + idx += 1 + new_work_idx = new_from_mlir_values( + self._current_work_linear_idx, [values[idx]] + ) + idx += 1 + new_cta_id = new_from_mlir_values(self.cta_id_in_cluster, values[idx : idx + 3]) + return MoEDirectPersistentTileScheduler( + new_params, + new_schedule, + new_schedule_tiles, + new_num_clusters, + new_work_idx, + new_cta_id, + ) + + @staticmethod + @dsl_user_op + def create( + params: MoESchedulerParams, + schedule: cute.Tensor, + schedule_tiles: cute.Tensor, + block_idx: Tuple[Integer, Integer, Integer], + grid_dim: Tuple[Integer, Integer, Integer], + *, + loc=None, + ip=None, + ) -> "MoEDirectPersistentTileScheduler": + num_persistent_clusters = cute.size(grid_dim, loc=loc, ip=ip) // cute.size( + params.cluster_shape_mn, loc=loc, ip=ip + ) + bidx, bidy, bidz = block_idx + return MoEDirectPersistentTileScheduler( + params, + schedule, + schedule_tiles, + Int32(num_persistent_clusters), + Int32(bidz), + ( + Int32(bidx % params.cluster_shape_mn[0]), + Int32(bidy % params.cluster_shape_mn[1]), + Int32(0), + ), + ) + + @dsl_user_op + @cute.jit + def initial_work_tile_info(self, *, loc=None, ip=None) -> MoEWorkTileInfo: + return self._get_current_work(loc=loc, ip=ip) + + @dsl_user_op + @cute.jit + def advance_to_next_work(self, *, loc=None, ip=None) -> MoEWorkTileInfo: + self._current_work_linear_idx += self.num_persistent_clusters + return self._get_current_work(loc=loc, ip=ip) + + @dsl_user_op + @cute.jit + def _get_current_work(self, *, loc=None, ip=None) -> MoEWorkTileInfo: + work = MoEWorkTileInfo(Int32(-1), Int32(0), Int32(0), Int32(0)) + if self._current_work_linear_idx < self.schedule_tiles[0]: + packed = Int64(self.schedule[self._current_work_linear_idx]) + expert = Int32(packed & Int64(EXPERT_MASK)) + cluster_m = Int32( + (packed >> Int64(TOKEN_CLUSTER_SHIFT)) & Int64(TOKEN_CLUSTER_MASK) + ) + cluster_n = Int32( + (packed >> Int64(OUTPUT_CLUSTER_SHIFT)) & Int64(OUTPUT_CLUSTER_MASK) + ) + tile_m = ( + cluster_m * self.params.cluster_shape_mn[0] + self.cta_id_in_cluster[0] # type: ignore[index] + ) + tile_n = ( + cluster_n * self.params.cluster_shape_mn[1] + self.cta_id_in_cluster[1] # type: ignore[index] + ) + k_tiles = ( + self.params.hidden + self.params.cta_tile_k - 1 + ) // self.params.cta_tile_k + work = MoEWorkTileInfo(expert, tile_m, tile_n, Int32(k_tiles)) + return work + + +def resolve_scheduler_params_and_grid( + *, + a: cute.Tensor, + cta_tile_k: int, + cluster_shape_mn, + swap_ab: bool, + persistent_clusters, + max_active_clusters, +): + """Keep tokens on scheduler M, transposing cluster axes under swap_ab.""" + # K can be hierarchical; the scheduler needs its scalar extent. + k = cute.size(a.shape[1]) + cluster = cluster_shape_mn + if swap_ab: + cluster = (cluster_shape_mn[1], cluster_shape_mn[0]) + params = MoESchedulerParams( + hidden=k, + cta_tile_k=cta_tile_k, + cluster_shape_mn=cluster, + ) + launch_clusters = ( + max_active_clusters if persistent_clusters is None else persistent_clusters + ) + grid = (cluster_shape_mn[0], cluster_shape_mn[1], launch_clusters) + return params, grid + + +def create_moe_tile_scheduler( + *, + tile_sched_params, + direct_schedule: cute.Tensor, + schedule_tiles: cute.Tensor, + swap_ab: bool, +): + """Restore scheduler axis order under swap_ab at trace time.""" + scheduler_block_idx = cute.arch.block_idx() + scheduler_grid_dim = cute.arch.grid_dim() + if swap_ab: + scheduler_block_idx = ( + scheduler_block_idx[1], + scheduler_block_idx[0], + scheduler_block_idx[2], + ) + scheduler_grid_dim = ( + scheduler_grid_dim[1], + scheduler_grid_dim[0], + scheduler_grid_dim[2], + ) + return MoEDirectPersistentTileScheduler.create( + tile_sched_params, + direct_schedule, + schedule_tiles, + scheduler_block_idx, + scheduler_grid_dim, + ) diff --git a/python/sglang/kernels/ops/lora/moe/dispatch_checks.py b/python/sglang/kernels/ops/lora/moe/dispatch_checks.py new file mode 100644 index 0000000000..a781dc7202 --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/dispatch_checks.py @@ -0,0 +1,28 @@ +"""Input contracts shared by the masked and contiguous row movers.""" + +from __future__ import annotations + +import torch + + +def check_source_rows( + hidden_states: torch.Tensor, topk_ids: torch.Tensor, top_k: int +) -> None: + if hidden_states.dtype != torch.bfloat16: + raise ValueError("the row movers take BF16 [num_tokens, hidden] input") + if hidden_states.ndim != 2 or not hidden_states.is_contiguous(): + raise ValueError("hidden_states must be contiguous [num_tokens, hidden]") + if not topk_ids.is_contiguous(): + raise ValueError("topk_ids must be contiguous") + if topk_ids.numel() != hidden_states.size(0) * top_k: + raise ValueError( + f"topk_ids carries {topk_ids.numel()} pairs for " + f"{hidden_states.size(0)} tokens x top_k={top_k}" + ) + + +def check_fp8_width(k: int) -> None: + if type(k) is not int or k <= 0 or k % 128: + raise ValueError( + f"the fp8 row movers need positive K divisible by 128, got {k}" + ) diff --git a/python/sglang/kernels/ops/lora/moe/dispatch_contiguous.py b/python/sglang/kernels/ops/lora/moe/dispatch_contiguous.py new file mode 100644 index 0000000000..f7d1cd6f7f --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/dispatch_contiguous.py @@ -0,0 +1,249 @@ +"""Dispatch rows into aligned expert segments, optionally quantizing to FP8. + +Negative expert IDs map to pair_to_row == -1, which every consumer skips. +Atomic slot order may vary, so every stage must use the same pair_to_row map. +""" + +from __future__ import annotations + +import torch +import triton +import triton.language as tl + +from sglang.kernels.ops.lora.moe.dispatch_checks import ( + check_fp8_width, + check_source_rows, +) +from sglang.kernels.ops.lora.moe.fp8_quant import quantize_fp8_groups + +PAIRS_PER_PROGRAM = 8 + + +def contiguous_m_pad_ceiling(num_pairs: int, num_experts: int, alignment: int) -> int: + """Bound padded rows by allowing alignment - 1 extra rows per expert.""" + raw = num_pairs + num_experts * (alignment - 1) + return -(-raw // alignment) * alignment + + +@triton.jit +def _count_slots_contiguous_kernel( + topk_ids_ptr, # [num_pairs]; a value < 0 marks a pair with no expert + slot_out_ptr, # [num_pairs] int32 out: slot of the pair inside its expert + seg_counts_ptr, # [E_local] int32 count and cursor; the caller must zero it + num_pairs, + PAIRS_PER_PROGRAM: tl.constexpr, +): + pairs = tl.program_id(0).to(tl.int64) * PAIRS_PER_PROGRAM + tl.arange( + 0, PAIRS_PER_PROGRAM + ) + in_range = pairs < num_pairs + experts = tl.load(topk_ids_ptr + pairs, mask=in_range, other=-1) + valid = in_range & (experts >= 0) + slots = tl.atomic_add(seg_counts_ptr + experts, 1, mask=valid) + tl.store(slot_out_ptr + pairs, slots, mask=valid) + + +@triton.jit +def _seg_layout_contiguous_kernel( + seg_counts_ptr, # [E_local] int32 per-expert routed-pair counts + seg_offsets_ptr, # [E_local + 1] int32 out: first row of each segment + ALIGN: tl.constexpr, + EXPERTS: tl.constexpr, + BLOCK_EXPERTS: tl.constexpr, +): + offs = tl.arange(0, BLOCK_EXPERTS) + counts = tl.load(seg_counts_ptr + offs, mask=offs < EXPERTS, other=0) + aligned = ((counts + (ALIGN - 1)) // ALIGN) * ALIGN + inclusive = tl.cumsum(aligned, axis=0) + tl.store(seg_offsets_ptr + offs, inclusive - aligned, mask=offs < EXPERTS) + tl.store(seg_offsets_ptr + EXPERTS, tl.sum(aligned)) + + +@triton.jit +def _fill_rows_contiguous_bf16_kernel( + input_ptr, # [num_tokens, hidden] bf16 source rows + compact_ptr, # [m_pad_ceiling, hidden] bf16, viewed flat + topk_ids_ptr, # [num_pairs] + pair_to_row_ptr, # [num_pairs] int32 finalized compact rows + hidden_size, + num_pairs, + TOPK: tl.constexpr, + PAIRS_PER_PROGRAM: tl.constexpr, + BLOCK_H: tl.constexpr, +): + # Row copying consumes the map finalized by the preceding launch. + lane = tl.arange(0, PAIRS_PER_PROGRAM) + base = tl.program_id(0).to(tl.int64) * PAIRS_PER_PROGRAM + pairs = base + lane + in_range = pairs < num_pairs + experts_vec = tl.load(topk_ids_ptr + pairs, mask=in_range, other=-1) + if tl.sum((experts_vec >= 0).to(tl.int32), axis=0) == 0: + return + + vec = tl.arange(0, BLOCK_H) + for i in tl.static_range(PAIRS_PER_PROGRAM): + pair = base + i + if pair < num_pairs: + expert = tl.load(topk_ids_ptr + pair) + if expert >= 0: + dst = tl.load(pair_to_row_ptr + pair).to(tl.int64) + token = pair // TOPK + src = input_ptr + token * hidden_size + out = compact_ptr + dst * hidden_size + for off in tl.range(0, hidden_size, BLOCK_H): + mask = off + vec < hidden_size + tl.store( + out + off + vec, + tl.load(src + off + vec, mask=mask), + mask=mask, + ) + + +@triton.jit +def _finalize_pair_to_row_contiguous_kernel( + topk_ids_ptr, # [num_pairs]; a value < 0 marks a pair with no expert + pair_to_row_ptr, # [num_pairs] int32: dense slots IN, compact rows OUT + seg_offsets_ptr, # [E_local + 1] int32 first row of each segment + num_pairs, + PAIRS_PER_PROGRAM: tl.constexpr, +): + base = tl.program_id(0).to(tl.int64) * PAIRS_PER_PROGRAM + for i in tl.static_range(PAIRS_PER_PROGRAM): + pair = base + i + if pair < num_pairs: + expert = tl.load(topk_ids_ptr + pair) + if expert >= 0: + slot = tl.load(pair_to_row_ptr + pair) + seg_base = tl.load(seg_offsets_ptr + expert) + tl.store(pair_to_row_ptr + pair, seg_base + slot) + else: + # Finalize gates on this map, so invalid pairs must read as -1. + tl.store(pair_to_row_ptr + pair, -1) + + +def dispatch_layout_contiguous( + hidden_states: torch.Tensor, + topk_ids: torch.Tensor, + num_local_experts: int, + top_k: int, + alignment: int, + *, + seg_counts_out: torch.Tensor, + seg_offsets_out: torch.Tensor, + pair_to_row_out: torch.Tensor, +) -> None: + """Write compact row indices to pair_to_row; row copies run separately.""" + check_source_rows(hidden_states, topk_ids, top_k) + num_pairs = topk_ids.numel() + pair_grid = (-(-num_pairs // PAIRS_PER_PROGRAM),) + + # Clear atomic cursors on every forward, including graph replay. + seg_counts_out.zero_() + if num_pairs > 0: + _count_slots_contiguous_kernel[pair_grid]( + topk_ids.view(-1), + pair_to_row_out, + seg_counts_out, + num_pairs, + PAIRS_PER_PROGRAM=PAIRS_PER_PROGRAM, + ) + # Initialize offsets even for an empty batch. + _seg_layout_contiguous_kernel[(1,)]( + seg_counts_out, + seg_offsets_out, + ALIGN=alignment, + EXPERTS=num_local_experts, + BLOCK_EXPERTS=max(triton.next_power_of_2(num_local_experts), 2), + ) + if num_pairs > 0: + _finalize_pair_to_row_contiguous_kernel[pair_grid]( + topk_ids.view(-1), + pair_to_row_out, + seg_offsets_out, + num_pairs, + PAIRS_PER_PROGRAM=PAIRS_PER_PROGRAM, + ) + + +def dispatch_fill_rows_contiguous_bf16( + hidden_states: torch.Tensor, + topk_ids: torch.Tensor, + pair_to_row: torch.Tensor, + *, + hidden_compact_out: torch.Tensor, +) -> None: + num_tokens = hidden_states.size(0) + num_pairs = topk_ids.numel() + if num_pairs == 0: + return + check_source_rows(hidden_states, topk_ids, num_pairs // num_tokens) + _fill_rows_contiguous_bf16_kernel[(-(-num_pairs // PAIRS_PER_PROGRAM),)]( + hidden_states, + hidden_compact_out, + topk_ids.view(-1), + pair_to_row, + hidden_states.size(1), + num_pairs, + TOPK=num_pairs // num_tokens, + PAIRS_PER_PROGRAM=PAIRS_PER_PROGRAM, + BLOCK_H=1024, + ) + + +@triton.jit +def _fill_rows_contiguous_fp8_kernel( + input_ptr, # bf16 [num_tokens, K] source rows + out_ptr, # fp8e4m3 [m_pad_ceiling, K] contiguous + scale_ptr, # fp32 [m_pad_ceiling, K // 128] contiguous + topk_ids_ptr, # [num_pairs]; < 0 = padding or EP-unrouted + pair_to_row_ptr, # [num_pairs] int32 finalized compact rows + TOPK: tl.constexpr, + K: tl.constexpr, + GROUPS: tl.constexpr, # K // 128 + BLOCK_K: tl.constexpr, +): + # Quantize each token once, then fan out to its routed destinations. + token = tl.program_id(0) + offs = tl.arange(0, BLOCK_K) + x = tl.load(input_ptr + token.to(tl.int64) * K + offs, mask=offs < K, other=0).to( + tl.float32 + ) + grouped = tl.reshape(x, (BLOCK_K // 128, 128)) + q, scale = quantize_fp8_groups(grouped, GROUPS == 1) + qf = tl.reshape(q, (BLOCK_K,)).to(out_ptr.dtype.element_ty) + goffs = tl.arange(0, BLOCK_K // 128) + for j in range(TOPK): + pair = token * TOPK + j + expert = tl.load(topk_ids_ptr + pair) + if expert >= 0: + dst = tl.load(pair_to_row_ptr + pair).to(tl.int64) + tl.store(out_ptr + dst * K + offs, qf, mask=offs < K) + tl.store(scale_ptr + dst * GROUPS + goffs, scale, mask=goffs < GROUPS) + + +def dispatch_fill_rows_contiguous_fp8( + hidden_states: torch.Tensor, + topk_ids: torch.Tensor, + pair_to_row: torch.Tensor, + *, + rows_fp8_out: torch.Tensor, + scale_out: torch.Tensor, +) -> None: + """Quantize and copy rows using the finalized pair_to_row map.""" + num_tokens, k = hidden_states.shape + num_pairs = topk_ids.numel() + if num_pairs == 0: + return + check_source_rows(hidden_states, topk_ids, num_pairs // num_tokens) + check_fp8_width(k) + _fill_rows_contiguous_fp8_kernel[(num_tokens,)]( + hidden_states, + rows_fp8_out, + scale_out, + topk_ids.view(-1), + pair_to_row, + TOPK=num_pairs // num_tokens, + K=k, + GROUPS=k // 128, + BLOCK_K=triton.next_power_of_2(k), + ) diff --git a/python/sglang/kernels/ops/lora/moe/dispatch_masked.py b/python/sglang/kernels/ops/lora/moe/dispatch_masked.py new file mode 100644 index 0000000000..648d42a26e --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/dispatch_masked.py @@ -0,0 +1,146 @@ +"""Dispatch rows into [expert, m_max, hidden] slabs, optionally quantizing to FP8. + +Negative expert IDs write pair_to_row == -1; consumers must skip those rows. +""" + +from __future__ import annotations + +import torch +import triton +import triton.language as tl + +from sglang.kernels.ops.lora.moe.dispatch_checks import ( + check_fp8_width, + check_source_rows, +) +from sglang.kernels.ops.lora.moe.fp8_quant import quantize_fp8_groups + + +@triton.jit +def _dispatch_fill_masked_bf16_kernel( + input_ptr, # [num_tokens, hidden] bf16 source rows + gateup_input_ptr, # [E_local, m_max, hidden] bf16 rows, viewed flat + topk_ids_ptr, # [num_tokens * topk]; < 0 = padding or EP-unrouted + pair_to_row_ptr, # [num_tokens * topk] int32 out; -1 for pairs without an expert + masked_m_ptr, # [E_local] int32 count and atomic cursor; caller zeroes it + m_max, + hidden_size, + TOPK: tl.constexpr, + BLOCK_H: tl.constexpr, +): + t = tl.program_id(0) + k = tl.program_id(1) + pair = t * TOPK + k + expert = tl.load(topk_ids_ptr + pair) + if expert < 0: + # The finalize gates on the row map: no expert reads as -1. + tl.store(pair_to_row_ptr + pair, -1) + else: + slot = tl.atomic_add(masked_m_ptr + expert, 1) + dst = expert.to(tl.int64) * m_max + slot + tl.store(pair_to_row_ptr + pair, dst.to(tl.int32)) + src = input_ptr + t.to(tl.int64) * hidden_size + out = gateup_input_ptr + dst * hidden_size + vec = tl.arange(0, BLOCK_H) + for off in tl.range(0, hidden_size, BLOCK_H): + mask = off + vec < hidden_size + tl.store(out + off + vec, tl.load(src + off + vec, mask=mask), mask=mask) + + +def dispatch_fill_masked_bf16( + hidden_states: torch.Tensor, + topk_ids: torch.Tensor, + top_k: int, + *, + masked_m_out: torch.Tensor, + pair_to_row_out: torch.Tensor, + rows_out: torch.Tensor, +) -> None: + check_source_rows(hidden_states, topk_ids, top_k) + num_tokens = hidden_states.size(0) + # Clear atomic cursors on every forward, including graph replay. + masked_m_out.zero_() + if num_tokens > 0: + _dispatch_fill_masked_bf16_kernel[(num_tokens, top_k)]( + hidden_states, + rows_out, + topk_ids.view(-1), + pair_to_row_out, + masked_m_out, + rows_out.size(1), + hidden_states.size(1), + TOPK=top_k, + BLOCK_H=1024, + ) + + +@triton.jit +def _dispatch_fill_masked_fp8_kernel( + input_ptr, # bf16 [num_tokens, K] source rows + out_ptr, # fp8e4m3 [E, m_max, K] contiguous + scale_ptr, # fp32 [E, m_max, K // 128] contiguous + topk_ids_ptr, # [num_tokens * top_k]; < 0 = padding or EP-unrouted + pair_to_row_ptr, # [num_tokens * top_k] int32 out; -1 for pairs without an expert + masked_m_ptr, # [E] int32 count and atomic cursor; caller zeroes it + m_max, + TOPK: tl.constexpr, + K: tl.constexpr, + GROUPS: tl.constexpr, # K // 128 + BLOCK_K: tl.constexpr, +): + t = tl.program_id(0) + k = tl.program_id(1) + pair = t * TOPK + k + expert = tl.load(topk_ids_ptr + pair) + if expert < 0: + tl.store(pair_to_row_ptr + pair, -1) + return + slot = tl.atomic_add(masked_m_ptr + expert, 1) + dst = expert.to(tl.int64) * m_max + slot + tl.store(pair_to_row_ptr + pair, dst.to(tl.int32)) + + offs = tl.arange(0, BLOCK_K) + x = tl.load(input_ptr + t.to(tl.int64) * K + offs, mask=offs < K, other=0).to( + tl.float32 + ) + grouped = tl.reshape(x, (BLOCK_K // 128, 128)) + q, scale = quantize_fp8_groups(grouped, GROUPS == 1) + tl.store( + out_ptr + dst * K + offs, + tl.reshape(q, (BLOCK_K,)).to(out_ptr.dtype.element_ty), + mask=offs < K, + ) + groups = tl.arange(0, BLOCK_K // 128) + tl.store(scale_ptr + dst * GROUPS + groups, scale, mask=groups < GROUPS) + + +def dispatch_fill_masked_fp8( + hidden_states: torch.Tensor, + topk_ids: torch.Tensor, + top_k: int, + *, + masked_m_out: torch.Tensor, + pair_to_row_out: torch.Tensor, + rows_fp8_out: torch.Tensor, + scale_out: torch.Tensor, +) -> None: + """Dispatch FP8 rows with FP32 scales per group of 128 values.""" + check_source_rows(hidden_states, topk_ids, top_k) + num_tokens, k = hidden_states.shape + check_fp8_width(k) + masked_m_out.zero_() + if num_tokens > 0: + _dispatch_fill_masked_fp8_kernel[(num_tokens, top_k)]( + hidden_states, + rows_fp8_out, + scale_out, + topk_ids.view(-1), + pair_to_row_out, + masked_m_out, + rows_fp8_out.size(1), + TOPK=top_k, + K=k, + GROUPS=k // 128, + BLOCK_K=triton.next_power_of_2(k), + num_warps=4 if k <= 4096 else 8, + ) diff --git a/python/sglang/kernels/ops/lora/moe/dispatch_masked_small.py b/python/sglang/kernels/ops/lora/moe/dispatch_masked_small.py new file mode 100644 index 0000000000..2d48ebde75 --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/dispatch_masked_small.py @@ -0,0 +1,183 @@ +"""Prepare masked rows, pair maps and both GEMM schedules in one launch. + +Admission is limited to small BF16 batches with one token cluster per expert. +""" + +from __future__ import annotations + +import torch +import triton +import triton.language as tl + +from sglang.kernels.ops.lora.moe.cutedsl.schedule_builder import ( + OUTPUT_CLUSTER_SHIFT, +) +from sglang.kernels.ops.lora.moe.dispatch_checks import check_source_rows + +_SMALL_PREPARE_MAX_PAIRS = 32 +# The narrowest decode token tile: with at most this many tokens every expert +# fits one token cluster whatever tile the provider picks. +_SMALL_PREPARE_MAX_TOKENS = 8 +# Pairs per program: the row-copy tile is [_PPP, BLOCK_H] with at most 8192 elements. +_PPP = 8 + + +def small_masked_prepare_applies(num_tokens: int, num_pairs: int) -> bool: + return ( + 0 < num_pairs <= _SMALL_PREPARE_MAX_PAIRS + and num_tokens <= _SMALL_PREPARE_MAX_TOKENS + ) + + +@triton.jit +def _small_masked_prepare_kernel( + input_ptr, # bf16 [num_tokens, hidden] + rows_ptr, # bf16 [E, m_max, hidden] + topk_ids_ptr, # int32 [num_tokens * TOPK]; < 0 = no expert + pair_to_row_ptr, # int32 [num_tokens * TOPK] out + masked_m_ptr, # int32 [E] out: the per-expert counts + scratch_ptr, # int32 [2 * E_P2]: the stage begins per expert + schedule1_ptr, + tiles1_ptr, + schedule2_ptr, + tiles2_ptr, + num_pairs, + m_max, + hidden, + token_width, + out_clusters1, + out_clusters2, + E: tl.constexpr, + E_P2: tl.constexpr, + PAIRS: tl.constexpr, + PPP: tl.constexpr, # pairs whose rows one program moves + TOPK: tl.constexpr, + OC_P2: tl.constexpr, + BLOCK_H: tl.constexpr, + OUTPUT_SHIFT: tl.constexpr, +): + # A pair's slot in its expert is its rank among the expert's pairs (stable + # by pair id), so every program derives the same placement without atomics. + pid = tl.program_id(0) + p = tl.arange(0, PAIRS) + pmask = p < num_pairs + expert = tl.load(topk_ids_ptr + p, mask=pmask, other=-1) + live = pmask & (expert >= 0) + if pid == 0: + same = (expert[None, :] == expert[:, None]) & live[None, :] & live[:, None] + rank = tl.sum((same & (p[None, :] < p[:, None])).to(tl.int32), axis=1) + count = tl.sum(same.to(tl.int32), axis=1) + head = live & (rank == 0) + e_safe = tl.where(live, expert, 0) + dst = e_safe.to(tl.int64) * m_max + rank + bins = tl.arange(0, E_P2) + tl.store(masked_m_ptr + bins, tl.zeros([E_P2], dtype=tl.int32), mask=bins < E) + tl.debug_barrier() + tl.store(masked_m_ptr + e_safe, count, mask=head) + tl.debug_barrier() + counts = tl.load( + masked_m_ptr + bins, mask=bins < E, other=0, cache_modifier=".cg" + ) + clusters = (counts + token_width - 1) // token_width # one per touched expert + ent1 = clusters * out_clusters1 + ent2 = clusters * out_clusters2 + tl.store(scratch_ptr + bins, tl.cumsum(ent1, axis=0) - ent1) + tl.store(scratch_ptr + E_P2 + bins, tl.cumsum(ent2, axis=0) - ent2) + tl.store(tiles1_ptr, tl.sum(ent1, axis=0)) + tl.store(tiles2_ptr, tl.sum(ent2, axis=0)) + tl.debug_barrier() + tl.store(pair_to_row_ptr + p, tl.where(live, dst, -1).to(tl.int32), mask=pmask) + # The first row of each touched expert writes the expert's entries: + # one token cluster (index 0) times the stage's output clusters. + begin1 = tl.load(scratch_ptr + e_safe, cache_modifier=".cg") + begin2 = tl.load(scratch_ptr + E_P2 + e_safe, cache_modifier=".cg") + oc = tl.arange(0, OC_P2) + packed = ( + expert.to(tl.int64)[:, None] | (oc.to(tl.int64) << OUTPUT_SHIFT)[None, :] + ) + tl.store( + schedule1_ptr + begin1[:, None] + oc[None, :], + packed, + mask=head[:, None] & (oc < out_clusters1)[None, :], + ) + tl.store( + schedule2_ptr + begin2[:, None] + oc[None, :], + packed, + mask=head[:, None] & (oc < out_clusters2)[None, :], + ) + # Rows: this program moves pairs [pid * PPP, (pid + 1) * PPP) as one + # [PPP, BLOCK_H] tile per column chunk. + q = pid * PPP + tl.arange(0, PPP) + qmask = q < num_pairs + my_expert = tl.load(topk_ids_ptr + q, mask=qmask, other=-1) + my_live = qmask & (my_expert >= 0) + my_rank = tl.sum( + ( + (expert[None, :] == my_expert[:, None]) + & live[None, :] + & (p[None, :] < q[:, None]) + ).to(tl.int32), + axis=1, + ) + my_dst = tl.where(my_live, my_expert, 0).to(tl.int64) * m_max + my_rank + src = input_ptr + (q // TOPK).to(tl.int64)[:, None] * hidden + out = rows_ptr + my_dst[:, None] * hidden + for off in tl.range(0, hidden, BLOCK_H): + cols = off + tl.arange(0, BLOCK_H) + m = my_live[:, None] & (cols < hidden)[None, :] + tl.store(out + cols[None, :], tl.load(src + cols[None, :], mask=m), mask=m) + + +def small_masked_prepare( + hidden_states: torch.Tensor, + topk_ids: torch.Tensor, + top_k: int, + *, + masked_m_out: torch.Tensor, + pair_to_row_out: torch.Tensor, + rows_out: torch.Tensor, + scratch: torch.Tensor, + token_width: int, + out_clusters1: int, + out_clusters2: int, + schedule1_out: torch.Tensor, + tiles1_out: torch.Tensor, + schedule2_out: torch.Tensor, + tiles2_out: torch.Tensor, +) -> None: + check_source_rows(hidden_states, topk_ids, top_k) + hidden = hidden_states.size(1) + num_pairs = topk_ids.numel() + num_experts = masked_m_out.numel() + e_p2 = max(16, triton.next_power_of_2(num_experts)) + if scratch.numel() < 2 * e_p2: + raise ValueError("the small prepare needs a 2 x E_P2 int32 scratch") + pairs = max(16, triton.next_power_of_2(num_pairs)) + block_h = max(128, triton.next_power_of_2(min(hidden, 8192 // _PPP))) + _small_masked_prepare_kernel[(triton.cdiv(num_pairs, _PPP),)]( + hidden_states, + rows_out, + topk_ids.view(-1), + pair_to_row_out, + masked_m_out, + scratch, + schedule1_out, + tiles1_out, + schedule2_out, + tiles2_out, + num_pairs, + rows_out.size(1), + hidden, + token_width, + out_clusters1, + out_clusters2, + E=num_experts, + E_P2=e_p2, + PAIRS=pairs, + PPP=_PPP, + TOPK=top_k, + OC_P2=max(2, triton.next_power_of_2(max(out_clusters1, out_clusters2))), + BLOCK_H=block_h, + OUTPUT_SHIFT=OUTPUT_CLUSTER_SHIFT, + num_warps=8, + ) diff --git a/python/sglang/kernels/ops/lora/moe/finalize.py b/python/sglang/kernels/ops/lora/moe/finalize.py new file mode 100644 index 0000000000..a4270a4788 --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/finalize.py @@ -0,0 +1,423 @@ +"""Materialized and shared-outer weighted finalizers. + +The one-pass path keeps the rank sum and delta in FP32; the staged path rounds +them to buffer dtypes. Neither is bitwise equivalent to per-pair BF16 deltas. +""" + +from __future__ import annotations + +from collections.abc import Mapping + +import torch +import triton +import triton.language as tl + +from sglang.kernels.ops.lora.common.route_view import RouteView + + +@triton.jit +def _shared_token_delta_reduce_kernel( + bridge_ptr, + token_rank_ptr, + weights_ptr, + topk_ids_ptr, + token_lora_mapping_ptr, + num_tokens, + stride_xm, + stride_xk, + stride_tm, + stride_tk, + stride_wm, + stride_wk, + rank: tl.constexpr, + top_k: tl.constexpr, + max_loras: tl.constexpr, + local_expert_count: tl.constexpr, + block_t: tl.constexpr, + block_r: tl.constexpr, +): + tokens = tl.program_id(0) * block_t + tl.arange(0, block_t) + token_mask = tokens < num_tokens + tokens64 = tokens.to(tl.int64) + rank_offsets = tl.arange(0, block_r).to(tl.int64) + rank_mask = rank_offsets < rank + adapter = tl.load(token_lora_mapping_ptr + tokens, mask=token_mask, other=-1) + adapter_valid = (adapter >= 0) & (adapter < max_loras) + acc = tl.zeros((block_t, block_r), tl.float32) + for k in range(top_k): + pairs = tokens * top_k + k + expert = tl.load(topk_ids_ptr + pairs, mask=token_mask, other=-1) + valid = ( + token_mask & adapter_valid & (expert >= 0) & (expert < local_expert_count) + ) + weight = tl.load( + weights_ptr + tokens64 * stride_wm + k * stride_wk, + mask=valid, + other=0.0, + ).to(tl.float32) + x = tl.load( + bridge_ptr + + pairs.to(tl.int64)[:, None] * stride_xm + + rank_offsets[None, :] * stride_xk, + mask=valid[:, None] & rank_mask[None, :], + other=0.0, + ) + acc += weight[:, None] * x.to(tl.float32) + tl.store( + token_rank_ptr + + tokens64[:, None] * stride_tm + + rank_offsets[None, :] * stride_tk, + acc.to(token_rank_ptr.dtype.element_ty), + mask=token_mask[:, None] & rank_mask[None, :], + ) + + +@triton.jit +def _shared_token_delta_tail_kernel( + down_ptr, + pair_to_row_ptr, + token_delta_ptr, + output_ptr, + weights_ptr, + topk_ids_ptr, + token_lora_mapping_ptr, + stride_dm, + stride_dh, + stride_om, + stride_oh, + stride_wm, + stride_wk, + stride_tdm, + stride_tdh, + routed_scaling, + num_local_experts: tl.constexpr, + hidden: tl.constexpr, + top_k: tl.constexpr, + max_loras: tl.constexpr, + block_h: tl.constexpr, +): + # Apply routed scaling once, after adding base and LoRA. + token = tl.program_id(0) + pid_h = tl.program_id(1) + token64 = token.to(tl.int64) + h_offsets = pid_h.to(tl.int64) * block_h + tl.arange(0, block_h).to(tl.int64) + h_mask = h_offsets < hidden + base_acc = tl.zeros((block_h,), tl.float32) + for k in range(top_k): + pair = token * top_k + k + expert = tl.load(topk_ids_ptr + pair) + valid = (expert >= 0) & (expert < num_local_experts) + dst = tl.load(pair_to_row_ptr + pair, mask=valid, other=0).to(tl.int64) + base = tl.load( + down_ptr + dst * stride_dm + h_offsets * stride_dh, + mask=valid & h_mask, + other=0.0, + ).to(tl.float32) + weight = tl.load( + weights_ptr + token64 * stride_wm + k * stride_wk, + mask=valid, + other=0.0, + ).to(tl.float32) + base_acc += weight * base + + adapter = tl.load(token_lora_mapping_ptr + token) + adapter_valid = (adapter >= 0) & (adapter < max_loras) + delta = tl.load( + token_delta_ptr + token64 * stride_tdm + h_offsets * stride_tdh, + mask=adapter_valid & h_mask, + other=0.0, + ).to(tl.float32) + + tl.store( + output_ptr + token64 * stride_om + h_offsets * stride_oh, + (routed_scaling * (base_acc + tl.where(adapter_valid, delta, 0.0))).to( + output_ptr.dtype.element_ty + ), + mask=h_mask, + ) + + +@triton.jit +def _shared_one_pass_kernel( + down_ptr, # [rows, H] provider row order, unweighted + pair_to_row_ptr, # [M * top_k] raw pair -> provider row + bridge_ptr, # [M * top_k, R] raw pair order, unweighted + weights_ptr, + b_ptr, # [S, H, R] + topk_ids_ptr, + token_lora_mapping_ptr, + output_ptr, + stride_dm, + stride_dh, + stride_xm, + stride_xr, + stride_wm, + stride_wk, + stride_bs, + stride_bh, + stride_br, + stride_om, + stride_oh, + routed_scaling, + num_local_experts: tl.constexpr, + hidden: tl.constexpr, + rank: tl.constexpr, + top_k: tl.constexpr, + max_loras: tl.constexpr, + block_h: tl.constexpr, + block_r: tl.constexpr, +): + """Weight and combine unweighted base and rank rows, then apply shared B.""" + token = tl.program_id(0) + pid_h = tl.program_id(1) + token64 = token.to(tl.int64) + h_offsets = pid_h.to(tl.int64) * block_h + tl.arange(0, block_h).to(tl.int64) + h_mask = h_offsets < hidden + r_offsets = tl.arange(0, block_r).to(tl.int64) + r_mask = r_offsets < rank + base_acc = tl.zeros((block_h,), tl.float32) + rank_acc = tl.zeros((block_r,), tl.float32) + for k in tl.static_range(top_k): + pair = token64 * top_k + k + expert = tl.load(topk_ids_ptr + pair) + valid = (expert >= 0) & (expert < num_local_experts) + dst = tl.load(pair_to_row_ptr + pair, mask=valid, other=0).to(tl.int64) + weight = tl.load( + weights_ptr + token64 * stride_wm + k * stride_wk, mask=valid, other=0.0 + ).to(tl.float32) + base = tl.load( + down_ptr + dst * stride_dm + h_offsets * stride_dh, + mask=valid & h_mask, + other=0.0, + ).to(tl.float32) + rank_row = tl.load( + bridge_ptr + pair * stride_xm + r_offsets * stride_xr, + mask=valid & r_mask, + other=0.0, + ).to(tl.float32) + base_acc += weight * base + rank_acc += weight * rank_row + + adapter = tl.load(token_lora_mapping_ptr + token) + adapter_valid = (adapter >= 0) & (adapter < max_loras) + safe_adapter = tl.maximum(adapter, 0).to(tl.int64) + b = tl.load( + b_ptr + + safe_adapter * stride_bs + + h_offsets[:, None] * stride_bh + + r_offsets[None, :] * stride_br, + mask=adapter_valid & h_mask[:, None] & r_mask[None, :], + other=0.0, + ) + delta = tl.sum(b.to(tl.float32) * rank_acc[None, :], axis=1) + tl.store( + output_ptr + token64 * stride_om + h_offsets * stride_oh, + (routed_scaling * (base_acc + tl.where(adapter_valid, delta, 0.0))).to( + output_ptr.dtype.element_ty + ), + mask=h_mask, + ) + + +def invoke_shared_token_delta_reduce( + *, + num_local_experts: int, + bridge: torch.Tensor, + routing: RouteView, + topk_weights: torch.Tensor, + token_rank: torch.Tensor, + config: Mapping[str, int], +) -> None: + num_tokens, top_k = routing.num_tokens, routing.width + if num_tokens == 0: + return + rank = bridge.shape[1] + block_t = int(config["BLOCK_SIZE_T"]) + _shared_token_delta_reduce_kernel[(triton.cdiv(num_tokens, block_t),)]( + bridge, + token_rank, + topk_weights, + routing.group_ids, + routing.token_slots, + num_tokens, + bridge.stride(0), + bridge.stride(1), + token_rank.stride(0), + token_rank.stride(1), + topk_weights.stride(0), + topk_weights.stride(1), + rank=rank, + top_k=top_k, + max_loras=routing.max_loras, + local_expert_count=num_local_experts, + block_t=block_t, + block_r=max(16, triton.next_power_of_2(rank)), + num_warps=int(config["num_warps"]), + num_stages=int(config["num_stages"]), + ) + + +def invoke_shared_token_delta_tail( + *, + num_local_experts: int, + down_rows: torch.Tensor, + pair_to_row: torch.Tensor, + token_delta: torch.Tensor, + routing: RouteView, + topk_weights: torch.Tensor, + routed_scaling_factor: float | None, + output: torch.Tensor, + config: Mapping[str, int], +) -> None: + num_tokens = routing.num_tokens + if num_tokens == 0: + return + hidden = down_rows.shape[-1] + block_h = int(config["BLOCK_SIZE_H"]) + _shared_token_delta_tail_kernel[(num_tokens, triton.cdiv(hidden, block_h))]( + down_rows.view(-1, hidden), + pair_to_row, + token_delta, + output, + topk_weights, + routing.group_ids, + routing.token_slots, + down_rows.stride(-2), + down_rows.stride(-1), + output.stride(0), + output.stride(1), + topk_weights.stride(0), + topk_weights.stride(1), + token_delta.stride(0), + token_delta.stride(1), + 1.0 if routed_scaling_factor is None else routed_scaling_factor, + num_local_experts=num_local_experts, + hidden=hidden, + top_k=routing.width, + max_loras=routing.max_loras, + block_h=block_h, + num_warps=int(config["num_warps"]), + num_stages=int(config["num_stages"]), + ) + + +def invoke_shared_one_pass( + *, + num_local_experts: int, + down_rows: torch.Tensor, + pair_to_row: torch.Tensor, + bridge: torch.Tensor, + b_down: torch.Tensor, + routing: RouteView, + topk_weights: torch.Tensor, + routed_scaling_factor: float | None, + output: torch.Tensor, + config: Mapping[str, int], +) -> None: + num_tokens, top_k = routing.num_tokens, routing.width + if num_tokens == 0: + return + hidden = down_rows.shape[-1] + rank = bridge.shape[-1] + block_h = int(config["BLOCK_SIZE_H"]) + _shared_one_pass_kernel[(num_tokens, triton.cdiv(hidden, block_h))]( + down_rows.view(-1, hidden), + pair_to_row, + bridge, + topk_weights, + b_down, + routing.group_ids, + routing.token_slots, + output, + down_rows.stride(-2), + down_rows.stride(-1), + bridge.stride(0), + bridge.stride(1), + topk_weights.stride(0), + topk_weights.stride(1), + b_down.stride(0), + b_down.stride(1), + b_down.stride(2), + output.stride(0), + output.stride(1), + 1.0 if routed_scaling_factor is None else routed_scaling_factor, + num_local_experts=num_local_experts, + hidden=hidden, + rank=rank, + top_k=top_k, + max_loras=routing.max_loras, + block_h=block_h, + block_r=max(16, triton.next_power_of_2(rank)), + num_warps=int(config["num_warps"]), + num_stages=int(config["num_stages"]), + ) + + +# Vectorize index/weight loads, retaining the shared finalizer's top-k sum order. +@triton.jit +def _small_finalize_kernel( + down_ptr, # [rows, H] base down rows (pair_to_row indexes them) + delta_ptr, # [T * TOPK, H] unweighted LoRA delta per pair (or down_ptr when absent) + out_ptr, # [T, H] + pair_to_row_ptr, # [T * TOPK]; < 0 = no row for this pair + topk_weights_ptr, # [T * TOPK] fp32 + hidden, + scaling, + TOPK: tl.constexpr, + TOPK_P2: tl.constexpr, + HAS_DELTA: tl.constexpr, + BLOCK_H: tl.constexpr, +): + t = tl.program_id(0).to(tl.int64) + cols = tl.program_id(1) * BLOCK_H + tl.arange(0, BLOCK_H) + cmask = cols < hidden + ks = tl.arange(0, TOPK_P2) + kmask = ks < TOPK + rows = tl.load(pair_to_row_ptr + t * TOPK + ks, mask=kmask, other=-1).to(tl.int64) + weights = tl.load(topk_weights_ptr + t * TOPK + ks, mask=kmask, other=0.0).to( + tl.float32 + ) + acc = tl.zeros([BLOCK_H], dtype=tl.float32) + for k in tl.static_range(TOPK): + pick = ks == k + row = tl.sum(tl.where(pick, rows, 0), axis=0) + weight = tl.sum(tl.where(pick, weights, 0.0), axis=0) + live = row >= 0 + x = tl.load(down_ptr + row * hidden + cols, mask=cmask & live, other=0.0).to( + tl.float32 + ) + if HAS_DELTA: + x += tl.load( + delta_ptr + (t * TOPK + k) * hidden + cols, mask=cmask & live, other=0.0 + ).to(tl.float32) + acc += x * weight + acc *= scaling + tl.store(out_ptr + t * hidden + cols, acc.to(out_ptr.dtype.element_ty), mask=cmask) + + +def invoke_small_finalize( + down_rows: torch.Tensor, + output: torch.Tensor, + pair_to_row: torch.Tensor, + topk_weights: torch.Tensor, + routed_scaling_factor: float, + *, + lora_delta: torch.Tensor | None, + block_h: int = 512, +) -> None: + num_tokens, hidden = output.shape + topk = topk_weights.shape[1] + _small_finalize_kernel[(num_tokens, triton.cdiv(hidden, block_h))]( + down_rows, + down_rows if lora_delta is None else lora_delta, + output, + pair_to_row, + topk_weights, + hidden, + float(routed_scaling_factor), + TOPK=topk, + TOPK_P2=triton.next_power_of_2(topk), + HAS_DELTA=lora_delta is not None, + BLOCK_H=block_h, + num_warps=4, + ) diff --git a/python/sglang/kernels/ops/lora/moe/fp8_quant.py b/python/sglang/kernels/ops/lora/moe/fp8_quant.py new file mode 100644 index 0000000000..e7e7cc77af --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/fp8_quant.py @@ -0,0 +1,34 @@ +"""Match upstream FP8 scale arithmetic, with zero codes for zero-scale rows. + +Whole-row division uses fast math only on SM90; group quantization always does. +""" + +from __future__ import annotations + +import torch +import triton +import triton.language as tl +from triton.language.extra.cuda import libdevice + +_WHOLE_ROW_FAST_DIV = tl.constexpr( + torch.cuda.is_available() and torch.cuda.get_device_capability() == (9, 0) +) + + +@triton.jit +def quantize_fp8_groups(grouped, WHOLE_ROW: tl.constexpr): + """Return FP32 codes and per-group scales for [groups, group_size] input.""" + amax = tl.max(tl.abs(grouped), axis=1) + if WHOLE_ROW: + if _WHOLE_ROW_FAST_DIV: + scale = amax / 448.0 + inv = tl.where(scale == 0.0, 0.0, 1.0 / scale) + else: + scale = libdevice.div_rn(amax, 448.0) + inv = tl.where(scale == 0.0, 0.0, libdevice.div_rn(1.0, scale)) + q = grouped * inv[:, None] + else: + amax = tl.maximum(amax, 1e-10) + scale = amax * (1.0 / 448.0) + q = grouped * (448.0 / amax)[:, None] + return tl.clamp(q, -448.0, 448.0), scale diff --git a/python/sglang/kernels/ops/lora/moe/fused_act.py b/python/sglang/kernels/ops/lora/moe/fused_act.py new file mode 100644 index 0000000000..dfbbe9308c --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/fused_act.py @@ -0,0 +1,295 @@ +"""Fuse gate/up LoRA-B with activation in either base row layout. + +The delta stays FP32 through activation, unlike a materialized BF16 delta. +The optional pair-major copy serves down-A kernels that cannot gather base rows. +""" + +from __future__ import annotations + +from collections.abc import Mapping + +import torch +import triton +import triton.language as tl + +from sglang.kernels.ops.lora.common.route_view import RouteView +from sglang.kernels.ops.lora.common.routing import grouped_tile_coords +from sglang.kernels.ops.lora.moe.activation import ActivationFn +from sglang.kernels.ops.lora.moe.activation_delta import ( + apply_activation, +) + + +@triton.jit +def _base_columns( + offsets, + width: tl.constexpr, + num_slices: tl.constexpr, + gate_first: tl.constexpr, + interleaved: tl.constexpr, +): + if num_slices == 1: + return offsets, offsets + if interleaved: + gate_offsets = 2 * offsets + up_offsets = 2 * offsets + 1 + else: + gate_offsets = offsets + up_offsets = width + offsets + if not gate_first: + gate_offsets, up_offsets = up_offsets, gate_offsets + return gate_offsets, up_offsets + + +@triton.jit +def _delta_slice( + bridge_ptr, + weight_bucket_ptr, + bridge_rows, + pair_mask, + w_offsets, + w_mask, + stride_xm, + stride_xk, + stride_wn, + stride_wk, + slice_id: tl.constexpr, + rank: tl.constexpr, + width: tl.constexpr, + block_m: tl.constexpr, + block_w: tl.constexpr, + block_k: tl.constexpr, +): + acc = tl.zeros((block_m, block_w), tl.float32) + for k_begin in range(0, rank, block_k): + k_offsets = k_begin + tl.arange(0, block_k).to(tl.int64) + k_mask = k_offsets < rank + lhs = tl.load( + bridge_ptr + + bridge_rows[:, None] * stride_xm + + (slice_id * rank + k_offsets)[None, :] * stride_xk, + mask=pair_mask[:, None] & k_mask[None, :], + other=0.0, + ) + rhs = tl.load( + weight_bucket_ptr + + (slice_id * width + w_offsets)[None, :] * stride_wn + + k_offsets[:, None] * stride_wk, + mask=k_mask[:, None] & w_mask[None, :], + other=0.0, + ) + acc += tl.dot(lhs, rhs, out_dtype=tl.float32) + return acc + + +@triton.jit(do_not_specialize=["num_pairs", "num_m_blocks"]) +def _b_act_kernel( + bridge_ptr, + b_ptr, + base_ptr, + act_rows_ptr, + act_pairs_ptr, + pair_to_row_ptr, + topk_ids_ptr, + sorted_pairs_ptr, + block_bucket_ids_ptr, + pairs_post_padded_ptr, + num_pairs, + stride_xm, + stride_xk, + stride_bg, + stride_bn, + stride_bk, + stride_pm, + stride_pn, + stride_am, + stride_an, + stride_qm, + stride_qn, + num_m_blocks, + num_local_experts: tl.constexpr, + top_k: tl.constexpr, + width: tl.constexpr, + rank: tl.constexpr, + num_slices: tl.constexpr, + activation_type: tl.constexpr, + gate_first: tl.constexpr, + interleaved: tl.constexpr, + bridge_token_major: tl.constexpr, + block_m: tl.constexpr, + block_w: tl.constexpr, + block_k: tl.constexpr, + group_m: tl.constexpr, + store_pair_act: tl.constexpr, +): + pid = tl.program_id(0) + # Keep the tile count constexpr for grouped scheduling. + num_w_tiles: tl.constexpr = (width + block_w - 1) // block_w + pid_m, pid_w = grouped_tile_coords(pid, num_w_tiles, num_m_blocks, group_m) + if pid_m * block_m >= tl.load(pairs_post_padded_ptr): + return + + slots = pid_m * block_m + tl.arange(0, block_m).to(tl.int64) + pair_ids = tl.load(sorted_pairs_ptr + slots).to(tl.int64) + pair_mask = pair_ids < num_pairs + expert = tl.load(topk_ids_ptr + pair_ids, mask=pair_mask, other=-1) + base_valid = pair_mask & (expert >= 0) & (expert < num_local_experts) + dst_rows = tl.load(pair_to_row_ptr + pair_ids, mask=base_valid, other=0).to( + tl.int64 + ) + bucket_id = tl.load(block_bucket_ids_ptr + pid_m).to(tl.int64) + + w_offsets = pid_w * block_w + tl.arange(0, block_w).to(tl.int64) + w_mask = w_offsets < width + gate_cols, up_cols = _base_columns( + w_offsets, + width, + num_slices, + gate_first, + interleaved, + ) + + delta_gate = tl.zeros((block_m, block_w), tl.float32) + delta_up = tl.zeros((block_m, block_w), tl.float32) + if bucket_id != -1: + bridge_rows = pair_ids // top_k if bridge_token_major else pair_ids + weight_bucket_ptr = b_ptr + bucket_id * stride_bg + delta_gate += _delta_slice( + bridge_ptr, + weight_bucket_ptr, + bridge_rows, + pair_mask, + w_offsets, + w_mask, + stride_xm, + stride_xk, + stride_bn, + stride_bk, + slice_id=0, + rank=rank, + width=width, + block_m=block_m, + block_w=block_w, + block_k=block_k, + ) + if num_slices == 2: + delta_up += _delta_slice( + bridge_ptr, + weight_bucket_ptr, + bridge_rows, + pair_mask, + w_offsets, + w_mask, + stride_xm, + stride_xk, + stride_bn, + stride_bk, + slice_id=1, + rank=rank, + width=width, + block_m=block_m, + block_w=block_w, + block_k=block_k, + ) + + base_gate = tl.load( + base_ptr + dst_rows[:, None] * stride_pm + gate_cols[None, :] * stride_pn, + mask=base_valid[:, None] & w_mask[None, :], + other=0.0, + ).to(tl.float32) + act = apply_activation(base_gate + delta_gate, activation_type) + if num_slices == 2: + base_up = tl.load( + base_ptr + dst_rows[:, None] * stride_pm + up_cols[None, :] * stride_pn, + mask=base_valid[:, None] & w_mask[None, :], + other=0.0, + ).to(tl.float32) + act = act * (base_up + delta_up) + value = act.to(act_rows_ptr.dtype.element_ty) + tl.store( + act_rows_ptr + dst_rows[:, None] * stride_am + w_offsets[None, :] * stride_an, + value, + mask=base_valid[:, None] & w_mask[None, :], + ) + if store_pair_act: + # Invalid pairs must overwrite stale graph-buffer rows with zero. + tl.store( + act_pairs_ptr + + pair_ids[:, None] * stride_qm + + w_offsets[None, :] * stride_qn, + tl.where(base_valid[:, None], act, 0.0).to(act_pairs_ptr.dtype.element_ty), + mask=pair_mask[:, None] & w_mask[None, :], + ) + + +def fused_b_act( + *, + activation: str, + base_gateup: torch.Tensor, + act_rows: torch.Tensor, + act_pairs: torch.Tensor | None, # [num_tokens, top_k, width] or None + pair_to_row: torch.Tensor, # [num_tokens * top_k] int32 + routing: RouteView, + num_local_experts: int, + gate_first: bool, + interleaved: bool, + config: Mapping[str, int], + bridge_gateup: torch.Tensor, + b_gate_up: torch.Tensor, + bridge_top_k: int = 1, +) -> None: + """Fuse LoRA-B and activation in either provider row layout.""" + ActivationFn.parse(activation) + pairs = routing.num_rows + if pairs == 0: + return + base_rows = base_gateup.view(-1, base_gateup.shape[-1]) + act_rows = act_rows.view(-1, act_rows.shape[-1]) + width = act_rows.shape[1] + slices = base_rows.shape[1] // width + rank = b_gate_up.shape[2] + block_w = int(config["BLOCK_SIZE_W"]) + num_m_blocks = triton.cdiv(routing.sorted_pair_ids.numel(), routing.block_size) + pair_target = act_pairs.view(-1, width) if act_pairs is not None else act_rows + num_w_tiles = triton.cdiv(width, block_w) + _b_act_kernel[(num_m_blocks * num_w_tiles,)]( + bridge_gateup, + b_gate_up, + base_rows, + act_rows, + pair_target, + pair_to_row, + routing.group_ids, + routing.sorted_pair_ids, + routing.block_bucket_ids, + routing.num_pairs_post_padded, + pairs, + bridge_gateup.stride(0), + bridge_gateup.stride(1), + b_gate_up.stride(0), + b_gate_up.stride(1), + b_gate_up.stride(2), + base_rows.stride(0), + base_rows.stride(1), + act_rows.stride(0), + act_rows.stride(1), + pair_target.stride(0), + pair_target.stride(1), + num_m_blocks=num_m_blocks, + num_local_experts=num_local_experts, + top_k=routing.width, + width=width, + rank=rank, + num_slices=slices, + activation_type=activation, + gate_first=gate_first, + interleaved=interleaved, + bridge_token_major=bridge_top_k != 1, + block_m=routing.block_size, + block_w=block_w, + block_k=int(config["BLOCK_SIZE_K"]), + group_m=int(config["GROUP_SIZE_M"]), + store_pair_act=act_pairs is not None, + num_warps=int(config["num_warps"]), + num_stages=int(config["num_stages"]), + ) diff --git a/python/sglang/kernels/ops/lora/moe/lora_b.py b/python/sglang/kernels/ops/lora/moe/lora_b.py new file mode 100644 index 0000000000..063978c23f --- /dev/null +++ b/python/sglang/kernels/ops/lora/moe/lora_b.py @@ -0,0 +1,229 @@ +"""MoE LoRA-B dispatch over shared grouped/per-row expand kernels. + +MoE slots are pre-scaled; every reachable delta cell is written. In-place +down-B uses the grouped kernel with provider row mappings. +""" + +from __future__ import annotations + +import functools +from collections.abc import Mapping, Sequence +from typing import TYPE_CHECKING + +import torch +import triton +import triton.language as tl + +from sglang.kernels.ops.lora.common import lora_b as shared +from sglang.kernels.ops.lora.common.route_view import RouteView +from sglang.kernels.ops.lora.common.routing import grouped_tile_coords + +if TYPE_CHECKING: + from sglang.srt.lora.moe.plan import BSpec + + +@functools.lru_cache(maxsize=None) +def _rows(weight_rows: int, num_slices: int) -> tuple[int, ...]: + width = weight_rows // num_slices + return tuple(s * width for s in range(num_slices + 1)) + + +def _geometry( + weight: torch.Tensor, destination_offsets: Sequence[int], config: Mapping[str, int] +) -> shared.SliceGeometry: + return shared.slice_geometry( + _rows(weight.shape[1], len(destination_offsets)), + config["BLOCK_SIZE_N"], + weight.device, + out_offsets=destination_offsets, + ) + + +def grouped_lora_b( + bridge: torch.Tensor, + weight: torch.Tensor, + destination: torch.Tensor, + routing: RouteView, + *, + destination_offsets: Sequence[int], + config: Mapping[str, int], + pair_bridge: bool = True, +) -> None: + shared.grouped_lora_b( + bridge, + weight, + destination, + routing, + geometry=_geometry(weight, destination_offsets, config), + config=config, + add_inplace=False, + zero_sentinel=True, + pair_bridge=pair_bridge, + ) + + +def run_lora_b( + spec: BSpec, + *, + bridge: torch.Tensor, + weight: torch.Tensor, + destination: torch.Tensor, + routing: RouteView, + destination_offsets: Sequence[int], + config: Mapping[str, int], + pair_bridge: bool = True, + slot_planes: bool = False, +) -> None: + """``slot_planes``: ``bridge`` is [slots, tokens, N], one plane per + adapter slot (the token_dense shrink); only the per_row family reads it.""" + family = spec.family.value + match family: + case "grouped": + grouped_lora_b( + bridge, + weight, + destination, + routing, + destination_offsets=destination_offsets, + config=config, + pair_bridge=pair_bridge, + ) + case "per_row": + shared.per_row_lora_b( + bridge, + weight, + destination, + routing, + geometry=_geometry(weight, destination_offsets, config), + config=config, + add_inplace=False, + zero_sentinel=True, + pair_bridge=pair_bridge, + slot_planes=slot_planes, + ) + case _: + raise NotImplementedError(f"no production LoRA-B executor for {family!r}") + + +@triton.jit(do_not_specialize=["num_pairs", "num_m_blocks"]) +def _down_b_into_base_kernel( + bridge_ptr, + weight_ptr, + down_rows_ptr, + pair_to_row_ptr, + sorted_pair_ids_ptr, + block_bucket_ids_ptr, + num_pairs_post_padded_ptr, + num_pairs, + stride_bm, + stride_bk, + stride_wg, + stride_wn, + stride_wk, + stride_dm, + stride_dn, + num_m_blocks, + N_HIDDEN: tl.constexpr, + RANK: tl.constexpr, + BLOCK_SIZE_M: tl.constexpr, + BLOCK_SIZE_N: tl.constexpr, + BLOCK_SIZE_K: tl.constexpr, + GROUP_SIZE_M: tl.constexpr, +): + pid = tl.program_id(0) + num_pairs_post_padded = tl.load(num_pairs_post_padded_ptr) + num_pid_n: tl.constexpr = (N_HIDDEN + BLOCK_SIZE_N - 1) // BLOCK_SIZE_N + pid_m, pid_n = grouped_tile_coords(pid, num_pid_n, num_m_blocks, GROUP_SIZE_M) + if pid_m * BLOCK_SIZE_M >= num_pairs_post_padded: + return + + bucket_id = tl.load(block_bucket_ids_ptr + pid_m).to(tl.int64) + if bucket_id == -1: + return + + pair_slots = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M).to(tl.int64) + pair_ids = tl.load(sorted_pair_ids_ptr + pair_slots).to(tl.int64) + pair_mask = pair_ids < num_pairs + n_offsets = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N).to(tl.int64) + n_mask = n_offsets < N_HIDDEN + # Valid buckets exclude sentinel pairs whose pair_to_row was never written. + dest_rows = tl.load(pair_to_row_ptr + pair_ids, mask=pair_mask, other=0).to( + tl.int64 + ) + destination_ptrs = ( + down_rows_ptr + dest_rows[:, None] * stride_dm + n_offsets[None, :] * stride_dn + ) + store_mask = pair_mask[:, None] & n_mask[None, :] + + accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) + for k_begin in range(0, RANK, BLOCK_SIZE_K): + k_offsets = k_begin + tl.arange(0, BLOCK_SIZE_K).to(tl.int64) + k_mask = k_offsets < RANK + lhs = tl.load( + bridge_ptr + pair_ids[:, None] * stride_bm + k_offsets[None, :] * stride_bk, + mask=pair_mask[:, None] & k_mask[None, :], + other=0.0, + ) + rhs = tl.load( + weight_ptr + + bucket_id * stride_wg + + n_offsets[None, :] * stride_wn + + k_offsets[:, None] * stride_wk, + mask=n_mask[None, :] & k_mask[:, None], + other=0.0, + ) + accumulator += tl.dot(lhs, rhs, out_dtype=tl.float32) + + base = tl.load(destination_ptrs, mask=store_mask, other=0.0).to(tl.float32) + tl.store( + destination_ptrs, + (base + accumulator).to(down_rows_ptr.dtype.element_ty), + mask=store_mask, + ) + + +def invoke_down_b_into_base( + *, + down_rows: torch.Tensor, + pair_to_row: torch.Tensor, + bridge: torch.Tensor, + b_down: torch.Tensor, + routing: RouteView, + config: Mapping[str, int], +) -> None: + """Add down-B into base rows addressed by pair_to_row.""" + num_tokens, top_k = routing.num_tokens, routing.width + pairs = num_tokens * top_k + hidden = down_rows.shape[1] + rank = bridge.shape[1] + if pairs == 0: + return + block_size_n = int(config["BLOCK_SIZE_N"]) + num_m_blocks = triton.cdiv(routing.sorted_pair_ids.numel(), routing.block_size) + num_pid_n = triton.cdiv(hidden, block_size_n) + _down_b_into_base_kernel[(num_m_blocks * num_pid_n,)]( + bridge, + b_down, + down_rows, + pair_to_row, + routing.sorted_pair_ids, + routing.block_bucket_ids, + routing.num_pairs_post_padded, + pairs, + bridge.stride(0), + bridge.stride(1), + b_down.stride(0), + b_down.stride(1), + b_down.stride(2), + down_rows.stride(0), + down_rows.stride(1), + num_m_blocks=num_m_blocks, + N_HIDDEN=hidden, + RANK=rank, + BLOCK_SIZE_M=routing.block_size, + BLOCK_SIZE_N=block_size_n, + BLOCK_SIZE_K=int(config["BLOCK_SIZE_K"]), + GROUP_SIZE_M=int(config["GROUP_SIZE_M"]), + num_warps=int(config["num_warps"]), + num_stages=int(config["num_stages"]), + ) diff --git a/python/sglang/kernels/ops/lora/moe/virtual_experts.py b/python/sglang/kernels/ops/lora/moe/virtual_experts.py index e8b35e4465..6267cfe217 100644 --- a/python/sglang/kernels/ops/lora/moe/virtual_experts.py +++ b/python/sglang/kernels/ops/lora/moe/virtual_experts.py @@ -306,18 +306,16 @@ def _align_block_size_jit( topk_ids: torch.Tensor, block_size: int, num_experts: int, + scratch=None, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """CUDA JIT align_block_size for num_experts > 1024 (up to 8191). - Uses the v2 kernel from moe_align_kernel.cu which supports large expert - counts via per-thread multi-expert processing and a two-level warp scan, - replacing the previous pure-PyTorch fallback that had excessive CPU overhead - from 15+ individual kernel launches and torch.argsort. + The v2 kernel in moe_align_kernel.cu uses per-thread multi-expert processing + and a two-level warp scan. IDs are shifted by +1 so the EP sentinel (-1) + maps to bucket 0. - The JIT kernel uses a +1 offset convention: topk_ids are shifted by +1 so - that the EP sentinel value (-1) maps to bucket 0. The kernel internally - handles histogram, padded prefix-sum, expert_ids assignment, and token - scattering in just 2–3 CUDA kernel launches. + ``scratch(numel)`` returns the int32 scratch buffer (default: a fresh + allocation); a caller under CUDA graphs passes a persistent buffer. """ assert num_experts <= 8191, ( f"_align_block_size_jit supports at most 8191 experts " @@ -362,7 +360,11 @@ def _align_block_size_jit( + num_post_pad_size + cumsum_size ) - buf = torch.empty(total_buf, dtype=torch.int32, device=device) + buf = ( + torch.empty(total_buf, dtype=torch.int32, device=device) + if scratch is None + else scratch(total_buf) + ) off = 0 sorted_token_ids = buf[off : off + max_num_tokens_padded] off += max_num_tokens_padded diff --git a/python/sglang/kernels/ops/moe/ep_moe_kernels.py b/python/sglang/kernels/ops/moe/ep_moe_kernels.py index 1f4587fd97..0b6d96469b 100644 --- a/python/sglang/kernels/ops/moe/ep_moe_kernels.py +++ b/python/sglang/kernels/ops/moe/ep_moe_kernels.py @@ -898,9 +898,22 @@ def post_reorder_for_cutlass_moe( ) +def _check_out_buffer(tensor, shape, device, name: str) -> None: + if ( + tuple(tensor.shape) != tuple(shape) + or tensor.device != device + or not tensor.is_contiguous() + ): + raise ValueError( + f"{name} must be contiguous {tuple(shape)} on {device}; got " + f"{tensor.dtype} {tuple(tensor.shape)} on {tensor.device}" + ) + + @triton.jit def post_reorder_deepgemm_triton_kernel( down_output_ptr, + lora_delta_ptr, output_ptr, src2dst_ptr, topk_ids_ptr, @@ -909,10 +922,13 @@ def post_reorder_deepgemm_triton_kernel( num_tokens, hidden_size, routed_scaling_factor: float, + HAS_LORA_DELTA: tl.constexpr, BLOCK_SIZE: tl.constexpr, NUM_STAGES: tl.constexpr, ): - """Accumulate valid permuted rows; routed_scaling_factor is folded into the store.""" + """Sum weight * (base + delta) over valid pairs, then apply routed scaling. + Delta is unweighted and indexed by [token, top-k, hidden]. + """ OutDtype = output_ptr.dtype.element_ty offset = BLOCK_SIZE * tl.program_id(1) + tl.arange(0, BLOCK_SIZE) @@ -939,6 +955,10 @@ def post_reorder_deepgemm_triton_kernel( weight_scale = tl.load(token_topk_weights_ptr + idx).to(tl.float32) load_ptr_offs = down_output_ptr_offs + dst_idx * hidden_size in_data = tl.load(load_ptr_offs, mask=mask).to(tl.float32) + if HAS_LORA_DELTA: + slot_idx = src_idx * topk + idx + delta_ptr_offs = lora_delta_ptr + slot_idx * hidden_size + offset + in_data += tl.load(delta_ptr_offs, mask=mask).to(tl.float32) sum_vec += in_data * weight_scale sum_vec *= routed_scaling_factor store_ptr_offs = output_ptr_offs + src_idx * hidden_size @@ -955,10 +975,19 @@ def post_reorder_deepgemm( num_tokens, hidden_size, routed_scaling_factor: float, + lora_delta=None, ): + if lora_delta is not None: + _check_out_buffer( + lora_delta, + (num_tokens, topk, hidden_size), + down_output.device, + "lora_delta", + ) grid, block_dim = _get_launch_config_2d(down_output.device, num_tokens, hidden_size) post_reorder_deepgemm_triton_kernel[grid]( down_output, + down_output if lora_delta is None else lora_delta, output, src2dst, topk_ids, @@ -967,6 +996,7 @@ def post_reorder_deepgemm( num_tokens, hidden_size, float(routed_scaling_factor), + HAS_LORA_DELTA=lora_delta is not None, BLOCK_SIZE=block_dim, NUM_STAGES=3, ) diff --git a/python/sglang/srt/arg_groups/choices.py b/python/sglang/srt/arg_groups/choices.py index e96ed1e0d6..b79f02ee62 100644 --- a/python/sglang/srt/arg_groups/choices.py +++ b/python/sglang/srt/arg_groups/choices.py @@ -150,6 +150,9 @@ MOE_RUNNER_BACKEND_CHOICES = [ "marlin", "humming", "experimental_sgl_marlin", + "lora_cutedsl", + "lora_triton", + "lora_marlin", "hpc_ops", # HPC-Ops (https://github.com/Tencent/hpc-ops), FP8 MoE on Hopper (SM90) only "megamoe", "intel_xpu", diff --git a/python/sglang/srt/arg_groups/fields/lora.py b/python/sglang/srt/arg_groups/fields/lora.py index c7ea9ea8f0..7f7c3cce4c 100644 --- a/python/sglang/srt/arg_groups/fields/lora.py +++ b/python/sglang/srt/arg_groups/fields/lora.py @@ -78,7 +78,7 @@ class Lora(msgspec.Struct): str, Arg( help="Choose the kernel backend for multi-LoRA serving.", - choices=["triton", "csgmv", "ascend", "torch_native"], + choices=["triton", "csgmv", "ascend", "torch_native", "triton_v2"], ), ] = "csgmv" max_lora_chunk_size: A[ diff --git a/python/sglang/srt/arg_groups/lora_hook.py b/python/sglang/srt/arg_groups/lora_hook.py index 35ba2dfa05..5295385202 100644 --- a/python/sglang/srt/arg_groups/lora_hook.py +++ b/python/sglang/srt/arg_groups/lora_hook.py @@ -12,10 +12,24 @@ from sglang.srt.arg_groups.overrides import ( ) from sglang.srt.environ import envs from sglang.srt.lora.lora_registry import LoRARef +from sglang.srt.runtime_context import get_platform logger = logging.getLogger(__name__) +def _check_v2_lora_modes(cfg: Any, option: str): + for unsupported, mode in ( + (cfg.attn_dp_size > 1, "DP-attention with --attn-dp-size > 1"), + (cfg.enable_pdmux, "PD-multiplexing"), + (cfg.enable_two_batch_overlap, "two-batch overlap"), + # Both reach the legacy kv_b correction kernels with V2 batch metadata. + (envs.SGLANG_EXPERIMENTAL_LORA_OPTI.get(), "SGLANG_EXPERIMENTAL_LORA_OPTI"), + (get_platform().is_hip, "ROCm"), + ): + if unsupported: + raise ValueError(f"{option} does not yet support {mode}") + + def check_lora_server_args(server_args: Any): cfg = resolving_view(server_args) @@ -34,6 +48,11 @@ def check_lora_server_args(server_args: Any): ) if cfg.enable_lora: + if cfg.lora_backend == "triton_v2" and not cfg.moe_runner_backend.startswith( + "lora" + ): + _check_v2_lora_modes(cfg, "--lora-backend triton_v2") + if cfg.enable_lora_overlap_loading is None: declare_resolution( server_args, "check_lora_server_args", enable_lora_overlap_loading=False @@ -158,6 +177,65 @@ def check_lora_server_args(server_args: Any): "--lora-drain-wait-threshold must be non-negative." ) + check_lora_moe_runner_args(server_args) + + +def check_lora_moe_runner_args(server_args: Any): + """Reject unsupported LoRA MoE configurations before layer attachment.""" + cfg = resolving_view(server_args) + if ( + cfg.speculative_algorithm is not None + and cfg.speculative_moe_runner_backend is not None + and cfg.speculative_moe_runner_backend.startswith("lora") + ): + # Draft models have no LoRA adapters. + raise ValueError( + f"--speculative-moe-runner-backend {cfg.speculative_moe_runner_backend} " + "is not supported: the LoRA MoE runner serves adapter traffic on the " + "target model" + ) + backend = cfg.moe_runner_backend + if not backend.startswith("lora"): + return + if not cfg.enable_lora: + raise ValueError( + f"--moe-runner-backend {backend} requires --enable-lora (or --lora-paths)" + ) + if cfg.lora_backend != "triton_v2": + raise ValueError( + f"--moe-runner-backend {backend} requires --lora-backend triton_v2" + ) + _check_v2_lora_modes(cfg, f"--moe-runner-backend {backend}") + # Layer attachment checks the specific weight layout within each scheme. + if cfg.quantization not in (None, "fp8", "modelopt_fp4"): + raise ValueError( + f"--moe-runner-backend {backend} supports unquantized BF16, 128-block " + f"FP8 and ModelOpt NVFP4 MoE, got --quantization {cfg.quantization}" + ) + if cfg.quantization == "modelopt_fp4" and backend != "lora_marlin": + raise ValueError( + f"--moe-runner-backend {backend} cannot run ModelOpt NVFP4 MoE; " + "use --moe-runner-backend lora_marlin" + ) + if cfg.moe_a2a_backend != "none": + raise ValueError( + f"--moe-runner-backend {backend} requires Standard dispatch, " + f"got --moe-a2a-backend {cfg.moe_a2a_backend}" + ) + if cfg.ep_join_mode is not None: + raise ValueError( + f"--moe-runner-backend {backend} does not yet support elastic EP" + ) + if ( + cfg.enable_eplb + or cfg.init_expert_location != "trivial" + or cfg.ep_num_redundant_experts > 0 + ): + raise ValueError( + f"--moe-runner-backend {backend} currently requires trivial expert placement " + "without EPLB or redundant experts" + ) + def check_lora_speculative_compatibility(server_args: Any): """Validate LoRA + speculative decoding combinations. diff --git a/python/sglang/srt/arg_groups/overrides.py b/python/sglang/srt/arg_groups/overrides.py index 3de5285c4b..d29583d124 100644 --- a/python/sglang/srt/arg_groups/overrides.py +++ b/python/sglang/srt/arg_groups/overrides.py @@ -1532,6 +1532,9 @@ def _moe_runner_fusion_disable(view: Any) -> dict: Runs before the deprecated cutlass environment override. """ runner = view.moe_runner_backend + if runner in ("lora_triton", "lora_cutedsl", "lora_marlin"): + logger.warning("LoRA MoE keeps shared experts separate for adapter attachment.") + return {"disable_shared_experts_fusion": True} if runner == "flashinfer_cutedsl": logger.warning( "FlashInfer CuteDSL MoE is enabled. --disable-shared-experts-fusion is automatically set." @@ -1639,11 +1642,16 @@ def _speculative_moe_runner_default(view: Any) -> dict: with a quantized draft can set --speculative-moe-runner-backend explicitly. (DeepGEMM megamoe is selected via the a2a backend and falls back per-layer when its weights are not prepared, so it needs no override.) + + A target-only lora_* runner defaults the draft to auto: the draft carries + no adapters, so it takes the regular runner chain. """ if view.speculative_moe_runner_backend is None: default = view.moe_runner_backend if default == "flashinfer_megamoe": default = "flashinfer_trtllm" + elif default.startswith("lora_"): + default = "auto" return {"speculative_moe_runner_backend": default} return {} diff --git a/python/sglang/srt/environ.py b/python/sglang/srt/environ.py index 4dbce1c0f1..d297fd0a46 100644 --- a/python/sglang/srt/environ.py +++ b/python/sglang/srt/environ.py @@ -1356,6 +1356,11 @@ class Envs: # device only, matching how the nvcc path pins -gencode to this GPU. SGLANG_SAIL_GPU_ARCH = EnvStr("native") + # Per-file overrides for packaged MoE LoRA plans, tiles, and base GEMM configs. + SGLANG_LORA_MOE_CONFIG_DIR = EnvStr(None) + # Per-file overrides for dense LoRA plan tables. + SGLANG_LORA_DENSE_CONFIG_DIR = EnvStr(None) + # =================================================================== # Expert-parallel dispatch and MoE execution # =================================================================== diff --git a/python/sglang/srt/layers/moe/fused_moe_triton/layer.py b/python/sglang/srt/layers/moe/fused_moe_triton/layer.py index e8629f0895..f15e6579f0 100644 --- a/python/sglang/srt/layers/moe/fused_moe_triton/layer.py +++ b/python/sglang/srt/layers/moe/fused_moe_triton/layer.py @@ -107,7 +107,11 @@ def _fuses_routed_scaling_factor_in_topk(quant_method, runner_backend) -> bool: getattr(quant_method, "fuse_routed_scaling_factor_in_topk", False) or ( isinstance(quant_method, ModelOptNvFp4FusedMoEMethod) - and (runner_backend is None or not runner_backend.is_marlin()) + # Marlin, or the LoRA MoE runner on its Marlin NVFP4 vendor. + and ( + runner_backend is None + or not (runner_backend.is_marlin() or runner_backend.is_lora_marlin()) + ) ) or ( runner_backend is not None @@ -426,7 +430,11 @@ class FusedMoE(torch.nn.Module): get_moe_runner_backend().is_flashinfer_trtllm() or get_moe_runner_backend().is_flashinfer_trtllm_routed() ) - self.use_deep_gemm = get_moe_runner_backend().is_deep_gemm() + # Unquantized BF16 LoRA uses DeepGEMM's resident weight layout. + self.use_deep_gemm = ( + get_moe_runner_backend().is_deep_gemm() + or get_moe_runner_backend().is_lora() + ) self.quant_config = quant_config self.use_flashinfer_mxfp4_moe = get_moe_runner_backend().is_flashinfer_mxfp4() diff --git a/python/sglang/srt/layers/moe/utils.py b/python/sglang/srt/layers/moe/utils.py index 9086da5da9..4f01ab99a3 100644 --- a/python/sglang/srt/layers/moe/utils.py +++ b/python/sglang/srt/layers/moe/utils.py @@ -171,6 +171,16 @@ class _MoeRunnerBackendPredicates: def is_experimental_sgl_marlin(self): return self.value == MoeRunnerBackend.EXPERIMENTAL_SGL_MARLIN.value + def is_lora(self): + return self.value in ( + MoeRunnerBackend.LORA_CUTEDSL.value, + MoeRunnerBackend.LORA_TRITON.value, + MoeRunnerBackend.LORA_MARLIN.value, + ) + + def is_lora_marlin(self): + return self.value == MoeRunnerBackend.LORA_MARLIN.value + def is_humming(self): return self.value == MoeRunnerBackend.HUMMING.value @@ -198,6 +208,9 @@ class MoeRunnerBackend(_MoeRunnerBackendPredicates, Enum): MARLIN = "marlin" HUMMING = "humming" EXPERIMENTAL_SGL_MARLIN = "experimental_sgl_marlin" + LORA_CUTEDSL = "lora_cutedsl" + LORA_TRITON = "lora_triton" + LORA_MARLIN = "lora_marlin" AITER = "aiter" HPC_OPS = "hpc_ops" INTEL_XPU = "intel_xpu" diff --git a/python/sglang/srt/layers/quantization/modelopt_quant.py b/python/sglang/srt/layers/quantization/modelopt_quant.py index 5108d85e3c..8e6ac103fd 100755 --- a/python/sglang/srt/layers/quantization/modelopt_quant.py +++ b/python/sglang/srt/layers/quantization/modelopt_quant.py @@ -2369,7 +2369,12 @@ class ModelOptNvFp4FusedMoEMethod(FusedMoEMethodBase): def __init__(self, quant_config: ModelOptFp4Config): self.quant_config = quant_config moe_runner_backend = get_moe_runner_backend() - if moe_runner_backend.is_auto() and is_cuda(): + self._lora_marlin = moe_runner_backend.is_lora_marlin() + if moe_runner_backend.is_lora() and not self._lora_marlin: + raise ValueError( + "NVFP4 MoE LoRA requires --moe-runner-backend lora_marlin." + ) + if (moe_runner_backend.is_auto() or moe_runner_backend.is_lora()) and is_cuda(): capability = get_device_capability() use_marlin_fallback = (8, 0) <= capability < (10, 0) else: @@ -2727,6 +2732,8 @@ class ModelOptNvFp4FusedMoEMethod(FusedMoEMethodBase): moe_runner_backend = getattr( self, "_moe_runner_backend", get_moe_runner_backend() ) + if moe_runner_backend.is_lora_marlin(): + moe_runner_backend = MoeRunnerBackend.MARLIN use_nvfp4_dispatch = _use_nvfp4_dispatch() if moe_runner_backend.is_marlin(): # Marlin supports only a single shared w1/w3 weight scale, so collapse @@ -3122,6 +3129,10 @@ class ModelOptNvFp4FusedMoEMethod(FusedMoEMethodBase): self.runner = None return + if moe_runner_backend.is_lora(): + self.runner = None + return + if moe_runner_backend.is_flashinfer_cutedsl(): import sglang.srt.layers.moe.moe_runner.flashinfer_cutedsl # noqa: F401 – triggers @register_fused_func diff --git a/python/sglang/srt/lora/backend/ascend_backend.py b/python/sglang/srt/lora/backend/ascend_backend.py index 9ddb94335a..289799e525 100644 --- a/python/sglang/srt/lora/backend/ascend_backend.py +++ b/python/sglang/srt/lora/backend/ascend_backend.py @@ -219,7 +219,7 @@ class AscendLoRABackend(BaseLoRABackend): return output_tensor - def init_cuda_graph_batch_info( + def init_decode_cuda_graph_batch_info( self, max_bs_in_cuda_graph: int, num_tokens_per_req: int, diff --git a/python/sglang/srt/lora/backend/base_backend.py b/python/sglang/srt/lora/backend/base_backend.py index 455e9f3fe4..8805e86f7a 100644 --- a/python/sglang/srt/lora/backend/base_backend.py +++ b/python/sglang/srt/lora/backend/base_backend.py @@ -27,6 +27,8 @@ class BaseLoRABackend(LoRABackendLmHeadMixing): supports_lora_a_overlap = False skip_inactive_lora_batches = False + # Requires a separate "nolora" decode graph for batches without adapters. + skip_inactive_dense_lora = False # Supporting backends implement init_prefill_cuda_graph_batch_info() and # honor use_prefill_cuda_graph in prepare_lora_batch(). @@ -53,6 +55,8 @@ class BaseLoRABackend(LoRABackendLmHeadMixing): self.prefill_moe_cg_buffers: dict | None = None self._moe_cg_buffer_init_args: tuple[int, torch.dtype, object] | None = None self._moe_cg_buffer_max_bs: int | None = None + # Sequential MoE layers share one workspace, including graph scratch. + self.lora_workspace = None def reset_batch_state(self): """Idle-forward counterpart of prepare_lora_batch(): clears all @@ -79,6 +83,15 @@ class BaseLoRABackend(LoRABackendLmHeadMixing): "prepare_global_lora_batch() to support DP attention." ) + def reset_routing_cache(self) -> None: + """Clear cached routes without changing batch metadata or storage. + + Called before every warmup and capture forward so route-building launches + are recorded in the graph. Repeated calls must be safe. + """ + if self.lora_workspace is not None: + self.lora_workspace.routes.clear() + def validate_lora_targets( self, base_model: torch.nn.Module, @@ -87,6 +100,35 @@ class BaseLoRABackend(LoRABackendLmHeadMixing): """Raise before wrapping when this backend cannot execute its targets.""" pass + def forward_with_base( + self, + layer, + x: torch.Tensor, + base_fn, + lora_a, + lora_b, + output_offset, + offsets, + *, + all_reduce=None, + kind="linear", + pruned_batch_info=None, + ) -> torch.Tensor: + """Run base + LoRA, retaining separate base/A reductions for legacy backends.""" + if all_reduce is None: + return layer.apply_lora(base_fn(), x) + output = base_fn() + lora_a_output = self.run_lora_a_sgemm(x, lora_a) + output = all_reduce(output) + lora_a_output = all_reduce(lora_a_output) + return self.run_lora_b_sgemm( + x=lora_a_output, + weights=lora_b, + output_offset=output_offset, + output_offset_cpu=layer.output_offset_cpu, + base_output=output, + ) + def run_lora_a_embedding( self, input_ids: torch.Tensor, @@ -208,19 +250,10 @@ class BaseLoRABackend(LoRABackendLmHeadMixing): """ pass - def init_cuda_graph_batch_info( - self, - max_bs_in_cuda_graph: int, - num_tokens_per_req: int, + def init_decode_cuda_graph_batch_info( + self, max_bs_in_cuda_graph: int, num_tokens_per_req: int ): - """Phase 2 of LoRA CUDA graph init: dense LoRA batch metadata. - - Called during CudaGraphRunner.__init__(), after init_memory_pool(). - - Args: - max_bs_in_cuda_graph: maximum batch size for CUDA Graph mode - num_tokens_per_req: number of tokens per sequence (1 for decoding, >1 for target_verify) - """ + """Allocate decode-runner metadata, including target verification.""" pass def init_dp_attention_cuda_graph_batch_info(self, max_num_tokens: int) -> None: @@ -231,7 +264,9 @@ class BaseLoRABackend(LoRABackendLmHeadMixing): ) def init_prefill_cuda_graph_batch_info( - self, max_num_tokens: int, max_num_requests: Optional[int] = None + self, + max_num_tokens: int, + max_num_requests: Optional[int] = None, ): """Allocate static LoRA batch metadata for the prefill CUDA graph, sized for the largest captured token bucket. Called before capture.""" @@ -266,7 +301,12 @@ class BaseLoRABackend(LoRABackendLmHeadMixing): base = moe_layer.base_layer top_k = base.top_k - device = moe_layer._quant_info.w13_weight.device + quant_info = moe_layer._quant_info + # Marlin quant info exposes packed weights as w13_qweight. + weight = getattr(quant_info, "w13_weight", None) + if weight is None: + weight = quant_info.w13_qweight + device = weight.device num_experts = base.num_experts block_size_m = 64 @@ -306,7 +346,6 @@ class BaseLoRABackend(LoRABackendLmHeadMixing): (max_bs,), -1, dtype=torch.int32, device=device ), } - if prefill: self.prefill_moe_cg_buffers = buffers else: @@ -392,14 +431,10 @@ class BaseLoRABackend(LoRABackendLmHeadMixing): weight_indices: list[int], lora_ranks: list[int], scalings: list[float], - use_cuda_graph: bool, + use_decode_cuda_graph: bool, use_prefill_cuda_graph: bool = False, ): - """Prepare the lora weights and batch info for current forward batch. - - use_cuda_graph / use_prefill_cuda_graph select in-place updates of the - static decode / prefill CUDA graph batch info respectively. - """ + """Bind eager metadata or update the selected graph family's static metadata.""" pass def prepare_lora_token_segments( @@ -424,11 +459,24 @@ def _compute_moe_lora_info_kernel( weight_indices_ptr, adapter_enabled_ptr, token_lora_mapping_ptr, - num_segments, max_len, + num_tokens, + bucket_len, + live_programs, BLOCK_SIZE: tl.constexpr, ): pid = tl.program_id(0) + if pid >= live_programs: + # A tile of the static bucket past the live tokens: no adapter. + offs = ( + num_tokens + (pid - live_programs) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + ) + tl.store( + token_lora_mapping_ptr + offs, + tl.full((BLOCK_SIZE,), -1, tl.int32), + mask=offs < bucket_len, + ) + return num_pid_m = tl.cdiv(max_len, BLOCK_SIZE) pid_seg = pid // num_pid_m @@ -441,12 +489,18 @@ def _compute_moe_lora_info_kernel( valid = offs < seg_len lora_id = tl.load(weight_indices_ptr + pid_seg) lora_rank = tl.load(lora_ranks_ptr + lora_id) + adapter_is_enabled = lora_rank > 0 + if adapter_enabled_ptr is not None: + tl.store( + adapter_enabled_ptr + lora_id, + adapter_is_enabled.to(tl.int32), + mask=pid_m == 0, + ) tl.store( - adapter_enabled_ptr + lora_id, - (lora_rank > 0).to(tl.int32), - mask=pid_m == 0, + token_lora_mapping_ptr + seg_start + offs, + tl.where(adapter_is_enabled, lora_id, -1), + mask=valid, ) - tl.store(token_lora_mapping_ptr + seg_start + offs, lora_id, mask=valid) def _compute_moe_lora_info( @@ -457,31 +511,60 @@ def _compute_moe_lora_info( adapter_enabled: torch.Tensor | None, token_lora_mapping: torch.Tensor | None, max_len: int, + bucket_len: int | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: + """Build token slots and the active-adapter mask for legacy backends.""" + if adapter_enabled is None: + adapter_enabled = torch.empty( + len(lora_ranks), dtype=torch.int32, device=lora_ranks.device + ) + else: + assert len(lora_ranks) <= adapter_enabled.shape[0], ( + "lora_ranks must be less than or equal to the shape of adapter_enabled" + ) + adapter_enabled.zero_() + token_lora_mapping = _compute_token_lora_mapping( + num_tokens, + seg_indptr, + lora_ranks, + weight_indices, + token_lora_mapping, + max_len, + bucket_len=bucket_len, + adapter_enabled=adapter_enabled, + ) + return adapter_enabled, token_lora_mapping + + +def _compute_token_lora_mapping( + num_tokens: int, + seg_indptr: torch.Tensor, + lora_ranks: torch.Tensor, + weight_indices: torch.Tensor, + token_lora_mapping: torch.Tensor | None, + max_len: int, + bucket_len: int | None = None, + adapter_enabled: torch.Tensor | None = None, +) -> torch.Tensor: + """Expand request slots, clearing graph padding in the same CUDA launch.""" + tail_tiles = 0 + full_mapping = token_lora_mapping if token_lora_mapping is not None: assert num_tokens <= token_lora_mapping.shape[0], ( "num_tokens must be less than or equal to the shape of token_lora_mapping" ) - # Clear padded replay rows left by a larger batch. + # Clear graph padding here unless the CUDA kernel will clear it. if num_tokens < token_lora_mapping.shape[0]: - token_lora_mapping[num_tokens:].fill_(-1) + if bucket_len is not None and token_lora_mapping.device.type == "cuda": + tail_tiles = triton.cdiv(bucket_len - num_tokens, 256) + else: + token_lora_mapping[num_tokens:].fill_(-1) token_lora_mapping = token_lora_mapping[:num_tokens] else: token_lora_mapping = torch.empty( (num_tokens,), dtype=torch.int32, device=seg_indptr.device ) - if adapter_enabled is not None: - assert len(lora_ranks) <= adapter_enabled.shape[0], ( - "lora_ranks must be less than or equal to the shape of adapter_enabled" - ) - else: - adapter_enabled = torch.empty( - len(lora_ranks), dtype=torch.int32, device=lora_ranks.device - ) - - adapter_enabled.zero_() - has_segments = weight_indices.numel() != 0 needs_launch = num_tokens != 0 and has_segments if needs_launch: @@ -496,28 +579,32 @@ def _compute_moe_lora_info( # Triton kernel on CUDA only; every other device (e.g. XPU) falls through to # the native torch path below, which yields the same mapping. if needs_launch and seg_indptr.device.type == "cuda": - _compute_moe_lora_info_kernel[(grid_size,)]( + _compute_moe_lora_info_kernel[(grid_size + tail_tiles,)]( seg_indptr, lora_ranks, weight_indices, adapter_enabled, token_lora_mapping, - weight_indices.numel(), max_len, + num_tokens, + bucket_len if tail_tiles else 0, + grid_size, BLOCK_SIZE=block_size, ) - return adapter_enabled, token_lora_mapping + return token_lora_mapping + if tail_tiles: + full_mapping[num_tokens:bucket_len].fill_(-1) - if has_segments: + if has_segments and adapter_enabled is not None: active_ranks = lora_ranks[weight_indices.long()] adapter_enabled.scatter_( 0, weight_indices.long(), (active_ranks > 0).to(torch.int32) ) if num_tokens == 0: - return adapter_enabled, token_lora_mapping + return token_lora_mapping if not has_segments: token_lora_mapping.fill_(-1) - return adapter_enabled, token_lora_mapping + return token_lora_mapping token_positions = torch.arange( num_tokens, device=seg_indptr.device, dtype=torch.int32 @@ -529,8 +616,12 @@ def _compute_moe_lora_info( torch.searchsorted(seg_indptr.to(torch.int32), token_positions, right=True) - 1 ) - token_lora_mapping = torch.index_select( + torch.index_select( weight_indices.to(torch.int32), 0, req_indices, out=token_lora_mapping ) + token_lora_ranks = torch.index_select( + lora_ranks, 0, token_lora_mapping.to(torch.int64) + ) + token_lora_mapping.masked_fill_(token_lora_ranks <= 0, -1) - return adapter_enabled, token_lora_mapping + return token_lora_mapping diff --git a/python/sglang/srt/lora/backend/chunked_backend.py b/python/sglang/srt/lora/backend/chunked_backend.py index c89f6f7d8b..fe932d5638 100644 --- a/python/sglang/srt/lora/backend/chunked_backend.py +++ b/python/sglang/srt/lora/backend/chunked_backend.py @@ -219,7 +219,7 @@ class ChunkedSgmvLoRABackend(BaseLoRABackend): torch.cumsum(seg_lens, dim=0, out=indptr[1:]) return indptr - def init_cuda_graph_batch_info( + def init_decode_cuda_graph_batch_info( self, max_bs_in_cuda_graph: int, num_tokens_per_req: int, diff --git a/python/sglang/srt/lora/backend/lora_registry.py b/python/sglang/srt/lora/backend/lora_registry.py index eeeefd4137..db2c1c825f 100644 --- a/python/sglang/srt/lora/backend/lora_registry.py +++ b/python/sglang/srt/lora/backend/lora_registry.py @@ -30,6 +30,13 @@ def create_triton_csgmv_backend(): return ChunkedSgmvLoRABackend +@register_lora_backend("triton_v2") +def create_triton_v2_backend(): + from sglang.srt.lora.backend.triton_v2_backend import TritonV2LoRABackend + + return TritonV2LoRABackend + + @register_lora_backend("ascend") def create_ascend_backend(): from sglang.srt.lora.backend.ascend_backend import AscendLoRABackend diff --git a/python/sglang/srt/lora/backend/torch_backend.py b/python/sglang/srt/lora/backend/torch_backend.py index c88e064032..7b43b432df 100644 --- a/python/sglang/srt/lora/backend/torch_backend.py +++ b/python/sglang/srt/lora/backend/torch_backend.py @@ -161,7 +161,7 @@ class TorchNativeLoRABackend(BaseLoRABackend): return output_tensor - def init_cuda_graph_batch_info( + def init_decode_cuda_graph_batch_info( self, max_bs_in_cuda_graph: int, num_tokens_per_req: int, diff --git a/python/sglang/srt/lora/backend/triton_backend.py b/python/sglang/srt/lora/backend/triton_backend.py index ddd291d2c2..9c88209dd8 100644 --- a/python/sglang/srt/lora/backend/triton_backend.py +++ b/python/sglang/srt/lora/backend/triton_backend.py @@ -377,7 +377,7 @@ class TritonLoRABackend(BaseLoRABackend): permutation=torch.zeros(max_tokens, dtype=torch.int32, device=self.device), ) - def init_cuda_graph_batch_info( + def init_decode_cuda_graph_batch_info( self, max_bs_in_cuda_graph: int, num_tokens_per_req: int, @@ -414,7 +414,7 @@ class TritonLoRABackend(BaseLoRABackend): def init_dp_attention_cuda_graph_batch_info(self, max_num_tokens: int) -> None: local_batch_info = getattr(self, "cuda_graph_batch_info", None) assert local_batch_info is not None, ( - "init_cuda_graph_batch_info must run before DP-attention graph init" + "init_decode_cuda_graph_batch_info must run before DP-attention graph init" ) max_global_num_tokens = max_num_tokens * get_parallel().attn_dp_size self.cuda_graph_global_batch_info = build_token_lora_batch_info( diff --git a/python/sglang/srt/lora/backend/triton_v2_backend.py b/python/sglang/srt/lora/backend/triton_v2_backend.py new file mode 100644 index 0000000000..251926e3cb --- /dev/null +++ b/python/sglang/srt/lora/backend/triton_v2_backend.py @@ -0,0 +1,343 @@ +"""Dense LoRA execution with request metadata shared by Linear and MoE layers.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import ClassVar + +import torch + +from sglang.kernels.ops.lora.dense.embedding_lora_a import embedding_lora_a_tokens_fwd +from sglang.srt.lora.backend.base_backend import ( + BaseLoRABackend, + _compute_token_lora_mapping, +) +from sglang.srt.lora.dense.plan import DenseLoraKind +from sglang.srt.lora.dense.runner import DenseLoraRunner +from sglang.srt.lora.utils import ( + Phase, + get_batch_token_counts, + get_lm_head_pruned_lens, + merge_and_chunk_segments, +) +from sglang.srt.lora.workspace import LoraWorkspace +from sglang.srt.model_executor.forward_batch_info import ForwardBatch + + +@dataclass +class _BatchInfo: + packed: torch.Tensor + lora_ranks: torch.Tensor + scalings: torch.Tensor + weight_indices: torch.Tensor + seg_indptr: torch.Tensor + token_slots: torch.Tensor + use_cuda_graph: bool # Static metadata for either graph family, including warmup. + num_tokens: int = 0 + tokens_per_request: int = 0 + has_active_lora: bool = False # Inkling's shared sink skips inactive eager batches. + is_prefill: bool = False # MoE plan phase; target verification uses decode. + + +@dataclass +class _LmHeadBatchInfo: + seg_indptr: torch.Tensor + weight_indices: torch.Tensor + expected_tokens: int + max_len: int + use_cuda_graph: ClassVar[bool] = False + + +class TritonV2LoRABackend(BaseLoRABackend): + name = "triton_v2" + supports_prefill_cuda_graph = True + skip_inactive_dense_lora = True + + def __init__(self, max_loras_per_batch: int, device: torch.device, **kwargs): + super().__init__(max_loras_per_batch, device) + self.lora_workspace = LoraWorkspace() + self.runner = DenseLoraRunner( + self.lora_workspace, max_loras=max_loras_per_batch, device=device + ) + self.lm_head_runner: DenseLoraRunner | None = None + self.decode_cuda_graph_batch_info: _BatchInfo | None = None + + def validate_lora_targets(self, base_model, target_modules: set[str]) -> None: + if "lm_head" in target_modules and self.lm_head_runner is None: + # Pruned/chunked logits run outside the model graph on their own rows. + self.lm_head_runner = DenseLoraRunner( + LoraWorkspace(), + max_loras=self.max_loras_per_batch, + device=self.device, + architecture=self.runner.architecture, + ) + + def reset_batch_state(self): + super().reset_batch_state() + self.runner.reset() + if self.lm_head_runner is not None: + self.lm_head_runner.reset() + + def reset_routing_cache(self) -> None: + self.runner.reset_routes() + if self.lm_head_runner is not None: + self.lm_head_runner.reset_routes() + + def init_cuda_graph_moe_buffers( + self, max_bs, max_loras, compute_dtype, moe_layer, *, prefill=False + ): + # V2 owns the metadata; the MoE workspace owns kernel scratch. + pass + + def _new_batch( + self, requests: int, tokens: int, *, graph: bool = False + ) -> _BatchInfo: + slots = self.max_loras_per_batch + head = 2 * slots + alloc = torch.zeros if graph else torch.empty + packed = alloc(head + 2 * requests + 1, dtype=torch.int32, device=self.device) + token_slots = torch.empty((tokens,), dtype=torch.int32, device=self.device) + if graph: + token_slots.fill_(-1) + return _BatchInfo( + packed=packed, + lora_ranks=packed[:slots], + scalings=packed[slots : 2 * slots].view(torch.float32), + weight_indices=packed[head : head + requests], + seg_indptr=packed[head + requests :], + token_slots=token_slots, + use_cuda_graph=graph, + ) + + def init_decode_cuda_graph_batch_info( + self, max_bs_in_cuda_graph: int, num_tokens_per_req: int + ): + batch = self._new_batch( + max_bs_in_cuda_graph, + max_bs_in_cuda_graph * num_tokens_per_req, + graph=True, + ) + batch.tokens_per_request = num_tokens_per_req + batch.seg_indptr.copy_( + torch.arange( + max_bs_in_cuda_graph + 1, dtype=torch.int32, device=self.device + ) + * num_tokens_per_req + ) + self.decode_cuda_graph_batch_info = batch + + def init_prefill_cuda_graph_batch_info( + self, max_num_tokens: int, max_num_requests: int | None = None + ): + requests = max_num_tokens if max_num_requests is None else max_num_requests + self.prefill_cuda_graph_batch_info = self._new_batch( + requests, max_num_tokens, graph=True + ) + self.prefill_cuda_graph_max_bs = requests + self.prefill_cuda_graph_max_tokens = max_num_tokens + + def _fill_batch( + self, + batch: _BatchInfo, + weight_indices: list[int], + lora_ranks: list[int], + scalings: list[float], + lengths: list[int] | None, + ) -> None: + slots = self.max_loras_per_batch + requests = len(weight_indices) + if requests > batch.weight_indices.numel(): + raise ValueError("LoRA requests exceed the graph metadata capacity") + indptr = [] + if lengths is not None: + indptr = [0] + for length in lengths: + indptr.append(indptr[-1] + length) + head = 2 * slots + requests + host = torch.empty(head + len(indptr), dtype=torch.int32, pin_memory=True) + host[:slots] = torch.as_tensor(lora_ranks, dtype=torch.int32) + host[slots : 2 * slots].view(torch.float32).copy_( + torch.as_tensor(scalings, dtype=torch.float32) + ) + host[2 * slots : head] = torch.as_tensor(weight_indices, dtype=torch.int32) + batch.packed[:head].copy_(host[:head], non_blocking=True) + if lengths is not None: + host[head:] = torch.as_tensor(indptr, dtype=torch.int32) + batch.seg_indptr[: requests + 1].copy_(host[head:], non_blocking=True) + + def prepare_lora_batch( + self, + forward_batch: ForwardBatch, + weight_indices: list[int], + lora_ranks: list[int], + scalings: list[float], + use_decode_cuda_graph: bool, + use_prefill_cuda_graph: bool = False, + ): + requests = forward_batch.batch_size + num_tokens, max_len = get_batch_token_counts(forward_batch) + if use_decode_cuda_graph: + batch = self.decode_cuda_graph_batch_info + if batch is None: + raise RuntimeError("LoRA decode graph metadata is not initialized") + if max_len != batch.tokens_per_request: + raise ValueError( + f"LoRA request width {max_len} does not match captured width " + f"{batch.tokens_per_request}" + ) + lengths = None + else: + if use_prefill_cuda_graph: + batch = self.prefill_cuda_graph_batch_info + if batch is None: + raise RuntimeError("LoRA prefill graph metadata is not initialized") + else: + batch = self._new_batch(requests, num_tokens) + lengths = ( + list(forward_batch.extend_seq_lens_cpu) + if forward_batch.forward_mode.is_extend_without_speculative() + else [max_len] * requests + ) + if len(weight_indices) != requests: + raise ValueError("LoRA needs one adapter slot per request") + self._fill_batch(batch, weight_indices, lora_ranks, scalings, lengths) + + request_indptr = batch.seg_indptr[: requests + 1] + request_slots = batch.weight_indices[:requests] + # Only live requests map tokens; the kernel also clears the padded tail. + _compute_token_lora_mapping( + num_tokens, + request_indptr, + batch.lora_ranks, + request_slots, + batch.token_slots, + max_len=max_len, + bucket_len=batch.token_slots.numel(), + ) + batch.num_tokens = num_tokens + self.batch_info = batch + self.runner.begin_batch( + token_slots=batch.token_slots, + lora_ranks=batch.lora_ranks, + scalings=batch.scalings, + num_tokens=num_tokens, + phase=( + Phase.PREFILL + if forward_batch.forward_mode.is_extend() + else Phase.DECODE + ), + graph_mode=batch.use_cuda_graph, + is_prefill_graph=use_prefill_cuda_graph, + ) + if self.lm_head_runner is not None: + self.lm_head_batch_info, self.lm_head_pass_batch_infos = ( + self._prepare_lm_head_batch_info(forward_batch, weight_indices) + ) + self._lm_head_pass_idx = None + + def _prepare_lm_head_batch_info(self, forward_batch, weight_indices): + pruned_lens = get_lm_head_pruned_lens(forward_batch) + if pruned_lens is None: + return None, None + pruned_total = sum(pruned_lens) + full_pruned_info = self._build_lm_head_batch_info( + merge_and_chunk_segments(weight_indices, pruned_lens, pruned_total) + ) + pass_segments = self._get_lm_head_pass_segments(weight_indices, pruned_lens) + return full_pruned_info, ( + [self._build_lm_head_batch_info(segments) for segments in pass_segments] + if pass_segments is not None + else None + ) + + def _build_lm_head_batch_info(self, segments) -> _LmHeadBatchInfo: + weight_indices, lengths = segments + indptr = [0] + for length in lengths: + indptr.append(indptr[-1] + length) + host = torch.tensor(indptr + weight_indices, dtype=torch.int32, pin_memory=True) + device = host.to(self.device, non_blocking=True) + return _LmHeadBatchInfo( + seg_indptr=device[: len(indptr)], + weight_indices=device[len(indptr) :], + expected_tokens=indptr[-1], + max_len=max(lengths, default=0), + ) + + def _runner_for( + self, pruned_batch_info: _LmHeadBatchInfo | None + ) -> DenseLoraRunner: + if pruned_batch_info is None: + return self.runner + if self.lm_head_runner is None: + raise RuntimeError("lm_head LoRA was not enabled in the target modules") + batch = self.batch_info + token_slots = _compute_token_lora_mapping( + pruned_batch_info.expected_tokens, + pruned_batch_info.seg_indptr, + batch.lora_ranks, + pruned_batch_info.weight_indices, + None, + max_len=pruned_batch_info.max_len, + ) + self.lm_head_runner.begin_batch( + token_slots=token_slots, + lora_ranks=batch.lora_ranks, + scalings=batch.scalings, + num_tokens=pruned_batch_info.expected_tokens, + phase=self.runner.phase, + graph_mode=False, + ) + return self.lm_head_runner + + def forward_with_base( + self, + layer, + x, + base_fn, + lora_a, + lora_b, + output_offset, + offsets, + *, + all_reduce=None, + kind: DenseLoraKind = DenseLoraKind.LINEAR, + pruned_batch_info: _LmHeadBatchInfo | None = None, + ): + runner = self._runner_for(pruned_batch_info) + plan = runner.plan_for( + kind, + lora_b.shape[-1], + 0 if kind is DenseLoraKind.EMBEDDING else lora_a.shape[-1], + offsets[-1], + num_tokens=x.shape[0], + ) + a_fn = None + if kind is DenseLoraKind.EMBEDDING: + + def a_fn(): + return embedding_lora_a_tokens_fwd( + input_ids=x, + weights=lora_a, + token_lora_mapping=runner.token_slots, + lora_ranks=runner.lora_ranks, + vocab_size=layer.vocab_size, + extra_embeddings=layer.new_embeddings_buffer, + ) + + return runner.apply( + x, + base_fn, + plan, + a=lora_a, + b=lora_b, + offsets=offsets, + all_reduce=all_reduce, + a_fn=a_fn, + ) + + def run_qkv_lora(self, *args, **kwargs): + raise NotImplementedError("triton_v2 linear layers must use forward_with_base") + + def run_gate_up_lora(self, *args, **kwargs): + raise NotImplementedError("triton_v2 linear layers must use forward_with_base") diff --git a/python/sglang/srt/lora/dense/__init__.py b/python/sglang/srt/lora/dense/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/python/sglang/srt/lora/dense/configs/README.md b/python/sglang/srt/lora/dense/configs/README.md new file mode 100644 index 0000000000..f0fc43f03a --- /dev/null +++ b/python/sglang/srt/lora/dense/configs/README.md @@ -0,0 +1,42 @@ +# Dense LoRA execution plans + +`.plans.json` selects kernels, routing tiles and overlap for +`--lora-backend triton_v2`. Capability major 9 selects `sm90`, major 10 or +above selects `sm100`, and other devices select `default`. + +## Selection and overrides + +Rows are tried in file order; the first compatible match wins. Selectors cover +phase, layer kind, token count, pool rank and input/output widths. Put narrow +rules before broad ones. A row name is only a label, not a selector. The +windowed Inkling sink-down site cannot use an all-slots shrink. + +`SGLANG_LORA_DENSE_CONFIG_DIR` can supply an override file for an architecture. +Missing files or unmatched queries use the defaults in `../plan.py`. Tables +are cached within the process; use a fresh server to evaluate a changed file. +Malformed tables fail loading, including invalid rows that the current model +would not select. + +Each plan contains: + +- `a_family`: grouped, per-row or all-slots shrink; +- `b_family`: grouped or per-row expand; +- `overlap`: `none`, `a`, or `ab_delta`; +- `block_size`: aligned routing tile; +- `a_tiles` and `b_tiles`: complete launch configurations. + +Grouped stages use aligned routes; per-row stages use raw routes. All-slots A +writes slot planes and requires per-row B. Split-K is grouped-A only, with +deterministic `serial` or `planes` reduction. These compatibility rules are +independent of which configuration is fastest. + +## Tuning + +Use the [dense tuner](../../../../../../benchmark/kernels/lora_dense/README.md) +for explicit resident shapes and devices. Independent validation of a kernel +candidate does not qualify an entire production selector region. Check every +affected kind/rank/geometry/phase, then measure model throughput with the actual +graphs and base backend before promoting a row. + +Historical exploration and measurements remain in Git history; they are not +instructions for the maintained tuner or a current no-regression guarantee. diff --git a/python/sglang/srt/lora/dense/configs/default.plans.json b/python/sglang/srt/lora/dense/configs/default.plans.json new file mode 100644 index 0000000000..d74c3e2420 --- /dev/null +++ b/python/sglang/srt/lora/dense/configs/default.plans.json @@ -0,0 +1,433 @@ +{ + "rows": [ + { + "name": "decode.vocab", + "kinds": [ + "embedding", + "lm_head" + ], + "phase": "decode", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.vocab", + "kinds": [ + "embedding", + "lm_head" + ], + "phase": "prefill", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2 + } + } + }, + { + "name": "decode.tokens_le8.k_le1024", + "phase": "decode", + "max_in_features": 1024, + "max_tokens": 8, + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.k_le1024", + "phase": "decode", + "max_in_features": 1024, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.n_le1024", + "phase": "decode", + "max_out_features": 1024, + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.tokens_le1.n_ge8192", + "phase": "decode", + "max_tokens": 1, + "min_out_features": 8192, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.tokens_le1", + "phase": "decode", + "max_tokens": 1, + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.tokens_le8.n_le4096", + "phase": "decode", + "max_tokens": 8, + "max_out_features": 4096, + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.tokens_le16.n_le4096", + "phase": "decode", + "max_tokens": 16, + "max_out_features": 4096, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.tokens_le16.n_le10240", + "phase": "decode", + "max_tokens": 16, + "max_out_features": 10240, + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "none", + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.tokens_le16", + "phase": "decode", + "max_tokens": 16, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.n_le10240", + "phase": "decode", + "max_out_features": 10240, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode", + "phase": "decode", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.tokens_le512.n_le4096", + "max_tokens": 512, + "max_out_features": 4096, + "phase": "prefill", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.tokens_le512", + "max_tokens": 512, + "phase": "prefill", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2 + } + } + }, + { + "name": "prefill.n_le4096", + "max_out_features": 4096, + "phase": "prefill", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "block_size": 32, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.n_le10240", + "max_out_features": 10240, + "phase": "prefill", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2 + } + } + }, + { + "name": "prefill", + "phase": "prefill", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "block_size": 128, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 1 + } + } + } + ] +} diff --git a/python/sglang/srt/lora/dense/configs/sm100.plans.json b/python/sglang/srt/lora/dense/configs/sm100.plans.json new file mode 100644 index 0000000000..73220fe2f4 --- /dev/null +++ b/python/sglang/srt/lora/dense/configs/sm100.plans.json @@ -0,0 +1,3096 @@ +{ + "rows": [ + { + "name": "decode.sink_gate_up.tokens_le16.n_le4096", + "kinds": [ + "sink_gate_up" + ], + "phase": "decode", + "max_tokens": 16, + "max_out_features": 4096, + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.sink_down.tokens_le16.k_le2048", + "kinds": [ + "sink_down" + ], + "phase": "decode", + "max_tokens": 16, + "max_in_features": 2048, + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.sink_gate_up.tokens_le32.n_le4096", + "kinds": [ + "sink_gate_up" + ], + "phase": "decode", + "max_tokens": 32, + "max_out_features": 4096, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.sink_gate_up.tokens_le32.n_ge4097", + "kinds": [ + "sink_gate_up" + ], + "phase": "decode", + "max_tokens": 32, + "min_out_features": 4097, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8, + "SPLIT_MODE": "serial" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.sink_down.tokens_le32.k_le2048", + "kinds": [ + "sink_down" + ], + "phase": "decode", + "max_tokens": 32, + "max_in_features": 2048, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.sink_down.tokens_le32.k_ge2049", + "kinds": [ + "sink_down" + ], + "phase": "decode", + "max_tokens": 32, + "min_in_features": 2049, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8, + "SPLIT_MODE": "serial" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.sink_gate_up.rank_le16.tokens_le1024.n_le4096", + "kinds": [ + "sink_gate_up" + ], + "phase": "prefill", + "max_tokens": 1024, + "max_rank": 16, + "max_out_features": 4096, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2 + } + } + }, + { + "name": "prefill.sink_gate_up.rank_le16.n_le4096", + "kinds": [ + "sink_gate_up" + ], + "phase": "prefill", + "max_rank": 16, + "max_out_features": 4096, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.sink_gate_up.n_le4096", + "kinds": [ + "sink_gate_up" + ], + "phase": "prefill", + "max_out_features": 4096, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 2, + "SPLIT_MODE": "serial" + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2 + } + } + }, + { + "name": "prefill.sink_gate_up.rank_le16.tokens_le512.n_ge4097", + "kinds": [ + "sink_gate_up" + ], + "phase": "prefill", + "max_tokens": 512, + "max_rank": 16, + "min_out_features": 4097, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.sink_gate_up.n_ge4097", + "kinds": [ + "sink_gate_up" + ], + "phase": "prefill", + "min_out_features": 4097, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2 + } + } + }, + { + "name": "prefill.sink_down", + "kinds": [ + "sink_down" + ], + "phase": "prefill", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2 + } + } + }, + { + "name": "decode.vocab", + "kinds": [ + "embedding", + "lm_head" + ], + "phase": "decode", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.vocab", + "kinds": [ + "embedding", + "lm_head" + ], + "phase": "prefill", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2 + } + } + }, + { + "name": "decode.tokens_le1.k_le1024", + "phase": "decode", + "max_in_features": 1024, + "max_tokens": 1, + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.tokens_le1.n_le1024", + "phase": "decode", + "max_out_features": 1024, + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + }, + "max_tokens": 1 + }, + { + "name": "decode.rank_le128.tokens_le1.n_ge8192", + "phase": "decode", + "max_tokens": 1, + "min_out_features": 8192, + "max_rank": 128, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.tokens_le1.n_ge8192", + "phase": "decode", + "max_tokens": 1, + "min_out_features": 8192, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.rank_le128.tokens_le1.k_ge2291_le4579.n_ge1847_le2290", + "phase": "decode", + "max_tokens": 1, + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 4, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + }, + "max_rank": 128, + "min_in_features": 2291, + "max_in_features": 4579, + "min_out_features": 1847, + "max_out_features": 2290 + }, + { + "name": "decode.tokens_le1", + "phase": "decode", + "max_tokens": 1, + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 8, + "max_in_features": 2290, + "max_out_features": 1173, + "name": "decode.rank_le8.tokens_le8.k_le2290.n_le1173", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 16, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 8, + "max_in_features": 2290, + "min_out_features": 7095, + "max_out_features": 15864, + "name": "decode.rank_le8.tokens_le8.k_le2290.n_ge7095_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 8, + "name": "decode.rank_le8.tokens_le8", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 8, + "max_in_features": 2290, + "min_out_features": 7095, + "max_out_features": 15864, + "name": "decode.rank_le8.tokens_le16.k_le2290.n_ge7095_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 8, + "min_in_features": 1255, + "max_in_features": 3547, + "max_out_features": 4344, + "name": "decode.rank_le8.tokens_le16.k_ge1255_le3547.n_le4344", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 8, + "name": "decode.rank_le8.tokens_le16", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 8, + "max_in_features": 2290, + "min_out_features": 7095, + "max_out_features": 9715, + "name": "decode.rank_le8.tokens_le32.k_le2290.n_ge7095_le9715", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 8, + "max_in_features": 627, + "max_out_features": 2290, + "name": "decode.rank_le8.tokens_le32.k_le627.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 8, + "name": "decode.rank_le8.tokens_le32.k_ge2291_le4579.n_ge1847_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 4, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + }, + "min_in_features": 2291, + "max_in_features": 4579, + "min_out_features": 1847, + "max_out_features": 2290 + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 8, + "name": "decode.rank_le8.tokens_le32", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 16, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 8, + "max_in_features": 2290, + "max_out_features": 9715, + "name": "decode.rank_le8.k_le2290.n_le9715", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 8, + "name": "decode.rank_le8", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 16, + "min_in_features": 628, + "max_in_features": 2804, + "min_out_features": 1438, + "max_out_features": 15864, + "name": "decode.rank_le16.tokens_le8.k_ge628_le2804.n_ge1438_le15864", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 16, + "max_in_features": 887, + "max_out_features": 5609, + "name": "decode.rank_le16.tokens_le8.k_le887.n_le5609", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 16, + "name": "decode.rank_le16.tokens_le8", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 16, + "max_in_features": 2290, + "min_out_features": 4345, + "max_out_features": 9715, + "name": "decode.rank_le16.tokens_le16.k_le2290.n_ge4345_le9715", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 16, + "min_in_features": 2805, + "max_out_features": 2290, + "name": "decode.rank_le16.tokens_le16.k_ge2805.n_le2290", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "ab_delta", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 16, + "name": "decode.rank_le16.tokens_le16", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 16, + "max_in_features": 627, + "max_out_features": 2290, + "name": "decode.rank_le16.tokens_le32.k_le627.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 16, + "min_in_features": 2291, + "max_in_features": 4579, + "min_out_features": 1847, + "max_out_features": 2290, + "name": "decode.rank_le16.tokens_le32.k_ge2291_le4579.n_ge1847_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 4, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 16, + "min_in_features": 628, + "max_in_features": 5609, + "min_out_features": 654, + "max_out_features": 2804, + "name": "decode.rank_le16.tokens_le32.k_ge628_le5609.n_ge654_le2804", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 16, + "name": "decode.rank_le16.tokens_le32", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 16, + "max_in_features": 4579, + "max_out_features": 1437, + "name": "decode.rank_le16.k_le4579.n_le1437", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 16, + "max_in_features": 627, + "max_out_features": 2290, + "name": "decode.rank_le16.k_le627.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 16, + "name": "decode.rank_le16", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 32, + "name": "decode.rank_le32.tokens_le8", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 32, + "min_in_features": 628, + "max_in_features": 4579, + "min_out_features": 1174, + "max_out_features": 2290, + "name": "decode.rank_le32.tokens_le16.k_ge628_le4579.n_ge1174_le2290", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 32, + "max_in_features": 2290, + "min_out_features": 2291, + "max_out_features": 15864, + "name": "decode.rank_le32.tokens_le16.k_le2290.n_ge2291_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 32, + "name": "decode.rank_le32.tokens_le16", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 32, + "max_in_features": 2290, + "min_out_features": 1174, + "max_out_features": 9715, + "name": "decode.rank_le32.tokens_le32.k_le2290.n_ge1174_le9715", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 32, + "name": "decode.rank_le32.tokens_le32.k_ge2291_le4579.n_ge1847_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 4, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + }, + "min_in_features": 2291, + "max_in_features": 4579, + "min_out_features": 1847, + "max_out_features": 2290 + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 32, + "name": "decode.rank_le32.tokens_le32", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 16, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 32, + "max_in_features": 2290, + "min_out_features": 2291, + "max_out_features": 9715, + "name": "decode.rank_le32.k_le2290.n_ge2291_le9715", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 16, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 32, + "name": "decode.rank_le32", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 64, + "max_in_features": 2290, + "min_out_features": 7095, + "max_out_features": 9715, + "name": "decode.rank_le64.tokens_le8.k_le2290.n_ge7095_le9715", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 64, + "min_in_features": 2291, + "max_in_features": 4579, + "min_out_features": 1847, + "max_out_features": 2290, + "name": "decode.rank_le64.tokens_le8.k_ge2291_le4579.n_ge1847_le2290", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 4, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 64, + "min_in_features": 888, + "max_in_features": 4579, + "min_out_features": 1847, + "max_out_features": 2290, + "name": "decode.rank_le64.tokens_le8.k_ge888_le4579.n_ge1847_le2290", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 64, + "name": "decode.rank_le64.tokens_le8", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 64, + "max_in_features": 2290, + "min_out_features": 654, + "max_out_features": 1599, + "name": "decode.rank_le64.tokens_le16.k_le2290.n_ge654_le1599", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 64, + "max_in_features": 362, + "max_out_features": 2290, + "name": "decode.rank_le64.tokens_le16.k_le362.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 64, + "name": "decode.rank_le64.tokens_le16", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 64, + "min_in_features": 2291, + "max_in_features": 4579, + "min_out_features": 1847, + "max_out_features": 2290, + "name": "decode.rank_le64.tokens_le32.k_ge2291_le4579.n_ge1847_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 4, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 64, + "max_in_features": 2290, + "min_out_features": 7095, + "max_out_features": 9715, + "name": "decode.rank_le64.tokens_le32.k_le2290.n_ge7095_le9715", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 64, + "name": "decode.rank_le64.tokens_le32", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 64, + "max_in_features": 2290, + "min_out_features": 7095, + "max_out_features": 9715, + "name": "decode.rank_le64.k_le2290.n_ge7095_le9715", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 64, + "max_in_features": 627, + "max_out_features": 2290, + "name": "decode.rank_le64.k_le627.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 64, + "name": "decode.rank_le64", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 128, + "max_in_features": 2290, + "min_out_features": 9716, + "max_out_features": 15864, + "name": "decode.rank_le128.tokens_le8.k_le2290.n_ge9716_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 128, + "max_in_features": 2290, + "min_out_features": 1174, + "max_out_features": 15864, + "name": "decode.rank_le128.tokens_le8.k_le2290.n_ge1174_le15864", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 128, + "name": "decode.rank_le128.tokens_le8", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 128, + "max_in_features": 2290, + "min_out_features": 9716, + "max_out_features": 15864, + "name": "decode.rank_le128.tokens_le16.k_le2290.n_ge9716_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 128, + "max_in_features": 2290, + "min_out_features": 1174, + "max_out_features": 9715, + "name": "decode.rank_le128.tokens_le16.k_le2290.n_ge1174_le9715", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 128, + "name": "decode.rank_le128.tokens_le16.k_ge2291_le4579.n_ge1847_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 4, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + }, + "min_in_features": 2291, + "max_in_features": 4579, + "min_out_features": 1847, + "max_out_features": 2290 + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 128, + "name": "decode.rank_le128.tokens_le16", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 128, + "max_in_features": 2290, + "max_out_features": 1173, + "name": "decode.rank_le128.tokens_le32.k_le2290.n_le1173", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "serial" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 128, + "max_in_features": 627, + "max_out_features": 2290, + "name": "decode.rank_le128.tokens_le32.k_le627.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 128, + "name": "decode.rank_le128.tokens_le32.k_ge2291_le4579.n_ge1847_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 4, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + }, + "min_in_features": 2291, + "max_in_features": 4579, + "min_out_features": 1847, + "max_out_features": 2290 + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 128, + "name": "decode.rank_le128.tokens_le32", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 128, + "max_in_features": 2290, + "min_out_features": 9716, + "max_out_features": 15864, + "name": "decode.rank_le128.k_le2290.n_ge9716_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 128, + "max_in_features": 2290, + "max_out_features": 2290, + "name": "decode.rank_le128.k_le2290.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 128, + "name": "decode.rank_le128", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "min_in_features": 628, + "max_in_features": 4579, + "min_out_features": 1174, + "max_out_features": 2290, + "name": "decode.tokens_le8.k_ge628_le4579.n_ge1174_le2290", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "name": "decode.tokens_le8", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_in_features": 2290, + "min_out_features": 1174, + "max_out_features": 9715, + "name": "decode.tokens_le16.k_le2290.n_ge1174_le9715", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_in_features": 2290, + "max_out_features": 2290, + "name": "decode.tokens_le16.k_le2290.n_le2290", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "name": "decode.tokens_le16", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_in_features": 2290, + "max_out_features": 1173, + "name": "decode.tokens_le32.k_le2290.n_le1173", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_in_features": 627, + "max_out_features": 2290, + "name": "decode.tokens_le32.k_le627.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "name": "decode.tokens_le32", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "serial" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_in_features": 627, + "max_out_features": 2290, + "name": "decode.k_le627.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "min_in_features": 628, + "max_in_features": 4579, + "min_out_features": 1174, + "max_out_features": 15864, + "name": "decode.k_ge628_le4579.n_ge1174_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "serial" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "name": "decode", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.rank_le8.tokens_le512", + "phase": "prefill", + "max_tokens": 512, + "max_rank": 8, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.rank_le8.tokens_le2048.k4096.n2048", + "phase": "prefill", + "max_tokens": 2048, + "max_rank": 8, + "min_in_features": 4096, + "max_in_features": 4096, + "min_out_features": 2048, + "max_out_features": 2048, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.rank_le8.tokens_le2048.n_le4096", + "max_out_features": 4096, + "phase": "prefill", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "block_size": 32, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + }, + "max_tokens": 2048, + "max_rank": 8 + }, + { + "name": "prefill.rank_le8.tokens_le2048.n_le10240", + "max_out_features": 10240, + "phase": "prefill", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2 + } + }, + "max_tokens": 2048, + "max_rank": 8 + }, + { + "name": "prefill.rank_le8.tokens_le2048", + "phase": "prefill", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "block_size": 128, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 1 + } + }, + "max_tokens": 2048, + "max_rank": 8 + }, + { + "name": "prefill.rank_le16.tokens_le512", + "phase": "prefill", + "max_tokens": 512, + "max_rank": 16, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.rank_le16.tokens_le2048", + "phase": "prefill", + "max_tokens": 2048, + "max_rank": 16, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.rank_le32.tokens_le512", + "phase": "prefill", + "max_tokens": 512, + "max_rank": 32, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.rank_le64.tokens_le512.k2048.n12288", + "phase": "prefill", + "max_tokens": 512, + "max_rank": 64, + "min_in_features": 2048, + "max_in_features": 2048, + "min_out_features": 12288, + "max_out_features": 12288, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.rank_le64.tokens_le512.n_le4096", + "phase": "prefill", + "max_tokens": 512, + "max_rank": 64, + "max_out_features": 4096, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.rank_le64.tokens_le2048.n_le2048", + "phase": "prefill", + "max_tokens": 2048, + "max_rank": 64, + "max_out_features": 2048, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.rank_le64.tokens_le2048.n_ge2049_le4096", + "phase": "prefill", + "max_tokens": 2048, + "max_rank": 64, + "min_out_features": 2049, + "max_out_features": 4096, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.tokens_le512.n_le4096", + "max_tokens": 512, + "max_out_features": 4096, + "phase": "prefill", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.tokens_le512", + "max_tokens": 512, + "phase": "prefill", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2 + } + } + }, + { + "name": "prefill.n_le4096", + "max_out_features": 4096, + "phase": "prefill", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "block_size": 32, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.n_le10240", + "max_out_features": 10240, + "phase": "prefill", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2 + } + } + }, + { + "name": "prefill", + "phase": "prefill", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "block_size": 128, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 1 + } + } + } + ] +} diff --git a/python/sglang/srt/lora/dense/configs/sm90.plans.json b/python/sglang/srt/lora/dense/configs/sm90.plans.json new file mode 100644 index 0000000000..4350f855f8 --- /dev/null +++ b/python/sglang/srt/lora/dense/configs/sm90.plans.json @@ -0,0 +1,3484 @@ +{ + "rows": [ + { + "name": "decode.sink_gate_up.tokens_le32.n_le4096", + "kinds": [ + "sink_gate_up" + ], + "phase": "decode", + "max_tokens": 32, + "max_out_features": 4096, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.sink_gate_up.tokens_le32.n_ge4097", + "kinds": [ + "sink_gate_up" + ], + "phase": "decode", + "max_tokens": 32, + "min_out_features": 4097, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8, + "SPLIT_MODE": "serial" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.sink_down.tokens_le32.k_le2048", + "kinds": [ + "sink_down" + ], + "phase": "decode", + "max_tokens": 32, + "max_in_features": 2048, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "decode.sink_down.tokens_le32.k_ge2049", + "kinds": [ + "sink_down" + ], + "phase": "decode", + "max_tokens": 32, + "min_in_features": 2049, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8, + "SPLIT_MODE": "serial" + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.sink_gate_up.rank_le16.tokens_le1024.n_le4096", + "kinds": [ + "sink_gate_up" + ], + "phase": "prefill", + "max_tokens": 1024, + "max_rank": 16, + "max_out_features": 4096, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8, + "SPLIT_MODE": "planes" + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2 + } + } + }, + { + "name": "prefill.sink_gate_up.tokens_le1024.n_le4096", + "kinds": [ + "sink_gate_up" + ], + "phase": "prefill", + "max_tokens": 1024, + "max_out_features": 4096, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4, + "SPLIT_MODE": "serial" + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2 + } + } + }, + { + "name": "decode.vocab", + "kinds": [ + "embedding", + "lm_head" + ], + "phase": "decode", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.vocab", + "kinds": [ + "embedding", + "lm_head" + ], + "phase": "prefill", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 1, + "max_rank": 8, + "max_in_features": 2290, + "max_out_features": 1173, + "name": "decode.rank_le8.tokens_le1.k_le2290.n_le1173", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 1, + "max_rank": 8, + "max_in_features": 1254, + "max_out_features": 2290, + "name": "decode.rank_le8.tokens_le1.k_le1254.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 1, + "max_rank": 8, + "name": "decode.rank_le8.tokens_le1", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 8, + "min_in_features": 4580, + "max_in_features": 7932, + "max_out_features": 2290, + "name": "decode.rank_le8.tokens_le8.k_ge4580_le7932.n_le2290", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 8, + "max_in_features": 1254, + "max_out_features": 2290, + "name": "decode.rank_le8.tokens_le8.k_le1254.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 8, + "name": "decode.rank_le8.tokens_le8", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 8, + "max_in_features": 2290, + "min_out_features": 2291, + "max_out_features": 4344, + "name": "decode.rank_le8.tokens_le16.k_le2290.n_ge2291_le4344", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 8, + "max_in_features": 1254, + "max_out_features": 2290, + "name": "decode.rank_le8.tokens_le32.k_le1254.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 8, + "max_in_features": 627, + "max_out_features": 2290, + "name": "decode.rank_le8.k_le627.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 8, + "name": "decode.rank_le8", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 1, + "max_rank": 16, + "max_in_features": 627, + "max_out_features": 4344, + "name": "decode.rank_le16.tokens_le1.k_le627.n_le4344", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 1, + "max_rank": 16, + "min_in_features": 1775, + "max_in_features": 4579, + "name": "decode.rank_le16.tokens_le1.k_ge1775_le4579", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 1, + "max_rank": 16, + "name": "decode.rank_le16.tokens_le1", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 16, + "max_in_features": 2290, + "max_out_features": 1173, + "name": "decode.rank_le16.tokens_le8.k_le2290.n_le1173", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 16, + "max_in_features": 2290, + "min_out_features": 5610, + "max_out_features": 11217, + "name": "decode.rank_le16.tokens_le8.k_le2290.n_ge5610_le11217", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 16, + "name": "decode.rank_le16.tokens_le8", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 16, + "min_in_features": 2291, + "max_in_features": 2804, + "max_out_features": 2290, + "name": "decode.rank_le16.tokens_le16.k_ge2291_le2804.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 16, + "name": "decode.rank_le16.tokens_le16", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 16, + "max_in_features": 627, + "max_out_features": 4344, + "name": "decode.rank_le16.tokens_le32.k_le627.n_le4344", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 16, + "min_in_features": 1255, + "max_in_features": 4579, + "min_out_features": 3548, + "name": "decode.rank_le16.tokens_le32.k_ge1255_le4579.n_ge3548", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 16 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 16, + "name": "decode.rank_le16.tokens_le32", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 16, + "max_in_features": 4579, + "max_out_features": 1599, + "name": "decode.rank_le16.k_le4579.n_le1599", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 16, + "max_in_features": 1254, + "max_out_features": 5609, + "name": "decode.rank_le16.k_le1254.n_le5609", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 16, + "name": "decode.rank_le16", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 1, + "max_rank": 32, + "max_in_features": 2290, + "min_out_features": 9716, + "max_out_features": 15864, + "name": "decode.rank_le32.tokens_le1.k_le2290.n_ge9716_le15864", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 1, + "max_rank": 32, + "max_in_features": 4579, + "min_out_features": 1174, + "max_out_features": 2290, + "name": "decode.rank_le32.tokens_le1.k_le4579.n_ge1174_le2290", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 1, + "max_rank": 32, + "name": "decode.rank_le32.tokens_le1", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 32, + "name": "decode.rank_le32.tokens_le8", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 32, + "max_in_features": 2290, + "min_out_features": 9716, + "max_out_features": 15864, + "name": "decode.rank_le32.tokens_le16.k_le2290.n_ge9716_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 32, + "max_in_features": 2290, + "min_out_features": 2291, + "max_out_features": 15864, + "name": "decode.rank_le32.tokens_le16.k_le2290.n_ge2291_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 32, + "name": "decode.rank_le32.tokens_le16", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 32, + "min_in_features": 628, + "max_in_features": 4579, + "max_out_features": 2290, + "name": "decode.rank_le32.tokens_le32.k_ge628_le4579.n_le2290", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 32, + "max_in_features": 2290, + "min_out_features": 1174, + "max_out_features": 9715, + "name": "decode.rank_le32.tokens_le32.k_le2290.n_ge1174_le9715", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 32, + "name": "decode.rank_le32.tokens_le32", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 32, + "min_in_features": 628, + "max_in_features": 2290, + "max_out_features": 15864, + "name": "decode.rank_le32.k_ge628_le2290.n_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 32, + "max_in_features": 627, + "max_out_features": 2290, + "name": "decode.rank_le32.k_le627.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 32, + "name": "decode.rank_le32", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 1, + "max_rank": 64, + "max_in_features": 2290, + "min_out_features": 9716, + "max_out_features": 15864, + "name": "decode.rank_le64.tokens_le1.k_le2290.n_ge9716_le15864", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 1, + "max_rank": 64, + "max_in_features": 1774, + "max_out_features": 5609, + "name": "decode.rank_le64.tokens_le1.k_le1774.n_le5609", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 1, + "max_rank": 64, + "name": "decode.rank_le64.tokens_le1", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 64, + "min_in_features": 1775, + "max_in_features": 3547, + "min_out_features": 654, + "max_out_features": 2290, + "name": "decode.rank_le64.tokens_le8.k_ge1775_le3547.n_ge654_le2290", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 64, + "min_in_features": 1775, + "max_in_features": 2290, + "max_out_features": 11217, + "name": "decode.rank_le64.tokens_le8.k_ge1775_le2290.n_le11217", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 64, + "name": "decode.rank_le64.tokens_le8", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 64, + "min_in_features": 2291, + "max_in_features": 2804, + "max_out_features": 2290, + "name": "decode.rank_le64.tokens_le16.k_ge2291_le2804.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 64, + "min_in_features": 888, + "max_in_features": 4579, + "min_out_features": 3548, + "name": "decode.rank_le64.tokens_le16.k_ge888_le4579.n_ge3548", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 64, + "name": "decode.rank_le64.tokens_le16", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 64, + "min_in_features": 888, + "max_in_features": 2290, + "max_out_features": 2290, + "name": "decode.rank_le64.tokens_le32.k_ge888_le2290.n_le2290", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 64, + "max_in_features": 887, + "max_out_features": 5609, + "name": "decode.rank_le64.tokens_le32.k_le887.n_le5609", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 64, + "name": "decode.rank_le64.tokens_le32", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 64, + "min_in_features": 3548, + "min_out_features": 1847, + "max_out_features": 8689, + "name": "decode.rank_le64.k_ge3548.n_ge1847_le8689", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 16 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 64, + "max_in_features": 887, + "max_out_features": 5609, + "name": "decode.rank_le64.k_le887.n_le5609", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 64, + "name": "decode.rank_le64", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 1, + "max_rank": 128, + "min_in_features": 628, + "max_in_features": 4579, + "min_out_features": 1174, + "max_out_features": 2290, + "name": "decode.rank_le128.tokens_le1.k_ge628_le4579.n_ge1174_le2290", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 1, + "max_rank": 128, + "max_in_features": 2290, + "max_out_features": 2290, + "name": "decode.rank_le128.tokens_le1.k_le2290.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 1, + "max_rank": 128, + "name": "decode.rank_le128.tokens_le1", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 128, + "max_in_features": 2290, + "min_out_features": 9716, + "max_out_features": 15864, + "name": "decode.rank_le128.tokens_le8.k_le2290.n_ge9716_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_rank": 128, + "name": "decode.rank_le128.tokens_le8", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 128, + "max_in_features": 2290, + "min_out_features": 2291, + "max_out_features": 15864, + "name": "decode.rank_le128.tokens_le16.k_le2290.n_ge2291_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_rank": 128, + "name": "decode.rank_le128.tokens_le16", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 32, + "max_rank": 128, + "min_in_features": 628, + "max_in_features": 4579, + "min_out_features": 1174, + "max_out_features": 15864, + "name": "decode.rank_le128.tokens_le32.k_ge628_le4579.n_ge1174_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 128, + "min_in_features": 628, + "max_in_features": 4579, + "min_out_features": 1174, + "max_out_features": 2290, + "name": "decode.rank_le128.k_ge628_le4579.n_ge1174_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 16 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 128, + "max_in_features": 627, + "max_out_features": 2290, + "name": "decode.rank_le128.k_le627.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_rank": 128, + "name": "decode.rank_le128", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 1, + "max_in_features": 2290, + "max_out_features": 1173, + "name": "decode.tokens_le1.k_le2290.n_le1173", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 1, + "max_in_features": 2290, + "max_out_features": 2290, + "name": "decode.tokens_le1.k_le2290.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 1, + "name": "decode.tokens_le1", + "spec": { + "a_family": "grouped", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "max_in_features": 2290, + "min_out_features": 9716, + "max_out_features": 15864, + "name": "decode.tokens_le8.k_le2290.n_ge9716_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 8, + "name": "decode.tokens_le8", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_in_features": 2290, + "min_out_features": 2291, + "max_out_features": 15864, + "name": "decode.tokens_le16.k_le2290.n_ge2291_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 8 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_tokens": 16, + "max_in_features": 2290, + "max_out_features": 2290, + "name": "decode.tokens_le16.k_le2290.n_le2290", + "spec": { + "a_family": "all_slots", + "b_family": "per_row", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_in_features": 2290, + "min_out_features": 2291, + "max_out_features": 15864, + "name": "decode.k_le2290.n_ge2291_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "max_in_features": 627, + "max_out_features": 2290, + "name": "decode.k_le627.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "decode", + "name": "decode", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "a", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + "SPLIT_K": 4 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 512, + "max_rank": 8, + "name": "prefill.rank_le8.tokens_le512", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 2048, + "max_rank": 8, + "max_in_features": 2290, + "min_out_features": 4345, + "max_out_features": 7094, + "name": "prefill.rank_le8.tokens_le2048.k_le2290.n_ge4345_le7094", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 32, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 2048, + "max_rank": 8, + "min_in_features": 1255, + "max_in_features": 7932, + "min_out_features": 1174, + "max_out_features": 9715, + "name": "prefill.rank_le8.tokens_le2048.k_ge1255_le7932.n_ge1174_le9715", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 2048, + "max_rank": 8, + "name": "prefill.rank_le8.tokens_le2048", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 32, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 4096, + "max_rank": 8, + "max_in_features": 2290, + "min_out_features": 7095, + "max_out_features": 9715, + "name": "prefill.rank_le8.tokens_le4096.k_le2290.n_ge7095_le9715", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 4096, + "max_rank": 8, + "min_in_features": 1255, + "max_in_features": 2290, + "min_out_features": 1174, + "max_out_features": 4344, + "name": "prefill.rank_le8.tokens_le4096.k_ge1255_le2290.n_ge1174_le4344", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 4096, + "max_rank": 8, + "name": "prefill.rank_le8.tokens_le4096", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 32, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_rank": 8, + "max_in_features": 2290, + "min_out_features": 2291, + "max_out_features": 4344, + "name": "prefill.rank_le8.k_le2290.n_ge2291_le4344", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_rank": 8, + "max_in_features": 2290, + "min_out_features": 7095, + "max_out_features": 9715, + "name": "prefill.rank_le8.k_le2290.n_ge7095_le9715", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_rank": 8, + "name": "prefill.rank_le8", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 32, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 512, + "max_rank": 16, + "name": "prefill.rank_le16.tokens_le512", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 2048, + "max_rank": 16, + "min_in_features": 4580, + "max_out_features": 2290, + "name": "prefill.rank_le16.tokens_le2048.k_ge4580.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 2048, + "max_rank": 16, + "max_in_features": 1774, + "max_out_features": 5609, + "name": "prefill.rank_le16.tokens_le2048.k_le1774.n_le5609", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 2048, + "max_rank": 16, + "name": "prefill.rank_le16.tokens_le2048", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 4096, + "max_rank": 16, + "min_in_features": 888, + "max_in_features": 2290, + "min_out_features": 4345, + "max_out_features": 9715, + "name": "prefill.rank_le16.tokens_le4096.k_ge888_le2290.n_ge4345_le9715", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 4096, + "max_rank": 16, + "max_in_features": 1774, + "max_out_features": 4344, + "name": "prefill.rank_le16.tokens_le4096.k_le1774.n_le4344", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 4096, + "max_rank": 16, + "name": "prefill.rank_le16.tokens_le4096", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 32, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_rank": 16, + "min_in_features": 3548, + "min_out_features": 1847, + "max_out_features": 4344, + "name": "prefill.rank_le16.k_ge3548.n_ge1847_le4344", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_rank": 16, + "min_in_features": 1255, + "max_in_features": 3547, + "max_out_features": 2290, + "name": "prefill.rank_le16.k_ge1255_le3547.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_rank": 16, + "name": "prefill.rank_le16", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 32, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 512, + "max_rank": 32, + "max_in_features": 2290, + "min_out_features": 2291, + "max_out_features": 15864, + "name": "prefill.rank_le32.tokens_le512.k_le2290.n_ge2291_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 512, + "max_rank": 32, + "name": "prefill.rank_le32.tokens_le512", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 2048, + "max_rank": 32, + "max_in_features": 2290, + "max_out_features": 2290, + "name": "prefill.rank_le32.tokens_le2048.k_le2290.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 2048, + "max_rank": 32, + "name": "prefill.rank_le32.tokens_le2048", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 4096, + "max_rank": 32, + "max_in_features": 2290, + "min_out_features": 2291, + "max_out_features": 15864, + "name": "prefill.rank_le32.tokens_le4096.k_le2290.n_ge2291_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 4096, + "max_rank": 32, + "name": "prefill.rank_le32.tokens_le4096", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_rank": 32, + "max_in_features": 4579, + "max_out_features": 2290, + "name": "prefill.rank_le32.k_le4579.n_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_rank": 32, + "name": "prefill.rank_le32", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 32, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "name": "prefill.rank_le64.tokens_le2048.k2048.n12288", + "phase": "prefill", + "max_tokens": 2048, + "max_rank": 64, + "min_in_features": 2048, + "max_in_features": 2048, + "min_out_features": 12288, + "max_out_features": 12288, + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 512, + "max_rank": 64, + "min_in_features": 2291, + "min_out_features": 1847, + "max_out_features": 2290, + "name": "prefill.rank_le64.tokens_le512.k_ge2291.n_ge1847_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 512, + "max_rank": 64, + "max_in_features": 4579, + "min_out_features": 2805, + "name": "prefill.rank_le64.tokens_le512.k_le4579.n_ge2805", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 512, + "max_rank": 64, + "name": "prefill.rank_le64.tokens_le512", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 2048, + "max_rank": 64, + "name": "prefill.rank_le64.tokens_le2048", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 4096, + "max_rank": 64, + "max_in_features": 2290, + "min_out_features": 15865, + "name": "prefill.rank_le64.tokens_le4096.k_le2290.n_ge15865", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 128, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 4096, + "max_rank": 64, + "max_in_features": 1254, + "max_out_features": 5609, + "name": "prefill.rank_le64.tokens_le4096.k_le1254.n_le5609", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 128, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 4096, + "max_rank": 64, + "name": "prefill.rank_le64.tokens_le4096", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_rank": 64, + "max_in_features": 1254, + "min_out_features": 2291, + "max_out_features": 5609, + "name": "prefill.rank_le64.k_le1254.n_ge2291_le5609", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 128, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_rank": 64, + "max_in_features": 7932, + "min_out_features": 924, + "max_out_features": 2290, + "name": "prefill.rank_le64.k_le7932.n_ge924_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 128, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_rank": 64, + "name": "prefill.rank_le64", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 512, + "max_rank": 128, + "max_in_features": 2290, + "max_out_features": 1173, + "name": "prefill.rank_le128.tokens_le512.k_le2290.n_le1173", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 512, + "max_rank": 128, + "min_in_features": 628, + "max_in_features": 4579, + "min_out_features": 1174, + "max_out_features": 2290, + "name": "prefill.rank_le128.tokens_le512.k_ge628_le4579.n_ge1174_le2290", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 16, + "a_tiles": { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_rank": 128, + "max_in_features": 2290, + "min_out_features": 2291, + "max_out_features": 15864, + "name": "prefill.rank_le128.k_le2290.n_ge2291_le15864", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 32, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "max_tokens": 512, + "name": "prefill.tokens_le512", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 32, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + }, + { + "phase": "prefill", + "name": "prefill", + "spec": { + "a_family": "grouped", + "b_family": "grouped", + "overlap": "none", + "block_size": 64, + "a_tiles": { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3 + }, + "b_tiles": { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2 + } + } + } + ] +} diff --git a/python/sglang/srt/lora/dense/mla_correction.py b/python/sglang/srt/lora/dense/mla_correction.py new file mode 100644 index 0000000000..66727f77f2 --- /dev/null +++ b/python/sglang/srt/lora/dense/mla_correction.py @@ -0,0 +1,138 @@ +"""Absorbed MLA: Q += Q @ B_k @ A; V += attention @ A.T @ B_v.T. + +Plans name the shrink/expand stages, not the original adapter A/B order. +Only B has per-head slices. Decode overlaps the grouped shrink with the base BMM. +""" + +from __future__ import annotations + +from contextlib import nullcontext +from dataclasses import dataclass +from functools import cache + +import torch + +from sglang.kernels.ops.lora.common.lora_a import grouped_lora_a +from sglang.kernels.ops.lora.common.lora_b import grouped_lora_b, slice_geometry +from sglang.kernels.ops.lora.common.route_view import RouteView +from sglang.srt.lora.dense.plan import DensePlan, Overlap +from sglang.srt.lora.utils import Phase + + +@cache +def _mla_plan(phase: Phase) -> DensePlan: + return DensePlan( + block_size=16 if phase is Phase.DECODE else 64, + overlap=Overlap.A if phase is Phase.DECODE else Overlap.NONE, + ) + + +def _b_slice_per_head(b: torch.Tensor, heads: int, start: int, width: int): + slots, output_dim, rank = b.shape + return b.view(slots, heads, output_dim // heads, rank)[ + :, :, start : start + width, : + ].reshape(slots * heads, width, rank) + + +@dataclass(slots=True) +class _Prepared: + runner: object + input: torch.Tensor # Retain reshape copies until the side-stream join. + weight: torch.Tensor + route: RouteView + plan: DensePlan + heads: int + side: str + bridge: torch.Tensor + done: torch.cuda.Event | None = None + + +def _prepare(attn, x, side): + layer = attn.kv_b_proj + runner = layer.lora_backend.runner + a, b = layer.A_buffer, layer.B_buffer + tokens, heads, input_dim = x.shape + if side == "q": + shrink_weight = _b_slice_per_head(b, heads, 0, input_dim).transpose(1, 2) + expand_weight = a.transpose(1, 2) + else: + shrink_weight = a + expand_weight = _b_slice_per_head( + b, heads, attn.qk_nope_head_dim, attn.v_head_dim + ) + plan = _mla_plan(runner.phase) + workspace = runner.workspace + # A reshape may copy; keep it before ready so side-stream reads are ordered. + flat_input = x.reshape(tokens * heads, input_dim) + done = None + # Build the route before forking so the side stream can start with shrink. + route = runner.pair_route(heads, plan.block_size, num_tokens=tokens) + if plan.overlap is Overlap.A: + current = torch.cuda.current_stream(x.device) + stream = workspace.side_stream(x.device) + ready = workspace.event(x.device, f"dense:mla_{side}:ready") + done = workspace.event(x.device, f"dense:mla_{side}:done") + ready.record(current) + stream.wait_event(ready) + context = torch.cuda.stream(stream) + else: + context = nullcontext() + with context: + bridge = workspace.tensor( + f"dense:mla_{side}:bridge", + (flat_input.shape[0], shrink_weight.shape[1]), + dtype=x.dtype, + device=x.device, + ) + grouped_lora_a( + flat_input, + shrink_weight, + bridge, + route, + config=plan.a_tiles, + pair_input=True, + weight_div=1 if side == "q" else heads, + lora_ranks=runner.lora_ranks, + ) + if done is not None: + done.record(stream) + return _Prepared( + runner, flat_input, expand_weight, route, plan, heads, side, bridge, done + ) + + +def apply_correction(prepared, out): + if prepared.done is not None: + torch.cuda.current_stream(out.device).wait_event(prepared.done) + weight, runner = prepared.weight, prepared.runner + destination = ( + out.view(-1, prepared.heads, weight.shape[1]) if out.ndim == 2 else out + ) + grouped_lora_b( + prepared.bridge, + weight, + destination, + prepared.route, + pair_heads=prepared.heads, + geometry=slice_geometry( + (0, weight.shape[1]), + int(prepared.plan.b_tiles["BLOCK_SIZE_N"]), + weight.device, + ), + config=prepared.plan.b_tiles, + add_inplace=True, + zero_sentinel=False, + lora_ranks=runner.lora_ranks, + scalings=runner.scalings, + weight_div=1 if prepared.side == "v" else prepared.heads, + ) + return out + + +def prepare_q_correction(attn_module, q_nope): + """Prepare before the base BMM; keep the result alive until apply.""" + return _prepare(attn_module, q_nope, "q") + + +def prepare_v_correction(attn_module, attn_output): + return _prepare(attn_module, attn_output, "v") diff --git a/python/sglang/srt/lora/dense/plan.py b/python/sglang/srt/lora/dense/plan.py new file mode 100644 index 0000000000..2af58218fa --- /dev/null +++ b/python/sglang/srt/lora/dense/plan.py @@ -0,0 +1,283 @@ +"""Dense LoRA kernel, overlap, routing and tile selection. + +``configs/.plans.json`` uses the first compatible matching row; order +narrow rules first. Missing tables or matches use the defaults below. +""" + +from __future__ import annotations + +import json +import logging +import os +from dataclasses import dataclass, field +from enum import Enum +from functools import cache + +import pydantic + +from sglang.srt.lora.utils import Phase + +logger = logging.getLogger(__name__) + +_CONFIG_DIR = os.path.join(os.path.dirname(__file__), "configs") + + +class AFamily(str, Enum): + GROUPED = "grouped" # aligned token route, one tile per (block, N tile) + PER_ROW = "per_row" # raw route, one program per route row: a GEMV + ALL_SLOTS = "all_slots" # one dense matmul over every slot's A + + +class BFamily(str, Enum): + GROUPED = "grouped" + PER_ROW = "per_row" + + +class DenseLoraKind(str, Enum): + LINEAR = "linear" + EMBEDDING = "embedding" + LM_HEAD = "lm_head" + SINK_GATE_UP = "sink_gate_up" # Inkling sink gate/up + SINK_DOWN = "sink_down" # Inkling per-expert sink down: the windowed shrink + + +class Overlap(str, Enum): + NONE = "none" # base GEMM, then A, then B into the base output + A = "a" # A on the side stream while the base GEMM runs; B after + AB_DELTA = "ab_delta" # A and B on the side stream into a delta; add after + + +def _a_tiles() -> dict[str, int]: + return { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + } + + +def _b_tiles() -> dict[str, int]: + return { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2, + } + + +@dataclass(frozen=True, slots=True) +class DensePlan: + a_family: AFamily = AFamily.GROUPED + b_family: BFamily = BFamily.GROUPED + overlap: Overlap = Overlap.NONE + block_size: int = 16 + a_tiles: dict[str, int | str] = field(default_factory=_a_tiles) + b_tiles: dict[str, int] = field(default_factory=_b_tiles) + + def __post_init__(self) -> None: + if self.block_size < 16 or self.block_size & (self.block_size - 1): + raise ValueError("block_size must be a power of two >= 16") + required = set(_a_tiles()) + for name, config in (("a_tiles", self.a_tiles), ("b_tiles", self.b_tiles)): + allowed = required | ( + {"SPLIT_K", "SPLIT_MODE"} if name == "a_tiles" else set() + ) + if not required <= config.keys() or config.keys() - allowed: + raise ValueError( + f"{name} requires {sorted(required)}; unknown keys are not allowed" + ) + for key, value in config.items(): + if key == "SPLIT_MODE": + continue + if not isinstance(value, int) or isinstance(value, bool) or value <= 0: + raise ValueError(f"{name}.{key} must be a positive integer") + if key.startswith("BLOCK_SIZE_") and value & (value - 1): + raise ValueError(f"{name}.{key} must be a power of two") + dot_tiles = () + if name == "a_tiles" and self.a_family is AFamily.GROUPED: + dot_tiles = ("BLOCK_SIZE_N", "BLOCK_SIZE_K") + elif name == "b_tiles" and self.b_family is BFamily.GROUPED: + dot_tiles = ("BLOCK_SIZE_N",) + for key in dot_tiles: + if config[key] < 16: + raise ValueError( + f"{name}.{key} must be at least 16 for grouped GEMM" + ) + if config["num_warps"] not in (1, 2, 4, 8, 16, 32): + raise ValueError(f"{name}.num_warps must be a supported power of two") + if self.a_family is AFamily.ALL_SLOTS and self.b_family is not BFamily.PER_ROW: + raise ValueError( + "all_slots A writes one bridge plane per slot; only per_row B reads planes" + ) + if ( + int(self.a_tiles.get("SPLIT_K", 1)) > 1 + and self.a_family is not AFamily.GROUPED + ): + raise ValueError("SPLIT_K is a grouped-A tile key") + if self.a_tiles.get("SPLIT_MODE", "serial") not in ("serial", "planes"): + raise ValueError("SPLIT_MODE is 'serial' or 'planes'") + + @property + def needs_aligned_route(self) -> bool: + return self.a_family is AFamily.GROUPED or self.b_family is BFamily.GROUPED + + +def _decode_default() -> DensePlan: + return DensePlan( + block_size=16, + a_tiles={**_a_tiles(), "SPLIT_K": 4}, + ) + + +def _prefill_default() -> DensePlan: + return DensePlan( + block_size=64, + b_tiles={**_b_tiles(), "BLOCK_SIZE_N": 64, "num_warps": 8}, + ) + + +class _PlanSpecModel(pydantic.BaseModel): + model_config = pydantic.ConfigDict(extra="forbid") + + a_family: AFamily = AFamily.GROUPED + b_family: BFamily = BFamily.GROUPED + overlap: Overlap = Overlap.NONE + block_size: int = 16 + a_tiles: dict[str, int | str] = pydantic.Field(default_factory=_a_tiles) + b_tiles: dict[str, int] = pydantic.Field(default_factory=_b_tiles) + + +class _PlanRowModel(pydantic.BaseModel): + model_config = pydantic.ConfigDict(extra="forbid") + + name: str + phase: Phase | None = None + kinds: list[DenseLoraKind] | None = None + max_tokens: int | None = None + max_rank: int | None = None + # Geometry bands: shrink input width and total output width across slices. + min_in_features: int | None = None + max_in_features: int | None = None + min_out_features: int | None = None + max_out_features: int | None = None + spec: _PlanSpecModel = pydantic.Field(default_factory=_PlanSpecModel) + + @pydantic.model_validator(mode="after") + def _kinds_can_run_the_plan(self) -> _PlanRowModel: + if ( + self.kinds + and DenseLoraKind.SINK_DOWN in self.kinds + and self.spec.a_family is AFamily.ALL_SLOTS + ): + raise ValueError( + f"row {self.name!r}: an all_slots shrink cannot serve sink_down " + "(the windowed shrink is not one dense matmul)" + ) + return self + + +class _PlansFileModel(pydantic.BaseModel): + model_config = pydantic.ConfigDict(extra="forbid") + + rows: list[_PlanRowModel] + + +def _read_table(name: str) -> dict | None: + from sglang.srt.environ import envs + + override_dir = envs.SGLANG_LORA_DENSE_CONFIG_DIR.get() + for directory in filter(None, (override_dir, _CONFIG_DIR)): + path = os.path.join(directory, name) + if os.path.isfile(path): + if directory == override_dir: + logger.info( + "dense LoRA table %r loaded from override dir %s", name, directory + ) + with open(path) as handle: + return json.load(handle) + return None + + +@cache +def load_plans(architecture: str) -> _PlansFileModel | None: + raw = _read_table(f"{architecture}.plans.json") + if raw is None: + return None + table = _PlansFileModel.model_validate(raw) + for row in table.rows: + try: + DensePlan(**row.spec.model_dump()) + except ValueError as exc: + raise ValueError(f"dense LoRA row {row.name!r}: {exc}") from exc + return table + + +class DensePlanTable: + """Select and cache the first compatible plan row.""" + + def __init__(self, architecture: str, max_rank: int) -> None: + table = load_plans(architecture) + self._rows = table.rows if table is not None else [] + self._max_rank = max_rank + self._bounds = sorted( + {row.max_tokens for row in self._rows if row.max_tokens is not None} + ) + self._cache: dict[tuple[DenseLoraKind, Phase, int, int, int], DensePlan] = {} + + def plan_for( + self, + kind: DenseLoraKind, + phase: Phase, + num_tokens: int, + in_features: int = 0, + out_features: int = 0, + ) -> DensePlan: + # Token counts bucket to the row bounds, so the cache stays small. + key = (kind, phase, self._bucket(num_tokens), in_features, out_features) + plan = self._cache.get(key) + if plan is None: + plan = self._resolve(kind, phase, num_tokens, in_features, out_features) + self._cache[key] = plan + return plan + + def _bucket(self, num_tokens: int) -> int: + for bound in self._bounds: + if num_tokens <= bound: + return bound + return 1 << 30 + + def _resolve( + self, + kind: DenseLoraKind, + phase: Phase, + num_tokens: int, + in_features: int, + out_features: int, + ) -> DensePlan: + for row in self._rows: + if row.phase is not None and row.phase is not phase: + continue + if row.kinds is not None and kind not in row.kinds: + continue + # Windowed shrink cannot use an all-slots GEMM. + if ( + kind is DenseLoraKind.SINK_DOWN + and row.spec.a_family is AFamily.ALL_SLOTS + ): + continue + if row.max_tokens is not None and num_tokens > row.max_tokens: + continue + if row.max_rank is not None and self._max_rank > row.max_rank: + continue + if row.min_in_features is not None and in_features < row.min_in_features: + continue + if row.max_in_features is not None and in_features > row.max_in_features: + continue + if row.min_out_features is not None and out_features < row.min_out_features: + continue + if row.max_out_features is not None and out_features > row.max_out_features: + continue + return DensePlan(**row.spec.model_dump()) + return _decode_default() if phase is Phase.DECODE else _prefill_default() diff --git a/python/sglang/srt/lora/dense/runner.py b/python/sglang/srt/lora/dense/runner.py new file mode 100644 index 0000000000..ad3ab1a9ce --- /dev/null +++ b/python/sglang/srt/lora/dense/runner.py @@ -0,0 +1,468 @@ +"""Plan-driven dense LoRA with shared routing, scratch and base-GEMM overlap.""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import NamedTuple + +import torch +import triton + +from sglang.kernels.ops.lora.common.lora_a import ( + grouped_lora_a, + per_row_lora_a, + shrink_column_tiles, +) +from sglang.kernels.ops.lora.common.lora_b import ( + grouped_lora_b, + per_row_lora_b, + slice_geometry, +) +from sglang.kernels.ops.lora.common.route_view import RouteView, RouteViewKind +from sglang.kernels.ops.lora.common.routing import build_route +from sglang.srt.lora.dense.plan import ( + AFamily, + BFamily, + DenseLoraKind, + DensePlan, + DensePlanTable, + Overlap, + load_plans, +) +from sglang.srt.lora.utils import Phase, architecture_for_capability +from sglang.srt.lora.workspace import LoraWorkspace + + +class Bridge(NamedTuple): + """Shrink output, normally [rows, bridge_width]. Split-K uses FP32 + [planes, rows, bridge_width], summed by expand; ``slot_planes`` uses + [slots, rows, bridge_width], indexed by adapter slot. + """ + + tensor: torch.Tensor + planes: int = 1 + slot_planes: bool = False + + +class DenseLoraRunner: + def __init__( + self, + workspace: LoraWorkspace, + *, + max_loras: int, + device: torch.device, + architecture: str | None = None, + ) -> None: + self.workspace = workspace + self.max_loras = max_loras + if architecture is None: + if device.type == "cuda": + major, _ = torch.cuda.get_device_capability(device) + architecture = architecture_for_capability(major) + else: + architecture = "default" + self.architecture = architecture + # Validate the architecture's plan table (and any override) at startup. + load_plans(architecture) + self._plan_tables: dict[int, DensePlanTable] = {} + self.reset() + + def reset(self) -> None: + self.phase = Phase.DECODE + self.num_tokens = 0 + self._token_slots: torch.Tensor | None = None + self.token_slots: torch.Tensor | None = None + self.lora_ranks: torch.Tensor | None = None + self.scalings: torch.Tensor | None = None + self.reset_routes() + + def reset_routes(self) -> None: + """Start a forward without dropping bound metadata or workspace storage.""" + self._raw_route: RouteView | None = None + self.workspace.routes.clear() + + def begin_batch( + self, + *, + token_slots: torch.Tensor, + lora_ranks: torch.Tensor, + scalings: torch.Tensor, + num_tokens: int, + phase: Phase, + graph_mode: bool, + is_prefill_graph: bool = False, + ) -> None: + """Bind the token-to-adapter metadata for this batch.""" + self.reset() + self.phase = phase + self.num_tokens = num_tokens + self._token_slots = token_slots + self.token_slots = token_slots[:num_tokens] + self.lora_ranks = lora_ranks + self.scalings = scalings + # Target verify uses prefill plans inside a decode graph. + self.workspace.begin_forward( + graph_mode=graph_mode, is_prefill_graph=is_prefill_graph + ) + + def set_num_tokens(self, num_tokens: int) -> None: + """Use the forward's input shape, including graph padding.""" + if not 0 <= num_tokens <= self._token_slots.numel(): + raise ValueError("dense LoRA input exceeds its token-to-adapter buffer") + if num_tokens != self.num_tokens: + self.reset_routes() + self.num_tokens = num_tokens + self.token_slots = self._token_slots[:num_tokens] + + def plan_for( + self, + kind: DenseLoraKind, + max_rank: int, + in_features: int = 0, + out_features: int = 0, + *, + num_tokens: int, + ) -> DensePlan: + self.set_num_tokens(num_tokens) + table = self._plan_tables.get(max_rank) + if table is None: + table = DensePlanTable(self.architecture, max_rank) + self._plan_tables[max_rank] = table + return table.plan_for(kind, self.phase, num_tokens, in_features, out_features) + + def route(self, block_size: int) -> RouteView: + """Return the adapter-aligned route, cached per forward and block size.""" + return self._cached_route(("sorted", block_size)) + + def _cached_route(self, key: tuple) -> RouteView: + return self.workspace.route( + self.token_slots, (*key, self.max_loras), lambda: self._build_route(key) + ) + + def _build_route(self, key: tuple) -> RouteView: + if key[0] == "pair": + return self._build_pair_route(*key[1:]) + block_size = key[1] + return build_route( + self.token_slots, + max_loras=self.max_loras, + block_size=block_size, + view=RouteViewKind.ALIGNED, + workspace=self.workspace, + tensor_prefix=f"dense:sorted:{block_size}", + ) + + def pair_route( + self, num_heads: int, block_size: int, *, num_tokens: int + ) -> RouteView: + """Sort (token, head) pairs by slot*H + head, once per forward.""" + self.set_num_tokens(num_tokens) + return self._cached_route(("pair", block_size, num_heads)) + + def _build_pair_route(self, block_size: int, num_heads: int) -> RouteView: + rows = self.num_tokens * num_heads + device = self.token_slots.device + head_ids = self.workspace.tensor( + f"dense:pairs:{num_heads}:heads", + (rows, 1), + dtype=torch.int32, + device=device, + ) + # Refresh assignments on every graph replay. + head_ids.copy_( + torch.arange(num_heads, dtype=torch.int32, device=device) + .expand(self.num_tokens, num_heads) + .reshape(rows, 1) + ) + row_slots = self.workspace.tensor( + f"dense:pairs:{num_heads}:slots", + (rows,), + dtype=torch.int32, + device=device, + ) + row_slots.copy_( + self.token_slots[:, None].expand(self.num_tokens, num_heads).reshape(rows) + ) + route = build_route( + row_slots, + group_ids=head_ids, + groups_per_slot=num_heads, + max_loras=self.max_loras, + block_size=block_size, + view=RouteViewKind.ALIGNED, + workspace=self.workspace, + tensor_prefix=f"dense:pairs:{num_heads}:{block_size}", + ) + return route + + def raw_route(self) -> RouteView: + if self._raw_route is None: + self._raw_route = RouteView( + view=RouteViewKind.RAW, + block_size=1, + token_slots=self.token_slots, + group_ids=None, + groups_per_slot=1, + max_loras=self.max_loras, + ) + return self._raw_route + + def run_a( + self, + x: torch.Tensor, + a: torch.Tensor, + *, + stack: int, + plan: DensePlan, + lora_ranks: torch.Tensor | None = None, + windowed: bool = False, + ) -> Bridge: + """Shrink into a bridge of width ``stack * rank_max`` (see ``Bridge``). + + A rank-r slot packs slice s at [s*r, (s+1)*r). With ``windowed``, + block s reads input columns [s*K, (s+1)*K) at full rank width, + ignoring per-slot ranks. + """ + num_tokens = x.shape[0] + slots, n_max, k = a.shape + # A caller with max-rank-spaced, zero-filled slots (the MoE-layout + # pool buffers) passes constant ranks; the batch's ranks otherwise. + ranks = lora_ranks if lora_ranks is not None else self.lora_ranks + match plan.a_family: + case AFamily.GROUPED: + split_k = int(plan.a_tiles.get("SPLIT_K", 1)) + mode = str(plan.a_tiles.get("SPLIT_MODE", "serial")) + bridge = self.workspace.tensor( + "dense:bridge", + (num_tokens, n_max), + dtype=x.dtype, + device=x.device, + ) + partial = counters = None + if split_k > 1: + partial = self.workspace.tensor( + "dense:bridge_partial", + (split_k, num_tokens, n_max), + dtype=torch.float32, + device=x.device, + ) + if mode == "serial": + route = self.route(plan.block_size) + tiles = ( + triton.cdiv(route.sorted_pair_ids.numel(), route.block_size) + * shrink_column_tiles( + int(plan.a_tiles["BLOCK_SIZE_N"]), + n_max, + stack, + windowed, + )[1] + ) + # Zero at rest; the last-arriving program resets its tile. + counters = self.workspace.tensor( + "dense:splitk_counters", + (tiles,), + dtype=torch.int32, + device=x.device, + zero_on_first_allocation=True, + ) + grouped_lora_a( + x, + a, + bridge, + self.route(plan.block_size), + config=plan.a_tiles, + pair_input=True, + lora_ranks=ranks, + stack=stack, + partial=partial, + counters=counters, + windowed=windowed, + ) + if split_k > 1 and mode == "planes": + return Bridge(partial, planes=split_k) + return Bridge(bridge) + case AFamily.PER_ROW: + bridge = self.workspace.tensor( + "dense:bridge", + (num_tokens, n_max), + dtype=x.dtype, + device=x.device, + ) + per_row_lora_a( + x, + a, + bridge, + self.raw_route(), + config=plan.a_tiles, + stack=stack, + windowed=windowed, + ) + return Bridge(bridge) + case AFamily.ALL_SLOTS: + if windowed: # plan_for never pairs them: a forced plan did + raise NotImplementedError( + "the all-slots GEMM cannot window per rank block" + ) + flat = self.workspace.tensor( + "dense:bridge_all", + (num_tokens, slots * n_max), + dtype=x.dtype, + device=x.device, + ) + torch.matmul(x, a.reshape(slots * n_max, k).t(), out=flat) + return Bridge( + flat.view(num_tokens, slots, n_max).transpose(0, 1), + slot_planes=True, + ) + case _: + raise NotImplementedError( + f"no engine executor for A family {plan.a_family.value!r}" + ) + + def run_b( + self, + bridge: Bridge, + b: torch.Tensor, + out: torch.Tensor, + *, + offsets: tuple[int, ...], + plan: DensePlan, + add_inplace: bool = True, + lora_ranks: torch.Tensor | None = None, + scalings: torch.Tensor | None = None, + bridge_slices: int = 0, + ) -> torch.Tensor: + """Expand into output columns delimited by the host ``offsets``. + + ``bridge_slices`` > 0 maps slice s to bridge block s % bridge_slices. + Optional ranks/scalings override the batch's for MoE-layout buffers. + """ + ranks = lora_ranks if lora_ranks is not None else self.lora_ranks + scales = scalings if scalings is not None else self.scalings + b_tiles = plan.b_tiles + geometry = slice_geometry(offsets, int(b_tiles["BLOCK_SIZE_N"]), b.device) + match plan.b_family: + case BFamily.GROUPED: + grouped_lora_b( + bridge.tensor, + b, + out, + self.route(plan.block_size), + geometry=geometry, + config=b_tiles, + add_inplace=add_inplace, + zero_sentinel=False, + lora_ranks=ranks, + scalings=scales, + planes=bridge.planes, + bridge_slices=bridge_slices, + ) + case BFamily.PER_ROW: + per_row_lora_b( + bridge.tensor, + b, + out, + self.raw_route(), + geometry=geometry, + config=b_tiles, + add_inplace=add_inplace, + zero_sentinel=False, + lora_ranks=ranks, + scalings=scales, + planes=bridge.planes, + slot_planes=bridge.slot_planes, + bridge_slices=bridge_slices, + ) + case _: + raise NotImplementedError( + f"no engine executor for B family {plan.b_family.value!r}" + ) + return out + + def apply( + self, + x: torch.Tensor, + base_fn: Callable[[], torch.Tensor], + plan: DensePlan, + *, + a: torch.Tensor, + b: torch.Tensor, + offsets: tuple[int, ...], + all_reduce: Callable[[torch.Tensor], torch.Tensor] | None = None, + lora_ranks: torch.Tensor | None = None, + scalings: torch.Tensor | None = None, + bridge_slices: int = 0, + a_blocks: int | None = None, + a_windowed: bool = False, + a_fn: Callable[[], torch.Tensor] | None = None, + ) -> torch.Tensor: + """Add LoRA to ``base_fn()`` with the plan's overlap strategy. + + A is [slots, a_blocks*rank, K]; B is [slots, offsets[-1], rank]. + ``a_blocks`` defaults to len(offsets)-1; windowing and bridge mapping + follow ``run_a``/``run_b``. ``all_reduce`` reduces base + LoRA once + with B replicated across TP ranks. + """ + self.set_num_tokens(x.shape[0]) + stack = len(offsets) - 1 if a_blocks is None else a_blocks + + def run_a() -> Bridge: + if a_fn is not None: + return Bridge(a_fn()) # the embedding shrink: one plain bridge + return self.run_a( + x, + a, + stack=stack, + plan=plan, + lora_ranks=lora_ranks, + windowed=a_windowed, + ) + + def run_b(bridge: Bridge, out: torch.Tensor, add_inplace: bool) -> None: + self.run_b( + bridge, + b, + out, + offsets=offsets, + plan=plan, + add_inplace=add_inplace, + lora_ranks=lora_ranks, + scalings=scalings, + bridge_slices=bridge_slices, + ) + + if plan.overlap is Overlap.AB_DELTA: + # The delta covers the output columns the LoRA slices reach. + out_end = offsets[-1] + delta = self.workspace.tensor( + "dense:delta", + (x.shape[0], out_end), + # Embedding inputs are integer token IDs, not activations. + dtype=b.dtype if a_fn is not None else x.dtype, + device=x.device, + ) + delta.zero_() + base = self.workspace.run_parallel( + name="dense", + device=x.device, + compute=base_fn, + side=lambda: run_b(run_a(), delta, False), + ) + base[:, :out_end].add_(delta) + return all_reduce(base) if all_reduce is not None else base + + if plan.overlap is Overlap.A: + side_result: list[Bridge] = [] + base = self.workspace.run_parallel( + name="dense", + device=x.device, + compute=base_fn, + side=lambda: side_result.append(run_a()), + ) + bridge = side_result[0] + else: + base = base_fn() + bridge = run_a() + + run_b(bridge, base, True) + return all_reduce(base) if all_reduce is not None else base diff --git a/python/sglang/srt/lora/layers.py b/python/sglang/srt/lora/layers.py index 9e47c6c4b6..0386a3ca54 100644 --- a/python/sglang/srt/lora/layers.py +++ b/python/sglang/srt/lora/layers.py @@ -26,7 +26,12 @@ from sglang.srt.layers.vocab_parallel_embedding import ( VocabParallelEmbedding, ) from sglang.srt.lora.backend.base_backend import BaseLoRABackend -from sglang.srt.lora.utils import LoRABatchInfo, get_lm_head_lora_b_shard_size +from sglang.srt.lora.dense.plan import DenseLoraKind +from sglang.srt.lora.utils import ( + LoRABatchInfo, + capturing_lora_graph, + get_lm_head_lora_b_shard_size, +) from sglang.srt.runtime_context import LoRABatchLayout, get_forward, get_parallel _SGLANG_EXPERIMENTAL_LORA_OPTI = envs.SGLANG_EXPERIMENTAL_LORA_OPTI.get() @@ -63,19 +68,22 @@ class BaseLayerWithLoRA(nn.Module): @property def lora_active(self) -> bool: - """True when this layer has LoRA buffers set AND the current forward - has LoRA batch metadata. batch_info is None on DP-attention idle - forwards (see LoRAManager.prepare_lora_batch), so idle forwards take - the base path.""" + """Whether this forward must execute LoRA kernels. + + DP-attention idle forwards have no batch metadata. Inactive batches + may still need LoRA kernels when capturing an adapter-capable graph. + """ batch_info = self.lora_backend.get_batch_info() - return ( - self.set_lora - and batch_info is not None - and ( - not self.lora_backend.skip_inactive_lora_batches - or batch_info.has_active_lora - ) - ) + if not self.set_lora or batch_info is None: + return False + backend = self.lora_backend + if not (backend.skip_inactive_lora_batches or backend.skip_inactive_dense_lora): + return True + if batch_info.has_active_lora: + return True + if backend.skip_inactive_lora_batches: + return False + return capturing_lora_graph() def set_lora_info(self, *args): pass @@ -124,6 +132,7 @@ class VocabParallelEmbeddingWithLoRA(BaseLayerWithLoRA): "VocabParallelEmbeddingWithLoRA with TP > 1 under input_scattered mode (e.g., DeepSeek-v2 MLA with --enable-attn-tp-input-scattered) is not fully supported and may produce incorrect results. Consider disabling input_scattered or removing embed_tokens from LoRA target modules." ) offsets = [0, self.embed_dim] + self.lora_offsets = tuple(offsets) self.output_offset = torch.tensor( offsets, dtype=torch.int32, @@ -149,7 +158,7 @@ class VocabParallelEmbeddingWithLoRA(BaseLayerWithLoRA): self.embedding_B_buffer = embedding_B_buffer # (num_loras, embed_dim, rank) def apply_lora( - self, base_output: torch.Tensor, input_: torch.Tensor, batch_info + self, base_output: torch.Tensor, input_: torch.Tensor, batch_info=None ) -> torch.Tensor: """ Apply LoRA to base embedding output. @@ -170,7 +179,7 @@ class VocabParallelEmbeddingWithLoRA(BaseLayerWithLoRA): return lora_output def run_lora_a_embedding( - self, input_: torch.Tensor, batch_info: LoRABatchInfo + self, input_: torch.Tensor, batch_info: LoRABatchInfo | None = None ) -> torch.Tensor: """ Apply LoRA A weights using efficient embedding lookup with CUDA graph support. @@ -218,37 +227,28 @@ class VocabParallelEmbeddingWithLoRA(BaseLayerWithLoRA): ) def forward(self, input_: torch.Tensor): - """ - Forward pass with LoRA support and CUDA graph compatibility. + def base_fn(): + # Mask only the base lookup; LoRA still sees the original token IDs. + base = self.base_layer.forward( + input_.masked_fill(input_ >= self.vocab_size, 0) + ) + if getattr(self, "new_embeddings_buffer", None) is not None: + base = self.extra_token_embedding(input_, base) + return base - Extra tokens (tokens >= vocab_size) are now handled efficiently - in the backend's run_lora_a_embedding method. - """ - batch_info = self.lora_backend.get_batch_info(LoRABatchLayout.DP_LOCAL) - - # Get base embedding output - # For tokens >= vocab_size, base_layer will clamp or handle them - # We mask them to 0 to avoid out-of-bounds access - added_tokens_mask = input_ > self.vocab_size - 1 - base_output = self.base_layer.forward(input_.masked_fill(added_tokens_mask, 0)) - - # [TODO] SGLang did not support extra/added token process; thus, self.extra_token_embedding only return original input_ now - # Extra tokens - It will replace extra token embedding with self.new_embeddings_buffer's emb (Default is 0) - if ( - hasattr(self, "new_embeddings_buffer") - and self.new_embeddings_buffer is not None - ): - base_output = self.extra_token_embedding(input_, base_output) - - # Apply LoRA if configured; DP-attention idle forwards take the base - # path (see lora_active). with get_forward().scoped(lora_batch_layout=LoRABatchLayout.DP_LOCAL): if self.lora_active: - # The backend's run_lora_a_embedding now handles both regular - # and extra tokens efficiently with CUDA graph support - base_output = self.apply_lora(base_output, input_, batch_info) - - return base_output + return self.lora_backend.forward_with_base( + self, + input_, + base_fn, + self.embedding_A_buffer, + self.embedding_B_buffer, + self.output_offset, + self.lora_offsets, + kind=DenseLoraKind.EMBEDDING, + ) + return base_fn() def slice_lora_a_weights(self, A: torch.Tensor): # LoRA A weights (rank, vocab_size) are kept unsharded. @@ -311,6 +311,7 @@ class ParallelLMHeadWithLoRA(BaseLayerWithLoRA): ) offsets = [0, self.shard_vocab_size] + self.lora_offsets = tuple(offsets) self.output_offset = torch.tensor( offsets, dtype=torch.int32, @@ -354,9 +355,8 @@ class ParallelLMHeadWithLoRA(BaseLayerWithLoRA): if batch_info is not None: if batch_info.use_cuda_graph: raise RuntimeError( - "lm_head LoRA with pruned batch info is not supported " - "under CUDA graph. lm_head pruning should only occur " - "during extend, which does not use CUDA graph." + "Pruned lm_head LoRA metadata is eager-only and must run " + "outside the captured model graph." ) if num_tokens != batch_info.expected_tokens: raise RuntimeError( @@ -403,15 +403,24 @@ class ParallelLMHeadWithLoRA(BaseLayerWithLoRA): return lora_output def forward(self, hidden_states: torch.Tensor): - # Apply base linear transformation - base_output = F.linear( - hidden_states, self.weight, bias=getattr(self.base_layer, "bias", None) - ) + def base_fn(): + return F.linear( + hidden_states, self.weight, bias=getattr(self.base_layer, "bias", None) + ) if self.lora_active: - base_output = self.apply_lora(base_output, hidden_states) - - return base_output + return self.lora_backend.forward_with_base( + self, + hidden_states, + base_fn, + self.lm_head_A_buffer, + self.lm_head_B_buffer, + self.output_offset, + self.lora_offsets, + kind=DenseLoraKind.LM_HEAD, + pruned_batch_info=self._get_lm_head_batch_info(hidden_states.shape[0]), + ) + return base_fn() # ------------------------------------------------------------------ # Multi-pass lm_head support (chunked logprobs) @@ -478,6 +487,8 @@ class ColumnParallelLinearWithLoRA(BaseLayerWithLoRA): self.set_lora = True self.A_buffer = A_buffer self.B_buffer = B_buffer + self.lora_a, self.lora_b = A_buffer, B_buffer + self.lora_offsets = tuple(self.output_offset_cpu.tolist()) def apply_lora(self, base_output: torch.Tensor, x: torch.Tensor) -> torch.Tensor: lora_a_output = self.lora_backend.run_lora_a_sgemm(x, self.A_buffer) @@ -501,12 +512,22 @@ class ColumnParallelLinearWithLoRA(BaseLayerWithLoRA): self.start_lora_a_overlap(input_) bias = self.base_layer.bias if not self.base_layer.skip_bias_add else None - output_parallel = self.base_layer.quant_method.apply( - self.base_layer, input_, bias - ) + + def base_fn(): + return self.base_layer.quant_method.apply(self.base_layer, input_, bias) if lora_active: - output_parallel = self.apply_lora(output_parallel, input_) + output_parallel = self.lora_backend.forward_with_base( + self, + input_, + base_fn, + self.lora_a, + self.lora_b, + self.output_offset, + self.lora_offsets, + ) + else: + output_parallel = base_fn() if self.base_layer.gather_output: output = tensor_model_parallel_all_gather(output_parallel) @@ -575,6 +596,8 @@ class MergedColumnParallelLinearWithLoRA(ColumnParallelLinearWithLoRA): self.use_gate_up_lora = ( lora_n_slices == 2 and partition_sizes[0] == partition_sizes[1] ) + self.lora_a, self.lora_b = A_buffer, B_buffer + self.lora_offsets = tuple(offsets) def _get_lora_n_slices(self) -> int: """Actual number of LoRA slices from the buffer shapes. @@ -711,6 +734,8 @@ class QKVParallelLinearWithLoRA(ColumnParallelLinearWithLoRA): self.set_lora = True self.A_buffer_qkv = A_buffer_qkv self.B_buffer_qkv = B_buffer_qkv + self.lora_a, self.lora_b = A_buffer_qkv, B_buffer_qkv + self.lora_offsets = tuple(self.output_offset_cpu.tolist()) def apply_lora(self, base_output: torch.Tensor, x: torch.Tensor) -> torch.Tensor: lora_output = self.lora_backend.run_qkv_lora( @@ -788,6 +813,8 @@ class RowParallelLinearWithLoRA(BaseLayerWithLoRA): device="cpu", pin_memory=True, ) + self.lora_a, self.lora_b = A_buffer, B_buffer + self.lora_offsets = tuple(offsets) def apply_lora(self, base_output: torch.Tensor, x: torch.Tensor) -> torch.Tensor: lora_a_output = self.lora_backend.run_lora_a_sgemm(x, self.A_buffer) @@ -821,9 +848,11 @@ class RowParallelLinearWithLoRA(BaseLayerWithLoRA): if (tp_rank > 0 or self.base_layer.skip_bias_add) else self.base_layer.bias ) - output_parallel = self.base_layer.quant_method.apply( - self.base_layer, input_parallel, bias=bias_ - ) + + def base_fn(): + return self.base_layer.quant_method.apply( + self.base_layer, input_parallel, bias=bias_ + ) should_reduce = ( self.base_layer.reduce_results @@ -839,26 +868,21 @@ class RowParallelLinearWithLoRA(BaseLayerWithLoRA): all_reduce = get_parallel().attn_tp_group.all_reduce else: all_reduce = tensor_model_parallel_all_reduce - if lora_active and should_reduce: - lora_a_output = self.lora_backend.run_lora_a_sgemm( - input_parallel, self.A_buffer - ) - output_ = all_reduce(output_parallel) - lora_a_output = all_reduce(lora_a_output) - output_ = self.lora_backend.run_lora_b_sgemm( - x=lora_a_output, - weights=self.B_buffer, - output_offset=self.output_offset, - output_offset_cpu=self.output_offset_cpu, - base_output=output_, + if lora_active: + output_ = self.lora_backend.forward_with_base( + self, + input_parallel, + base_fn, + self.lora_a, + self.lora_b, + self.output_offset, + self.lora_offsets, + all_reduce=all_reduce if should_reduce else None, ) + elif should_reduce: + output_ = all_reduce(base_fn()) else: - if lora_active: - output_parallel = self.apply_lora(output_parallel, input_parallel) - if should_reduce: - output_ = all_reduce(output_parallel) - else: - output_ = output_parallel + output_ = base_fn() output_bias = self.base_layer.bias if self.base_layer.skip_bias_add else None return output_, output_bias @@ -920,6 +944,8 @@ class ReplicatedLinearWithLoRA(BaseLayerWithLoRA): dtype=torch.int32, device=B_buffer.device, ) + self.lora_a, self.lora_b = A_buffer, B_buffer + self.lora_offsets = tuple(self._output_offset.tolist()) def apply_lora(self, base_output: torch.Tensor, x: torch.Tensor) -> torch.Tensor: first_dim = self.first_output_dim @@ -952,9 +978,22 @@ class ReplicatedLinearWithLoRA(BaseLayerWithLoRA): def forward(self, x: torch.Tensor): bias = self.base_layer.bias if not self.base_layer.skip_bias_add else None - output = self.base_layer.quant_method.apply(self.base_layer, x, bias) + + def base_fn(): + return self.base_layer.quant_method.apply(self.base_layer, x, bias) + if self.lora_active: - output = self.apply_lora(output, x) + output = self.lora_backend.forward_with_base( + self, + x, + base_fn, + self.lora_a, + self.lora_b, + self._output_offset, + self.lora_offsets, + ) + else: + output = base_fn() output_bias = self.base_layer.bias if self.base_layer.skip_bias_add else None return output, output_bias @@ -981,13 +1020,17 @@ class FusedMoEWithLoRA(BaseLayerWithLoRA): self, base_layer: FusedMoE, lora_backend: BaseLoRABackend, + *, + experts_shared_outer_loras: bool = False, + max_lora_rank: Optional[int] = None, ): # initializes FusedMoE with its own moe_runner for base path super().__init__(base_layer, lora_backend) lora_backend.is_moe_lora = True - self.experts_shared_outer_loras: bool = False + # Match the factor layout and physical rank allocated by the memory pool. + self.experts_shared_outer_loras: bool = experts_shared_outer_loras self.lora_use_virtual_experts: bool = False self.quant_method = base_layer.quant_method self.moe_runner_config = base_layer.moe_runner_config @@ -1012,15 +1055,19 @@ class FusedMoEWithLoRA(BaseLayerWithLoRA): base_layer.moe_runner_config.gemm1_alpha is not None ) - # Initialize triton_lora moe runner for batches with lora enabled from sglang.srt.layers.moe import MoeRunnerBackend from sglang.srt.layers.moe.moe_runner.runner import MoeRunner from sglang.srt.layers.moe.utils import get_moe_runner_backend - # Use the runner selected by the quant method so per-format backend resolution - # stays identical between base and LoRA forwards. + # Explicit LoRA engines take precedence over the base layer's vendor runner. global_backend = get_moe_runner_backend() - if base_layer.runner is not None: + if ( + global_backend.is_lora() + or global_backend.is_experimental_sgl_trtllm() + or global_backend.is_experimental_sgl_marlin() + ): + runner_backend = global_backend + elif base_layer.runner is not None: runner_backend = base_layer.runner.runner_backend elif not global_backend.is_auto(): runner_backend = global_backend @@ -1038,8 +1085,27 @@ class FusedMoEWithLoRA(BaseLayerWithLoRA): if isinstance(base_layer.quant_method, UnquantizedFusedMoEMethod): runner_backend = MoeRunnerBackend.TRITON - # ===== TO BE REFACTORED ==== self._lora_runner_backend = runner_backend + if (lora_backend.name == "triton_v2") != runner_backend.is_lora(): + raise ValueError( + "Routed MoE LoRA must pair --lora-backend triton_v2 with " + "--moe-runner-backend lora_cutedsl, lora_triton, or lora_marlin; " + "mixing new and legacy LoRA backends is unsupported" + ) + if runner_backend.is_lora(): + from sglang.srt.lora.moe.runner import MoeLoraRunner + + self._moe_lora_runner = MoeLoraRunner.from_layer( + base_layer, + workspace=lora_backend.lora_workspace, + is_shared_outer=experts_shared_outer_loras, + physical_rank=max_lora_rank, + ) + # Keep dispatch, combine, and distributed reduction in the base layer. + self._base_run_moe_core = base_layer.run_moe_core + base_layer.run_moe_core = self._run_moe_core_with_lora + return + if runner_backend.is_experimental_sgl_trtllm(): from sglang.srt.lora.trtllm_lora_temp.lora_layer import ( init_experimental_sgl_trtllm_lora, @@ -1102,7 +1168,7 @@ class FusedMoEWithLoRA(BaseLayerWithLoRA): self.down_lora_b_weights = down_lora_b_weights def _get_lora_info(self): - """Build LoRAInfo for the current batch.""" + """Build the legacy engine's batch payload.""" from sglang.srt.lora.lora_moe_runners import LoRAInfo batch_info = self.lora_backend.get_batch_info(LoRABatchLayout.TP_GLOBAL) @@ -1159,8 +1225,11 @@ class FusedMoEWithLoRA(BaseLayerWithLoRA): 1. After gate_up projection, before activation 2. After down projection, before final reduction """ - # DP-attention idle forward: no batch_info, run the base MoE path. - if self.lora_backend.get_batch_info(LoRABatchLayout.TP_GLOBAL) is None: + # The lora_* path replaces run_moe_core inside the base forward. + if ( + self.lora_backend.get_batch_info(LoRABatchLayout.TP_GLOBAL) is None + or self._lora_runner_backend.is_lora() + ): return self.base_layer.forward(hidden_states, topk_output, **kwargs) # Build LoRA info for this batch @@ -1169,6 +1238,25 @@ class FusedMoEWithLoRA(BaseLayerWithLoRA): # run lora moe_runner return self._forward_with_lora(hidden_states, topk_output, lora_info, **kwargs) + def _run_moe_core_with_lora(self, dispatch_output): + batch_info = self.lora_backend.get_batch_info(LoRABatchLayout.TP_GLOBAL) + if batch_info is None: + return self._base_run_moe_core(dispatch_output=dispatch_output) + from sglang.srt.lora.moe.runner import MoeLoraBatch + + return self._moe_lora_runner.run( + dispatch_output, + MoeLoraBatch( + gate_up_lora_a=self.gate_up_lora_a_weights, + gate_up_lora_b=self.gate_up_lora_b_weights, + down_lora_a=self.down_lora_a_weights, + down_lora_b=self.down_lora_b_weights, + token_lora_mapping=batch_info.token_slots[: batch_info.num_tokens], + use_cuda_graph=batch_info.use_cuda_graph, + is_prefill=batch_info.is_prefill, + ), + ) + def _forward_with_lora( self, hidden_states: torch.Tensor, @@ -1328,11 +1416,25 @@ class FusedMoEWithLoRA(BaseLayerWithLoRA): def get_lora_layer( - layer: nn.Module, lora_backend: BaseLoRABackend + layer: nn.Module, + lora_backend: BaseLoRABackend, + *, + experts_shared_outer_loras: bool = False, + max_lora_rank: Optional[int] = None, ) -> BaseLayerWithLoRA: + if isinstance(layer, FusedMoE): + return FusedMoEWithLoRA( + layer, + lora_backend, + experts_shared_outer_loras=experts_shared_outer_loras, + max_lora_rank=max_lora_rank, + ) + # Inkling QKVR needs custom LoRA-B slicing despite being a merged linear. + if getattr(layer, "is_inkling_qkvr", False): + return InklingQKVRLinearWithLoRA(layer, lora_backend) + supported_layer_types = { # the order matters - FusedMoE: FusedMoEWithLoRA, ParallelLMHead: ParallelLMHeadWithLoRA, VocabParallelEmbedding: VocabParallelEmbeddingWithLoRA, ReplicatedLinear: ReplicatedLinearWithLoRA, @@ -1341,14 +1443,9 @@ def get_lora_layer( ColumnParallelLinear: ColumnParallelLinearWithLoRA, RowParallelLinear: RowParallelLinearWithLoRA, } - # Inkling's fused qkvr needs replication-aware LoRA-B slicing (see InklingQKVRLinear); - # it IS a MergedColumnParallelLinear, so this must precede the isinstance loop. - if getattr(layer, "is_inkling_qkvr", False): - return InklingQKVRLinearWithLoRA(layer, lora_backend) for src_layer_type, lora_layer_type in supported_layer_types.items(): if isinstance(layer, src_layer_type): # pylint: disable=unidiomatic-typecheck - ret = lora_layer_type(layer, lora_backend) - return ret + return lora_layer_type(layer, lora_backend) raise Exception(f"No corresponding LoRA layer supported for {type(layer)}.") diff --git a/python/sglang/srt/lora/lora_manager.py b/python/sglang/srt/lora/lora_manager.py index f365836e63..b342197202 100644 --- a/python/sglang/srt/lora/lora_manager.py +++ b/python/sglang/srt/lora/lora_manager.py @@ -122,6 +122,9 @@ class LoRAManager: self._experts_shared_outer_override: Optional[bool] = ( get_lora().experts_shared_outer_loras ) + from sglang.srt.layers.moe.utils import get_moe_runner_backend + + self.moe_lora_runner_backend = get_moe_runner_backend() self.lora_use_virtual_experts: bool = get_lora().lora_use_virtual_experts self.lora_strict_loading: bool = get_lora().lora_strict_loading self.speculative_algorithm: Optional[str] = get_spec().speculative_algorithm @@ -146,16 +149,12 @@ class LoRAManager: lora_paths=lora_paths, ) - def init_cuda_graph_batch_info( + def init_decode_cuda_graph_batch_info( self, max_bs_in_cuda_graph: int, num_tokens_per_req: int ): - """Phase 2 of LoRA CUDA graph init: dense LoRA batch metadata. - - Called during CudaGraphRunner.__init__(), after init_memory_pool(). - Phase 1 (MoE buffers) is handled earlier via init_cuda_graph_moe_buffers(). - """ - self.max_bs_in_cuda_graph = max_bs_in_cuda_graph - self.lora_backend.init_cuda_graph_batch_info( + """Initialize decode-runner metadata after model memory-pool setup.""" + self.max_bs_in_decode_cuda_graph = max_bs_in_cuda_graph + self.lora_backend.init_decode_cuda_graph_batch_info( max_bs_in_cuda_graph=max_bs_in_cuda_graph, num_tokens_per_req=num_tokens_per_req, ) @@ -247,12 +246,16 @@ class LoRAManager: ) def init_cuda_graph_moe_buffers( - self, max_bs: int, max_loras: int, compute_dtype, moe_layer + self, + max_bs: int, + max_loras: int, + compute_dtype, + moe_layer, ): """Phase 1 of LoRA CUDA graph init: MoE intermediate buffers. Called before init_memory_pool() so memory profiling accounts for them. - Phase 2 (dense batch metadata) is handled later via init_cuda_graph_batch_info(). + Phase 2 (dense batch metadata) uses init_decode_cuda_graph_batch_info(). """ self.lora_backend.init_cuda_graph_moe_buffers( max_bs=max_bs, @@ -322,6 +325,15 @@ class LoRAManager: return self.create_lora_update_result(success=True) + def _validate_replicated_q_targets(self, target_modules): + # q_proj adapter targets normalize to qkv_proj. + unsupported = set(target_modules) & {"q_b_proj", "qkv_proj", "kv_b_proj"} + if unsupported and get_parallel().dcp_replicate_q_proj: + raise ValueError( + f"Replicated-Q decode is incompatible with LoRA targets {sorted(unsupported)}; " + "pass --no-dcp-replicate-q-proj to use the local-head Q path." + ) + def validate_new_adapter(self, lora_config: LoRAConfig, lora_ref: LoRARef): """ Validate if an adapter can be loaded into the current LoRA memory pool and generate error if it is incompatible. @@ -479,6 +491,9 @@ class LoRAManager: metadata.""" self.lora_backend.reset_batch_state() + def reset_routing_cache(self) -> None: + self.lora_backend.reset_routing_cache() + def prepare_lora_batch(self, forward_batch: ForwardBatch): # Some internal-only backends (currently UNO) use explicit token-row # routing for their adapted forwards and want all-base batches to run @@ -491,11 +506,11 @@ class LoRAManager: return # set up batch info shared by all lora modules - use_cuda_graph = self._use_cuda_graph_batch(forward_batch) + use_decode_cuda_graph = self._use_cuda_graph_batch(forward_batch) # Eligible extend batches refresh the static prefill batch info in # place so captured kernels read current values at replay. - use_prefill_cuda_graph = not use_cuda_graph and self.can_use_prefill_cuda_graph( - forward_batch + use_prefill_cuda_graph = ( + not use_decode_cuda_graph and self.can_use_prefill_cuda_graph(forward_batch) ) active_lora_ids = set(forward_batch.lora_ids) @@ -534,16 +549,20 @@ class LoRAManager: # Do in-place updates when CUDA graph is enabled and the batch forward mode # could use CUDA graph. self.lora_backend.prepare_lora_batch( - forward_batch=forward_batch, - weight_indices=weight_indices, - lora_ranks=lora_ranks, - scalings=scalings, - use_cuda_graph=use_cuda_graph, + forward_batch, + weight_indices, + lora_ranks, + scalings, + use_decode_cuda_graph, use_prefill_cuda_graph=use_prefill_cuda_graph, ) self.lora_backend.batch_info.has_active_lora = any( lora_ranks[wi] > 0 for wi in weight_indices ) + self.lora_backend.batch_info.is_prefill = ( + forward_batch.forward_mode.is_extend() + and not forward_batch.forward_mode.is_cuda_graph() + ) if self.attn_dp_enabled: self.lora_backend.prepare_global_lora_batch(forward_batch) if forward_batch.forward_mode.is_idle(): @@ -553,8 +572,8 @@ class LoRAManager: def _use_cuda_graph_batch(self, forward_batch: ForwardBatch) -> bool: return ( - hasattr(self, "max_bs_in_cuda_graph") - and forward_batch.batch_size <= self.max_bs_in_cuda_graph + hasattr(self, "max_bs_in_decode_cuda_graph") + and forward_batch.batch_size <= self.max_bs_in_decode_cuda_graph and forward_batch.forward_mode.is_cuda_graph() and (not self.attn_dp_enabled or forward_batch.can_run_decode_cuda_graph) ) @@ -705,6 +724,7 @@ class LoRAManager: base_model=self.base_model, target_modules=self.target_modules, ) + self._validate_replicated_q_targets(self.target_modules) if self._experts_shared_outer_override is not None: self.experts_shared_outer_loras = self._experts_shared_outer_override @@ -858,19 +878,18 @@ class LoRAManager: # Fusion folds wk + weights_proj into wk_weights_proj, so the modules # LoRA wraps are absent and an indexer-targeted adapter is silently dropped. + # Each Indexer decides fusion when it is built (CUDA, env, RoPE style). indexer_targets = self.target_modules & DSA_INDEXER_LORA_NAMES - if indexer_targets: - from sglang.srt.layers.attention.dsa.dsa_indexer import ( - _use_dsa_indexer_fusion, + if indexer_targets and any( + getattr(module, "use_dsa_indexer_fusion", False) + for _, module in self.base_model.named_modules() + ): + raise ValueError( + f"LoRA targets the DSA indexer ({sorted(indexer_targets)}), which is " + "incompatible with DSA indexer Q/K fusion. Set " + "SGLANG_DISABLE_DSA_INDEXER_FUSION=1 to disable fusion and use indexer LoRA." ) - if _use_dsa_indexer_fusion: - raise ValueError( - f"LoRA targets the DSA indexer ({sorted(indexer_targets)}), which is " - "incompatible with DSA indexer Q/K fusion. Set " - "SGLANG_DISABLE_DSA_INDEXER_FUSION=1 to disable fusion and use indexer LoRA." - ) - if max_lora_rank is not None: self.max_lora_rank = max_lora_rank else: @@ -1013,9 +1032,9 @@ class LoRAManager: # Initializing memory pool with base model self.fetch_new_loras({None}) - def set_lora_module(self, module_name, module): + def set_lora_module(self, module_name, module, **kwargs): """Wrap any module (standard or MoE) with LoRA support.""" - lora_module = get_lora_layer(module, self.lora_backend) + lora_module = get_lora_layer(module, self.lora_backend, **kwargs) replace_submodule(self.base_model, module_name, lora_module) return lora_module @@ -1148,21 +1167,37 @@ class LoRAManager: # `self.lora_modules` with `None`. continue if isinstance(module, InklingBatchDenseMLP): - from sglang.srt.models.inkling_common.lora import ( - InklingBatchDenseMLPWithLoRA, - ) - - module.__class__ = InklingBatchDenseMLPWithLoRA module.initialize_lora(self.lora_backend) + logger.info_once( + "Inkling shared-sink LoRA: %s on the %s backend", + type(module).__name__, + self.lora_backend.name, + ) lora_module = module else: - lora_module = self.set_lora_module(module_name, module) - lora_module.experts_shared_outer_loras = ( - self.experts_shared_outer_loras + lora_module = self.set_lora_module( + module_name, + module, + experts_shared_outer_loras=self.experts_shared_outer_loras, + max_lora_rank=self.max_lora_rank, ) lora_module.lora_use_virtual_experts = self.lora_use_virtual_experts self.lora_modules[layer_id][module_name] = lora_module + # lora_* quant methods leave execution to the LoRA wrapper; reject + # target sets that leave every MoE layer without one. + backend = getattr(self, "moe_lora_runner_backend", None) + if backend is not None and backend.is_lora(): + modules = list(self.base_model.modules()) + if any(isinstance(module, FusedMoE) for module in modules) and not any( + isinstance(module, FusedMoEWithLoRA) for module in modules + ): + raise ValueError( + f"--moe-runner-backend {backend.value} requires " + "the LoRA target modules to include gate_up_proj and down_proj; " + "this adapter leaves the MoE experts without a runner" + ) + def init_lora_cuda_graph_moe_buffers( *, @@ -1170,18 +1205,14 @@ def init_lora_cuda_graph_moe_buffers( lora_manager: LoRAManager, dtype: torch.dtype, ): - """Phase 1 of LoRA CUDA graph init: pre-allocate MoE intermediate buffers. + """Allocate legacy MoE buffers before init_memory_pool() sizes the KV cache. - Must be called before init_memory_pool() so that memory profiling - sees the reduced available memory and sizes KV cache correctly. - All MoE LoRA layers share one set of buffers (managed by the - lora_backend) since they execute sequentially during forward. - - Phase 2 (dense LoRA batch metadata) is handled later in - CudaGraphRunner.__init__() via lora_manager.init_cuda_graph_batch_info(), - because it needs capture-time parameters (max_bs, num_tokens_per_req) - that are only available at that stage. + Sequential MoE layers reuse these buffers. Dense batch metadata is allocated + later by DecodeCudaGraphRunner, which owns the capture-time batch sizes. """ + if lora_manager.lora_backend.name == "triton_v2": + logger.debug("V2 MoE scratch is allocated during warmup, not reserved here") + return from sglang.srt.lora.layers import FusedMoEWithLoRA max_bs = get_exec().graph.cuda_graph_config.decode.max_bs @@ -1201,7 +1232,10 @@ def init_lora_cuda_graph_moe_buffers( for module in model.modules(): if isinstance(module, FusedMoEWithLoRA): lora_manager.init_cuda_graph_moe_buffers( - max_tokens, max_loras, dtype, module + max_tokens, + max_loras, + dtype, + module, ) logger.info( f"Pre-allocated shared MoE LoRA CUDA graph buffers " diff --git a/python/sglang/srt/lora/mem_pool.py b/python/sglang/srt/lora/mem_pool.py index 4c52e2fd78..58078dc602 100644 --- a/python/sglang/srt/lora/mem_pool.py +++ b/python/sglang/srt/lora/mem_pool.py @@ -350,9 +350,7 @@ class LoRAMemoryPool: return any(isinstance(m, FusedMoE) for m in base_model.modules()) def _get_num_local_experts(self, base_model: torch.nn.Module) -> int: - """Experts owned by this rank. Equals the global count when EP is - off, the runner keeps global IDs, or the split isn't even (all - three cases fold into `moe_use_local_expert_ids == False`).""" + """Resident factor count; new MoE LoRA providers use EP-local factors.""" total = self._get_num_experts(base_model) if not self.moe_use_local_expert_ids: return total @@ -1015,6 +1013,13 @@ class LoRAMemoryPool: else: temp_B_buffer[target_module] = weights temp_B_cache_keys[target_module] = name + elif is_shared_expert and expert_match: + # Without a shared-MoE destination, "shared_experts.." + # would match "experts.." and overwrite routed weights. + raise ValueError( + f"Cannot load LoRA weight {name!r}: layer {layer_id} has no " + "matching target for indexed shared-expert weights." + ) elif expert_match: # Per-expert MoE weight — 2D tensors, one per expert target_module = target_module + "_moe" diff --git a/python/sglang/srt/lora/moe/__init__.py b/python/sglang/srt/lora/moe/__init__.py new file mode 100644 index 0000000000..fc53be76b5 --- /dev/null +++ b/python/sglang/srt/lora/moe/__init__.py @@ -0,0 +1 @@ +"""MoE LoRA execution plans, runner, and base-GEMM providers.""" diff --git a/python/sglang/srt/lora/moe/base_gemm_provider/__init__.py b/python/sglang/srt/lora/moe/base_gemm_provider/__init__.py new file mode 100644 index 0000000000..79a3b8a53a --- /dev/null +++ b/python/sglang/srt/lora/moe/base_gemm_provider/__init__.py @@ -0,0 +1,85 @@ +"""Lazy selection of base-MoE providers.""" + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from sglang.srt.lora.moe.base_gemm_provider.base import MoeBaseProvider + +logger = logging.getLogger(__name__) + +# The first vendor is the default for each weight family. +VENDORS = { + "bf16": ("cutedsl", "triton"), + "fp8": ("cutedsl", "triton"), + "nvfp4": ("marlin",), +} + + +def select_provider_cls( + base_gemm_rows: str, family: str, vendor: str | None = None +) -> type[MoeBaseProvider]: + """Use the family default when the requested vendor cannot serve it. + + Triton and Marlin use route-major rows for either requested row order. + """ + if base_gemm_rows not in ("expert_major", "route_major"): + raise ValueError( + f"unknown MoE LoRA base-GEMM row order {base_gemm_rows!r}; " + "expected 'expert_major' or 'route_major'" + ) + vendors = VENDORS[family] + if vendor not in vendors: + if vendor is not None: + logger.info( + "MoE LoRA base-GEMM vendor %r serves no %s layers; this layer " + "family uses its default vendor %r", + vendor, + family, + vendors[0], + ) + vendor = vendors[0] + expert_major = base_gemm_rows == "expert_major" + match vendor, family: + case "cutedsl", "bf16": + from sglang.srt.lora.moe.base_gemm_provider.cutedsl_bf16 import ( + CuteDslBf16ContiguousProvider, + CuteDslBf16MaskedProvider, + ) + + return ( + CuteDslBf16MaskedProvider + if expert_major + else CuteDslBf16ContiguousProvider + ) + case "cutedsl", "fp8": + from sglang.srt.lora.moe.base_gemm_provider.cutedsl_fp8 import ( + CuteDslFp8ContiguousProvider, + CuteDslFp8MaskedProvider, + ) + + return ( + CuteDslFp8MaskedProvider + if expert_major + else CuteDslFp8ContiguousProvider + ) + case "triton", "bf16": + from sglang.srt.lora.moe.base_gemm_provider.triton_bf16 import ( + TritonBf16ContiguousProvider, + ) + + return TritonBf16ContiguousProvider + case "triton", "fp8": + from sglang.srt.lora.moe.base_gemm_provider.triton_fp8 import ( + TritonFp8ContiguousProvider, + ) + + return TritonFp8ContiguousProvider + case "marlin", "nvfp4": + from sglang.srt.lora.moe.base_gemm_provider.marlin_nvfp4 import ( + MarlinNvFp4ContiguousProvider, + ) + + return MarlinNvFp4ContiguousProvider diff --git a/python/sglang/srt/lora/moe/base_gemm_provider/base.py b/python/sglang/srt/lora/moe/base_gemm_provider/base.py new file mode 100644 index 0000000000..db59b32638 --- /dev/null +++ b/python/sglang/srt/lora/moe/base_gemm_provider/base.py @@ -0,0 +1,305 @@ +"""Base MoE stages with insertion points for LoRA.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING + +import msgspec +import torch + +if TYPE_CHECKING: + from sglang.kernels.ops.lora.common.route_view import RouteView + from sglang.srt.lora.moe.plan import FinalizeFamily, MoeLoraLaunchConfig + from sglang.srt.lora.workspace import LoraWorkspace + + +# Token-count cutoff for the vectorized top-k gather. +_SMALL_FINALIZE_MAX_TOKENS = 64 + + +class MoeBaseProviderContract(msgspec.Struct, frozen=True, kw_only=True): + key: str + quant_info_cls: type + # Base output order; the LoRA delta is always [gate | up]. + gate_first: bool + interleaved: bool + gate_up_output_dtype: torch.dtype + lora_delta_dtype: torch.dtype + lora_activation_dtype: torch.dtype + # Fuse FP8 quantization into activation for the down GEMM. + act_quant_group: int | None = None + + +def expected_rows_per_expert(num_pairs: int, num_experts: int) -> int: + """Rounded-up mean rows per expert; use one for an empty batch.""" + return (num_pairs - 1) // num_experts + 1 if num_pairs else 1 + + +def prepare_buffer(workspace, name: str, shape, *, dtype, device) -> torch.Tensor: + if workspace is not None: + return workspace.tensor(name, shape, dtype=dtype, device=device) + return torch.empty(shape, dtype=dtype, device=device) + + +def admit_weight_layout(quant_info) -> int: + """Validate [E, S*I, H] / [E, H, I] weights and return S.""" + if quant_info.intermediate_size <= 0: + raise ValueError("intermediate_size must be positive") + expected_w2 = ( + quant_info.num_local_experts, + quant_info.hidden_size, + quant_info.intermediate_size, + ) + if quant_info.w2_weight.shape != expected_w2: + raise ValueError( + f"w2_weight must be {expected_w2}, got {tuple(quant_info.w2_weight.shape)}" + ) + if ( + quant_info.w13_weight.ndim != 3 + or quant_info.w13_weight.shape[0] != quant_info.num_local_experts + or quant_info.w13_weight.shape[2] != quant_info.hidden_size + ): + raise ValueError( + "w13_weight must be [num_local_experts, slices*intermediate, hidden]" + ) + gateup_width = quant_info.w13_weight.shape[1] + if gateup_width % quant_info.intermediate_size: + raise ValueError( + "w13 output width must be an integer multiple of intermediate_size" + ) + gate_up_slices = gateup_width // quant_info.intermediate_size + if gate_up_slices not in (1, 2): + raise ValueError( + "the base providers support one non-gated slice or two gated " + f"gate/up slices, got {gate_up_slices}" + ) + return gate_up_slices + + +class MoeBaseProvider: + """One provider per layer; logical sizes come from quant_info.""" + + contract: MoeBaseProviderContract + + @property + def num_local_experts(self) -> int: + return self.quant_info.num_local_experts + + @property + def intermediate_size(self) -> int: + """Logical intermediate width of one TP shard.""" + return self.quant_info.intermediate_size + + @property + def hidden_size(self) -> int: + return self.quant_info.hidden_size + + @property + def gate_up_slices(self) -> int: + return self._gate_up_slices + + def prepare( + self, + hidden_states: torch.Tensor, + topk_ids: torch.Tensor, + top_k: int, + workspace: LoraWorkspace | None = None, + ): + """Prepare rows with graph-stable buffers when a workspace is supplied.""" + raise NotImplementedError + + def gateup(self, row_state, out: torch.Tensor) -> None: + raise NotImplementedError + + def release_prepared_inputs(self, row_state) -> None: + raise NotImplementedError + + def act_with_delta( + self, + row_state, + gateup_out: torch.Tensor, + gate_up_delta: torch.Tensor | None, + topk_ids: torch.Tensor, + act_out: torch.Tensor, + activation_lora_input: torch.Tensor, + *, + activation: str = "silu", + ) -> None: + raise NotImplementedError + + def fused_act( + self, + row_state, + *, + activation: str, + base_gateup: torch.Tensor, + act_rows: torch.Tensor, + act_pairs: torch.Tensor | None, + routing: RouteView, + config: Mapping[str, int], + bridge_gateup: torch.Tensor | None = None, + b_gate_up: torch.Tensor | None = None, + bridge_top_k: int = 1, + ) -> None: + raise NotImplementedError( + f"{self.contract.key} has no fused-act implementation" + ) + + def down( + self, + row_state, + act_out: torch.Tensor, + out: torch.Tensor, + ) -> None: + raise NotImplementedError + + def down_output(self, row_state, workspace: LoraWorkspace) -> torch.Tensor: + return workspace.tensor( + "base:down", + self.down_out_shape(row_state), + dtype=torch.bfloat16, + device=row_state.pair_to_row.device, + ) + + def finalize( + self, + row_state, + down_out: torch.Tensor, + topk_ids: torch.Tensor, + topk_weights: torch.Tensor, + routed_scaling_factor: float | None, + output: torch.Tensor, + *, + lora_delta: torch.Tensor | None = None, + ) -> None: + """Weight base + unweighted LoRA delta [T, K, H], then scale once.""" + from sglang.kernels.ops.lora.moe.finalize import invoke_small_finalize + from sglang.kernels.ops.moe.ep_moe_kernels import post_reorder_deepgemm + + num_tokens, hidden = output.shape + scaling = routed_scaling_factor if routed_scaling_factor is not None else 1.0 + if num_tokens <= _SMALL_FINALIZE_MAX_TOKENS and topk_weights.is_contiguous(): + # Gather top-k rows together instead of issuing dependent row loads. + invoke_small_finalize( + down_out.view(-1, hidden), + output, + row_state.pair_to_row, + topk_weights, + scaling, + lora_delta=lora_delta, + ) + return + post_reorder_deepgemm( + down_out.view(-1, hidden), + output, + row_state.pair_to_row, + topk_ids, + topk_weights.contiguous(), + topk_ids.shape[1], + num_tokens, + hidden, + scaling, + lora_delta=lora_delta, + ) + + def shared_outer_finalize( + self, + row_state, + *, + down_rows: torch.Tensor, + bridge: torch.Tensor, + b_down: torch.Tensor, + routing: RouteView, + topk_weights: torch.Tensor, + routed_scaling_factor: float | None, + output: torch.Tensor, + family: FinalizeFamily, + launch_config: MoeLoraLaunchConfig, + workspace: LoraWorkspace, + token_route: RouteView | None, + ) -> None: + """Apply shared down-B with the plan's fused or staged finalize.""" + from sglang.srt.lora.moe.plan import FinalizeFamily, Site + + if topk_weights.dtype != torch.float32: + raise TypeError( + "topk_weights must stay FP32 until the finalize applies them" + ) + if family is FinalizeFamily.SHARED_ONE_PASS: + from sglang.kernels.ops.lora.moe.finalize import invoke_shared_one_pass + + invoke_shared_one_pass( + num_local_experts=self.num_local_experts, + down_rows=down_rows, + pair_to_row=row_state.pair_to_row, + bridge=bridge, + b_down=b_down, + routing=routing, + topk_weights=topk_weights, + routed_scaling_factor=routed_scaling_factor, + output=output, + config=launch_config.shared_one_pass, + ) + return + if family is not FinalizeFamily.SHARED_TOKEN_DELTA: + raise ValueError(f"not a shared-outer finalize family: {family}") + if token_route is None: + raise ValueError("shared token route was not constructed") + + num_tokens = output.shape[0] + token_rank = workspace.tensor( + "finalize:shared_token_rank", + (num_tokens, bridge.shape[1]), + dtype=bridge.dtype, + device=bridge.device, + ) + token_delta = workspace.tensor( + "finalize:shared_token_delta", + (num_tokens, self.hidden_size), + dtype=self.contract.lora_delta_dtype, + device=bridge.device, + ) + from sglang.kernels.ops.lora.moe.finalize import ( + invoke_shared_token_delta_reduce, + invoke_shared_token_delta_tail, + ) + from sglang.kernels.ops.lora.moe.lora_b import grouped_lora_b + + invoke_shared_token_delta_reduce( + num_local_experts=self.num_local_experts, + bridge=bridge, + routing=routing, + topk_weights=topk_weights, + token_rank=token_rank, + config=launch_config.shared_token_delta["reduce"], + ) + grouped_lora_b( + token_rank, + b_down, + token_delta, + token_route, + destination_offsets=(0,), + config=launch_config.for_b(Site.DOWN), + pair_bridge=True, + ) + invoke_shared_token_delta_tail( + num_local_experts=self.num_local_experts, + down_rows=down_rows, + pair_to_row=row_state.pair_to_row, + token_delta=token_delta, + routing=routing, + topk_weights=topk_weights, + routed_scaling_factor=routed_scaling_factor, + output=output, + config=launch_config.shared_token_delta["tail"], + ) + + def gateup_out_shape(self, row_state) -> tuple[int, ...]: + raise NotImplementedError + + def act_out_shape(self, row_state) -> tuple[int, ...]: + raise NotImplementedError + + def down_out_shape(self, row_state) -> tuple[int, ...]: + raise NotImplementedError diff --git a/python/sglang/srt/lora/moe/base_gemm_provider/contiguous_row_domain.py b/python/sglang/srt/lora/moe/base_gemm_provider/contiguous_row_domain.py new file mode 100644 index 0000000000..0ea610d59b --- /dev/null +++ b/python/sglang/srt/lora/moe/base_gemm_provider/contiguous_row_domain.py @@ -0,0 +1,212 @@ +"""Routed rows packed into aligned, contiguous expert segments.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING + +import msgspec +import torch + +from sglang.kernels.ops.lora.moe.activation_delta import act_delta +from sglang.kernels.ops.lora.moe.dispatch_contiguous import ( + contiguous_m_pad_ceiling, + dispatch_fill_rows_contiguous_bf16, + dispatch_layout_contiguous, +) +from sglang.kernels.ops.lora.moe.fused_act import fused_b_act +from sglang.srt.lora.moe.base_gemm_provider.base import ( + MoeBaseProvider, + admit_weight_layout, + prepare_buffer, +) +from sglang.srt.lora.moe.quant_info import StandardLayoutQuantInfo + +if TYPE_CHECKING: + from sglang.kernels.ops.lora.common.route_view import RouteView + from sglang.srt.lora.workspace import LoraWorkspace + + +class ContiguousRowState(msgspec.Struct, kw_only=True): + hidden_compact: torch.Tensor | None # [m_pad_ceiling, hidden], the GEMM input dtype + seg_counts: torch.Tensor # [E_local] int32 + seg_offsets: torch.Tensor # [E_local + 1] int32 first row of each segment + pair_to_row: torch.Tensor # [num_tokens * top_k] int32 compact rows + m_pad_ceiling: int + input_buffer_reuse: bool + # Quantized activation and scales for the down GEMM. + act_quant: tuple[torch.Tensor, torch.Tensor] | None = None + + +class ContiguousRowDomainProvider(MoeBaseProvider): + def __init__(self, quant_info: StandardLayoutQuantInfo, *, m_alignment: int): + self.quant_info = quant_info + if not isinstance(m_alignment, int) or m_alignment < 1: + raise ValueError(f"m_alignment must be a positive int, got {m_alignment!r}") + self._m_alignment = m_alignment + self._gate_up_slices = admit_weight_layout(quant_info) + + def prepare( + self, + hidden_states: torch.Tensor, + topk_ids: torch.Tensor, + top_k: int, + workspace: LoraWorkspace | None = None, + *, + fill_rows: bool = True, + ) -> ContiguousRowState: + num_pairs = topk_ids.numel() + num_experts = self.quant_info.num_local_experts + m_pad_ceiling = contiguous_m_pad_ceiling( + num_pairs, num_experts, self._m_alignment + ) + device = hidden_states.device + prefix = f"contiguous:a{self._m_alignment}" + seg_counts = prepare_buffer( + workspace, + f"{prefix}:seg_counts", + (num_experts,), + dtype=torch.int32, + device=device, + ) + seg_offsets = prepare_buffer( + workspace, + f"{prefix}:seg_offsets", + (num_experts + 1,), + dtype=torch.int32, + device=device, + ) + pair_to_row = prepare_buffer( + workspace, + f"{prefix}:pair_to_row", + (num_pairs,), + dtype=torch.int32, + device=device, + ) + if workspace is not None: + # Padding outputs are ignored, so reused padding needs no reset. + hidden_compact = ( + None + if not fill_rows + else workspace.tensor( + f"{prefix}:hidden_compact", + (m_pad_ceiling, hidden_states.size(1)), + dtype=torch.bfloat16, + device=device, + zero_on_first_allocation=True, + ) + ) + else: + hidden_compact = ( + None + if not fill_rows + else torch.zeros( + (m_pad_ceiling, hidden_states.size(1)), + dtype=torch.bfloat16, + device=device, + ) + ) + dispatch_layout_contiguous( + hidden_states, + topk_ids, + num_experts, + top_k, + self._m_alignment, + seg_counts_out=seg_counts, + seg_offsets_out=seg_offsets, + pair_to_row_out=pair_to_row, + ) + if hidden_compact is not None: + dispatch_fill_rows_contiguous_bf16( + hidden_states, topk_ids, pair_to_row, hidden_compact_out=hidden_compact + ) + return ContiguousRowState( + hidden_compact=hidden_compact, + seg_counts=seg_counts, + seg_offsets=seg_offsets, + pair_to_row=pair_to_row, + m_pad_ceiling=m_pad_ceiling, + input_buffer_reuse=workspace is not None, + ) + + def release_prepared_inputs(self, row_state: ContiguousRowState) -> None: + # Workspace buffers retain their addresses for graph replay. + if row_state.input_buffer_reuse or row_state.hidden_compact is None: + return + from sglang.srt.utils import dispose_tensor + + dispose_tensor(row_state.hidden_compact) + + def act_with_delta( + self, + row_state: ContiguousRowState, + gateup_out: torch.Tensor, + gate_up_delta: torch.Tensor | None, + topk_ids: torch.Tensor, + act_out: torch.Tensor, + activation_lora_input: torch.Tensor, + *, + activation: str = "silu", + act_quant: tuple[torch.Tensor, torch.Tensor] | None = None, + ) -> None: + if act_quant is not None: + row_state.act_quant = act_quant + act_delta( + gateup_out, + gate_up_delta, + act_out, + activation_lora_input, + row_state.pair_to_row, + topk_ids, + num_local_experts=self.num_local_experts, + gate_first=self.contract.gate_first, + interleaved=self.contract.interleaved, + activation=activation, + act_quant=( + (*act_quant, self.contract.act_quant_group) + if act_quant is not None + else None + ), + ) + + def fused_act( + self, + row_state: ContiguousRowState, + *, + activation: str, + base_gateup: torch.Tensor, + act_rows: torch.Tensor, + act_pairs: torch.Tensor | None, + routing: RouteView, + config: Mapping[str, int], + bridge_gateup: torch.Tensor | None = None, + b_gate_up: torch.Tensor | None = None, + bridge_top_k: int = 1, + ) -> None: + fused_b_act( + activation=activation, + base_gateup=base_gateup, + act_rows=act_rows, + act_pairs=act_pairs, + pair_to_row=row_state.pair_to_row, + routing=routing, + num_local_experts=self.num_local_experts, + gate_first=self.contract.gate_first, + interleaved=self.contract.interleaved, + config=config, + bridge_gateup=bridge_gateup, + b_gate_up=b_gate_up, + bridge_top_k=bridge_top_k, + ) + + def gateup_out_shape(self, row_state: ContiguousRowState) -> tuple[int, ...]: + return ( + row_state.m_pad_ceiling, + self.gate_up_slices * self.quant_info.intermediate_size, + ) + + def act_out_shape(self, row_state: ContiguousRowState) -> tuple[int, ...]: + return (row_state.m_pad_ceiling, self.quant_info.intermediate_size) + + def down_out_shape(self, row_state: ContiguousRowState) -> tuple[int, ...]: + return (row_state.m_pad_ceiling, self.quant_info.hidden_size) diff --git a/python/sglang/srt/lora/moe/base_gemm_provider/cutedsl_bf16.py b/python/sglang/srt/lora/moe/base_gemm_provider/cutedsl_bf16.py new file mode 100644 index 0000000000..2937b43ec0 --- /dev/null +++ b/python/sglang/srt/lora/moe/base_gemm_provider/cutedsl_bf16.py @@ -0,0 +1,383 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch + +from sglang.kernels.ops.lora.moe.dispatch_masked_small import ( + small_masked_prepare, + small_masked_prepare_applies, +) +from sglang.srt.lora.moe.base_gemm_provider.base import ( + MoeBaseProviderContract, + expected_rows_per_expert, +) +from sglang.srt.lora.moe.base_gemm_provider.contiguous_row_domain import ( + ContiguousRowDomainProvider, + ContiguousRowState, +) +from sglang.srt.lora.moe.base_gemm_provider.cutedsl_common import CuteDslTileMixin +from sglang.srt.lora.moe.base_gemm_provider.masked_row_domain import ( + MaskedRowDomainProvider, + MaskedRowState, + masked_m_max, + prepare_buffer, +) +from sglang.srt.lora.moe.quant_info import MoeLoraBf16QuantInfo + +if TYPE_CHECKING: + from sglang.srt.lora.workspace import LoraWorkspace + + +class _CuteDslBf16Mixin(CuteDslTileMixin): + _DTYPE_TAG = "bf16" + WIDE_EXPECTED_M_THRESHOLD = 16 + + def _launch( + self, + stage: str, + a: torch.Tensor, + c: torch.Tensor, + row_state, + schedule: torch.Tensor, + tiles: torch.Tensor, + ) -> None: + call = self._compiled[row_state.token_width][stage] + # Runtime wrapping must match the compiled argument's MLIR type. + dyn = self._as_dynamic_cute_tensor + call.compiled_fn( + dyn(self._rows_arg(a), leading_dim=2), + call.b_arg, + dyn(self._rows_arg(c), leading_dim=2), + dyn(self._group_arg(row_state), leading_dim=0), + dyn(schedule, leading_dim=0), + dyn(tiles, leading_dim=0), + self._stream(a.device), + ) + + def gateup(self, row_state, out: torch.Tensor) -> None: + self._launch( + "gemm1", + self._input_rows(row_state), + out, + row_state, + row_state.gemm1_schedule, + row_state.gemm1_tiles, + ) + + def down(self, row_state, act_out: torch.Tensor, out: torch.Tensor) -> None: + self._launch( + "gemm2", + act_out, + out, + row_state, + row_state.gemm2_schedule, + row_state.gemm2_tiles, + ) + + def down_output(self, row_state, workspace: LoraWorkspace) -> torch.Tensor: + # Gate/up has finished reading the prepared rows before down starts. + if row_state.input_buffer_reuse: + return self._input_rows(row_state) + return super().down_output(row_state, workspace) + + +class CuteDslBf16MaskedRowState(MaskedRowState, kw_only=True): + token_width: int + gemm1_schedule: torch.Tensor + gemm1_tiles: torch.Tensor + gemm2_schedule: torch.Tensor + gemm2_tiles: torch.Tensor + + +class CuteDslBf16MaskedProvider(_CuteDslBf16Mixin, MaskedRowDomainProvider): + contract = MoeBaseProviderContract( + key="cutedsl_bf16_masked", + quant_info_cls=MoeLoraBf16QuantInfo, + gate_first=True, + interleaved=False, + gate_up_output_dtype=torch.bfloat16, + lora_delta_dtype=torch.bfloat16, + lora_activation_dtype=torch.bfloat16, + ) + + _ROW_MODE = "masked" + + def __init__(self, quant_info: MoeLoraBf16QuantInfo): + super().__init__(quant_info) + from sglang.kernels.ops.lora.moe.cutedsl.api import prepare_masked_bf16 + from sglang.kernels.ops.lora.moe.cutedsl.schedule_builder import ( + build_dual_stage_schedules_masked, + dual_stage_schedule_capacities_masked, + ) + + self._prepare_masked_gemm = prepare_masked_bf16 + self._build_schedules = build_dual_stage_schedules_masked + self._schedule_capacities = dual_stage_schedule_capacities_masked + self._init_tiles(quant_info) + + def _prepare_dummy(self, stage: str, config): + weight = self._stage_weight(stage) + device = weight.device + experts, n, k = weight.shape + # Compile the layout with a dynamic M extent. + dummy_a = torch.zeros((experts, 256, k), dtype=torch.bfloat16, device=device) + dummy_c = torch.empty((experts, 256, n), dtype=torch.bfloat16, device=device) + dummy_masked = torch.zeros(experts, dtype=torch.int32, device=device) + return self._prepare_masked_gemm( + dummy_a, + weight, + dummy_c, + dummy_masked, + config=config, + ) + + @staticmethod + def _rows_arg(tensor: torch.Tensor) -> torch.Tensor: + return tensor + + @staticmethod + def _input_rows(row_state: CuteDslBf16MaskedRowState) -> torch.Tensor: + return row_state.hidden_permuted + + @staticmethod + def _group_arg(row_state: CuteDslBf16MaskedRowState) -> torch.Tensor: + return row_state.masked_m + + def _masked_geometry(self, token_width: int) -> dict: + return dict( + token_width=token_width, + n_gemm1=self.gate_up_slices * self.quant_info.intermediate_size, + n_gemm2=self.quant_info.hidden_size, + output_width=self.OUTPUT_WIDTH, + cluster_shape_mn=self.CLUSTER_SHAPE_MN, + use_2cta_instrs=self.USE_2CTA_INSTRS, + ) + + def prepare( + self, + hidden_states: torch.Tensor, + topk_ids: torch.Tensor, + top_k: int, + workspace: LoraWorkspace | None = None, + ) -> CuteDslBf16MaskedRowState: + num_pairs = topk_ids.numel() + if small_masked_prepare_applies(hidden_states.size(0), num_pairs): + # Prepare rows, pair map and both schedules in one launch. + num_experts = self.quant_info.num_local_experts + m_max = masked_m_max(hidden_states.size(0)) + expected_m = expected_rows_per_expert(num_pairs, num_experts) + token_width = self._token_width_for(m_max, expected_m) + geometry = self._masked_geometry(token_width) + device = hidden_states.device + masked_m = prepare_buffer( + workspace, + "masked:masked_m", + (num_experts,), + dtype=torch.int32, + device=device, + ) + pair_to_row = prepare_buffer( + workspace, + "masked:pair_to_row", + (num_pairs,), + dtype=torch.int32, + device=device, + ) + hidden_permuted = prepare_buffer( + workspace, + "masked:hidden_permuted", + (num_experts, m_max, hidden_states.size(1)), + dtype=torch.bfloat16, + device=device, + ) + outputs = self._small_prepare_outputs( + workspace, + f"cutedsl_masked:tw{token_width}", + self._schedule_capacities( + num_experts=num_experts, m_max=m_max, **geometry + ), + num_experts, + device, + ) + small_masked_prepare( + hidden_states, + topk_ids, + top_k, + masked_m_out=masked_m, + pair_to_row_out=pair_to_row, + rows_out=hidden_permuted, + token_width=token_width, + out_clusters1=self._output_clusters(geometry["n_gemm1"]), + out_clusters2=self._output_clusters(geometry["n_gemm2"]), + **outputs, + ) + return CuteDslBf16MaskedRowState( + hidden_permuted=hidden_permuted, + masked_m=masked_m, + expected_m=expected_m, + pair_to_row=pair_to_row, + m_max=m_max, + input_buffer_reuse=workspace is not None, + token_width=token_width, + gemm1_schedule=outputs["schedule1_out"], + gemm1_tiles=outputs["tiles1_out"], + gemm2_schedule=outputs["schedule2_out"], + gemm2_tiles=outputs["tiles2_out"], + ) + base = super().prepare(hidden_states, topk_ids, top_k, workspace) + token_width = self._token_width_for(base.m_max, base.expected_m) + geometry = self._masked_geometry(token_width) + schedule_outputs = {} + if workspace is not None: + schedule_outputs = self._schedule_buffers( + workspace, + f"cutedsl_masked:tw{token_width}", + self._schedule_capacities( + num_experts=base.masked_m.numel(), m_max=base.m_max, **geometry + ), + hidden_states.device, + ) + schedule1, tiles1, schedule2, tiles2 = self._build_schedules( + base.masked_m, m_max=base.m_max, **geometry, **schedule_outputs + ) + return CuteDslBf16MaskedRowState( + hidden_permuted=base.hidden_permuted, + masked_m=base.masked_m, + expected_m=base.expected_m, + pair_to_row=base.pair_to_row, + m_max=base.m_max, + input_buffer_reuse=base.input_buffer_reuse, + token_width=token_width, + gemm1_schedule=schedule1, + gemm1_tiles=tiles1, + gemm2_schedule=schedule2, + gemm2_tiles=tiles2, + ) + + +class CuteDslBf16ContiguousRowState(ContiguousRowState, kw_only=True): + token_width: int + gemm1_schedule: torch.Tensor + gemm1_tiles: torch.Tensor + gemm2_schedule: torch.Tensor + gemm2_tiles: torch.Tensor + + +class CuteDslBf16ContiguousProvider(_CuteDslBf16Mixin, ContiguousRowDomainProvider): + contract = MoeBaseProviderContract( + key="cutedsl_bf16_contiguous", + quant_info_cls=MoeLoraBf16QuantInfo, + gate_first=True, + interleaved=False, + gate_up_output_dtype=torch.bfloat16, + lora_delta_dtype=torch.bfloat16, + lora_activation_dtype=torch.bfloat16, + ) + + # Every compiled token width divides 128. + M_ALIGNMENT = 128 + + _ROW_MODE = "contiguous" + + def __init__(self, quant_info: MoeLoraBf16QuantInfo): + super().__init__(quant_info, m_alignment=self.M_ALIGNMENT) + + from sglang.kernels.ops.lora.moe.cutedsl.api import prepare_contiguous_bf16 + from sglang.kernels.ops.lora.moe.cutedsl.schedule_builder import ( + build_dual_stage_schedules_contiguous, + dual_stage_schedule_capacities_contiguous, + validate_tile_geometry_contiguous, + ) + + self._prepare_contiguous_gemm = prepare_contiguous_bf16 + self._validate_tile_geometry = validate_tile_geometry_contiguous + self._build_schedules_contiguous = build_dual_stage_schedules_contiguous + self._schedule_capacities = dual_stage_schedule_capacities_contiguous + + # Hopper prefill uses wide tiles. + device_capability = torch.cuda.get_device_capability( + quant_info.w13_weight.device + ) + self._init_tiles(quant_info, drop_narrow_tile=device_capability < (10, 0)) + + def _admit_tile_width(self, token_width: int) -> None: + self._validate_tile_geometry(token_width, self._m_alignment) + + def _prepare_dummy(self, stage: str, config): + weight = self._stage_weight(stage) + device = weight.device + num_experts, n, k = weight.shape + # Compile the layout with a dynamic M extent. + dummy_a = torch.zeros((256, k), dtype=torch.bfloat16, device=device) + dummy_c = torch.empty((256, n), dtype=torch.bfloat16, device=device) + dummy_seg = torch.zeros(num_experts + 1, dtype=torch.int32, device=device) + return self._prepare_contiguous_gemm( + dummy_a, + weight, + dummy_c, + dummy_seg, + config=config, + ) + + @staticmethod + def _rows_arg(tensor: torch.Tensor) -> torch.Tensor: + # Flat rows occupy one expert slot in the swap_ab wrapper. + return tensor.unsqueeze(0) + + @staticmethod + def _input_rows(row_state: CuteDslBf16ContiguousRowState) -> torch.Tensor: + return row_state.hidden_compact + + @staticmethod + def _group_arg(row_state: CuteDslBf16ContiguousRowState) -> torch.Tensor: + return row_state.seg_offsets + + def prepare( + self, + hidden_states: torch.Tensor, + topk_ids: torch.Tensor, + top_k: int, + workspace: LoraWorkspace | None = None, + ) -> CuteDslBf16ContiguousRowState: + base = super().prepare(hidden_states, topk_ids, top_k, workspace) + num_experts = self.quant_info.num_local_experts + # Distinct top-k experts bound each expert to one row per token. + max_expert_rows = max(int(hidden_states.size(0)), 1) + expected_m = expected_rows_per_expert(topk_ids.numel(), num_experts) + token_width = self._token_width_for(max_expert_rows, expected_m) + geometry = dict( + m_pad_ceiling=base.m_pad_ceiling, + max_expert_rows=max_expert_rows, + m_alignment=self._m_alignment, + token_width=token_width, + n_gemm1=self.gate_up_slices * self.quant_info.intermediate_size, + n_gemm2=self.quant_info.hidden_size, + output_width=self.OUTPUT_WIDTH, + cluster_shape_mn=self.CLUSTER_SHAPE_MN, + use_2cta_instrs=self.USE_2CTA_INSTRS, + ) + schedule_outputs = {} + if workspace is not None: + schedule_outputs = self._schedule_buffers( + workspace, + f"cutedsl_contiguous:a{self._m_alignment}:tw{token_width}", + self._schedule_capacities(num_experts=num_experts, **geometry), + hidden_states.device, + ) + schedule1, tiles1, schedule2, tiles2 = self._build_schedules_contiguous( + base.seg_counts, **geometry, **schedule_outputs + ) + return CuteDslBf16ContiguousRowState( + hidden_compact=base.hidden_compact, + seg_counts=base.seg_counts, + seg_offsets=base.seg_offsets, + pair_to_row=base.pair_to_row, + m_pad_ceiling=base.m_pad_ceiling, + input_buffer_reuse=base.input_buffer_reuse, + token_width=token_width, + gemm1_schedule=schedule1, + gemm1_tiles=tiles1, + gemm2_schedule=schedule2, + gemm2_tiles=tiles2, + ) diff --git a/python/sglang/srt/lora/moe/base_gemm_provider/cutedsl_common.py b/python/sglang/srt/lora/moe/base_gemm_provider/cutedsl_common.py new file mode 100644 index 0000000000..05c1acbf00 --- /dev/null +++ b/python/sglang/srt/lora/moe/base_gemm_provider/cutedsl_common.py @@ -0,0 +1,282 @@ +"""Shared compilation, tile selection, and launch buffers for CuTeDSL.""" + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING + +import msgspec +import torch + +from sglang.srt.lora.moe.base_gemm_provider.base import prepare_buffer + +if TYPE_CHECKING: + from sglang.srt.lora.moe.quant_info import StandardLayoutQuantInfo + from sglang.srt.lora.workspace import LoraWorkspace + +logger = logging.getLogger(__name__) + +# Cache code only: caching bound arguments would retain layer weights. +_COMPILE_CACHE: dict[tuple, object] = {} + + +class CuteDslStageCall(msgspec.Struct, frozen=True): + compiled_fn: object + b_arg: object + sf_weights: torch.Tensor | None = None + + +class CuteDslTileMixin: + NARROW_TOKEN_WIDTH = 8 + NARROW_PERSISTENT_CLUSTERS = 128 + WIDE_TOKEN_WIDTH = 64 + WIDE_PERSISTENT_CLUSTERS = 128 + XWIDE_TOKEN_WIDTH = 128 + XWIDE_PERSISTENT_CLUSTERS = 128 + # The packed schedule supports only 1x1 clusters and 1-CTA MMA. + CLUSTER_SHAPE_MN = (1, 1) + USE_2CTA_INSTRS = False + OCCUPANCY = 1 + MMA_INST_TILE_K = 4 + WIDE_EXPECTED_M_THRESHOLD: int + XWIDE_EXPECTED_M_THRESHOLD = 96 + OUTPUT_WIDTH = 128 + + _ROW_MODE: str + _DTYPE_TAG: str + + def _init_tiles( + self, quant_info: StandardLayoutQuantInfo, *, drop_narrow_tile: bool = False + ) -> None: + import cuda.bindings.driver as cuda_driver + + from sglang.kernels.ops.lora.moe.cutedsl.api import ( + GroupedGemmConfig, + as_dynamic_cute_tensor, + ) + from sglang.kernels.ops.lora.moe.cutedsl.schedule_builder import ( + MAX_EXPERTS, + MAX_TOKEN_CLUSTERS, + ) + from sglang.srt.lora.moe.base_gemm_provider.gemm_config_store import ( + cutedsl_version, + load_config_table, + ) + + self._as_dynamic_cute_tensor = as_dynamic_cute_tensor + self._cu_stream = cuda_driver.CUstream + if quant_info.num_local_experts > MAX_EXPERTS: + raise ValueError( + f"{quant_info.num_local_experts} local experts exceed the " + f"direct schedule's {MAX_EXPERTS}-expert packing" + ) + self._max_token_clusters = MAX_TOKEN_CLUSTERS + self._bind_weights(quant_info) + + device = quant_info.w13_weight.device + # Keep the SM90 FP8 heuristic at 64-wide tiles; tables may override it. + self._xwide_by_heuristic = not ( + self._DTYPE_TAG == "fp8" + and torch.cuda.get_device_capability(device) < (10, 0) + ) + # Use one persistent cluster per SM on 152-SM Blackwell devices. + xwide_clusters = self.XWIDE_PERSISTENT_CLUSTERS + if ( + torch.cuda.get_device_capability(device) >= (10, 0) + and torch.cuda.get_device_properties(device).multi_processor_count == 152 + ): + xwide_clusters = 152 + tile_set = ( + (self.NARROW_TOKEN_WIDTH, self.NARROW_PERSISTENT_CLUSTERS), + (self.WIDE_TOKEN_WIDTH, self.WIDE_PERSISTENT_CLUSTERS), + (self.XWIDE_TOKEN_WIDTH, xwide_clusters), + ) + if drop_narrow_tile: + tile_set = tile_set[1:] + + version = cutedsl_version() + self._config_table = load_config_table( + self.contract.key, + num_local_experts=quant_info.num_local_experts, + n_gemm1=self._gate_up_slices * quant_info.intermediate_size, + n_gemm2=quant_info.hidden_size, + k=quant_info.hidden_size, + installed_versions={"cutedsl": version} if version else None, + ) + tile_set = self._merge_table_tiles(tile_set) + + self._compiled: dict[int, dict[str, CuteDslStageCall]] = {} + for token_width, persistent_clusters in tile_set: + self._admit_tile_width(token_width) + config = GroupedGemmConfig( + mma_tiler_mn=(self.OUTPUT_WIDTH, token_width), + cluster_shape_mn=self.CLUSTER_SHAPE_MN, + use_2cta_instrs=self.USE_2CTA_INSTRS, + occupancy=self.OCCUPANCY, + mma_inst_tile_k=self.MMA_INST_TILE_K, + persistent_clusters=persistent_clusters, + ) + self._compiled[token_width] = {} + self._compile_stage(token_width, "gemm1", config) + self._compile_stage(token_width, "gemm2", config) + torch.cuda.synchronize(device) + + def _merge_table_tiles( + self, tile_set: tuple[tuple[int, int], ...] + ) -> tuple[tuple[int, int], ...]: + """Add the table's tiles; drop a table whose buckets pick uncompiled widths.""" + if self._config_table is None: + return tile_set + widths = dict(tile_set) + widths.update( + (tile.token_width, tile.persistent_clusters) + for tile in self._config_table.tiles + ) + undeclared = { + payload["token_width"] for payload in self._config_table.buckets.values() + } - set(widths) + if undeclared: + logger.warning( + "Ignoring the %s GEMM config: buckets select token widths %s that " + "no tile declares", + self.contract.key, + sorted(undeclared), + ) + self._config_table = None + return tile_set + return tuple(sorted(widths.items())) + + def _bind_weights(self, quant_info: StandardLayoutQuantInfo) -> None: + """Optional hook for dtype-specific weight preparation.""" + + def _admit_tile_width(self, token_width: int) -> None: + """Optional hook for row-layout constraints.""" + + def _stage_weight(self, stage: str) -> torch.Tensor: + if stage == "gemm1": + return self.quant_info.w13_weight + if stage == "gemm2": + return self.quant_info.w2_weight + raise ValueError(f"unknown CuTeDSL base stage {stage!r}") + + def _stage_scale(self, stage: str) -> torch.Tensor | None: + return None + + def _compile_stage(self, token_width: int, stage: str, config) -> None: + weight = self._stage_weight(stage) + device = weight.device + key = ( + device.type, + device.index, + config, + self._ROW_MODE, + self._DTYPE_TAG, + self.quant_info.num_local_experts, + weight.shape[1], + weight.shape[2], + ) + compiled_fn = _COMPILE_CACHE.get(key) + if compiled_fn is None: + prepared = self._prepare_dummy(stage, config) + # Load the module before graph capture with a zero-tile launch. + prepared.launch() + compiled_fn = prepared.compiled_fn + _COMPILE_CACHE[key] = compiled_fn + self._compiled[token_width][stage] = CuteDslStageCall( + compiled_fn=compiled_fn, + b_arg=self._as_dynamic_cute_tensor(weight, leading_dim=2), + sf_weights=self._stage_scale(stage), + ) + + def _token_width_for(self, max_expert_rows: int, expected_m: int) -> int: + """Widen the tuned choice if needed to fit the packed schedule.""" + if self._config_table is not None: + performance_width = self._config_table.pick(expected_m)["token_width"] + elif expected_m >= self.XWIDE_EXPECTED_M_THRESHOLD and self._xwide_by_heuristic: + performance_width = self.XWIDE_TOKEN_WIDTH + elif ( + expected_m >= self.WIDE_EXPECTED_M_THRESHOLD + or self.NARROW_TOKEN_WIDTH not in self._compiled + ): + performance_width = self.WIDE_TOKEN_WIDTH + else: + performance_width = self.NARROW_TOKEN_WIDTH + for width in sorted(self._compiled): + if ( + width >= performance_width + and max_expert_rows <= width * self._max_token_clusters + ): + return width + widest = max(self._compiled) + raise ValueError( + f"max_expert_rows={max_expert_rows} exceeds the widest compiled " + f"tile's schedule packing ({widest * self._max_token_clusters})" + ) + + def _stream(self, device: torch.device): + return self._cu_stream(torch.cuda.current_stream(device).cuda_stream) + + @staticmethod + def _output_clusters(n: int) -> int: + return (n + CuteDslTileMixin.OUTPUT_WIDTH - 1) // CuteDslTileMixin.OUTPUT_WIDTH + + def _small_prepare_outputs( + self, + workspace: LoraWorkspace | None, + prefix: str, + capacities: tuple[int, int], + num_experts: int, + device: torch.device, + ) -> dict[str, torch.Tensor]: + """Schedule buffers plus the small prepare's stage-begin scratch.""" + import triton + + scratch_len = 2 * max(16, triton.next_power_of_2(num_experts)) + outputs = self._schedule_buffers(workspace, prefix, capacities, device) + outputs["scratch"] = prepare_buffer( + workspace, + f"{prefix}:small_scratch", + (scratch_len,), + dtype=torch.int32, + device=device, + ) + return outputs + + @staticmethod + def _schedule_buffers( + workspace: LoraWorkspace | None, + prefix: str, + capacities: tuple[int, int], + device: torch.device, + ) -> dict[str, torch.Tensor]: + capacity1, capacity2 = capacities + return { + "schedule1_out": prepare_buffer( + workspace, + f"{prefix}:gemm1_schedule", + (capacity1,), + dtype=torch.int64, + device=device, + ), + "tiles1_out": prepare_buffer( + workspace, + f"{prefix}:gemm1_tiles", + (1,), + dtype=torch.int32, + device=device, + ), + "schedule2_out": prepare_buffer( + workspace, + f"{prefix}:gemm2_schedule", + (capacity2,), + dtype=torch.int64, + device=device, + ), + "tiles2_out": prepare_buffer( + workspace, + f"{prefix}:gemm2_tiles", + (1,), + dtype=torch.int32, + device=device, + ), + } diff --git a/python/sglang/srt/lora/moe/base_gemm_provider/cutedsl_fp8.py b/python/sglang/srt/lora/moe/base_gemm_provider/cutedsl_fp8.py new file mode 100644 index 0000000000..af4ed3082b --- /dev/null +++ b/python/sglang/srt/lora/moe/base_gemm_provider/cutedsl_fp8.py @@ -0,0 +1,446 @@ +"""CuTeDSL GEMMs using checkpoint FP8 values and FP32 block scales. + +Activations use group-128 quantization; GEMM outputs remain BF16 for LoRA. +""" + +from __future__ import annotations + +import torch + +from sglang.kernels.ops.lora.moe.dispatch_contiguous import ( + dispatch_fill_rows_contiguous_fp8, +) +from sglang.kernels.ops.lora.moe.dispatch_masked import dispatch_fill_masked_fp8 +from sglang.kernels.ops.quantization.fp8_kernel import ( + sglang_per_token_group_quant_fp8, +) +from sglang.srt.lora.moe.base_gemm_provider.base import ( + MoeBaseProviderContract, + expected_rows_per_expert, + prepare_buffer, +) +from sglang.srt.lora.moe.base_gemm_provider.contiguous_row_domain import ( + ContiguousRowDomainProvider, + ContiguousRowState, +) +from sglang.srt.lora.moe.base_gemm_provider.cutedsl_common import CuteDslTileMixin +from sglang.srt.lora.moe.base_gemm_provider.masked_row_domain import ( + MaskedRowDomainProvider, + MaskedRowState, + masked_m_max, +) +from sglang.srt.lora.moe.quant_info import MoeLoraFp8QuantInfo + +QUANT_GROUP = 128 + + +class _CuteDslFp8Mixin(CuteDslTileMixin): + _DTYPE_TAG = "fp8" + WIDE_EXPECTED_M_THRESHOLD = 32 + + @staticmethod + def _prepare_input_rows(workspace, shape, device): + if workspace is None: + return torch.empty(shape, dtype=torch.float8_e4m3fn, device=device) + output = workspace.tensor( + "base:down", shape, dtype=torch.bfloat16, device=device + ) + # Gate/up consumes the packed FP8 prefix before down overwrites the BF16 slab. + return output.view(torch.float8_e4m3fn).flatten()[: output.numel()].view(shape) + + def _bind_weights(self, quant_info: MoeLoraFp8QuantInfo) -> None: + self._sf_w13 = quant_info.w13_scale.contiguous() + self._sf_w2 = quant_info.w2_scale.contiguous() + + def _stage_scale(self, stage: str) -> torch.Tensor: + return self._sf_w13 if stage == "gemm1" else self._sf_w2 + + def _launch( + self, + stage: str, + a_fp8: torch.Tensor, + sf_tokens: torch.Tensor, + c: torch.Tensor, + row_state, + schedule: torch.Tensor, + tiles: torch.Tensor, + ) -> None: + call = self._compiled[row_state.token_width][stage] + # Runtime wrapping must match the compiled argument's MLIR type. + dyn = self._as_dynamic_cute_tensor + a_rows = self._rows_arg(a_fp8) + call.compiled_fn( + dyn(a_rows, leading_dim=2), + call.b_arg, + dyn(sf_tokens.view(*a_rows.shape[:2], -1), leading_dim=2), + dyn(call.sf_weights, leading_dim=2), + dyn(self._rows_arg(c), leading_dim=2), + dyn(self._group_arg(row_state), leading_dim=0), + dyn(schedule, leading_dim=0), + dyn(tiles, leading_dim=0), + self._stream(a_fp8.device), + ) + + def gateup(self, row_state, out: torch.Tensor) -> None: + self._launch( + "gemm1", + self._input_rows(row_state), + row_state.sf_rows, + out, + row_state, + row_state.gemm1_schedule, + row_state.gemm1_tiles, + ) + + def down(self, row_state, act_out: torch.Tensor, out: torch.Tensor) -> None: + act_fp8, sf_act = self._down_operands(row_state, act_out) + self._launch( + "gemm2", + act_fp8, + sf_act, + out, + row_state, + row_state.gemm2_schedule, + row_state.gemm2_tiles, + ) + + +class CuteDslFp8MaskedRowState(MaskedRowState, kw_only=True): + token_width: int + sf_rows: torch.Tensor # [E_local, m_max, hidden // 128] fp32 group scales + gemm1_schedule: torch.Tensor + gemm1_tiles: torch.Tensor + gemm2_schedule: torch.Tensor + gemm2_tiles: torch.Tensor + # Only materialized activation fills these; fused-B activation stays BF16. + act_fp8: torch.Tensor + act_scale: torch.Tensor + act_quant_ready: bool = False + + +class CuteDslFp8MaskedProvider(_CuteDslFp8Mixin, MaskedRowDomainProvider): + contract = MoeBaseProviderContract( + key="cutedsl_fp8_masked", + quant_info_cls=MoeLoraFp8QuantInfo, + gate_first=True, + interleaved=False, + gate_up_output_dtype=torch.bfloat16, + lora_delta_dtype=torch.bfloat16, + lora_activation_dtype=torch.bfloat16, + ) + + _ROW_MODE = "masked" + + def __init__(self, quant_info: MoeLoraFp8QuantInfo): + super().__init__(quant_info) + from sglang.kernels.ops.lora.moe.cutedsl.api import prepare_masked_fp8 + from sglang.kernels.ops.lora.moe.cutedsl.schedule_builder import ( + build_dual_stage_schedules_masked, + dual_stage_schedule_capacities_masked, + ) + + self._prepare_masked_gemm = prepare_masked_fp8 + self._build_schedules = build_dual_stage_schedules_masked + self._schedule_capacities = dual_stage_schedule_capacities_masked + self._init_tiles(quant_info) + + def _prepare_dummy(self, stage: str, config): + weight, weight_sf = self._stage_weight(stage), self._stage_scale(stage) + device = weight.device + experts, n, k = weight.shape + dummy_a = torch.zeros( + (experts, 256, k), dtype=torch.float8_e4m3fn, device=device + ) + dummy_sf = torch.zeros( + (experts, 256, k // QUANT_GROUP), dtype=torch.float32, device=device + ) + dummy_c = torch.empty((experts, 256, n), dtype=torch.bfloat16, device=device) + dummy_masked = torch.zeros(experts, dtype=torch.int32, device=device) + return self._prepare_masked_gemm( + dummy_a, + weight, + dummy_sf, + weight_sf, + dummy_c, + dummy_masked, + config=config, + ) + + @staticmethod + def _rows_arg(tensor: torch.Tensor) -> torch.Tensor: + return tensor + + @staticmethod + def _input_rows(row_state: CuteDslFp8MaskedRowState) -> torch.Tensor: + return row_state.hidden_permuted + + @staticmethod + def _group_arg(row_state: CuteDslFp8MaskedRowState) -> torch.Tensor: + return row_state.masked_m + + def prepare( + self, + hidden_states: torch.Tensor, + topk_ids: torch.Tensor, + top_k: int, + workspace=None, + ) -> CuteDslFp8MaskedRowState: + experts = self.quant_info.num_local_experts + k = hidden_states.size(1) + inter = self.quant_info.intermediate_size + expected_m = expected_rows_per_expert(topk_ids.numel(), experts) + token_width = self._token_width_for(hidden_states.size(0), expected_m) + # FP8 scale loads are unpredicated across the whole selected token tile. + m_max = masked_m_max(hidden_states.size(0), token_width) + device = hidden_states.device + + def _buf(name, shape, dtype): + return prepare_buffer(workspace, name, shape, dtype=dtype, device=device) + + masked_m = _buf("masked:masked_m", (experts,), torch.int32) + pair_to_row = _buf("masked:pair_to_row", (topk_ids.numel(),), torch.int32) + rows_fp8 = self._prepare_input_rows(workspace, (experts, m_max, k), device) + sf_rows = _buf( + "masked:sf_rows", (experts, m_max, k // QUANT_GROUP), torch.float32 + ) + act_fp8 = _buf("masked:act_fp8", (experts, m_max, inter), torch.float8_e4m3fn) + act_scale = _buf( + "masked:act_scale", (experts, m_max, inter // QUANT_GROUP), torch.float32 + ) + geometry = dict( + token_width=token_width, + n_gemm1=self.gate_up_slices * inter, + n_gemm2=self.quant_info.hidden_size, + output_width=self.OUTPUT_WIDTH, + cluster_shape_mn=self.CLUSTER_SHAPE_MN, + use_2cta_instrs=self.USE_2CTA_INSTRS, + ) + capacities = self._schedule_capacities( + num_experts=experts, m_max=m_max, **geometry + ) + dispatch_fill_masked_fp8( + hidden_states, + topk_ids, + top_k, + masked_m_out=masked_m, + pair_to_row_out=pair_to_row, + rows_fp8_out=rows_fp8, + scale_out=sf_rows, + ) + schedule_outputs = {} + if workspace is not None: + schedule_outputs = self._schedule_buffers( + workspace, f"cutedsl_masked:tw{token_width}", capacities, device + ) + schedule1, tiles1, schedule2, tiles2 = self._build_schedules( + masked_m, m_max=m_max, **geometry, **schedule_outputs + ) + return CuteDslFp8MaskedRowState( + hidden_permuted=rows_fp8, + masked_m=masked_m, + expected_m=expected_m, + pair_to_row=pair_to_row, + m_max=m_max, + input_buffer_reuse=workspace is not None, + token_width=token_width, + sf_rows=sf_rows, + gemm1_schedule=schedule1, + gemm1_tiles=tiles1, + gemm2_schedule=schedule2, + gemm2_tiles=tiles2, + act_fp8=act_fp8, + act_scale=act_scale, + ) + + def act_with_delta( + self, + row_state: CuteDslFp8MaskedRowState, + gateup_out: torch.Tensor, + gate_up_delta: torch.Tensor | None, + topk_ids: torch.Tensor, + act_out: torch.Tensor, + activation_lora_input: torch.Tensor, + *, + activation: str = "silu", + ) -> None: + self._act_kernel( + gateup_out, + gate_up_delta, + act_out, + activation_lora_input, + row_state.pair_to_row, + topk_ids, + num_local_experts=self.num_local_experts, + gate_first=self.contract.gate_first, + interleaved=self.contract.interleaved, + activation=activation, + act_quant=(row_state.act_fp8, row_state.act_scale, QUANT_GROUP), + ) + row_state.act_quant_ready = True + + @staticmethod + def _down_operands( + row_state: CuteDslFp8MaskedRowState, act_out: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + if row_state.act_quant_ready: + return row_state.act_fp8, row_state.act_scale + # Fused-B activation needs separate quantization. + return sglang_per_token_group_quant_fp8( + act_out, QUANT_GROUP, masked_m=row_state.masked_m + ) + + +class CuteDslFp8ContiguousRowState(ContiguousRowState, kw_only=True): + token_width: int + sf_rows: torch.Tensor # [m_pad_ceiling, hidden // 128] fp32 group scales + gemm1_schedule: torch.Tensor + gemm1_tiles: torch.Tensor + gemm2_schedule: torch.Tensor + gemm2_tiles: torch.Tensor + + +class CuteDslFp8ContiguousProvider(_CuteDslFp8Mixin, ContiguousRowDomainProvider): + contract = MoeBaseProviderContract( + key="cutedsl_fp8_contiguous", + quant_info_cls=MoeLoraFp8QuantInfo, + gate_first=True, + interleaved=False, + gate_up_output_dtype=torch.bfloat16, + lora_delta_dtype=torch.bfloat16, + lora_activation_dtype=torch.bfloat16, + ) + + M_ALIGNMENT = 128 + + _ROW_MODE = "contiguous" + + def __init__(self, quant_info: MoeLoraFp8QuantInfo): + super().__init__(quant_info, m_alignment=self.M_ALIGNMENT) + from sglang.kernels.ops.lora.moe.cutedsl.api import prepare_contiguous_fp8 + from sglang.kernels.ops.lora.moe.cutedsl.schedule_builder import ( + build_dual_stage_schedules_contiguous, + dual_stage_schedule_capacities_contiguous, + validate_tile_geometry_contiguous, + ) + + self._prepare_contiguous_gemm = prepare_contiguous_fp8 + self._validate_tile_geometry = validate_tile_geometry_contiguous + self._build_schedules_contiguous = build_dual_stage_schedules_contiguous + self._schedule_capacities = dual_stage_schedule_capacities_contiguous + self._init_tiles(quant_info) + + def _admit_tile_width(self, token_width: int) -> None: + self._validate_tile_geometry(token_width, self._m_alignment) + + def _prepare_dummy(self, stage: str, config): + weight, weight_sf = self._stage_weight(stage), self._stage_scale(stage) + device = weight.device + num_experts, n, k = weight.shape + dummy_a = torch.zeros((256, k), dtype=torch.float8_e4m3fn, device=device) + dummy_sf = torch.zeros( + (1, 256, k // QUANT_GROUP), dtype=torch.float32, device=device + ) + dummy_c = torch.empty((256, n), dtype=torch.bfloat16, device=device) + dummy_seg = torch.zeros(num_experts + 1, dtype=torch.int32, device=device) + return self._prepare_contiguous_gemm( + dummy_a, + weight, + dummy_sf, + weight_sf, + dummy_c, + dummy_seg, + config=config, + ) + + @staticmethod + def _rows_arg(tensor: torch.Tensor) -> torch.Tensor: + # Flat rows occupy one expert slot in the swap_ab wrapper. + return tensor.unsqueeze(0) + + @staticmethod + def _input_rows(row_state: CuteDslFp8ContiguousRowState) -> torch.Tensor: + return row_state.hidden_compact + + @staticmethod + def _group_arg(row_state: CuteDslFp8ContiguousRowState) -> torch.Tensor: + return row_state.seg_offsets + + def prepare( + self, + hidden_states: torch.Tensor, + topk_ids: torch.Tensor, + top_k: int, + workspace=None, + ) -> CuteDslFp8ContiguousRowState: + base = super().prepare( + hidden_states, topk_ids, top_k, workspace, fill_rows=False + ) + num_experts = self.quant_info.num_local_experts + hidden = hidden_states.size(1) + device = hidden_states.device + prefix = f"contiguous:a{self._m_alignment}" + rows_fp8 = self._prepare_input_rows( + workspace, + (base.m_pad_ceiling, hidden), + device, + ) + sf_rows = prepare_buffer( + workspace, + f"{prefix}:sf_rows", + (base.m_pad_ceiling, hidden // QUANT_GROUP), + dtype=torch.float32, + device=device, + ) + dispatch_fill_rows_contiguous_fp8( + hidden_states, + topk_ids, + base.pair_to_row, + rows_fp8_out=rows_fp8, + scale_out=sf_rows, + ) + # Distinct top-k experts bound each expert to one row per token. + max_expert_rows = max(int(hidden_states.size(0)), 1) + expected_m = expected_rows_per_expert(topk_ids.numel(), num_experts) + token_width = self._token_width_for(max_expert_rows, expected_m) + geometry = dict( + m_pad_ceiling=base.m_pad_ceiling, + max_expert_rows=max_expert_rows, + m_alignment=self._m_alignment, + token_width=token_width, + n_gemm1=self.gate_up_slices * self.quant_info.intermediate_size, + n_gemm2=self.quant_info.hidden_size, + output_width=self.OUTPUT_WIDTH, + cluster_shape_mn=self.CLUSTER_SHAPE_MN, + use_2cta_instrs=self.USE_2CTA_INSTRS, + ) + schedule_outputs = {} + if workspace is not None: + schedule_outputs = self._schedule_buffers( + workspace, + f"cutedsl_contiguous:a{self._m_alignment}:tw{token_width}", + self._schedule_capacities(num_experts=num_experts, **geometry), + device, + ) + schedule1, tiles1, schedule2, tiles2 = self._build_schedules_contiguous( + base.seg_counts, **geometry, **schedule_outputs + ) + return CuteDslFp8ContiguousRowState( + hidden_compact=rows_fp8, + seg_counts=base.seg_counts, + seg_offsets=base.seg_offsets, + pair_to_row=base.pair_to_row, + m_pad_ceiling=base.m_pad_ceiling, + input_buffer_reuse=base.input_buffer_reuse, + token_width=token_width, + sf_rows=sf_rows, + gemm1_schedule=schedule1, + gemm1_tiles=tiles1, + gemm2_schedule=schedule2, + gemm2_tiles=tiles2, + ) + + @staticmethod + def _down_operands( + row_state: CuteDslFp8ContiguousRowState, act_out: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + return sglang_per_token_group_quant_fp8(act_out, QUANT_GROUP) diff --git a/python/sglang/srt/lora/moe/base_gemm_provider/gemm_config_store.py b/python/sglang/srt/lora/moe/base_gemm_provider/gemm_config_store.py new file mode 100644 index 0000000000..1c6e033b75 --- /dev/null +++ b/python/sglang/srt/lora/moe/base_gemm_provider/gemm_config_store.py @@ -0,0 +1,142 @@ +"""GEMM configs keyed by provider, geometry, device, and nearest expected M.""" + +from __future__ import annotations + +import functools +import logging +import os +from collections.abc import Mapping + +import msgspec + +from sglang.srt.environ import envs + +logger = logging.getLogger(__name__) + +_PACKAGE_CONFIG_DIR = os.path.join( + os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "configs" +) + + +class GemmTile(msgspec.Struct, frozen=True, kw_only=True, forbid_unknown_fields=True): + token_width: int + persistent_clusters: int + + +class GemmConfigTable(msgspec.Struct, kw_only=True, forbid_unknown_fields=True): + buckets: dict[int, dict[str, int]] + tiles: tuple[GemmTile, ...] = () + version: dict[str, str] = {} + + def pick(self, expected_m: int) -> dict[str, int]: + return self.buckets[min(self.buckets, key=lambda m: abs(m - expected_m))] + + +def _validate(table: GemmConfigTable) -> None: + if not table.buckets: + raise ValueError("buckets must be non-empty") + for bucket_m, payload in table.buckets.items(): + if bucket_m <= 0: + raise ValueError(f"bucket key {bucket_m} must be positive") + if set(payload) != {"token_width"}: + raise ValueError(f"bucket {bucket_m} must contain only token_width") + width = payload["token_width"] + if width <= 0 or width & (width - 1): + raise ValueError( + f"bucket {bucket_m} token_width must be a positive power of two" + ) + widths = [tile.token_width for tile in table.tiles] + if len(set(widths)) != len(widths): + raise ValueError("tiles must declare one persistent_clusters per token_width") + for tile in table.tiles: + if tile.token_width <= 0 or tile.token_width & (tile.token_width - 1): + raise ValueError("tile token_width must be a positive power of two") + if tile.persistent_clusters <= 0: + raise ValueError("persistent_clusters must be positive") + + +def config_file_name( + provider_key: str, + *, + num_local_experts: int, + n_gemm1: int, + n_gemm2: int, + k: int, + device_name: str, +) -> str: + device = device_name.replace(" ", "_") + return ( + f"provider={provider_key},E={num_local_experts},N1={n_gemm1}," + f"N2={n_gemm2},K={k},device_name={device}.json" + ) + + +@functools.lru_cache(maxsize=None) +def _load( + path: str, installed_versions: tuple[tuple[str, str], ...] +) -> GemmConfigTable | None: + if not os.path.exists(path): + return None + try: + with open(path, "rb") as f: + table = msgspec.json.decode(f.read(), type=GemmConfigTable) + _validate(table) + except (msgspec.DecodeError, ValueError) as exc: + logger.warning("Ignoring malformed MoE LoRA GEMM config %s: %s", path, exc) + return None + # The recorded version is tuning provenance. A table tuned with another + # release is still used: its tiles are compiled and checked before use, + # but their speed on this release has not been re-validated here. + for name, installed in installed_versions: + recorded = table.version.get(name) + if recorded is not None and recorded != installed: + logger.warning( + "MoE LoRA GEMM config %s was tuned with %s %s; installed %s. " + "The table is used, but its tile choices were not re-validated " + "on this release.", + path, + name, + recorded, + installed, + ) + logger.info("Using MoE LoRA GEMM config from %s.", path) + return table + + +def load_config_table( + provider_key: str, + *, + num_local_experts: int, + n_gemm1: int, + n_gemm2: int, + k: int, + device_name: str | None = None, + installed_versions: Mapping[str, str] | None = None, +) -> GemmConfigTable | None: + if device_name is None: + from sglang.srt.utils import get_device_name + + device_name = get_device_name() + name = config_file_name( + provider_key, + num_local_experts=num_local_experts, + n_gemm1=n_gemm1, + n_gemm2=n_gemm2, + k=k, + device_name=device_name, + ) + versions = tuple(sorted((installed_versions or {}).items())) + roots = (envs.SGLANG_LORA_MOE_CONFIG_DIR.get(), _PACKAGE_CONFIG_DIR) + for root in filter(None, roots): + path = os.path.join(root, "base_gemm", name) + if os.path.isfile(path): + return _load(path, versions) + return None + + +def cutedsl_version() -> str | None: + try: + import cutlass + except ImportError: + return None + return getattr(cutlass, "__version__", None) diff --git a/python/sglang/srt/lora/moe/base_gemm_provider/input_alignment.py b/python/sglang/srt/lora/moe/base_gemm_provider/input_alignment.py new file mode 100644 index 0000000000..fb873dbb8b --- /dev/null +++ b/python/sglang/srt/lora/moe/base_gemm_provider/input_alignment.py @@ -0,0 +1,38 @@ +"""Select the single-token or upstream general expert-row alignment.""" + +from __future__ import annotations + +import torch + +from sglang.kernels.ops.lora.moe.align_rows import ( + moe_align_single_token, + pair_to_row_map, +) + + +def align_rows( + topk_ids: torch.Tensor, + block_size: int, + num_experts: int, + *, + pair_to_row_out: torch.Tensor | None = None, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Align pairs, optionally filling pair_to_row_out [tokens * topk]. + + The single-token path fills the row map in its alignment launch. + """ + if ( + topk_ids.shape[0] == 1 + and topk_ids.shape[1] <= 32 + and topk_ids.dtype == torch.int32 + ): + return moe_align_single_token(topk_ids, block_size, pair_to_row_out) + if pair_to_row_out is not None: + pair_to_row_map(topk_ids, pair_to_row_out) + from sglang.srt.layers.moe.moe_runner.triton_utils.moe_align_block_size import ( + moe_align_block_size, + ) + + return moe_align_block_size( + topk_ids, block_size, num_experts, ignore_invalid_expert=True + ) diff --git a/python/sglang/srt/lora/moe/base_gemm_provider/marlin_nvfp4.py b/python/sglang/srt/lora/moe/base_gemm_provider/marlin_nvfp4.py new file mode 100644 index 0000000000..43d970b6f5 --- /dev/null +++ b/python/sglang/srt/lora/moe/base_gemm_provider/marlin_nvfp4.py @@ -0,0 +1,216 @@ +"""Marlin W4A16 GEMMs with BF16 activations in raw pair order.""" + +from __future__ import annotations + +import msgspec +import torch + +from sglang.srt.lora.moe.base_gemm_provider.base import ( + MoeBaseProviderContract, + prepare_buffer, +) +from sglang.srt.lora.moe.base_gemm_provider.contiguous_row_domain import ( + ContiguousRowDomainProvider, +) +from sglang.srt.lora.moe.quant_info import MoeLoraNvFp4MarlinQuantInfo + + +class MarlinNvFp4RowState(msgspec.Struct, kw_only=True): + hidden_states: torch.Tensor # [num_tokens, hidden] bf16, borrowed + sorted_token_ids: torch.Tensor + expert_ids: torch.Tensor + num_tokens_post_padded: torch.Tensor + # Per-forward locks prevent aliasing across CUDA graph pools. + lock_workspace: torch.Tensor + pair_to_row: torch.Tensor # [num_pairs] int32 identity + num_pairs: int + top_k: int + block_size_m: int + padded_intermediate: torch.Tensor | None = None + + +class MarlinNvFp4ContiguousProvider(ContiguousRowDomainProvider): + contract = MoeBaseProviderContract( + key="marlin_nvfp4_contiguous", + quant_info_cls=MoeLoraNvFp4MarlinQuantInfo, + gate_first=True, + interleaved=False, + gate_up_output_dtype=torch.bfloat16, + lora_delta_dtype=torch.bfloat16, + lora_activation_dtype=torch.bfloat16, + ) + + def __init__(self, quant_info: MoeLoraNvFp4MarlinQuantInfo): + # Packed weights use explicit logical sizes instead of shape admission. + self.quant_info = quant_info + self._gate_up_slices = quant_info.gate_up_slices + self._padded_intermediate_size = quant_info.w2_qweight.shape[1] * 16 + from sglang.srt.layers.moe.fused_moe_triton.fused_marlin_moe import ( + get_scalar_type, + ) + + self._scalar_type_w13 = get_scalar_type( + 4, False, quant_info.w13_scales, quant_info.w13_global_scale + ) + self._scalar_type_w2 = get_scalar_type( + 4, False, quant_info.w2_scales, quant_info.w2_global_scale + ) + # Finalize owns router weights; the dummy is unread when mul_topk_weights=False. + self._unused_topk_weights = torch.zeros( + (1, 1), dtype=torch.float32, device=quant_info.w13_qweight.device + ) + + def prepare( + self, + hidden_states: torch.Tensor, + topk_ids: torch.Tensor, + top_k: int, + workspace=None, + ) -> MarlinNvFp4RowState: + from sglang.srt.layers.quantization.marlin_utils import marlin_make_workspace + from sglang.srt.lora.moe.base_gemm_provider.input_alignment import align_rows + + num_tokens = hidden_states.shape[0] + num_experts = self.quant_info.num_local_experts + # fused_marlin_moe's M block size rule. + for block_size_m in (8, 16, 32, 48, 64): + if num_tokens * top_k / num_experts / block_size_m < 0.9: + break + num_pairs = topk_ids.numel() + device = hidden_states.device + pair_to_row = prepare_buffer( + workspace, "pair_to_row", (num_pairs,), dtype=torch.int32, device=device + ) + # Finalize uses pair_to_row, with -1 for pairs without an expert. + sorted_token_ids, expert_ids, num_tokens_post_padded = align_rows( + topk_ids, block_size_m, num_experts, pair_to_row_out=pair_to_row + ) + return MarlinNvFp4RowState( + hidden_states=hidden_states, + sorted_token_ids=sorted_token_ids, + expert_ids=expert_ids, + num_tokens_post_padded=num_tokens_post_padded, + lock_workspace=marlin_make_workspace(device, max_blocks_per_sm=4), + pair_to_row=pair_to_row, + num_pairs=num_pairs, + top_k=top_k, + block_size_m=block_size_m, + padded_intermediate=( + prepare_buffer( + workspace, + "marlin:padded_intermediate", + (num_pairs, self._padded_intermediate_size), + dtype=hidden_states.dtype, + device=device, + ) + if self._padded_intermediate_size != self.intermediate_size + else None + ), + ) + + def release_prepared_inputs(self, row_state: MarlinNvFp4RowState) -> None: + pass + + def _invoke( + self, + a: torch.Tensor, + out: torch.Tensor, + row_state: MarlinNvFp4RowState, + *, + qweight: torch.Tensor, + scales: torch.Tensor, + global_scale: torch.Tensor, + scalar_type, + top_k: int, + size_m: int, + size_n: int, + size_k: int, + ) -> None: + from sglang.kernels.ops.moe.moe_wna16_marlin import moe_wna16_marlin_gemm + + moe_wna16_marlin_gemm( + a, + out, + qweight, + None, + scales, + global_scale, + None, + None, + None, + row_state.lock_workspace, + row_state.sorted_token_ids, + row_state.expert_ids, + row_state.num_tokens_post_padded, + self._unused_topk_weights, + moe_block_size=row_state.block_size_m, + top_k=top_k, + mul_topk_weights=False, + is_ep=False, + b_q_type=scalar_type, + size_m=size_m, + size_n=size_n, + size_k=size_k, + is_k_full=True, # NVFP4 has no GPTQ act-order; K is never permuted + use_atomic_add=True, + use_fp32_reduce=True, + is_zp_float=False, + ) + + def gateup(self, row_state: MarlinNvFp4RowState, out: torch.Tensor) -> None: + qi = self.quant_info + padded = row_state.padded_intermediate + self._invoke( + row_state.hidden_states, + out if padded is None else padded, + row_state, + qweight=qi.w13_qweight, + scales=qi.w13_scales, + global_scale=qi.w13_global_scale, + scalar_type=self._scalar_type_w13, + top_k=row_state.top_k, + size_m=row_state.hidden_states.shape[0], + size_n=self._gate_up_slices * self._padded_intermediate_size, + size_k=qi.hidden_size, + ) + if padded is not None: + out.copy_(padded[:, : qi.intermediate_size]) + + def down( + self, + row_state: MarlinNvFp4RowState, + act_out: torch.Tensor, + out: torch.Tensor, + ) -> None: + qi = self.quant_info + padded = row_state.padded_intermediate + if padded is not None: + padded[:, : qi.intermediate_size].copy_(act_out) + # Gateup reused this buffer; clear its tail on every replay. + padded[:, qi.intermediate_size :].zero_() + act_out = padded + self._invoke( + act_out, + out, + row_state, + qweight=qi.w2_qweight, + scales=qi.w2_scales, + global_scale=qi.w2_global_scale, + scalar_type=self._scalar_type_w2, + top_k=1, + size_m=row_state.num_pairs, + size_n=qi.hidden_size, + size_k=self._padded_intermediate_size, + ) + + def gateup_out_shape(self, row_state: MarlinNvFp4RowState) -> tuple[int, ...]: + return ( + row_state.num_pairs, + self._gate_up_slices * self.quant_info.intermediate_size, + ) + + def act_out_shape(self, row_state: MarlinNvFp4RowState) -> tuple[int, ...]: + return (row_state.num_pairs, self.quant_info.intermediate_size) + + def down_out_shape(self, row_state: MarlinNvFp4RowState) -> tuple[int, ...]: + return (row_state.num_pairs, self.quant_info.hidden_size) diff --git a/python/sglang/srt/lora/moe/base_gemm_provider/masked_row_domain.py b/python/sglang/srt/lora/moe/base_gemm_provider/masked_row_domain.py new file mode 100644 index 0000000000..a4494c3e8f --- /dev/null +++ b/python/sglang/srt/lora/moe/base_gemm_provider/masked_row_domain.py @@ -0,0 +1,189 @@ +"""Expert slabs [E_local, m_max, ...] with valid counts and pair mappings.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING + +import msgspec +import torch + +from sglang.srt.lora.moe.base_gemm_provider.base import ( + MoeBaseProvider, + admit_weight_layout, + expected_rows_per_expert, + prepare_buffer, +) +from sglang.srt.lora.moe.quant_info import StandardLayoutQuantInfo + +if TYPE_CHECKING: + from sglang.kernels.ops.lora.common.route_view import RouteView + from sglang.srt.lora.workspace import LoraWorkspace + + +def masked_m_max(num_tokens: int, alignment: int = 8) -> int: + """Fit all input rows in one expert, with a nonzero aligned slab extent.""" + return max(alignment, (num_tokens + alignment - 1) // alignment * alignment) + + +class MaskedRowState(msgspec.Struct, kw_only=True): + """``pair_to_row[t * top_k + k]`` is ``expert * m_max + offset``; a pair is + valid only when ``topk_ids[t, k] >= 0``. + """ + + hidden_permuted: torch.Tensor # [E_local, m_max, hidden], the GEMM input dtype + masked_m: torch.Tensor # [E_local] int32 + expected_m: int + pair_to_row: torch.Tensor # [num_tokens * top_k] int32 + m_max: int + input_buffer_reuse: bool + + +class MaskedRowDomainProvider(MoeBaseProvider): + def __init__(self, quant_info: StandardLayoutQuantInfo): + self.quant_info = quant_info + self._gate_up_slices = admit_weight_layout(quant_info) + + from sglang.kernels.ops.lora.moe.activation_delta import act_delta + from sglang.kernels.ops.lora.moe.dispatch_masked import ( + dispatch_fill_masked_bf16, + ) + + self._preprocess = dispatch_fill_masked_bf16 + self._act_kernel = act_delta + + from sglang.kernels.ops.lora.moe.fused_act import fused_b_act + + self._fused_act = fused_b_act + + def prepare( + self, + hidden_states: torch.Tensor, + topk_ids: torch.Tensor, + top_k: int, + workspace: LoraWorkspace | None = None, + ) -> MaskedRowState: + num_experts = self.quant_info.num_local_experts + num_pairs = topk_ids.numel() + m_max = masked_m_max(hidden_states.size(0)) + device = hidden_states.device + masked_m = prepare_buffer( + workspace, + "masked:masked_m", + (num_experts,), + dtype=torch.int32, + device=device, + ) + pair_to_row = prepare_buffer( + workspace, + "masked:pair_to_row", + (num_pairs,), + dtype=torch.int32, + device=device, + ) + hidden_permuted = prepare_buffer( + workspace, + "masked:hidden_permuted", + (num_experts, m_max, hidden_states.size(1)), + dtype=torch.bfloat16, + device=device, + ) + self._preprocess( + hidden_states, + topk_ids, + top_k, + masked_m_out=masked_m, + pair_to_row_out=pair_to_row, + rows_out=hidden_permuted, + ) + return MaskedRowState( + hidden_permuted=hidden_permuted, + masked_m=masked_m, + expected_m=expected_rows_per_expert(num_pairs, num_experts), + pair_to_row=pair_to_row, + m_max=m_max, + input_buffer_reuse=workspace is not None, + ) + + def release_prepared_inputs(self, row_state: MaskedRowState) -> None: + # Workspace buffers retain their addresses for graph replay. + if row_state.input_buffer_reuse: + return + from sglang.srt.utils import dispose_tensor + + dispose_tensor(row_state.hidden_permuted) + + def act_with_delta( + self, + row_state: MaskedRowState, + gateup_out: torch.Tensor, + gate_up_delta: torch.Tensor | None, + topk_ids: torch.Tensor, + act_out: torch.Tensor, + activation_lora_input: torch.Tensor, + *, + activation: str = "silu", + ) -> None: + self._act_kernel( + gateup_out, + gate_up_delta, + act_out, + activation_lora_input, + row_state.pair_to_row, + topk_ids, + num_local_experts=self.num_local_experts, + gate_first=self.contract.gate_first, + interleaved=self.contract.interleaved, + activation=activation, + ) + + def fused_act( + self, + row_state: MaskedRowState, + *, + activation: str, + base_gateup: torch.Tensor, + act_rows: torch.Tensor, + act_pairs: torch.Tensor | None, + routing: RouteView, + config: Mapping[str, int], + bridge_gateup: torch.Tensor | None = None, + b_gate_up: torch.Tensor | None = None, + bridge_top_k: int = 1, + ) -> None: + self._fused_act( + activation=activation, + base_gateup=base_gateup, + act_rows=act_rows, + act_pairs=act_pairs, + pair_to_row=row_state.pair_to_row, + routing=routing, + num_local_experts=self.num_local_experts, + gate_first=self.contract.gate_first, + interleaved=self.contract.interleaved, + config=config, + bridge_gateup=bridge_gateup, + b_gate_up=b_gate_up, + bridge_top_k=bridge_top_k, + ) + + def gateup_out_shape(self, row_state: MaskedRowState) -> tuple[int, ...]: + return ( + self.quant_info.num_local_experts, + row_state.m_max, + self.gate_up_slices * self.quant_info.intermediate_size, + ) + + def act_out_shape(self, row_state: MaskedRowState) -> tuple[int, ...]: + return ( + self.quant_info.num_local_experts, + row_state.m_max, + self.quant_info.intermediate_size, + ) + + def down_out_shape(self, row_state: MaskedRowState) -> tuple[int, ...]: + return ( + self.quant_info.num_local_experts, + row_state.m_max, + self.quant_info.hidden_size, + ) diff --git a/python/sglang/srt/lora/moe/base_gemm_provider/triton_bf16.py b/python/sglang/srt/lora/moe/base_gemm_provider/triton_bf16.py new file mode 100644 index 0000000000..d1c0b02485 --- /dev/null +++ b/python/sglang/srt/lora/moe/base_gemm_provider/triton_bf16.py @@ -0,0 +1,202 @@ +"""Triton GEMMs gather sorted token IDs and scatter into raw pair order.""" + +from __future__ import annotations + +import msgspec +import torch + +from sglang.srt.lora.moe.base_gemm_provider.base import ( + MoeBaseProviderContract, + prepare_buffer, +) +from sglang.srt.lora.moe.base_gemm_provider.contiguous_row_domain import ( + ContiguousRowDomainProvider, +) +from sglang.srt.lora.moe.quant_info import MoeLoraBf16QuantInfo + + +class TritonRowState(msgspec.Struct, kw_only=True): + hidden_states: torch.Tensor # [num_tokens, hidden] bf16, borrowed + topk_ids: torch.Tensor # [num_tokens, top_k] borrowed + sorted_token_ids: torch.Tensor # [em_ceiling] int32 route ids, pad = numel + expert_ids: torch.Tensor # [em_ceiling / block_m] int32 per-block expert + num_tokens_post_padded: torch.Tensor # [1] int32 device scalar + pair_to_row: torch.Tensor # [num_pairs] int32 pair index, or -1 when dropped + num_pairs: int + top_k: int + config: dict + down_config: dict | None + # Quantized activation and scales for the down GEMM. + act_quant: tuple[torch.Tensor, torch.Tensor] | None = None + + +class TritonBf16ContiguousProvider(ContiguousRowDomainProvider): + contract = MoeBaseProviderContract( + key="triton_bf16_contiguous", + quant_info_cls=MoeLoraBf16QuantInfo, + gate_first=True, + interleaved=False, + gate_up_output_dtype=torch.bfloat16, + lora_delta_dtype=torch.bfloat16, + lora_activation_dtype=torch.bfloat16, + ) + + def __init__(self, quant_info: MoeLoraBf16QuantInfo): + # prepare() replaces parent compaction with the tuned BLOCK_SIZE_M. + super().__init__(quant_info, m_alignment=1) + # Finalize applies router weights; the launcher only checks this stride. + self._unused_topk_weights = torch.zeros( + (1, 1), dtype=torch.float32, device=quant_info.w2_weight.device + ) + self._configs: dict[int, tuple[dict, dict | None]] = {} + + _config_dtype_tag: str | None = None + _config_block_shape: list[int] | None = None + + def _config_for(self, num_tokens: int, top_k: int) -> tuple[dict, dict | None]: + cached = self._configs.get(num_tokens) + if cached is not None: + return cached + from sglang.srt.layers.moe.moe_runner.triton_utils.fused_moe_triton_config import ( + try_get_optimal_moe_config, + ) + + config, (down_config, _max_block_m) = try_get_optimal_moe_config( + tuple(self.quant_info.w13_weight.shape), + tuple(self.quant_info.w2_weight.shape), + top_k, + self._config_dtype_tag, + num_tokens, + return_down_config=True, + block_shape=self._config_block_shape, + ) + # Both GEMMs share a sort; upstream makes their BLOCK_SIZE_M equal. + resolved = (dict(config), dict(down_config) if down_config else None) + for stage_config in resolved: + if stage_config is None: + continue + # Classic Triton kernels do not accept the TMA launcher's flag. + stage_config.pop("USE_TMA", None) + if self._config_block_shape is not None: + # One dot tile must not span independently scaled K groups. + stage_config["BLOCK_SIZE_K"] = min( + stage_config["BLOCK_SIZE_K"], self._config_block_shape[1] + ) + self._configs[num_tokens] = resolved + return resolved + + def prepare( + self, + hidden_states: torch.Tensor, + topk_ids: torch.Tensor, + top_k: int, + workspace=None, + ) -> TritonRowState: + from sglang.srt.lora.moe.base_gemm_provider.input_alignment import align_rows + + config, down_config = self._config_for(hidden_states.shape[0], top_k) + num_pairs = topk_ids.numel() + device = hidden_states.device + pair_to_row = prepare_buffer( + workspace, "pair_to_row", (num_pairs,), dtype=torch.int32, device=device + ) + # Finalize uses pair_to_row, with -1 for pairs without an expert. + sorted_token_ids, expert_ids, num_tokens_post_padded = align_rows( + topk_ids, + int(config["BLOCK_SIZE_M"]), + self.quant_info.num_local_experts, + pair_to_row_out=pair_to_row, + ) + return TritonRowState( + hidden_states=hidden_states, + topk_ids=topk_ids, + sorted_token_ids=sorted_token_ids, + expert_ids=expert_ids, + num_tokens_post_padded=num_tokens_post_padded, + pair_to_row=pair_to_row, + num_pairs=num_pairs, + top_k=top_k, + config=config, + down_config=down_config, + ) + + def release_prepared_inputs(self, row_state: TritonRowState) -> None: + pass + + def _invoke( + self, + a: torch.Tensor, + b: torch.Tensor, + out: torch.Tensor, + row_state: TritonRowState, + *, + top_k: int, + config: dict, + ) -> None: + import triton.language as tl + + from sglang.kernels.ops.moe.fused_moe_triton_kernels import ( + invoke_fused_moe_kernel, + ) + + invoke_fused_moe_kernel( + a, + b, + None, + out, + None, + None, + None, + self._unused_topk_weights, + row_state.topk_ids, + row_state.sorted_token_ids, + row_state.expert_ids, + row_state.num_tokens_post_padded, + False, + top_k, + config, + compute_type=tl.bfloat16, + use_fp8_w8a8=False, + use_int8_w8a8=False, + use_int8_w8a16=False, + use_int4_w4a16=False, + per_channel_quant=False, + ) + + def gateup(self, row_state: TritonRowState, out: torch.Tensor) -> None: + # GEMM1 gathers token row pair_id // top_k. + self._invoke( + row_state.hidden_states, + self.quant_info.w13_weight, + out, + row_state, + top_k=row_state.top_k, + config=row_state.config, + ) + + def down( + self, + row_state: TritonRowState, + act_out: torch.Tensor, + out: torch.Tensor, + ) -> None: + self._invoke( + act_out, + self.quant_info.w2_weight, + out, + row_state, + top_k=1, + config=row_state.down_config or row_state.config, + ) + + def gateup_out_shape(self, row_state: TritonRowState) -> tuple[int, ...]: + return ( + row_state.num_pairs, + self.gate_up_slices * self.quant_info.intermediate_size, + ) + + def act_out_shape(self, row_state: TritonRowState) -> tuple[int, ...]: + return (row_state.num_pairs, self.quant_info.intermediate_size) + + def down_out_shape(self, row_state: TritonRowState) -> tuple[int, ...]: + return (row_state.num_pairs, self.quant_info.hidden_size) diff --git a/python/sglang/srt/lora/moe/base_gemm_provider/triton_fp8.py b/python/sglang/srt/lora/moe/base_gemm_provider/triton_fp8.py new file mode 100644 index 0000000000..3a343ad1b0 --- /dev/null +++ b/python/sglang/srt/lora/moe/base_gemm_provider/triton_fp8.py @@ -0,0 +1,106 @@ +"""Triton FP8 GEMMs with 128-block scales and BF16 LoRA inputs/outputs.""" + +from __future__ import annotations + +import torch + +from sglang.srt.lora.moe.base_gemm_provider.base import MoeBaseProviderContract +from sglang.srt.lora.moe.base_gemm_provider.triton_bf16 import ( + TritonBf16ContiguousProvider, + TritonRowState, +) +from sglang.srt.lora.moe.quant_info import MoeLoraFp8QuantInfo + + +class TritonFp8ContiguousProvider(TritonBf16ContiguousProvider): + contract = MoeBaseProviderContract( + key="triton_fp8_contiguous", + quant_info_cls=MoeLoraFp8QuantInfo, + gate_first=True, + interleaved=False, + gate_up_output_dtype=torch.bfloat16, + lora_delta_dtype=torch.bfloat16, + lora_activation_dtype=torch.bfloat16, + act_quant_group=128, + ) + + _config_dtype_tag = "fp8_w8a8" + + def __init__(self, quant_info: MoeLoraFp8QuantInfo): + super().__init__(quant_info) + self._config_block_shape = list(quant_info.block_shape) + + def _invoke_fp8( + self, + a: torch.Tensor, + b: torch.Tensor, + b_scale: torch.Tensor, + out: torch.Tensor, + row_state: TritonRowState, + *, + top_k: int, + config: dict, + a_scale: torch.Tensor | None = None, + ) -> None: + import triton.language as tl + + from sglang.kernels.ops.moe.fused_moe_triton_kernels import ( + invoke_fused_moe_kernel, + ) + + invoke_fused_moe_kernel( + a, + b, + None, + out, + # Pre-quantized activations carry their matching scales. + a_scale, + b_scale, + None, + self._unused_topk_weights, + row_state.topk_ids, + row_state.sorted_token_ids, + row_state.expert_ids, + row_state.num_tokens_post_padded, + False, + top_k, + config, + compute_type=tl.bfloat16, + use_fp8_w8a8=True, + use_int8_w8a8=False, + use_int8_w8a16=False, + use_int4_w4a16=False, + per_channel_quant=False, + block_shape=self._config_block_shape, + ) + + def gateup(self, row_state: TritonRowState, out: torch.Tensor) -> None: + self._invoke_fp8( + row_state.hidden_states, + self.quant_info.w13_weight, + self.quant_info.w13_scale, + out, + row_state, + top_k=row_state.top_k, + config=row_state.config, + ) + + def down( + self, + row_state: TritonRowState, + act_out: torch.Tensor, + out: torch.Tensor, + ) -> None: + a, a_scale = act_out, None + if row_state.act_quant is not None: + a, a_scale = row_state.act_quant + self._invoke_fp8( + a, + self.quant_info.w2_weight, + self.quant_info.w2_scale, + out, + row_state, + top_k=1, + config=row_state.down_config or row_state.config, + a_scale=a_scale, + ) diff --git a/python/sglang/srt/lora/moe/configs/README.md b/python/sglang/srt/lora/moe/configs/README.md new file mode 100644 index 0000000000..c53d8f600d --- /dev/null +++ b/python/sglang/srt/lora/moe/configs/README.md @@ -0,0 +1,56 @@ +# MoE LoRA execution plans + +`.plans.json` selects the base row layout and LoRA execution stages for +`lora_triton`, `lora_cutedsl` and `lora_marlin`. Supported capability majors +9 and 10 select `sm90` and `sm100`, respectively. Other architectures, +including SM120, are unsupported. A missing table uses `default.plans.json`. + +## Selection and overrides + +`SGLANG_LORA_MOE_CONFIG_DIR` supplies override files before packaged files. +Tables are process-cached; use a fresh server to evaluate an override. + +The file contains a tuned `domain`, ordered `scenarios`, and conservative +`fallback` rows. Scenario selection matches adapter layout, phase, pool rank, +resident expert count and quantization. Shapes outside the tuned domain use +fallback rows. Row names are labels, not selectors. + +Each row declares: + +- `base_gemm_rows`: `expert_major` or `route_major`; +- `plan`: A/B, activation and finalization families plus overlap and routing; +- `tiles`: ordered rank/token rules containing per-site launch configurations. + +Rank filters are applied before the first matching token bound is selected. +An unbounded token rule ends that rank's ladder. `{ "sites": {} }` or no +surviving rank rule uses launch defaults; a supplied site section must be +complete. Invalid keys, tiles or shadowed ladders fail at loading, even in an +unselected row. + +The plan determines which route views and buffers are consumed. Per-expert +adapters have factors for each resident expert; shared-outer adapters share +the gate/up A and down B factors across experts. Raw views retain token/expert +pairs. Aligned views bucket and pad pairs for grouped kernels. Shared-token +plans instead group one row per token. Route construction must not create +views the selected stages do not need. + +Runtime orchestration remains in `srt/lora`: MoE plans, runner and base-GEMM +providers under `srt/lora/moe`, the shared workspace in `srt/lora/workspace.py`. +Device kernels live in `kernels/ops/lora/common` for +shared routing/A/B operations and `kernels/ops/lora/moe` for MoE stages and +CuTeDSL kernels. Existing upstream LoRA registry and dense token kernels keep +their paths. + +## Tuning and evidence + +Search bounded launch tiles while retaining plan families and base-GEMM +configurations. Whole-runner fixture timings are not model TPS. Base-GEMM +tables have a separate schema and admission policy. + +New production rows need numerical checks, independent locked validation and +model-level target/control measurements on their exact device and affected +selector regions. Do not copy isolated kernel winners into broader rules or +treat aggregate gains as proof that every cell is regression-free. + +Historical exploration and measurements remain in Git history; private +campaign paths and retired tools are not part of the public tuning contract. diff --git a/python/sglang/srt/lora/moe/configs/base_gemm/README.md b/python/sglang/srt/lora/moe/configs/base_gemm/README.md new file mode 100644 index 0000000000..b48fe95bbe --- /dev/null +++ b/python/sglang/srt/lora/moe/configs/base_gemm/README.md @@ -0,0 +1,39 @@ +# MoE LoRA base-GEMM launch-config store + +M-bucketed JSON tables consumed by `gemm_config_store.load_config_table`. +One file per (provider, geometry, device); the provider key names the +weight dtype, so the file name carries no separate dtype field: + +``` +provider={cutedsl_bf16_masked|cutedsl_bf16_contiguous|cutedsl_fp8_masked|cutedsl_fp8_contiguous},E={E_local},N1={gate_up_slices*I},N2={H},K={H},device_name={NVIDIA_...}.json +``` + +Payload keys are `expected_m` buckets (nearest-M lookup); each bucket payload +carries `token_width`. The optional `tiles` list declares the tile set to +compile at attach — one `persistent_clusters` per `token_width`. The +optional `version` map (e.g. `{"cutedsl": "..."}`) records the package +release the table was tuned with. It is provenance, not a guarantee: with a +different installed release the table is still used (its tiles are compiled +and checked before use) and a warning names the table and both releases, +because the tile choices have not been re-validated on that release. + +When the pinned compiler release changes: + +1. List the tables whose recorded release differs (the startup warnings). +2. For each affected provider, geometry and device you can run, check the + numerics against the FP32 reference and compare the table with the + built-in heuristics on a representative serving shape. +3. Re-tune only where that evidence calls for it, and record the new release + in `version`. Keep a note of the scopes you could not test. + +Missing or malformed files use the provider's built-in heuristics. + +`SGLANG_LORA_MOE_CONFIG_DIR` names an override config root at load time; +tables are read from its `base_gemm/` subdirectory. + +The [maintained LoRA tuner](../../../../../../../benchmark/kernels/lora_moe/README.md) +currently searches LoRA launch tiles while retaining these base configurations. +It does not emit base-GEMM tables. The old partial-GEMM sweep is historical +screening evidence, not a complete-runner correctness or performance gate. +New tables need numerical checks and complete-runner validation on their exact +device/geometry; do not populate this directory from isolated stage timings. diff --git a/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=256,N1=1024,N2=2048,K=2048,device_name=NVIDIA_H200.json b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=256,N1=1024,N2=2048,K=2048,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000..7523359c61 --- /dev/null +++ b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=256,N1=1024,N2=2048,K=2048,device_name=NVIDIA_H200.json @@ -0,0 +1,34 @@ +{ + "version": { + "generated_on": "NVIDIA H200", + "cutedsl": "4.6.0" + }, + "buckets": { + "8": { + "token_width": 8 + }, + "16": { + "token_width": 32 + }, + "32": { + "token_width": 32 + }, + "48": { + "token_width": 64 + } + }, + "tiles": [ + { + "token_width": 8, + "persistent_clusters": 128 + }, + { + "token_width": 32, + "persistent_clusters": 128 + }, + { + "token_width": 64, + "persistent_clusters": 128 + } + ] +} diff --git a/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_B200.json b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_B200.json new file mode 100644 index 0000000000..562beb4140 --- /dev/null +++ b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_B200.json @@ -0,0 +1,41 @@ +{ + "version": { + "generated_on": "NVIDIA B200", + "cutedsl": "4.8.0" + }, + "buckets": { + "16": { + "token_width": 16 + }, + "24": { + "token_width": 32 + }, + "32": { + "token_width": 64 + }, + "64": { + "token_width": 64 + }, + "80": { + "token_width": 128 + } + }, + "tiles": [ + { + "token_width": 16, + "persistent_clusters": 148 + }, + { + "token_width": 32, + "persistent_clusters": 148 + }, + { + "token_width": 64, + "persistent_clusters": 148 + }, + { + "token_width": 128, + "persistent_clusters": 148 + } + ] +} diff --git a/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_H200.json b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000..0cb5861f31 --- /dev/null +++ b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_H200.json @@ -0,0 +1,31 @@ +{ + "version": { + "generated_on": "NVIDIA H200", + "cutedsl": "4.8.0" + }, + "buckets": { + "16": { + "token_width": 16 + }, + "32": { + "token_width": 32 + }, + "96": { + "token_width": 64 + } + }, + "tiles": [ + { + "token_width": 16, + "persistent_clusters": 132 + }, + { + "token_width": 32, + "persistent_clusters": 132 + }, + { + "token_width": 64, + "persistent_clusters": 128 + } + ] +} diff --git a/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=512,N1=256,N2=4096,K=4096,device_name=NVIDIA_B200.json b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=512,N1=256,N2=4096,K=4096,device_name=NVIDIA_B200.json new file mode 100644 index 0000000000..cff75547dd --- /dev/null +++ b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=512,N1=256,N2=4096,K=4096,device_name=NVIDIA_B200.json @@ -0,0 +1,31 @@ +{ + "version": { + "generated_on": "NVIDIA B200", + "cutedsl": "4.6.2" + }, + "buckets": { + "16": { + "token_width": 16 + }, + "32": { + "token_width": 32 + }, + "160": { + "token_width": 64 + } + }, + "tiles": [ + { + "token_width": 16, + "persistent_clusters": 148 + }, + { + "token_width": 32, + "persistent_clusters": 148 + }, + { + "token_width": 64, + "persistent_clusters": 128 + } + ] +} diff --git a/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=512,N1=256,N2=4096,K=4096,device_name=NVIDIA_H200.json b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=512,N1=256,N2=4096,K=4096,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000..0cb5861f31 --- /dev/null +++ b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=512,N1=256,N2=4096,K=4096,device_name=NVIDIA_H200.json @@ -0,0 +1,31 @@ +{ + "version": { + "generated_on": "NVIDIA H200", + "cutedsl": "4.8.0" + }, + "buckets": { + "16": { + "token_width": 16 + }, + "32": { + "token_width": 32 + }, + "96": { + "token_width": 64 + } + }, + "tiles": [ + { + "token_width": 16, + "persistent_clusters": 132 + }, + { + "token_width": 32, + "persistent_clusters": 132 + }, + { + "token_width": 64, + "persistent_clusters": 128 + } + ] +} diff --git a/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=512,N1=512,N2=4096,K=4096,device_name=NVIDIA_B200.json b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=512,N1=512,N2=4096,K=4096,device_name=NVIDIA_B200.json new file mode 100644 index 0000000000..4fd05d7502 --- /dev/null +++ b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=512,N1=512,N2=4096,K=4096,device_name=NVIDIA_B200.json @@ -0,0 +1,46 @@ +{ + "version": { + "generated_on": "NVIDIA B200", + "cutedsl": "4.6.2" + }, + "buckets": { + "8": { + "token_width": 8 + }, + "10": { + "token_width": 64 + }, + "64": { + "token_width": 64 + }, + "80": { + "token_width": 128 + }, + "128": { + "token_width": 128 + }, + "160": { + "token_width": 64 + }, + "192": { + "token_width": 64 + }, + "256": { + "token_width": 128 + } + }, + "tiles": [ + { + "token_width": 8, + "persistent_clusters": 128 + }, + { + "token_width": 64, + "persistent_clusters": 128 + }, + { + "token_width": 128, + "persistent_clusters": 128 + } + ] +} diff --git a/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=512,N1=512,N2=4096,K=4096,device_name=NVIDIA_GB300.json b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=512,N1=512,N2=4096,K=4096,device_name=NVIDIA_GB300.json new file mode 100644 index 0000000000..a235a2fae5 --- /dev/null +++ b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_contiguous,E=512,N1=512,N2=4096,K=4096,device_name=NVIDIA_GB300.json @@ -0,0 +1,34 @@ +{ + "version": { + "generated_on": "NVIDIA GB300", + "cutedsl": "4.6.2" + }, + "buckets": { + "8": { + "token_width": 8 + }, + "10": { + "token_width": 64 + }, + "64": { + "token_width": 64 + }, + "80": { + "token_width": 128 + } + }, + "tiles": [ + { + "token_width": 8, + "persistent_clusters": 128 + }, + { + "token_width": 64, + "persistent_clusters": 128 + }, + { + "token_width": 128, + "persistent_clusters": 152 + } + ] +} diff --git a/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_B200.json b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_B200.json new file mode 100644 index 0000000000..b4b1676c04 --- /dev/null +++ b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_B200.json @@ -0,0 +1,45 @@ +{ + "version": { + "generated_on": "NVIDIA B200", + "cutedsl": "4.6.2" + }, + "buckets": { + "2": { + "token_width": 8 + }, + "8": { + "token_width": 16 + }, + "32": { + "token_width": 32 + }, + "64": { + "token_width": 64 + }, + "128": { + "token_width": 128 + } + }, + "tiles": [ + { + "token_width": 8, + "persistent_clusters": 148 + }, + { + "token_width": 16, + "persistent_clusters": 148 + }, + { + "token_width": 32, + "persistent_clusters": 148 + }, + { + "token_width": 64, + "persistent_clusters": 148 + }, + { + "token_width": 128, + "persistent_clusters": 148 + } + ] +} diff --git a/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_GB300.json b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_GB300.json new file mode 100644 index 0000000000..7bba1683d4 --- /dev/null +++ b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_GB300.json @@ -0,0 +1,45 @@ +{ + "version": { + "generated_on": "NVIDIA GB300", + "cutedsl": "4.6.2" + }, + "buckets": { + "2": { + "token_width": 8 + }, + "8": { + "token_width": 16 + }, + "32": { + "token_width": 32 + }, + "64": { + "token_width": 64 + }, + "128": { + "token_width": 128 + } + }, + "tiles": [ + { + "token_width": 8, + "persistent_clusters": 152 + }, + { + "token_width": 16, + "persistent_clusters": 152 + }, + { + "token_width": 32, + "persistent_clusters": 152 + }, + { + "token_width": 64, + "persistent_clusters": 152 + }, + { + "token_width": 128, + "persistent_clusters": 152 + } + ] +} diff --git a/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_H200.json b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000..53e3874491 --- /dev/null +++ b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=256,N1=256,N2=2048,K=2048,device_name=NVIDIA_H200.json @@ -0,0 +1,38 @@ +{ + "version": { + "generated_on": "NVIDIA H200", + "cutedsl": "4.6.0" + }, + "buckets": { + "8": { + "token_width": 8 + }, + "16": { + "token_width": 16 + }, + "32": { + "token_width": 32 + }, + "96": { + "token_width": 64 + } + }, + "tiles": [ + { + "token_width": 8, + "persistent_clusters": 128 + }, + { + "token_width": 16, + "persistent_clusters": 128 + }, + { + "token_width": 32, + "persistent_clusters": 128 + }, + { + "token_width": 64, + "persistent_clusters": 128 + } + ] +} diff --git a/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=512,N1=256,N2=4096,K=4096,device_name=NVIDIA_B200.json b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=512,N1=256,N2=4096,K=4096,device_name=NVIDIA_B200.json new file mode 100644 index 0000000000..e45ff5d16d --- /dev/null +++ b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=512,N1=256,N2=4096,K=4096,device_name=NVIDIA_B200.json @@ -0,0 +1,41 @@ +{ + "version": { + "generated_on": "NVIDIA B200", + "cutedsl": "4.6.2" + }, + "buckets": { + "2": { + "token_width": 8 + }, + "8": { + "token_width": 16 + }, + "32": { + "token_width": 64 + }, + "64": { + "token_width": 64 + }, + "128": { + "token_width": 128 + } + }, + "tiles": [ + { + "token_width": 8, + "persistent_clusters": 148 + }, + { + "token_width": 16, + "persistent_clusters": 148 + }, + { + "token_width": 64, + "persistent_clusters": 148 + }, + { + "token_width": 128, + "persistent_clusters": 148 + } + ] +} diff --git a/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=512,N1=256,N2=4096,K=4096,device_name=NVIDIA_H200.json b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=512,N1=256,N2=4096,K=4096,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000..53e3874491 --- /dev/null +++ b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=512,N1=256,N2=4096,K=4096,device_name=NVIDIA_H200.json @@ -0,0 +1,38 @@ +{ + "version": { + "generated_on": "NVIDIA H200", + "cutedsl": "4.6.0" + }, + "buckets": { + "8": { + "token_width": 8 + }, + "16": { + "token_width": 16 + }, + "32": { + "token_width": 32 + }, + "96": { + "token_width": 64 + } + }, + "tiles": [ + { + "token_width": 8, + "persistent_clusters": 128 + }, + { + "token_width": 16, + "persistent_clusters": 128 + }, + { + "token_width": 32, + "persistent_clusters": 128 + }, + { + "token_width": 64, + "persistent_clusters": 128 + } + ] +} diff --git a/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=512,N1=512,N2=4096,K=4096,device_name=NVIDIA_GB300.json b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=512,N1=512,N2=4096,K=4096,device_name=NVIDIA_GB300.json new file mode 100644 index 0000000000..ee4eae0a75 --- /dev/null +++ b/python/sglang/srt/lora/moe/configs/base_gemm/provider=cutedsl_fp8_masked,E=512,N1=512,N2=4096,K=4096,device_name=NVIDIA_GB300.json @@ -0,0 +1,41 @@ +{ + "version": { + "generated_on": "NVIDIA GB300", + "cutedsl": "4.6.2" + }, + "buckets": { + "2": { + "token_width": 8 + }, + "8": { + "token_width": 16 + }, + "32": { + "token_width": 64 + }, + "64": { + "token_width": 64 + }, + "128": { + "token_width": 128 + } + }, + "tiles": [ + { + "token_width": 8, + "persistent_clusters": 152 + }, + { + "token_width": 16, + "persistent_clusters": 152 + }, + { + "token_width": 64, + "persistent_clusters": 152 + }, + { + "token_width": 128, + "persistent_clusters": 152 + } + ] +} diff --git a/python/sglang/srt/lora/moe/configs/default.plans.json b/python/sglang/srt/lora/moe/configs/default.plans.json new file mode 100644 index 0000000000..1d46205090 --- /dev/null +++ b/python/sglang/srt/lora/moe/configs/default.plans.json @@ -0,0 +1,101 @@ +{ + "domain": { + "max_hidden": 0, + "max_local_experts": 0 + }, + "scenarios": [], + "fallback": [ + { + "name": "fallback.decode.shared", + "layout": "shared", + "phase": "decode", + "base_gemm_rows": "expert_major", + "plan": { + "gate_up_a_family": "grouped", + "down_a_family": "grouped", + "gate_up_b_family": "grouped", + "act_family": "materialized", + "finalize_family": "shared_one_pass" + }, + "tiles": [ + { + "sites": { + "shared_one_pass": { + "BLOCK_SIZE_H": 128, + "num_stages": 3, + "num_warps": 4 + } + } + } + ] + }, + { + "name": "fallback.decode", + "phase": "decode", + "base_gemm_rows": "expert_major", + "plan": { + "gate_up_a_family": "grouped", + "down_a_family": "grouped", + "gate_up_b_family": "grouped", + "down_b_family": "grouped", + "act_family": "materialized", + "finalize_family": "materialized" + }, + "tiles": [ + { + "sites": {} + } + ] + }, + { + "name": "fallback.prefill.per_expert", + "layout": "per_expert", + "phase": "prefill", + "base_gemm_rows": "route_major", + "plan": { + "gate_up_a_family": "grouped", + "down_a_family": "grouped", + "down_b_family": "grouped", + "act_family": "b_activation", + "finalize_family": "materialized", + "down_b_into_base": true + }, + "tiles": [ + { + "sites": {} + } + ] + }, + { + "name": "fallback.prefill.shared", + "layout": "shared", + "phase": "prefill", + "base_gemm_rows": "route_major", + "plan": { + "gate_up_a_family": "token_grouped", + "down_a_family": "grouped", + "act_family": "b_activation", + "finalize_family": "shared_token_delta", + "route_builder": "parallel_shared_outer" + }, + "tiles": [ + { + "sites": { + "shared_token_delta": { + "reduce": { + "BLOCK_SIZE_T": 32, + "num_stages": 2, + "num_warps": 4 + }, + "tail": { + "BLOCK_SIZE_H": 128, + "num_stages": 3, + "num_warps": 4 + } + } + } + } + ] + } + ] +} diff --git a/python/sglang/srt/lora/moe/configs/sm100.plans.json b/python/sglang/srt/lora/moe/configs/sm100.plans.json new file mode 100644 index 0000000000..3eaa361b5a --- /dev/null +++ b/python/sglang/srt/lora/moe/configs/sm100.plans.json @@ -0,0 +1,974 @@ +{ + "domain": { + "max_hidden": 8192, + "max_local_experts": 512 + }, + "scenarios": [ + { + "name": "decode.per_expert", + "layout": "per_expert", + "phase": "decode", + "base_gemm_rows": "expert_major", + "plan": { + "gate_up_a_family": "grouped", + "down_a_family": "grouped", + "gate_up_b_family": "per_row", + "down_b_family": "per_row", + "act_family": "materialized", + "finalize_family": "materialized", + "gate_up_overlap": "gate_up_a_b", + "down_overlap": "down_a_b" + }, + "tiles": [ + { + "max_rank": 16, + "max_tokens": 4, + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 16, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_N": 256, + "GROUP_SIZE_M": 1, + "num_stages": 2, + "num_warps": 8 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 16, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 4, + "SPLIT_K": 8 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 4, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 16 + } + }, + { + "max_rank": 16, + "max_tokens": 16, + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 16, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_N": 256, + "GROUP_SIZE_M": 1, + "num_stages": 2, + "num_warps": 8 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 16, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 4, + "SPLIT_K": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 4, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 16 + } + }, + { + "max_rank": 16, + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 16, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_N": 256, + "GROUP_SIZE_M": 1, + "num_stages": 2, + "num_warps": 8 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 16, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 4, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 16 + } + }, + { + "max_tokens": 4, + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 16, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_N": 256, + "GROUP_SIZE_M": 1, + "num_stages": 2, + "num_warps": 8 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 16, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 4, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 16 + } + }, + { + "max_tokens": 16, + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 8 + }, + "down_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 1, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_N": 512, + "GROUP_SIZE_M": 4, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 16 + } + }, + { + "max_rank": 32, + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 8 + }, + "down_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 1, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_N": 512, + "GROUP_SIZE_M": 4, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 16 + } + }, + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 8 + }, + "down_b": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 256, + "GROUP_SIZE_M": 4, + "num_stages": 2, + "num_warps": 8 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_N": 256, + "GROUP_SIZE_M": 16, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 16 + } + } + ] + }, + { + "name": "prefill.per_expert", + "layout": "per_expert", + "phase": "prefill", + "base_gemm_rows": "route_major", + "plan": { + "gate_up_a_family": "grouped", + "down_a_family": "grouped", + "down_b_family": "grouped", + "act_family": "b_activation", + "finalize_family": "materialized" + }, + "tiles": [ + { + "max_rank": 8, + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 16, + "num_stages": 2, + "num_warps": 2 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 16, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 2 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 32 + } + }, + { + "max_rank": 16, + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 16, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 16, + "num_stages": 2, + "num_warps": 2 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 2 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 32 + } + }, + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 16, + "num_stages": 2, + "num_warps": 2 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 1 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 32 + } + } + ] + }, + { + "name": "decode.shared.fp8.e_ge512", + "layout": "shared", + "phase": "decode", + "min_local_experts": 512, + "quant": [ + "fp8" + ], + "base_gemm_rows": "expert_major", + "plan": { + "gate_up_a_family": "grouped", + "down_a_family": "grouped", + "act_family": "b_activation", + "finalize_family": "shared_one_pass", + "gate_up_overlap": "gate_up_a", + "down_overlap": "down_a", + "route_builder": "parallel_shared_outer" + }, + "tiles": [ + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 1, + "num_stages": 2, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 16, + "shared_one_pass": { + "BLOCK_SIZE_H": 128, + "num_stages": 3, + "num_warps": 4 + } + } + } + ] + }, + { + "name": "decode.shared.nvfp4", + "layout": "shared", + "phase": "decode", + "quant": [ + "nvfp4" + ], + "base_gemm_rows": "expert_major", + "plan": { + "gate_up_a_family": "token_dense", + "gate_up_b_family": "per_row", + "down_a_family": "per_row", + "act_family": "materialized", + "finalize_family": "shared_one_pass", + "gate_up_overlap": "gate_up_a_b", + "down_overlap": "down_a", + "route_builder": "standard" + }, + "tiles": [ + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 1, + "num_stages": 2, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 16, + "shared_one_pass": { + "BLOCK_SIZE_H": 128, + "num_stages": 2, + "num_warps": 4 + } + } + } + ] + }, + { + "name": "decode.shared", + "layout": "shared", + "phase": "decode", + "base_gemm_rows": "expert_major", + "plan": { + "gate_up_a_family": "grouped", + "down_a_family": "grouped", + "gate_up_b_family": "grouped", + "act_family": "materialized", + "finalize_family": "shared_one_pass", + "gate_up_overlap": "gate_up_a_b", + "down_overlap": "down_a", + "route_builder": "parallel_shared_outer" + }, + "tiles": [ + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 1, + "num_stages": 2, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 16, + "shared_one_pass": { + "BLOCK_SIZE_H": 128, + "num_stages": 3, + "num_warps": 4 + } + } + } + ] + }, + { + "name": "prefill.shared", + "layout": "shared", + "phase": "prefill", + "base_gemm_rows": "route_major", + "plan": { + "gate_up_a_family": "token_grouped", + "down_a_family": "grouped", + "act_family": "b_activation", + "finalize_family": "shared_token_delta", + "route_builder": "parallel_shared_outer" + }, + "tiles": [ + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_W": 128, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 256, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 2 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 32, + "shared_token_delta": { + "reduce": { + "BLOCK_SIZE_T": 32, + "num_stages": 2, + "num_warps": 4 + }, + "tail": { + "BLOCK_SIZE_H": 1024, + "num_stages": 2, + "num_warps": 8 + } + } + } + } + ] + } + ], + "fallback": [ + { + "name": "fallback.decode.shared", + "layout": "shared", + "phase": "decode", + "base_gemm_rows": "expert_major", + "plan": { + "gate_up_a_family": "grouped", + "down_a_family": "grouped", + "gate_up_b_family": "grouped", + "act_family": "materialized", + "finalize_family": "shared_one_pass", + "gate_up_overlap": "gate_up_a_b", + "down_overlap": "down_a", + "route_builder": "parallel_shared_outer" + }, + "tiles": [ + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 1, + "num_stages": 2, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 16, + "shared_one_pass": { + "BLOCK_SIZE_H": 128, + "num_stages": 3, + "num_warps": 4 + } + } + } + ] + }, + { + "name": "fallback.decode", + "phase": "decode", + "base_gemm_rows": "expert_major", + "plan": { + "gate_up_a_family": "per_row", + "down_a_family": "grouped", + "gate_up_b_family": "grouped", + "down_b_family": "grouped", + "act_family": "materialized", + "finalize_family": "materialized", + "down_overlap": "down_a_b", + "gate_up_overlap": "gate_up_a_b" + }, + "tiles": [ + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 1, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 16 + } + } + ] + }, + { + "name": "fallback.prefill.per_expert", + "layout": "per_expert", + "phase": "prefill", + "base_gemm_rows": "route_major", + "plan": { + "gate_up_a_family": "grouped", + "down_a_family": "grouped", + "down_b_family": "grouped", + "act_family": "b_activation", + "finalize_family": "materialized" + }, + "tiles": [ + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 32 + } + } + ] + }, + { + "name": "fallback.prefill.shared", + "layout": "shared", + "phase": "prefill", + "base_gemm_rows": "route_major", + "plan": { + "gate_up_a_family": "token_grouped", + "down_a_family": "grouped", + "act_family": "b_activation", + "finalize_family": "shared_token_delta", + "route_builder": "parallel_shared_outer" + }, + "tiles": [ + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 32, + "shared_token_delta": { + "reduce": { + "BLOCK_SIZE_T": 32, + "num_stages": 2, + "num_warps": 4 + }, + "tail": { + "BLOCK_SIZE_H": 1024, + "num_stages": 2, + "num_warps": 8 + } + } + } + } + ] + } + ] +} diff --git a/python/sglang/srt/lora/moe/configs/sm90.plans.json b/python/sglang/srt/lora/moe/configs/sm90.plans.json new file mode 100644 index 0000000000..c0a6ce5189 --- /dev/null +++ b/python/sglang/srt/lora/moe/configs/sm90.plans.json @@ -0,0 +1,634 @@ +{ + "domain": { + "max_hidden": 4096, + "max_local_experts": 512 + }, + "scenarios": [ + { + "name": "decode.per_expert", + "layout": "per_expert", + "phase": "decode", + "base_gemm_rows": "expert_major", + "plan": { + "gate_up_a_family": "grouped", + "down_a_family": "per_row", + "gate_up_b_family": "grouped", + "down_b_family": "grouped", + "act_family": "materialized", + "finalize_family": "materialized", + "gate_up_overlap": "gate_up_a_b", + "down_overlap": "down_a_b" + }, + "tiles": [ + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 16, + "num_stages": 2, + "num_warps": 8 + }, + "down_b": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 1, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 16 + } + } + ] + }, + { + "name": "prefill.per_expert.rank_le16", + "layout": "per_expert", + "phase": "prefill", + "base_gemm_rows": "route_major", + "plan": { + "gate_up_a_family": "grouped", + "down_a_family": "grouped", + "down_b_family": "grouped", + "act_family": "b_activation", + "finalize_family": "materialized", + "down_b_into_base": true, + "gate_up_overlap": "gate_up_a" + }, + "max_rank": 16, + "tiles": [ + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 16, + "num_stages": 2, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 16, + "GROUP_SIZE_M": 16, + "num_stages": 2, + "num_warps": 2 + }, + "down_b": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 1, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 2 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 32 + } + } + ] + }, + { + "name": "prefill.per_expert", + "layout": "per_expert", + "phase": "prefill", + "base_gemm_rows": "route_major", + "plan": { + "gate_up_a_family": "grouped", + "down_a_family": "grouped", + "down_b_family": "grouped", + "act_family": "b_activation", + "finalize_family": "materialized", + "down_b_into_base": true + }, + "tiles": [ + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_W": 256, + "GROUP_SIZE_M": 16, + "num_stages": 4, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 1, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 32 + } + } + ] + }, + { + "name": "decode.shared", + "layout": "shared", + "phase": "decode", + "base_gemm_rows": "expert_major", + "plan": { + "gate_up_a_family": "grouped", + "down_a_family": "grouped", + "gate_up_b_family": "grouped", + "act_family": "materialized", + "finalize_family": "shared_one_pass", + "gate_up_overlap": "gate_up_a_b", + "down_overlap": "down_a", + "route_builder": "parallel_shared_outer" + }, + "tiles": [ + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 1, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 256, + "GROUP_SIZE_M": 4, + "num_stages": 3, + "num_warps": 8 + }, + "routing_block_size": 16, + "shared_one_pass": { + "BLOCK_SIZE_H": 128, + "num_stages": 3, + "num_warps": 4 + } + } + } + ] + }, + { + "name": "prefill.shared.rank_le16", + "layout": "shared", + "phase": "prefill", + "max_rank": 16, + "base_gemm_rows": "route_major", + "plan": { + "gate_up_a_family": "token_grouped", + "down_a_family": "grouped", + "act_family": "b_activation", + "finalize_family": "shared_token_delta", + "gate_up_overlap": "gate_up_a" + }, + "tiles": [ + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_W": 128, + "GROUP_SIZE_M": 1, + "num_stages": 4, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 16, + "shared_token_delta": { + "reduce": { + "BLOCK_SIZE_T": 16, + "num_stages": 2, + "num_warps": 8 + }, + "tail": { + "BLOCK_SIZE_H": 1024, + "num_stages": 2, + "num_warps": 8 + } + } + } + } + ] + }, + { + "name": "prefill.shared", + "layout": "shared", + "phase": "prefill", + "base_gemm_rows": "route_major", + "plan": { + "gate_up_a_family": "token_grouped", + "down_a_family": "grouped", + "act_family": "b_activation", + "finalize_family": "shared_token_delta", + "route_builder": "parallel_shared_outer" + }, + "tiles": [ + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 1, + "num_stages": 4, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 64, + "shared_token_delta": { + "reduce": { + "BLOCK_SIZE_T": 16, + "num_stages": 2, + "num_warps": 8 + }, + "tail": { + "BLOCK_SIZE_H": 1024, + "num_stages": 2, + "num_warps": 8 + } + } + } + } + ] + } + ], + "fallback": [ + { + "name": "fallback.decode.shared", + "layout": "shared", + "phase": "decode", + "base_gemm_rows": "expert_major", + "plan": { + "gate_up_a_family": "grouped", + "down_a_family": "grouped", + "gate_up_b_family": "grouped", + "act_family": "materialized", + "finalize_family": "shared_one_pass", + "gate_up_overlap": "gate_up_a_b", + "down_overlap": "down_a", + "route_builder": "parallel_shared_outer" + }, + "tiles": [ + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 1, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 4 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 256, + "GROUP_SIZE_M": 4, + "num_stages": 3, + "num_warps": 8 + }, + "routing_block_size": 16, + "shared_one_pass": { + "BLOCK_SIZE_H": 128, + "num_stages": 3, + "num_warps": 4 + } + } + } + ] + }, + { + "name": "fallback.decode", + "phase": "decode", + "base_gemm_rows": "expert_major", + "plan": { + "gate_up_a_family": "grouped", + "down_a_family": "grouped", + "gate_up_b_family": "grouped", + "down_b_family": "grouped", + "act_family": "materialized", + "finalize_family": "materialized", + "down_overlap": "down_a_b", + "gate_up_overlap": "gate_up_a_b" + }, + "tiles": [ + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 4 + }, + "down_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 1, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 256, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "num_stages": 4, + "num_warps": 8 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 16 + } + } + ] + }, + { + "name": "fallback.prefill.per_expert", + "layout": "per_expert", + "phase": "prefill", + "base_gemm_rows": "route_major", + "plan": { + "gate_up_a_family": "grouped", + "down_a_family": "grouped", + "down_b_family": "grouped", + "act_family": "b_activation", + "finalize_family": "materialized", + "down_b_into_base": true + }, + "tiles": [ + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 8 + }, + "down_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 16, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 2 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 32 + } + } + ] + }, + { + "name": "fallback.prefill.shared", + "layout": "shared", + "phase": "prefill", + "base_gemm_rows": "route_major", + "plan": { + "gate_up_a_family": "token_grouped", + "down_a_family": "grouped", + "act_family": "b_activation", + "finalize_family": "shared_token_delta", + "route_builder": "parallel_shared_outer" + }, + "tiles": [ + { + "sites": { + "b_activation": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_W": 64, + "GROUP_SIZE_M": 8, + "num_stages": 3, + "num_warps": 8 + }, + "down_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "down_b": { + "BLOCK_SIZE_K": 16, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "gate_up_a": { + "BLOCK_SIZE_K": 64, + "BLOCK_SIZE_N": 16, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 2 + }, + "gate_up_b": { + "BLOCK_SIZE_K": 32, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 8, + "num_stages": 2, + "num_warps": 4 + }, + "routing_block_size": 32, + "shared_token_delta": { + "reduce": { + "BLOCK_SIZE_T": 32, + "num_stages": 2, + "num_warps": 4 + }, + "tail": { + "BLOCK_SIZE_H": 1024, + "num_stages": 2, + "num_warps": 8 + } + } + } + } + ] + } + ] +} diff --git a/python/sglang/srt/lora/moe/plan.py b/python/sglang/srt/lora/moe/plan.py new file mode 100644 index 0000000000..d8027cbf7b --- /dev/null +++ b/python/sglang/srt/lora/moe/plan.py @@ -0,0 +1,759 @@ +"""Select and validate MoE LoRA plans and their launch tiles.""" + +from __future__ import annotations + +import json +import logging +import os +from dataclasses import dataclass, field +from enum import Enum +from functools import cache +from typing import Any, Literal, Mapping + +import pydantic +from pydantic.dataclasses import dataclass as pydantic_dataclass + +from sglang.kernels.ops.lora.moe.activation import ActivationFn +from sglang.srt.lora.utils import Phase + +logger = logging.getLogger(__name__) + +_STRICT = pydantic.ConfigDict(strict=True, extra="forbid") + + +class Site(str, Enum): + GATE_UP = "gate_up" + DOWN = "down" + + +class BridgeLayout(str, Enum): + PAIR_MAJOR = "pair_major" + TOKEN_MAJOR = "token_major" + + +class RouteRequirement(str, Enum): + RAW_PER_EXPERT = "raw_per_expert" + RAW_SHARED_OUTER = "raw_shared_outer" + ALIGNED_PER_EXPERT = "aligned_per_expert" + ALIGNED_SHARED_OUTER = "aligned_shared_outer" + SHARED_TOKEN_PLAN = "shared_token_plan" + + +class RouteBuilderFamily(str, Enum): + STANDARD = "standard" + # Build the shared route on the workspace side stream. + PARALLEL_SHARED_OUTER = "parallel_shared_outer" + + +class AFamily(str, Enum): + GROUPED = "grouped" + PER_ROW = "per_row" + TOKEN_GROUPED = "token_grouped" + # Shared gate/up A writes one token-domain bridge plane per adapter slot. + TOKEN_DENSE = "token_dense" + + +class BFamily(str, Enum): + GROUPED = "grouped" + PER_ROW = "per_row" + + +class ActFamily(str, Enum): + MATERIALIZED = "materialized" + B_ACTIVATION = "b_activation" + + +class FinalizeFamily(str, Enum): + MATERIALIZED = "materialized" + # Reduce in rank space before expanding the shared B once per token. + SHARED_TOKEN_DELTA = "shared_token_delta" + # Fuse the rank reduction, B expansion, and base reduction. + SHARED_ONE_PASS = "shared_one_pass" + + +class GateUpOverlap(str, Enum): + NONE = "none" + GATE_UP_A = "gate_up_a" + GATE_UP_A_B = "gate_up_a_b" + + +class DownOverlap(str, Enum): + NONE = "none" + DOWN_A = "down_a" + DOWN_A_B = "down_a_b" + + +def _raw_requirement(is_shared_outer: bool) -> RouteRequirement: + if is_shared_outer: + return RouteRequirement.RAW_SHARED_OUTER + return RouteRequirement.RAW_PER_EXPERT + + +def _aligned_requirement(is_shared_outer: bool) -> RouteRequirement: + if is_shared_outer: + return RouteRequirement.ALIGNED_SHARED_OUTER + return RouteRequirement.ALIGNED_PER_EXPERT + + +def _check_down_bridge_layout(site: Site, layout: BridgeLayout) -> None: + if site is Site.DOWN and layout is BridgeLayout.TOKEN_MAJOR: + raise ValueError( + "the down bridge is inherently pair-major: each routed expert " + "produces a different activation" + ) + + +@pydantic_dataclass(frozen=True, slots=True, config=_STRICT) +class ASpec: + site: Site + family: AFamily + is_shared_outer: bool = False + output_layout: BridgeLayout = BridgeLayout.PAIR_MAJOR + + def __post_init__(self) -> None: + _check_down_bridge_layout(self.site, self.output_layout) + if self.family in (AFamily.GROUPED, AFamily.PER_ROW): + if self.output_layout is not BridgeLayout.PAIR_MAJOR: + raise ValueError(f"{self.family.value} A writes a pair-major bridge") + else: + if self.site is not Site.GATE_UP: + raise ValueError(f"{self.family.value} is a shared gate/up-A family") + if not self.is_shared_outer: + raise ValueError( + f"{self.family.value} requires shared-outer A ownership" + ) + if self.output_layout is not BridgeLayout.TOKEN_MAJOR: + raise ValueError(f"{self.family.value} writes a token-major bridge") + + def route_requirements(self) -> frozenset[RouteRequirement]: + if self.family in ( + AFamily.PER_ROW, + AFamily.TOKEN_DENSE, + ): + return frozenset((_raw_requirement(self.is_shared_outer),)) + if self.family is AFamily.TOKEN_GROUPED: + return frozenset((RouteRequirement.SHARED_TOKEN_PLAN,)) + return frozenset((_aligned_requirement(self.is_shared_outer),)) + + +@pydantic_dataclass(frozen=True, slots=True, config=_STRICT) +class BSpec: + site: Site + family: BFamily + is_shared_outer: bool = False + input_layout: BridgeLayout = BridgeLayout.PAIR_MAJOR + + def __post_init__(self) -> None: + _check_down_bridge_layout(self.site, self.input_layout) + + def route_requirements(self) -> frozenset[RouteRequirement]: + if self.family is BFamily.PER_ROW: + return frozenset((_raw_requirement(self.is_shared_outer),)) + return frozenset((_aligned_requirement(self.is_shared_outer),)) + + +@pydantic_dataclass(frozen=True, slots=True, config=_STRICT) +class ActSpec: + """B_ACTIVATION owns gate/up B and consumes the A bridge.""" + + family: ActFamily + activation: ActivationFn + + def route_requirements(self) -> frozenset[RouteRequirement]: + if self.family is not ActFamily.B_ACTIVATION: + return frozenset() + return frozenset((_aligned_requirement(False),)) + + +@pydantic_dataclass(frozen=True, slots=True, config=_STRICT) +class FinalizeSpec: + family: FinalizeFamily + is_shared_outer: bool = False + + def __post_init__(self) -> None: + if ( + self.family + in (FinalizeFamily.SHARED_TOKEN_DELTA, FinalizeFamily.SHARED_ONE_PASS) + and not self.is_shared_outer + ): + raise ValueError( + f"{self.family.value} requires shared-outer down-B ownership" + ) + + def route_requirements(self) -> frozenset[RouteRequirement]: + if self.family is FinalizeFamily.MATERIALIZED: + return frozenset() + if self.family is FinalizeFamily.SHARED_TOKEN_DELTA: + return frozenset( + ( + _raw_requirement(self.is_shared_outer), + RouteRequirement.SHARED_TOKEN_PLAN, + ) + ) + return frozenset((_raw_requirement(self.is_shared_outer),)) + + +@pydantic_dataclass(frozen=True, slots=True, kw_only=True, config=_STRICT) +class MoePlan: + gate_up_a: ASpec + gate_up_b: BSpec | None = None + act: ActSpec + down_a: ASpec + down_b: BSpec | None = None + finalize: FinalizeSpec + gate_up_overlap: GateUpOverlap = GateUpOverlap.NONE + down_overlap: DownOverlap = DownOverlap.NONE + down_b_into_base: bool = False + route_builder: RouteBuilderFamily = RouteBuilderFamily.STANDARD + + def __post_init__(self) -> None: + if self.gate_up_a.site is not Site.GATE_UP: + raise ValueError("gate_up_a must describe the gate/up site") + if self.gate_up_b is not None and self.gate_up_b.site is not Site.GATE_UP: + raise ValueError("gate_up_b must describe the gate/up site") + if self.down_a.site is not Site.DOWN: + raise ValueError("down_a must describe the down site") + if self.down_b is not None and self.down_b.site is not Site.DOWN: + raise ValueError("down_b must describe the down site") + + gate_up_b_consumed = self.act.family is ActFamily.B_ACTIVATION + if gate_up_b_consumed == (self.gate_up_b is not None): + raise ValueError( + "gate/up B must have exactly one owner: standalone gate_up_b or the act stage" + ) + down_b_consumed = self.finalize.family is not FinalizeFamily.MATERIALIZED + if down_b_consumed == (self.down_b is not None): + raise ValueError( + "down B must have exactly one owner: standalone down_b or finalize" + ) + + # Fused consumers inherit A's layout; standalone B must match it. + if ( + self.gate_up_b is not None + and self.gate_up_a.output_layout is not self.gate_up_b.input_layout + ): + raise ValueError( + "gate/up A output layout must match the gate/up B input layout" + ) + if ( + self.down_b is not None + and self.down_a.output_layout is not self.down_b.input_layout + ): + raise ValueError("down A output layout must match the down B input layout") + if self.gate_up_a.family is AFamily.TOKEN_DENSE and ( + self.gate_up_b is None or self.gate_up_b.family is not BFamily.PER_ROW + ): + raise ValueError( + "token_dense A writes one bridge plane per adapter slot; only a " + "standalone per_row gate/up B selects planes" + ) + + if self.gate_up_overlap is GateUpOverlap.GATE_UP_A_B and self.gate_up_b is None: + raise ValueError( + "gate/up-A+B overlap requires standalone gate/up B; the act stage owns it" + ) + if self.down_overlap is DownOverlap.DOWN_A_B and self.down_b is None: + raise ValueError( + f"{self.down_overlap.value} overlap requires standalone down B" + ) + + # In-place B must wait for the base down GEMM to finish writing. + if self.down_b_into_base and not ( + self.down_b is not None + and self.down_overlap in (DownOverlap.NONE, DownOverlap.DOWN_A) + ): + raise ValueError( + "down-B into-base requires a standalone down-B stage and no " + "late overlap window (it read-modify-writes the base down " + "output)" + ) + + def route_requirements(self) -> frozenset[RouteRequirement]: + requirements: set[RouteRequirement] = set() + for stage in ( + self.gate_up_a, + self.gate_up_b, + self.act, + self.down_a, + self.finalize, + ): + if stage is not None: + requirements.update(stage.route_requirements()) + if self.down_b is not None: + # The in-place B kernel replaces the selected family with aligned rows. + if self.down_b_into_base: + requirements.add(_aligned_requirement(self.down_b.is_shared_outer)) + else: + requirements.update(self.down_b.route_requirements()) + return frozenset(requirements) + + +def _a_default() -> dict[str, int]: + return { + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2, + } + + +def _b_default() -> dict[str, int]: + return { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2, + } + + +def _b_act_default() -> dict[str, int]: + return { + "BLOCK_SIZE_W": 64, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, + } + + +def _shared_token_delta_default() -> dict[str, dict[str, int]]: + return { + "reduce": {"BLOCK_SIZE_T": 32, "num_warps": 4, "num_stages": 2}, + "tail": {"BLOCK_SIZE_H": 128, "num_warps": 4, "num_stages": 3}, + } + + +def _shared_one_pass_default() -> dict[str, int]: + return {"BLOCK_SIZE_H": 128, "num_warps": 4, "num_stages": 3} + + +def _is_power_of_two(value: int) -> bool: + return value > 0 and value & (value - 1) == 0 + + +def _validate_flat_config( + name: str, config: Mapping[str, int], allowed: frozenset[str] +) -> None: + if not config: + raise ValueError(f"{name} must be a non-empty launch-config mapping") + unknown = set(config) - allowed + if unknown: + raise ValueError(f"{name} has unknown launch keys: {sorted(unknown)}") + required = allowed - {"GROUP_SIZE_M", "BLOCK_SIZE_M", "SPLIT_K"} + missing = required - set(config) + if missing: + raise ValueError(f"{name} is missing launch keys: {sorted(missing)}") + for key, value in config.items(): + if value <= 0: + raise ValueError(f"{name}.{key} must be positive") + if ( + key.startswith("BLOCK_SIZE_") or key in ("num_warps", "SPLIT_K") + ) and not _is_power_of_two(value): + raise ValueError(f"{name}.{key} must be a power of two") + + +_GEMM_LAUNCH_KEYS = frozenset( + ("BLOCK_SIZE_N", "BLOCK_SIZE_K", "GROUP_SIZE_M", "num_warps", "num_stages") +) + + +@pydantic_dataclass(frozen=True, slots=True, kw_only=True, config=_STRICT) +class MoeLoraLaunchConfig: + """Per-site Triton launch configs of one plan row.""" + + # Shared row tile for aligned LoRA kernels; independent of base-GEMM tiles. + routing_block_size: int = 16 + gate_up_a: dict[str, int] = field(default_factory=_a_default) + gate_up_b: dict[str, int] = field(default_factory=_b_default) + down_a: dict[str, int] = field(default_factory=_a_default) + down_b: dict[str, int] = field(default_factory=_b_default) + b_activation: dict[str, int] = field(default_factory=_b_act_default) + shared_token_delta: dict[str, dict[str, int]] = field( + default_factory=_shared_token_delta_default + ) + shared_one_pass: dict[str, int] = field(default_factory=_shared_one_pass_default) + + def __post_init__(self) -> None: + # tl.dot requires a power-of-two row tile of at least 16. + if ( + not _is_power_of_two(self.routing_block_size) + or self.routing_block_size < 16 + ): + raise ValueError("routing_block_size must be a power of two >= 16") + # MoE consumes the combined shrink output, so split-K is serial. + for name in ("gate_up_a", "down_a"): + _validate_flat_config( + name, getattr(self, name), _GEMM_LAUNCH_KEYS | {"SPLIT_K"} + ) + for name in ("gate_up_b", "down_b"): + _validate_flat_config( + name, getattr(self, name), _GEMM_LAUNCH_KEYS | {"BLOCK_SIZE_M"} + ) + _validate_flat_config( + "b_activation", + self.b_activation, + (_GEMM_LAUNCH_KEYS - {"BLOCK_SIZE_N"}) | {"BLOCK_SIZE_W"}, + ) + # Grouped B takes its row tile from the route, not its config section. + for name in ("gate_up_b", "down_b"): + declared = getattr(self, name).get("BLOCK_SIZE_M") + if declared is not None and int(declared) != self.routing_block_size: + raise ValueError( + f"{name} declares BLOCK_SIZE_M={declared}, but the aligned " + f"route uses routing_block_size={self.routing_block_size}" + ) + if set(self.shared_token_delta) != {"reduce", "tail"}: + raise ValueError( + "shared_token_delta must contain exactly 'reduce' and 'tail'" + ) + for name, tile_key in (("reduce", "BLOCK_SIZE_T"), ("tail", "BLOCK_SIZE_H")): + _validate_flat_config( + f"shared_token_delta.{name}", + self.shared_token_delta[name], + frozenset((tile_key, "num_warps", "num_stages")), + ) + _validate_flat_config( + "shared_one_pass", + self.shared_one_pass, + frozenset(("BLOCK_SIZE_H", "num_warps", "num_stages")), + ) + + def for_a(self, site: Site) -> Mapping[str, int]: + return self.gate_up_a if site is Site.GATE_UP else self.down_a + + def for_b(self, site: Site) -> Mapping[str, int]: + return self.gate_up_b if site is Site.GATE_UP else self.down_b + + def for_act(self, family: ActFamily) -> Mapping[str, int]: + if family is ActFamily.B_ACTIVATION: + return self.b_activation + raise ValueError(f"{family.value} has no fused-act launch config") + + +class TileTable: + """Launch configs of one bound plan row, picked per forward by token count.""" + + def __init__(self, rules: list[tuple[int, MoeLoraLaunchConfig]]) -> None: + self._rules = rules + + def config_for(self, num_tokens: int) -> MoeLoraLaunchConfig: + for bound, config in self._rules: + if num_tokens <= bound: + return config + return self._rules[-1][1] + + +def _validate_plan_launch_config(plan: MoePlan, config: MoeLoraLaunchConfig) -> None: + dot_sites = {} + for name, spec in (("gate_up_a", plan.gate_up_a), ("down_a", plan.down_a)): + if spec.family in (AFamily.GROUPED, AFamily.TOKEN_GROUPED): + dot_sites[name] = ("BLOCK_SIZE_N", "BLOCK_SIZE_K") + if ( + spec.family is AFamily.TOKEN_GROUPED + and getattr(config, name).get("SPLIT_K", 1) > 1 + ): + raise ValueError(f"{name} token_grouped does not provide split-K scratch") + for name, spec in (("gate_up_b", plan.gate_up_b), ("down_b", plan.down_b)): + if spec is not None and spec.family is BFamily.GROUPED: + dot_sites[name] = ("BLOCK_SIZE_N",) + if plan.act.family is ActFamily.B_ACTIVATION: + dot_sites["b_activation"] = ("BLOCK_SIZE_W", "BLOCK_SIZE_K") + if plan.down_b_into_base: + dot_sites["down_b"] = ("BLOCK_SIZE_N", "BLOCK_SIZE_K") + elif plan.finalize.family is FinalizeFamily.SHARED_TOKEN_DELTA: + dot_sites["down_b"] = ("BLOCK_SIZE_N",) + for name, tile_keys in sorted(dot_sites.items()): + tiles = getattr(config, name) + if "GROUP_SIZE_M" not in tiles: + raise ValueError(f"{name} requires GROUP_SIZE_M for its selected consumer") + for key in tile_keys: + if tiles[key] < 16: + raise ValueError( + f"{name}.{key} must be at least 16 for its selected consumer" + ) + + +class _PlanSpecModel(pydantic.BaseModel): + model_config = pydantic.ConfigDict(extra="forbid") + + gate_up_a_family: AFamily = AFamily.GROUPED + down_a_family: AFamily = AFamily.GROUPED + gate_up_b_family: BFamily = BFamily.GROUPED + down_b_family: BFamily = BFamily.GROUPED + act_family: ActFamily = ActFamily.MATERIALIZED + finalize_family: FinalizeFamily = FinalizeFamily.MATERIALIZED + gate_up_overlap: GateUpOverlap = GateUpOverlap.NONE + down_overlap: DownOverlap = DownOverlap.NONE + route_builder: RouteBuilderFamily = RouteBuilderFamily.STANDARD + down_b_into_base: bool = False + + +class _TileRuleModel(pydantic.BaseModel): + model_config = pydantic.ConfigDict(extra="forbid") + + max_rank: int | None = pydantic.Field(default=None, gt=0) + max_tokens: int | None = pydantic.Field(default=None, gt=0) + sites: dict[str, Any] = pydantic.Field(default_factory=dict) + + +class _PlanRowModel(pydantic.BaseModel): + model_config = pydantic.ConfigDict(extra="forbid") + + name: str + layout: Literal["per_expert", "shared"] | None = None + phase: Phase | None = None + max_rank: int | None = None + min_local_experts: int | None = None + max_local_experts: int | None = None + quant: list[str] | None = None + base_gemm_rows: Literal["expert_major", "route_major"] + plan: _PlanSpecModel + # Rank rules precede token buckets; an unbounded rule ends the ladder. + # Tiles are required. Use {"sites": {}} to select defaults explicitly. + tiles: list[_TileRuleModel] = pydantic.Field(min_length=1) + + +class _DomainModel(pydantic.BaseModel): + """Geometry covered by the tuned scenario rows.""" + + model_config = pydantic.ConfigDict(extra="forbid") + + max_hidden: int | None = None + max_local_experts: int | None = None + + def admits(self, *, hidden_size: int, num_local_experts: int) -> bool: + return (self.max_hidden is None or hidden_size <= self.max_hidden) and ( + self.max_local_experts is None + or num_local_experts <= self.max_local_experts + ) + + +class _PlansFileModel(pydantic.BaseModel): + model_config = pydantic.ConfigDict(extra="forbid") + + domain: _DomainModel = pydantic.Field(default_factory=_DomainModel) + scenarios: list[_PlanRowModel] = pydantic.Field(default_factory=list) + fallback: list[_PlanRowModel] + + +_CONFIG_DIR = os.path.join(os.path.dirname(__file__), "configs") + + +def _validate_tile_ladder(rules: list[_TileRuleModel]) -> None: + ranks = {1} | {rule.max_rank + 1 for rule in rules if rule.max_rank is not None} + reachable = set() + for rank in ranks: + previous = 0 + for index, rule in enumerate(rules): + if rule.max_rank is not None and rank > rule.max_rank: + continue + reachable.add(index) + if rule.max_tokens is None: + break + if rule.max_tokens <= previous: + raise ValueError(f"tile token bounds must increase for rank {rank}") + previous = rule.max_tokens + if len(reachable) != len(rules): + raise ValueError("tile rules must not be shadowed for every rank") + + +def _read_table(name: str) -> dict | None: + from sglang.srt.environ import envs + + override_dir = envs.SGLANG_LORA_MOE_CONFIG_DIR.get() + for directory in filter(None, (override_dir, _CONFIG_DIR)): + path = os.path.join(directory, name) + if os.path.isfile(path): + if directory == override_dir: + logger.info( + "MoE LoRA table %r loaded from override dir %s", name, directory + ) + with open(path) as handle: + return json.load(handle) + return None + + +@cache +def _load_plans(architecture: str) -> _PlansFileModel: + raw = _read_table(f"{architecture}.plans.json") + if raw is None: + logger.warning( + "no MoE LoRA plan table for architecture %s; serving the " + "conservative default plans", + architecture, + ) + raw = _read_table("default.plans.json") + if raw is None: + raise RuntimeError("MoE LoRA plan tables are missing from the package") + table = _PlansFileModel.model_validate(raw) + for row in (*table.scenarios, *table.fallback): + layouts = (row.layout,) if row.layout is not None else ("per_expert", "shared") + plans = [ + _build_plan( + row.plan, + activation=ActivationFn.SILU, + is_shared_outer=layout == "shared", + ) + for layout in layouts + ] + for rule in row.tiles: + config = MoeLoraLaunchConfig(**rule.sites) + for plan in plans: + _validate_plan_launch_config(plan, config) + _validate_tile_ladder(row.tiles) + return table + + +@dataclass(frozen=True, slots=True) +class SelectedPlan: + name: str + base_gemm_rows: str + plan: MoePlan + tiles: TileTable + + +def _tile_table(rules: list[_TileRuleModel], physical_rank: int) -> TileTable: + """Drop the rules the bound rank excludes; keep the token bounds for each forward.""" + resolved: list[tuple[int, MoeLoraLaunchConfig]] = [] + for rule in rules: + if rule.max_rank is not None and physical_rank > rule.max_rank: + continue + bound = rule.max_tokens if rule.max_tokens is not None else 1 << 30 + resolved.append((bound, MoeLoraLaunchConfig(**rule.sites))) + if rule.max_tokens is None: + break # An unbounded rule shadows all later rules. + if not resolved: + resolved.append((1 << 30, MoeLoraLaunchConfig())) + return TileTable(resolved) + + +def _build_plan( + spec: _PlanSpecModel, + *, + activation: ActivationFn, + is_shared_outer: bool, +) -> MoePlan: + gate_up_a_family = spec.gate_up_a_family + gate_up_layout = ( + BridgeLayout.TOKEN_MAJOR + if gate_up_a_family in (AFamily.TOKEN_GROUPED, AFamily.TOKEN_DENSE) + else BridgeLayout.PAIR_MAJOR + ) + act_family = spec.act_family + finalize_family = spec.finalize_family + consumes_gate_up_b = act_family is ActFamily.B_ACTIVATION + consumes_down_b = finalize_family is not FinalizeFamily.MATERIALIZED + plan = MoePlan( + gate_up_a=ASpec( + Site.GATE_UP, gate_up_a_family, is_shared_outer, gate_up_layout + ), + gate_up_b=( + None + if consumes_gate_up_b + else BSpec( + Site.GATE_UP, + spec.gate_up_b_family, + False, + gate_up_layout, + ) + ), + act=ActSpec(act_family, activation), + down_a=ASpec( + Site.DOWN, + spec.down_a_family, + False, + BridgeLayout.PAIR_MAJOR, + ), + down_b=( + None + if consumes_down_b + else BSpec( + Site.DOWN, + spec.down_b_family, + is_shared_outer, + BridgeLayout.PAIR_MAJOR, + ) + ), + finalize=FinalizeSpec( + finalize_family, is_shared_outer if consumes_down_b else False + ), + gate_up_overlap=spec.gate_up_overlap, + down_overlap=spec.down_overlap, + route_builder=spec.route_builder, + down_b_into_base=spec.down_b_into_base, + ) + return plan + + +@cache +def _warn_out_of_domain( + architecture: str, hidden_size: int, num_local_experts: int +) -> None: + logger.warning( + "MoE LoRA geometry (hidden=%d, local_experts=%d) is outside the tuned " + "domain of table %r; serving the fallback rows", + hidden_size, + num_local_experts, + architecture, + ) + + +def resolve_plans( + *, + architecture: str, + is_shared_outer: bool, + physical_rank: int, + activation: ActivationFn, + hidden_size: int, + num_local_experts: int, + quant_family: str, +) -> dict[Phase, SelectedPlan]: + table = _load_plans(architecture) + layout_name = "shared" if is_shared_outer else "per_expert" + in_domain = table.domain.admits( + hidden_size=hidden_size, num_local_experts=num_local_experts + ) + rows = table.scenarios if in_domain else [] + if not in_domain: + _warn_out_of_domain(architecture, hidden_size, num_local_experts) + selected: dict[Phase, SelectedPlan] = {} + for phase in Phase: + # Earlier rows take precedence, including wildcard rows. + row = next( + ( + candidate + for candidate in (*rows, *table.fallback) + if candidate.layout in (None, layout_name) + and candidate.phase in (None, phase) + and (candidate.max_rank is None or physical_rank <= candidate.max_rank) + and ( + candidate.min_local_experts is None + or num_local_experts >= candidate.min_local_experts + ) + and ( + candidate.max_local_experts is None + or num_local_experts <= candidate.max_local_experts + ) + and (candidate.quant is None or quant_family in candidate.quant) + ), + None, + ) + if row is None: + raise RuntimeError( + f"no MoE LoRA plan row matches ({layout_name}, {phase.value}) " + f"on {architecture}" + ) + selected[phase] = SelectedPlan( + name=row.name, + base_gemm_rows=row.base_gemm_rows, + plan=_build_plan( + row.plan, + activation=activation, + is_shared_outer=is_shared_outer, + ), + tiles=_tile_table(row.tiles, physical_rank), + ) + return selected diff --git a/python/sglang/srt/lora/moe/quant_info.py b/python/sglang/srt/lora/moe/quant_info.py new file mode 100644 index 0000000000..d9636d81be --- /dev/null +++ b/python/sglang/srt/lora/moe/quant_info.py @@ -0,0 +1,135 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import msgspec +import torch + +if TYPE_CHECKING: + from sglang.srt.layers.moe.fused_moe_triton.layer import FusedMoE + + +class MoeLoraBf16QuantInfo(msgspec.Struct, kw_only=True): + """W13: [E, S*I, H], gate first when S=2. W2: [E, H, I].""" + + w13_weight: torch.Tensor + w2_weight: torch.Tensor + num_local_experts: int + intermediate_size: int + hidden_size: int + + @classmethod + def from_layer(cls, base_layer: FusedMoE) -> MoeLoraBf16QuantInfo: + return cls( + w13_weight=base_layer.w13_weight, + w2_weight=base_layer.w2_weight, + num_local_experts=int(base_layer.num_local_experts), + intermediate_size=int(base_layer.w2_weight.shape[2]), + hidden_size=int(base_layer.w2_weight.shape[1]), + ) + + +class MoeLoraFp8QuantInfo(msgspec.Struct, kw_only=True): + """FP8 weights in standard layout, with FP32 inverse block scales.""" + + w13_weight: torch.Tensor # [E_local, S * I, H] float8_e4m3fn + w13_scale: torch.Tensor # [E_local, ceil(S*I/block_n), ceil(H/block_k)] + w2_weight: torch.Tensor # [E_local, H, I] float8_e4m3fn + w2_scale: torch.Tensor # [E_local, ceil(H/block_n), ceil(I/block_k)] + block_shape: tuple[int, int] + num_local_experts: int + intermediate_size: int + hidden_size: int + + @classmethod + def from_layer(cls, base_layer: FusedMoE) -> MoeLoraFp8QuantInfo: + quant_info = cls( + w13_weight=base_layer.w13_weight, + w13_scale=base_layer.w13_weight_scale_inv, + w2_weight=base_layer.w2_weight, + w2_scale=base_layer.w2_weight_scale_inv, + block_shape=tuple(base_layer.quant_method.weight_block_size), + num_local_experts=int(base_layer.num_local_experts), + intermediate_size=int(base_layer.w2_weight.shape[2]), + hidden_size=int(base_layer.w2_weight.shape[1]), + ) + _admit_fp8_block_weights(quant_info) + return quant_info + + +def _admit_fp8_block_weights(quant_info: MoeLoraFp8QuantInfo) -> None: + """Validate 128x128 weight blocks and scales once when binding weights.""" + if tuple(quant_info.block_shape) != (128, 128): + raise NotImplementedError( + f"MoE LoRA FP8 supports [128, 128] weight blocks, got " + f"{list(quant_info.block_shape)}" + ) + for name, value in ( + ("hidden_size", quant_info.hidden_size), + ("intermediate_size", quant_info.intermediate_size), + ): + if value % 128: + raise NotImplementedError( + f"MoE LoRA FP8 requires {name} % 128 == 0, got {value}" + ) + for name, scale, rows, cols in ( + ( + "w13_scale", + quant_info.w13_scale, + quant_info.w13_weight.shape[1], + quant_info.hidden_size, + ), + ( + "w2_scale", + quant_info.w2_scale, + quant_info.hidden_size, + quant_info.intermediate_size, + ), + ): + expected = (quant_info.num_local_experts, -(-rows // 128), -(-cols // 128)) + if scale.dtype != torch.float32 or tuple(scale.shape) != expected: + raise ValueError( + f"{name} must be fp32 {list(expected)}, got {scale.dtype} " + f"{tuple(scale.shape)}" + ) + + +# Marlin's packed weights do not use the standard row-domain layout. +StandardLayoutQuantInfo = MoeLoraBf16QuantInfo | MoeLoraFp8QuantInfo + + +class MoeLoraNvFp4MarlinQuantInfo(msgspec.Struct, kw_only=True): + """Prepared Marlin W4A16 for BF16 activations and global scales.""" + + w13_qweight: torch.Tensor + w2_qweight: torch.Tensor + w13_scales: torch.Tensor + w2_scales: torch.Tensor + w13_global_scale: torch.Tensor + w2_global_scale: torch.Tensor + num_local_experts: int + intermediate_size: int + hidden_size: int + gate_up_slices: int + + @classmethod + def from_layer(cls, base_layer: FusedMoE) -> MoeLoraNvFp4MarlinQuantInfo: + if base_layer.params_dtype != torch.bfloat16: + raise NotImplementedError("NVFP4 MoE LoRA requires BF16 activations.") + for name in ("w13_weight", "w2_weight"): + if getattr(base_layer, name).dtype != torch.int32: + raise ValueError( + f"NVFP4 MoE LoRA requires already-prepared Marlin {name}." + ) + return cls( + w13_qweight=base_layer.w13_weight, + w2_qweight=base_layer.w2_weight, + w13_scales=base_layer.w13_weight_scale, + w2_scales=base_layer.w2_weight_scale, + w13_global_scale=base_layer.w13_weight_scale_2, + w2_global_scale=base_layer.w2_weight_scale_2, + num_local_experts=int(base_layer.num_local_experts), + intermediate_size=int(base_layer.intermediate_size_per_partition), + hidden_size=int(base_layer.hidden_size), + gate_up_slices=2 if base_layer.moe_runner_config.is_gated else 1, + ) diff --git a/python/sglang/srt/lora/moe/routing.py b/python/sglang/srt/lora/moe/routing.py new file mode 100644 index 0000000000..12190eccfc --- /dev/null +++ b/python/sglang/srt/lora/moe/routing.py @@ -0,0 +1,132 @@ +"""Build the route views required by a MoE LoRA plan.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import torch + +from sglang.kernels.ops.lora.common.route_view import RouteView, RouteViewKind +from sglang.kernels.ops.lora.common.routing import build_route +from sglang.srt.lora.moe.plan import ( + MoePlan, + RouteBuilderFamily, + RouteRequirement, +) +from sglang.srt.lora.workspace import LoraWorkspace + + +@dataclass(frozen=True, slots=True) +class MoeLoraRoutes: + raw_per_expert: RouteView | None = None + raw_shared_outer: RouteView | None = None + aligned_per_expert: RouteView | None = None + aligned_shared_outer: RouteView | None = None + shared_token: RouteView | None = None + + def raw(self, is_shared_outer: bool) -> RouteView: + if is_shared_outer: + return self._require(self.raw_shared_outer, "raw_shared_outer") + return self._require(self.raw_per_expert, "raw_per_expert") + + def aligned(self, is_shared_outer: bool) -> RouteView: + if is_shared_outer: + return self._require(self.aligned_shared_outer, "aligned_shared_outer") + return self._require(self.aligned_per_expert, "aligned_per_expert") + + @staticmethod + def _require(route: RouteView | None, field: str) -> RouteView: + if route is None: + raise ValueError(f"the execution plan did not request {field}") + return route + + +def build_moe_routes( + plan: MoePlan, + *, + topk_ids: torch.Tensor, + token_lora_mapping: torch.Tensor, + num_local_experts: int, + max_loras: int, + block_size: int, + workspace: LoraWorkspace, +) -> MoeLoraRoutes: + requirements = plan.route_requirements() + values: dict[str, RouteView] = {} + if RouteRequirement.RAW_PER_EXPERT in requirements: + values["raw_per_expert"] = build_route( + token_lora_mapping, + group_ids=topk_ids, + groups_per_slot=num_local_experts, + max_loras=max_loras, + block_size=block_size, + view=RouteViewKind.RAW, + ) + if RouteRequirement.RAW_SHARED_OUTER in requirements: + values["raw_shared_outer"] = build_route( + token_lora_mapping, + group_ids=topk_ids, + groups_per_slot=1, + max_loras=max_loras, + block_size=block_size, + view=RouteViewKind.RAW, + ) + + def _build_per_expert() -> RouteView: + return build_route( + token_lora_mapping, + group_ids=topk_ids, + groups_per_slot=num_local_experts, + max_loras=max_loras, + block_size=block_size, + view=RouteViewKind.ALIGNED, + workspace=workspace, + tensor_prefix="route:aligned_per_expert", + ) + + def _build_shared() -> None: + values["aligned_shared_outer"] = build_route( + token_lora_mapping, + group_ids=topk_ids, + groups_per_slot=1, + max_loras=max_loras, + block_size=block_size, + view=RouteViewKind.ALIGNED, + workspace=workspace, + tensor_prefix="route:aligned_shared_outer", + ) + + if ( + plan.route_builder is RouteBuilderFamily.PARALLEL_SHARED_OUTER + and RouteRequirement.ALIGNED_PER_EXPERT in requirements + and RouteRequirement.ALIGNED_SHARED_OUTER in requirements + ): + values["aligned_per_expert"] = workspace.run_parallel( + name="route:parallel", + device=topk_ids.device, + compute=_build_per_expert, + side=_build_shared, + ) + else: + if RouteRequirement.ALIGNED_PER_EXPERT in requirements: + values["aligned_per_expert"] = _build_per_expert() + if RouteRequirement.ALIGNED_SHARED_OUTER in requirements: + _build_shared() + + if RouteRequirement.SHARED_TOKEN_PLAN in requirements: + + def build_token_route(): + # Shared experts use one row per token, grouped by adapter slot. + return build_route( + token_lora_mapping, + max_loras=max_loras, + block_size=block_size, + view=RouteViewKind.ALIGNED, + workspace=workspace, + tensor_prefix=f"route:shared_token:sorted:{block_size}", + ) + + values["shared_token"] = workspace.route( + token_lora_mapping, ("sorted", block_size, max_loras), build_token_route + ) + return MoeLoraRoutes(**values) diff --git a/python/sglang/srt/lora/moe/runner.py b/python/sglang/srt/lora/moe/runner.py new file mode 100644 index 0000000000..8bc87ba441 --- /dev/null +++ b/python/sglang/srt/lora/moe/runner.py @@ -0,0 +1,856 @@ +"""Execute a bound MoE LoRA plan; base-only tokens use adapter slot -1.""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass +from typing import TYPE_CHECKING + +import msgspec +import torch +import triton + +from sglang.kernels.ops.lora.common.lora_a import ( + grouped_lora_a, + per_row_lora_a, + shrink_column_tiles, +) +from sglang.kernels.ops.lora.moe.activation import ActivationFn +from sglang.kernels.ops.lora.moe.lora_b import invoke_down_b_into_base, run_lora_b +from sglang.srt.layers.moe.utils import get_moe_runner_backend +from sglang.srt.lora.moe.base_gemm_provider import select_provider_cls +from sglang.srt.lora.moe.base_gemm_provider.base import ( + MoeBaseProvider, +) +from sglang.srt.lora.moe.plan import ( + ActFamily, + AFamily, + ASpec, + BFamily, + BridgeLayout, + BSpec, + DownOverlap, + FinalizeFamily, + GateUpOverlap, + MoeLoraLaunchConfig, + MoePlan, + SelectedPlan, + Site, + resolve_plans, +) +from sglang.srt.lora.moe.routing import MoeLoraRoutes, build_moe_routes +from sglang.srt.lora.utils import Phase, architecture_for_capability +from sglang.srt.lora.workspace import LoraWorkspace + +if TYPE_CHECKING: + from sglang.srt.layers.moe.fused_moe_triton.layer import FusedMoE + from sglang.srt.layers.moe.token_dispatcher.standard import ( + StandardCombineInput, + StandardDispatchOutput, + ) + + +@dataclass(slots=True) +class _LoraStageState: + rank: torch.Tensor | None = None + delta: torch.Tensor | None = None + + +class MoeLoraBatch(msgspec.Struct, kw_only=True): + gate_up_lora_a: torch.Tensor # [L_cap, E_f, slices*R_phys, H] + gate_up_lora_b: torch.Tensor # [L_cap, E_local, slices*I, R_phys] + down_lora_a: torch.Tensor # [L_cap, E_local, R_phys, I] + down_lora_b: torch.Tensor # [L_cap, E_f_down, H, R_phys] + token_lora_mapping: torch.Tensor # [T] int, adapter slot per token (-1 = base) + use_cuda_graph: bool = False # Graph-stable storage for either graph family. + is_prefill: bool = False # MoE plan phase; target verification uses decode. + + @property + def max_loras(self) -> int: + return self.gate_up_lora_a.shape[0] + + +class MoeLoraRunner: + def __init__( + self, + *, + providers: Mapping[str, MoeBaseProvider], + top_k: int, + routed_scaling_factor: float | None, + activation: ActivationFn = ActivationFn.SILU, + is_gated: bool = True, + workspace: LoraWorkspace | None = None, + ) -> None: + if not providers: + raise ValueError("a MoE LoRA runner needs at least one provider") + self.providers = dict(providers) + geometries = { + ( + provider.hidden_size, + provider.intermediate_size, + provider.num_local_experts, + provider.gate_up_slices, + provider.contract.lora_delta_dtype, + ) + for provider in self.providers.values() + } + if len(geometries) != 1: + raise ValueError("providers of one layer must share resident geometry") + ( + self.hidden_size, + self.intermediate_size, + self.num_local_experts, + self.gate_up_slices, + self.lora_delta_dtype, + ) = next(iter(geometries)) + self.top_k = top_k + self.routed_scaling_factor = routed_scaling_factor + self.activation = activation + self.is_gated = is_gated + self.workspace = workspace if workspace is not None else LoraWorkspace() + self.plans: dict[Phase, SelectedPlan] = {} + + @classmethod + def from_layer( + cls, + base_layer: FusedMoE, + *, + workspace: LoraWorkspace | None = None, + is_shared_outer: bool, + physical_rank: int, + ) -> MoeLoraRunner: + family = cls._admit(base_layer) + weight_device = base_layer.w2_weight.device + if weight_device.type != "cuda": + raise NotImplementedError("MoE LoRA requires a CUDA layer") + major, _ = torch.cuda.get_device_capability(weight_device) + architecture = architecture_for_capability(major) + config = base_layer.moe_runner_config + activation = ActivationFn.parse(config.activation) + plans = resolve_plans( + architecture=architecture, + is_shared_outer=is_shared_outer, + physical_rank=physical_rank, + activation=activation, + hidden_size=int(base_layer.hidden_size), + num_local_experts=int(base_layer.num_local_experts), + quant_family=family, + ) + # Shared finalizers hold the rank reduction in one tile, tested up to 256. + if physical_rank > 256 and any( + sel.plan.finalize.family is not FinalizeFamily.MATERIALIZED + for sel in plans.values() + ): + raise ValueError( + f"the shared finalizes are capped at rank 256, got {physical_rank}" + ) + vendor = get_moe_runner_backend().value.removeprefix("lora_") + runner = cls( + providers={ + rows: cls._build_provider( + base_layer, base_gemm_rows=rows, vendor=vendor, family=family + ) + for rows in dict.fromkeys(sel.base_gemm_rows for sel in plans.values()) + }, + top_k=int(config.top_k), + routed_scaling_factor=config.routed_scaling_factor, + activation=activation, + is_gated=bool(config.is_gated), + workspace=workspace, + ) + for sel in plans.values(): + runner.validate_plan(sel.plan, base_gemm_rows=sel.base_gemm_rows) + runner.plans = dict(plans) + return runner + + @staticmethod + def _weight_family(base_layer: FusedMoE) -> str: + from sglang.srt.layers.quantization.unquant import UnquantizedFusedMoEMethod + + quant_method = base_layer.quant_method + if isinstance(quant_method, UnquantizedFusedMoEMethod): + if ( + base_layer.w13_weight.dtype != torch.bfloat16 + or base_layer.w2_weight.dtype != torch.bfloat16 + ): + raise NotImplementedError( + "MoE LoRA on an unquantized layer requires resident BF16 weights" + ) + return "bf16" + from sglang.srt.layers.quantization.fp8 import Fp8MoEMethod + + if isinstance(quant_method, Fp8MoEMethod): + if base_layer.params_dtype != torch.bfloat16: + raise NotImplementedError("FP8 MoE LoRA requires BF16 activations.") + if not quant_method.block_quant or getattr( + quant_method, "use_mxfp8", False + ): + raise NotImplementedError( + "MoE LoRA on FP8 requires 128-block weight quantization; " + "per-tensor and MXFP8 layers are unsupported" + ) + if base_layer.w13_weight.dtype != torch.float8_e4m3fn: + raise NotImplementedError( + "MoE LoRA on FP8 requires resident float8_e4m3fn weights; " + "a Marlin-repacked FP8 layer is unsupported" + ) + return "fp8" + from sglang.srt.layers.quantization.modelopt_quant import ( + ModelOptNvFp4FusedMoEMethod, + ) + + if isinstance(quant_method, ModelOptNvFp4FusedMoEMethod): + return "nvfp4" + raise NotImplementedError( + "MoE LoRA supports unquantized BF16, 128-block FP8, and NVFP4 " + f"MoE; this layer's quant method is {type(quant_method).__name__}" + ) + + @classmethod + def _admit(cls, base_layer: FusedMoE) -> str: + from sglang.srt.layers.moe.token_dispatcher.standard import StandardDispatcher + + family = cls._weight_family(base_layer) + if not isinstance(base_layer.dispatcher, StandardDispatcher): + raise NotImplementedError( + "MoE LoRA currently requires the Standard dispatcher" + ) + + major, minor = torch.cuda.get_device_capability() + if major not in (9, 10): + raise NotImplementedError( + f"MoE LoRA supports SM90 and SM100 only; this device is " + f"sm{major}{minor}. Its base GEMMs are WGMMA (SM90) and " + "tcgen05 (SM100) kernels, and no other architecture implements " + "either -- SM120 included, despite reporting a higher major." + ) + if base_layer.dispatcher.skip_local_expert_mapping: + raise NotImplementedError( + "MoE LoRA requires EP-local expert IDs at the runner " + "boundary, but this dispatcher keeps global IDs" + ) + if base_layer.should_fuse_routed_scaling_factor_in_topk: + raise NotImplementedError( + "MoE LoRA applies routed scaling exactly once in its own " + "finalize; this layer already folds it into the top-k weights. " + "Under a lora backend only ModelOpt NVFP4 does that, so those " + "experts need --moe-runner-backend lora_marlin" + ) + if getattr(base_layer, "with_bias", False): + raise NotImplementedError( + "MoE LoRA providers carry no expert biases; this layer has them" + ) + + config = base_layer.moe_runner_config + # Membership by value: `str in Enum` raises TypeError before Python 3.12. + supported_activation = config.activation in {fn.value for fn in ActivationFn} + if ( + not supported_activation + or config.gemm1_alpha is not None + or config.gemm1_clamp_limit is not None + or config.swiglu_limit is not None + or config.apply_router_weight_on_input + or config.no_combine + or config.num_fused_shared_experts + ): + raise NotImplementedError( + "MoE LoRA supports SiLU or ReLU2 (gated or not) without " + "fused shared experts, with route weighting owned by finalize" + ) + return family + + @staticmethod + def _build_provider( + base_layer: FusedMoE, + *, + base_gemm_rows: str, + vendor: str, + family: str, + ) -> MoeBaseProvider: + provider_cls = select_provider_cls(base_gemm_rows, family, vendor) + quant_info = provider_cls.contract.quant_info_cls.from_layer(base_layer) + return provider_cls(quant_info) + + def validate_plan(self, plan: MoePlan, *, base_gemm_rows: str) -> None: + provider = self.providers[base_gemm_rows] + if plan.act.activation is not self.activation: + raise ValueError( + f"plan activation {plan.act.activation.value} does not match " + f"resident layer activation {self.activation.value}" + ) + expected_slices = 2 if self.is_gated else 1 + if provider.gate_up_slices != expected_slices: + raise ValueError( + f"provider exposes {provider.gate_up_slices} gate/up slices " + f"but is_gated={self.is_gated} needs {expected_slices}" + ) + + def run( + self, + dispatch_output: StandardDispatchOutput, + batch: MoeLoraBatch, + ) -> StandardCombineInput: + from sglang.srt.layers.moe.token_dispatcher.standard import StandardCombineInput + from sglang.srt.layers.moe.topk import TopKOutputChecker + + phase = Phase.PREFILL if batch.is_prefill else Phase.DECODE + selected = self.plans[phase] + launch_config = selected.tiles.config_for( + dispatch_output.hidden_states.shape[0] + ) + + provider = self.providers[selected.base_gemm_rows] + hidden_states = dispatch_output.hidden_states + topk_output = dispatch_output.topk_output + assert TopKOutputChecker.format_is_standard(topk_output) + topk_ids = topk_output.topk_ids + + num_tokens = hidden_states.shape[0] + if ( + batch.token_lora_mapping.ndim != 1 + or batch.token_lora_mapping.shape[0] != num_tokens + ): + raise RuntimeError( + "MoE LoRA token/adapter assignment does not match the MoE " + f"token domain: mapping has {batch.token_lora_mapping.shape[0]} rows " + f"but the runner received {num_tokens}. Gather/remap " + "assignments before MoE-DP execution." + ) + + self.workspace.begin_forward( + graph_mode=batch.use_cuda_graph, is_prefill_graph=batch.is_prefill + ) + routes = build_moe_routes( + selected.plan, + topk_ids=topk_ids, + token_lora_mapping=batch.token_lora_mapping, + num_local_experts=self.num_local_experts, + max_loras=batch.max_loras, + block_size=launch_config.routing_block_size, + workspace=self.workspace, + ) + + gate_up, base_gemm_state, gateup_out = self._run_gate_up( + selected.plan, + launch_config, + provider, + routes, + hidden_states, + topk_ids, + batch, + num_tokens, + ) + act_out, down_a_input, down_a_gather = self._run_act( + selected.plan, + launch_config, + provider, + routes, + base_gemm_state, + gateup_out, + gate_up, + topk_ids, + batch, + num_tokens, + ) + output = self._allocate_output( + num_tokens=num_tokens, + dtype=hidden_states.dtype, + device=act_out.device, + ) + down_out, down_rank, down_delta = self._run_down( + selected.plan, + launch_config, + provider, + routes, + base_gemm_state, + act_out, + down_a_input, + down_a_gather, + batch, + ) + output = self._run_finalize( + selected.plan, + launch_config, + provider, + routes, + base_gemm_state, + output, + down_out, + down_rank, + down_delta, + topk_output, + batch, + num_tokens, + ) + return StandardCombineInput(hidden_states=output) + + def _run_a( + self, + launch_config: MoeLoraLaunchConfig, + spec: ASpec, + input: torch.Tensor, + weight: torch.Tensor, + routes: MoeLoraRoutes, + name: str, + *, + pair_to_row: torch.Tensor | None = None, + ) -> torch.Tensor: + if spec.family is AFamily.TOKEN_GROUPED: + route = routes.shared_token + if route is None: + raise ValueError("shared token route was not constructed") + elif spec.family in (AFamily.PER_ROW, AFamily.TOKEN_DENSE): + route = routes.raw(spec.is_shared_outer) + else: + route = routes.aligned(spec.is_shared_outer) + num_output_rows = ( + route.num_tokens + if spec.output_layout is BridgeLayout.TOKEN_MAJOR + else route.num_rows + ) + shape: tuple[int, ...] = (num_output_rows, weight.shape[1]) + if spec.family is AFamily.TOKEN_DENSE: + # One bridge plane per resident slot; per-row B indexes the planes. + shape = (route.max_loras, num_output_rows, weight.shape[1]) + output = self.workspace.tensor( + f"{name}:output", + shape, + dtype=self.lora_delta_dtype, + device=input.device, + ) + config = launch_config.for_a(spec.site) + pair_input = spec.site is Site.DOWN + match spec.family.value: + case "token_grouped": + grouped_lora_a(input, weight, output, route, config=config) + case "grouped": + partial = counters = None + split_k = int(config.get("SPLIT_K", 1)) + if split_k > 1: + # Serial split-K: the last arrival sums the FP32 planes and + # resets its counter for the next graph replay. + partial = self.workspace.tensor( + f"{name}:partial", + (split_k, num_output_rows, weight.shape[1]), + dtype=torch.float32, + device=input.device, + ) + tiles = ( + triton.cdiv(route.sorted_pair_ids.numel(), route.block_size) + * shrink_column_tiles( + int(config["BLOCK_SIZE_N"]), weight.shape[1], 1, False + )[1] + ) + counters = self.workspace.tensor( + f"{name}:splitk_counters", + (tiles,), + dtype=torch.int32, + device=input.device, + zero_on_first_allocation=True, + ) + grouped_lora_a( + input, + weight, + output, + route, + config=config, + pair_input=pair_input, + pair_to_row=pair_to_row, + partial=partial, + counters=counters, + ) + case "per_row": + per_row_lora_a( + input, weight, output, route, config=config, pair_input=pair_input + ) + case "token_dense": + torch.matmul( + input, + weight.transpose(1, 2), + out=output.view(weight.shape[0], input.shape[0], weight.shape[1]), + ) + case family: + raise NotImplementedError(f"no LoRA-A executor for {family!r}") + return output + + def _run_b( + self, + launch_config: MoeLoraLaunchConfig, + spec: BSpec, + bridge: torch.Tensor, + weight: torch.Tensor, + destination: torch.Tensor, + routes: MoeLoraRoutes, + *, + slot_planes: bool = False, + ) -> None: + route = ( + routes.raw(spec.is_shared_outer) + if spec.family is BFamily.PER_ROW + else routes.aligned(spec.is_shared_outer) + ) + config = launch_config.for_b(spec.site) + if spec.site is Site.GATE_UP: + width = weight.shape[1] // self.gate_up_slices + offsets = tuple(slice_id * width for slice_id in range(self.gate_up_slices)) + else: + offsets = (0,) + run_lora_b( + spec, + bridge=bridge, + weight=weight, + destination=destination, + routing=route, + destination_offsets=offsets, + config=config, + pair_bridge=spec.input_layout is BridgeLayout.PAIR_MAJOR, + slot_planes=slot_planes, + ) + + def _run_gate_up( + self, + plan: MoePlan, + launch_config: MoeLoraLaunchConfig, + provider: MoeBaseProvider, + routes: MoeLoraRoutes, + hidden_states: torch.Tensor, + topk_ids: torch.Tensor, + batch: MoeLoraBatch, + num_tokens: int, + ) -> tuple[_LoraStageState, object, torch.Tensor]: + state = _LoraStageState() + + def gate_up_a() -> None: + state.rank = self._run_a( + launch_config, + plan.gate_up_a, + hidden_states, + batch.gate_up_lora_a.flatten(0, 1), + routes, + "gate_up_a", + ) + + def gate_up_b() -> None: + delta = self.workspace.tensor( + "gate_up_b:delta", + ( + num_tokens * self.top_k, + self.gate_up_slices * self.intermediate_size, + ), + dtype=self.lora_delta_dtype, + device=state.rank.device, + ) + self._run_b( + launch_config, + plan.gate_up_b, + state.rank, + batch.gate_up_lora_b.flatten(0, 1), + delta, + routes, + slot_planes=plan.gate_up_a.family is AFamily.TOKEN_DENSE, + ) + state.delta = delta + + def base() -> tuple[object, torch.Tensor]: + base_gemm_state = provider.prepare( + hidden_states, + topk_ids, + self.top_k, + self.workspace, + ) + gateup_out = self.workspace.tensor( + "base:gateup", + provider.gateup_out_shape(base_gemm_state), + dtype=provider.contract.gate_up_output_dtype, + device=hidden_states.device, + ) + provider.gateup(base_gemm_state, gateup_out) + provider.release_prepared_inputs(base_gemm_state) + return base_gemm_state, gateup_out + + if plan.gate_up_overlap is GateUpOverlap.NONE: + gate_up_a() + if plan.gate_up_b is not None: + gate_up_b() + base_gemm_state, gateup = base() + elif plan.gate_up_overlap is GateUpOverlap.GATE_UP_A: + base_gemm_state, gateup = self.workspace.run_parallel( + name=plan.gate_up_overlap.value, + device=hidden_states.device, + compute=base, + side=gate_up_a, + ) + if plan.gate_up_b is not None: + gate_up_b() + else: + + def gate_up_a_b() -> None: + gate_up_a() + gate_up_b() + + base_gemm_state, gateup = self.workspace.run_parallel( + name=plan.gate_up_overlap.value, + device=hidden_states.device, + compute=base, + side=gate_up_a_b, + ) + return state, base_gemm_state, gateup + + def _run_act( + self, + plan: MoePlan, + launch_config: MoeLoraLaunchConfig, + provider: MoeBaseProvider, + routes: MoeLoraRoutes, + base_gemm_state, + gateup_out: torch.Tensor, + gate_up: _LoraStageState, + topk_ids: torch.Tensor, + batch: MoeLoraBatch, + num_tokens: int, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]: + act_out = self.workspace.tensor( + "act:masked", + provider.act_out_shape(base_gemm_state), + dtype=provider.contract.lora_activation_dtype, + device=gateup_out.device, + ) + provider_rows = act_out.view(-1, act_out.shape[-1]) + pair_to_row = base_gemm_state.pair_to_row + # Fused B+activation can feed grouped down-A through the provider's row map. + exposes_pair_activation = not ( + plan.act.family is ActFamily.B_ACTIVATION + and plan.down_a.family is AFamily.GROUPED + ) + act_pairs = ( + self.workspace.tensor( + "act:pairs", + (num_tokens, self.top_k, provider.intermediate_size), + dtype=provider.contract.lora_activation_dtype, + device=gateup_out.device, + ) + if exposes_pair_activation + else None + ) + if plan.act.family is ActFamily.MATERIALIZED: + quant_group = provider.contract.act_quant_group + act_quant = None + if quant_group is not None: + # Quantize during activation to avoid a separate down-GEMM input pass. + act_quant = ( + self.workspace.tensor( + "act:quant_rows", + act_out.shape, + dtype=torch.float8_e4m3fn, + device=gateup_out.device, + ), + self.workspace.tensor( + "act:quant_scales", + (act_out.shape[0], act_out.shape[1] // quant_group), + dtype=torch.float32, + device=gateup_out.device, + ), + ) + provider.act_with_delta( + base_gemm_state, + gateup_out, + gate_up.delta.view( + num_tokens, + self.top_k, + provider.gate_up_slices * provider.intermediate_size, + ), + topk_ids, + act_out, + act_pairs, + activation=self.activation.value, + **({"act_quant": act_quant} if act_quant is not None else {}), + ) + # Pair-major input needs no gather. + return act_out, act_pairs, None + + provider.fused_act( + base_gemm_state, + activation=self.activation.value, + base_gateup=gateup_out, + act_rows=act_out, + act_pairs=act_pairs, + routing=routes.aligned(False), + config=launch_config.for_act(plan.act.family), + bridge_gateup=gate_up.rank, + b_gate_up=batch.gate_up_lora_b.flatten(0, 1), + bridge_top_k=( + self.top_k + if plan.gate_up_a.output_layout is BridgeLayout.TOKEN_MAJOR + else 1 + ), + ) + if exposes_pair_activation: + return act_out, act_pairs, None + # Only provider-ordered input uses pair_to_row; pair-major input must not. + return act_out, provider_rows, pair_to_row + + def _run_down( + self, + plan: MoePlan, + launch_config: MoeLoraLaunchConfig, + provider: MoeBaseProvider, + routes: MoeLoraRoutes, + base_gemm_state, + act_out: torch.Tensor, + down_a_input: torch.Tensor, + down_a_gather: torch.Tensor | None, + batch: MoeLoraBatch, + ) -> tuple[ + torch.Tensor, + torch.Tensor, + torch.Tensor | None, + ]: + state = _LoraStageState() + + def down_a() -> None: + state.rank = self._run_a( + launch_config, + plan.down_a, + down_a_input.view(-1, self.intermediate_size), + batch.down_lora_a.flatten(0, 1), + routes, + "down_a", + pair_to_row=down_a_gather, + ) + + def down_b() -> None: + delta = self.workspace.tensor( + "down_b:delta", + (state.rank.shape[0], self.hidden_size), + dtype=self.lora_delta_dtype, + device=state.rank.device, + ) + self._run_b( + launch_config, + plan.down_b, + state.rank, + batch.down_lora_b.flatten(0, 1), + delta, + routes, + ) + state.delta = delta + + def down_b_into_base(down_out: torch.Tensor) -> None: + invoke_down_b_into_base( + down_rows=down_out.view(-1, provider.hidden_size), + pair_to_row=base_gemm_state.pair_to_row, + bridge=state.rank, + b_down=batch.down_lora_b.flatten(0, 1), + # In-place B requires aligned rows even when the selected family is raw. + routing=routes.aligned(plan.down_b.is_shared_outer), + config=launch_config.for_b(plan.down_b.site), + ) + + def base() -> torch.Tensor: + down_out = provider.down_output(base_gemm_state, self.workspace) + provider.down(base_gemm_state, act_out, down_out) + return down_out + + if plan.down_overlap is DownOverlap.NONE: + down_a() + if plan.down_b_into_base: + down_out = base() + down_b_into_base(down_out) + else: + if plan.down_b is not None: + down_b() + down_out = base() + elif plan.down_overlap is DownOverlap.DOWN_A: + down_out = self.workspace.run_parallel( + name=plan.down_overlap.value, + device=act_out.device, + compute=base, + side=down_a, + ) + if plan.down_b_into_base: + down_b_into_base(down_out) + elif plan.down_b is not None: + down_b() + else: + + def down_a_b() -> None: + down_a() + down_b() + + down_out = self.workspace.run_parallel( + name=plan.down_overlap.value, + device=act_out.device, + compute=base, + side=down_a_b, + ) + + return down_out, state.rank, state.delta + + def _allocate_output( + self, + *, + num_tokens: int, + dtype: torch.dtype, + device: torch.device, + ) -> torch.Tensor: + from sglang.srt.distributed.device_communicators.pynccl_allocator import ( + use_symmetric_memory, + ) + from sglang.srt.layers.dp_attention import is_allocation_symmetric + from sglang.srt.runtime_context import get_parallel + + with use_symmetric_memory( + get_parallel().tp_group, disabled=not is_allocation_symmetric() + ): + return torch.empty( + (num_tokens, self.hidden_size), + dtype=dtype, + device=device, + ) + + def _run_finalize( + self, + plan: MoePlan, + launch_config: MoeLoraLaunchConfig, + provider: MoeBaseProvider, + routes: MoeLoraRoutes, + base_gemm_state, + output: torch.Tensor, + down_out: torch.Tensor, + down_rank: torch.Tensor, + down_delta: torch.Tensor | None, + topk_output, + batch: MoeLoraBatch, + num_tokens: int, + ) -> torch.Tensor: + if plan.finalize.family is FinalizeFamily.MATERIALIZED: + provider.finalize( + base_gemm_state, + down_out, + topk_output.topk_ids, + topk_output.topk_weights, + self.routed_scaling_factor, + output, + lora_delta=( + None + if plan.down_b_into_base + else down_delta.view(num_tokens, self.top_k, self.hidden_size) + ), + ) + return output + + provider.shared_outer_finalize( + base_gemm_state, + down_rows=down_out, + bridge=down_rank, + b_down=batch.down_lora_b.flatten(0, 1), + routing=routes.raw(plan.finalize.is_shared_outer), + topk_weights=topk_output.topk_weights, + routed_scaling_factor=self.routed_scaling_factor, + output=output, + family=plan.finalize.family, + launch_config=launch_config, + workspace=self.workspace, + token_route=routes.shared_token, + ) + return output diff --git a/python/sglang/srt/lora/utils.py b/python/sglang/srt/lora/utils.py index 9d21463ee5..48bc29d6ec 100644 --- a/python/sglang/srt/lora/utils.py +++ b/python/sglang/srt/lora/utils.py @@ -78,7 +78,7 @@ class LoRABatchInfo: seg_lens: Optional[torch.Tensor] # The logical (re)ordering of input rows (tokens), in shape (num_tokens,) - permutation: Optional[torch.Tensor] + permutation: Optional[torch.Tensor] = None # Total number of tokens this batch info expects (host-side int). # Used by lm_head LoRA to validate input shape without GPU sync. @@ -88,6 +88,8 @@ class LoRABatchInfo: # Computed from Python lists in prepare_lora_batch to avoid GPU sync. has_active_lora: bool = False + is_prefill: bool = False + # Per-request segment indptrs, shape (bs + 1,). Required by MoE virtual # experts which map tokens to requests regardless of the dense-LoRA # backend's internal segmentation. For the triton backend these are @@ -107,6 +109,20 @@ class LoRAType(Enum): LORA_B = 1 +class Phase(str, Enum): + DECODE = "decode" + PREFILL = "prefill" + + +def architecture_for_capability(major: int) -> str: + """Plan-table name for compute capability major: sm90, sm100 (>= 10) or default.""" + if major == 9: + return "sm90" + if major >= 10: + return "sm100" + return "default" + + def copy_weight_into_buffer( buffer_view: torch.Tensor, weight: torch.Tensor, @@ -659,3 +675,23 @@ def build_lm_head_pass_segments( result.append((seg_wi, seg_lens)) return result + + +def capturing_lora_graph() -> bool: + """Whether capture is active, excluding the decode "nolora" variant.""" + from sglang.srt.model_executor.runner_utils.capture_mode import ( + get_capture_lora_variant, + get_is_capture_mode, + ) + + return get_is_capture_mode() and get_capture_lora_variant() != "nolora" + + +def kv_b_lora_correction(attn_module) -> str | None: + """Select legacy or capture-aware v2 correction, or None.""" + layer = getattr(attn_module, "kv_b_proj", None) + if not getattr(layer, "set_lora", False): + return None + if layer.lora_backend.name != "triton_v2": + return "legacy" + return "v2" if layer.lora_active else None diff --git a/python/sglang/srt/lora/workspace.py b/python/sglang/srt/lora/workspace.py new file mode 100644 index 0000000000..ec7e2a6d4a --- /dev/null +++ b/python/sglang/srt/lora/workspace.py @@ -0,0 +1,180 @@ +from __future__ import annotations + +from collections.abc import Callable, Sequence +from typing import TYPE_CHECKING, TypeVar + +import torch + +if TYPE_CHECKING: + from sglang.kernels.ops.lora.common.route_view import RouteView + +_raw_stream = getattr(torch._C, "_cuda_getCurrentRawStream", None) + + +_T = TypeVar("_T") + + +class LoraWorkspace: + """Reusable, stream-local scratch for LoRA runners. + + Warm up on the streams used during capture. Graph phases use separate + buffers; outgrown graph storage stays alive for existing captures. + """ + + def __init__(self) -> None: + self._graph_storage: dict[ + tuple[str, torch.dtype, torch.device, int, bool], torch.Tensor + ] = {} + self._retired: list[torch.Tensor] = [] + self._eager_buffers: dict[ + tuple[str, torch.dtype, torch.device, int], torch.Tensor + ] = {} + self._streams: dict[tuple[torch.device, int], torch.cuda.Stream] = {} + self._events: dict[tuple[torch.device, int, str], torch.cuda.Event] = {} + self._graph_mode = False + self._is_prefill_graph = False + self.routes: dict[tuple, dict[tuple, RouteView]] = {} + + def route( + self, mapping: torch.Tensor, key: tuple, build: Callable[[], RouteView] + ) -> RouteView: + stream = self._caller(mapping.device) if mapping.is_cuda else 0 + routes = self.routes.setdefault((mapping.device, stream), {}) + key = ( + self._graph_mode, + self._is_prefill_graph if self._graph_mode else False, + mapping.dtype, + mapping.data_ptr(), + mapping.numel(), + mapping.stride(), + *key, + ) + route = routes.get(key) + if route is None: + route = build() + routes[key] = route + return route + + def begin_forward( + self, *, graph_mode: bool, is_prefill_graph: bool = False + ) -> None: + self._graph_mode = bool(graph_mode) + self._is_prefill_graph = bool(is_prefill_graph) + + @staticmethod + def _capturing(device: torch.device) -> bool: + return device.type == "cuda" and torch.cuda.is_current_stream_capturing() + + def tensor( + self, + name: str, + shape: Sequence[int], + *, + dtype: torch.dtype, + device: torch.device | str, + zero_on_first_allocation: bool = False, + ) -> torch.Tensor: + # Per-forward clears belong to the caller so graphs replay them. + resolved_device = torch.device(device) + resolved_shape = tuple(int(dim) for dim in shape) + elements = 1 + for dimension in resolved_shape: + elements *= dimension + stream = self._caller(resolved_device) if resolved_device.type == "cuda" else 0 + key = (name, dtype, resolved_device, stream) + if self._graph_mode: + key = (*key, self._is_prefill_graph) + storage = self._graph_storage.get(key) + if storage is None or storage.numel() < elements: + if self._capturing(resolved_device): + raise RuntimeError( + "MoE LoRA workspace was not warmed before CUDA capture: " + f"missing {name!r} {resolved_shape} {dtype} on " + f"{resolved_device}" + ) + if storage is not None: + self._retired.append(storage) + factory = torch.zeros if zero_on_first_allocation else torch.empty + storage = factory((elements,), dtype=dtype, device=resolved_device) + self._graph_storage[key] = storage + tensor = storage[:elements].view(resolved_shape) + else: + storage = self._eager_buffers.get(key) + if storage is None or storage.numel() < elements: + if self._capturing(resolved_device): + raise RuntimeError( + "an eager MoE LoRA workspace cannot grow inside CUDA capture" + ) + factory = torch.zeros if zero_on_first_allocation else torch.empty + storage = factory((elements,), dtype=dtype, device=resolved_device) + self._eager_buffers[key] = storage + tensor = storage[:elements].view(resolved_shape) + return tensor + + @staticmethod + def _caller(device: torch.device) -> int: + # Read the raw handle without constructing a Python Stream wrapper. + if _raw_stream is not None and device.type == "cuda": + index = device.index + return _raw_stream( + index if index is not None else torch.cuda.current_device() + ) + return torch.cuda.current_stream(device).cuda_stream + + def side_stream(self, device: torch.device | str) -> torch.cuda.Stream: + resolved_device = torch.device(device) + caller = self._caller(resolved_device) + key = (resolved_device, caller) + stream = self._streams.get(key) + if stream is None: + # The stream pool can return the caller's stream, preventing overlap. + stream = torch.cuda.Stream(device=resolved_device) + while stream.cuda_stream == caller: + stream = torch.cuda.Stream(device=resolved_device) + self._streams[key] = stream + return stream + + def event(self, device: torch.device | str, name: str) -> torch.cuda.Event: + resolved_device = torch.device(device) + key = (resolved_device, self._caller(resolved_device), name) + event = self._events.get(key) + if event is None: + event = torch.cuda.Event() + self._events[key] = event + return event + + def run_parallel( + self, + *, + name: str, + device: torch.device, + compute: Callable[[], _T], + side: Callable[[], object], + ) -> _T: + if device.type != "cuda": + side() + return compute() + + current = torch.cuda.current_stream(device) + side_stream = self.side_stream(device) + ready = self.event(device, f"{name}:ready") + done = self.event(device, f"{name}:done") + + ready.record(current) + side_stream.wait_event(ready) + caller_routes = self.routes.setdefault( + (current.device, current.cuda_stream), {} + ) + side_routes = self.routes.setdefault( + (side_stream.device, side_stream.cuda_stream), {} + ) + # Routes become visible across streams at the existing event waits. + side_routes.update(caller_routes) + with torch.cuda.stream(side_stream): + side() + done.record(side_stream) + completed_routes = side_routes.copy() + result = compute() + current.wait_event(done) + caller_routes.update(completed_routes) + return result diff --git a/python/sglang/srt/model_executor/runner/__init__.py b/python/sglang/srt/model_executor/runner/__init__.py index 29d15f4471..7051b74b3d 100644 --- a/python/sglang/srt/model_executor/runner/__init__.py +++ b/python/sglang/srt/model_executor/runner/__init__.py @@ -47,7 +47,6 @@ from sglang.srt.model_executor.runner_utils.buffers import ( # noqa: F401 _grouped_foreach_copy_, ) from sglang.srt.model_executor.runner_utils.capture_mode import ( # noqa: F401 - _set_capture_lora_variant, compile_in_capture_mode, get_capture_lora_variant, get_is_capture_mode, diff --git a/python/sglang/srt/model_executor/runner/decode_cuda_graph_runner.py b/python/sglang/srt/model_executor/runner/decode_cuda_graph_runner.py index 889f69360e..b29db21af2 100644 --- a/python/sglang/srt/model_executor/runner/decode_cuda_graph_runner.py +++ b/python/sglang/srt/model_executor/runner/decode_cuda_graph_runner.py @@ -94,7 +94,7 @@ from sglang.srt.model_executor.runner_backend_utils import CUDA_GRAPH_CAPTURE_FA from sglang.srt.model_executor.runner_utils.buffers import DecodeInputBuffers from sglang.srt.model_executor.runner_utils.capture_mode import ( _set_capture_attention_variant, - _set_capture_lora_variant, + capture_lora_variant, model_capture_mode, ) from sglang.srt.model_executor.runner_utils.deepep_adapter import ( @@ -216,6 +216,11 @@ def build_replay_fb_view( ) +def _lora_backend_skips_inactive(model_runner) -> bool: + manager = model_runner.lora_manager + return manager is not None and manager.lora_backend.skip_inactive_dense_lora + + class DecodeCudaGraphRunner(BaseCudaGraphRunner): """Decode-phase CUDA graph runner. @@ -237,7 +242,10 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): record_nolora_graph: bool = False, ): super().__init__(model_runner) - self.record_nolora_graph = record_nolora_graph + # Inactive dense LoRA batches replay a separate base-only graph. + self.record_nolora_graph = record_nolora_graph or _lora_backend_skips_inactive( + model_runner + ) # In-graph metadata prep: shared buffers -> in-graph private data self.in_graph_metadata_prep_done: Optional[torch.cuda.Event] = None @@ -394,7 +402,7 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): # Phase 2 of LoRA CUDA graph init: dense LoRA batch metadata. # Phase 1 (MoE buffers) was handled earlier in ModelRunner via # lora_manager.init_cuda_graph_moe_buffers(). - self.model_runner.lora_manager.init_cuda_graph_batch_info( + self.model_runner.lora_manager.init_decode_cuda_graph_batch_info( max_bs_in_cuda_graph=self.max_bs, num_tokens_per_req=self.captured_req_width, ) @@ -1187,11 +1195,7 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): if get_parallel().tp_rank == 0 else reversed(self.capture_bs) ) - lora_variants = ( - [("lora", True), ("nolora", False)] - if self.record_nolora_graph - else [(None, None)] - ) + lora_variants = ("lora", "nolora") if self.record_nolora_graph else (None,) variants = self.attention_graph_variants for bs in capture_range: attention_variants = ( @@ -1207,26 +1211,26 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): f"Capturing batches ({bs=} {avail_mem=:.2f} GB)" ) - for variant_label, _variant_has_lora in lora_variants: - _set_capture_lora_variant(variant_label) - for attention_variant in attention_variants: - _set_capture_attention_variant(attention_variant) - self._set_profile_trace_tag( - bs, stream_idx, variant_label, attention_variant - ) - with torch_compile_decoration.patch_model( - self.model_runner.model, - bs in self.compile_bs, - num_tokens=bs * self.captured_req_width, - tp_group=get_parallel().tp_group, - ) as forward: - self.capture_one_shape( - bs, - forward, - stream_idx, - variant_label, - attention_variant, + for variant_label in lora_variants: + with capture_lora_variant(variant_label): + for attention_variant in attention_variants: + _set_capture_attention_variant(attention_variant) + self._set_profile_trace_tag( + bs, stream_idx, variant_label, attention_variant ) + with torch_compile_decoration.patch_model( + self.model_runner.model, + bs in self.compile_bs, + num_tokens=bs * self.captured_req_width, + tp_group=get_parallel().tp_group, + ) as forward: + self.capture_one_shape( + bs, + forward, + stream_idx, + variant_label, + attention_variant, + ) _set_capture_attention_variant(None) def capture_one_shape( @@ -1269,6 +1273,8 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): ForwardContext(attn_backend=attn_backend), forward_batch=forward_batch, ): + if forward_batch.lora_ids is not None: + self.model_runner.lora_manager.reset_routing_cache() # Backends may gather live pool mappings into their static # metadata here; these nodes run before any model KV reads. attn_backend.init_forward_metadata_in_graph(forward_batch) diff --git a/python/sglang/srt/model_executor/runner/prefill_cuda_graph_runner.py b/python/sglang/srt/model_executor/runner/prefill_cuda_graph_runner.py index ead3da2d6e..affdd79198 100644 --- a/python/sglang/srt/model_executor/runner/prefill_cuda_graph_runner.py +++ b/python/sglang/srt/model_executor/runner/prefill_cuda_graph_runner.py @@ -1785,6 +1785,8 @@ class PrefillCudaGraphRunner(BaseCudaGraphRunner): self._init_forward_metadata_for_capture(forward_batch, shape_key) def run_once(): + if forward_batch.lora_ids is not None: + self.model_runner.lora_manager.reset_routing_cache() # Record LoRA kernels even when capture uses base-model requests. with ( model_capture_mode() diff --git a/python/sglang/srt/model_executor/runner_utils/capture_mode.py b/python/sglang/srt/model_executor/runner_utils/capture_mode.py index ce4f08f1fb..0f2ec178c5 100644 --- a/python/sglang/srt/model_executor/runner_utils/capture_mode.py +++ b/python/sglang/srt/model_executor/runner_utils/capture_mode.py @@ -63,9 +63,19 @@ def get_capture_lora_variant() -> Optional[str]: return _capture_lora_variant -def _set_capture_lora_variant(variant: Optional[str]) -> None: +@contextmanager +def capture_lora_variant(variant: Optional[str]): + """Scope the "lora"/"nolora" label so later captures cannot inherit it. + + None denotes a single graph serving both variants. + """ global _capture_lora_variant + previous = _capture_lora_variant _capture_lora_variant = variant + try: + yield + finally: + _capture_lora_variant = previous def get_capture_attention_variant() -> Optional[str]: diff --git a/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mla.py b/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mla.py index 476b91efa7..c840af960e 100644 --- a/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mla.py +++ b/python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mla.py @@ -24,15 +24,7 @@ from sglang.srt.layers.dcp import ( ) from sglang.srt.layers.layer_boundary import get_attn_tp_context from sglang.srt.layers.logits_processor import get_in_autotune_dummy_run -from sglang.srt.lora.deepseek_mla_correction import ( - apply_q_correction as apply_kv_b_lora_q_correction, -) -from sglang.srt.lora.deepseek_mla_correction import ( - apply_v_correction as apply_kv_b_lora_v_correction, -) -from sglang.srt.lora.deepseek_mla_correction import ( - is_kv_b_lora_active, -) +from sglang.srt.lora.utils import kv_b_lora_correction from sglang.srt.model_executor.forward_batch_info import ForwardBatch from sglang.srt.model_executor.forward_context import ( get_attn_backend, @@ -72,6 +64,10 @@ if TYPE_CHECKING: from sglang.srt.models.deepseek_v2 import DeepseekV2AttentionMLA +def is_kv_b_lora_active(attn_module: DeepseekV2AttentionMLA) -> bool: + return getattr(getattr(attn_module, "kv_b_proj", None), "set_lora", False) + + @dataclass(frozen=True) class MlaBmmFusionPlan: q_nope_t: torch.Tensor @@ -521,6 +517,7 @@ class DeepseekMLAForwardMixin: # fp8 q directly into the q8kv8 backend buffer. q_nope_out = None else: + kv_b_lora = kv_b_lora_correction(self) if _SGLANG_EXPERIMENTAL_LORA_OPTI: # Fork the kv_b q-correction A-step onto the LoRA side stream to overlap the bmm. from sglang.srt.lora.trtllm_lora_temp.deepseek_mla_correction import ( @@ -528,6 +525,10 @@ class DeepseekMLAForwardMixin: ) _kvb_q = kv_b_lora_q_prepare(self, q_nope) + elif kv_b_lora == "v2": + from sglang.srt.lora.dense import mla_correction + + _kvb_q = mla_correction.prepare_q_correction(self, q_nope) if self.use_deep_gemm_bmm: ( @@ -583,8 +584,14 @@ class DeepseekMLAForwardMixin: ) q_nope_out = kv_b_lora_q_apply(self, q_nope, q_nope_out, _kvb_q) - elif is_kv_b_lora_active(self): - q_nope_out = apply_kv_b_lora_q_correction(self, q_nope, q_nope_out) + elif kv_b_lora == "v2": + q_nope_out = mla_correction.apply_correction(_kvb_q, q_nope_out) + elif kv_b_lora == "legacy": + from sglang.srt.lora import deepseek_mla_correction + + q_nope_out = deepseek_mla_correction.apply_q_correction( + self, q_nope, q_nope_out + ) fuse_rope_for_trtllm_mla = self._fuse_rope_for_trtllm_mla(forward_batch) if ( @@ -812,6 +819,7 @@ class DeepseekMLAForwardMixin: attn_output = attn_output.view(-1, self.num_local_heads, self.kv_lora_rank) _kvb_v = None + kv_b_lora = kv_b_lora_correction(self) if _SGLANG_EXPERIMENTAL_LORA_OPTI: # Fork the kv_b v-correction A-step onto the LoRA side stream to overlap the bmm. from sglang.srt.lora.trtllm_lora_temp.deepseek_mla_correction import ( @@ -819,6 +827,10 @@ class DeepseekMLAForwardMixin: ) _kvb_v = kv_b_lora_v_prepare(self, attn_output) + elif kv_b_lora == "v2": + from sglang.srt.lora.dense import mla_correction + + _kvb_v = mla_correction.prepare_v_correction(self, attn_output) if getattr(self, "_kimi_split_gguf_kv_b", False): from sglang.srt.layers.quantization.gguf import fused_mul_mat_gguf @@ -908,8 +920,12 @@ class DeepseekMLAForwardMixin: attn_bmm_output = kv_b_lora_v_apply( self, attn_output, attn_bmm_output, _kvb_v ) - elif is_kv_b_lora_active(self): - attn_bmm_output = apply_kv_b_lora_v_correction( + elif kv_b_lora == "v2": + attn_bmm_output = mla_correction.apply_correction(_kvb_v, attn_bmm_output) + elif kv_b_lora == "legacy": + from sglang.srt.lora import deepseek_mla_correction + + attn_bmm_output = deepseek_mla_correction.apply_v_correction( self, attn_output, attn_bmm_output ) if attention_output_gate is not None: diff --git a/python/sglang/srt/models/inkling_common/dense_mlp.py b/python/sglang/srt/models/inkling_common/dense_mlp.py index 522e359f3a..a1c3e38ac4 100644 --- a/python/sglang/srt/models/inkling_common/dense_mlp.py +++ b/python/sglang/srt/models/inkling_common/dense_mlp.py @@ -16,10 +16,11 @@ from sglang.srt.models.inkling_common.kernels.comm import ( ) from sglang.srt.models.inkling_common.util import ( FusedMoELoadingMixin, + deinterleave_gate_up, lora_compatible_layout_enabled, ) from sglang.srt.models.llama import LlamaMLP -from sglang.srt.runtime_context import get_exec, get_model +from sglang.srt.runtime_context import get_exec, get_lora, get_model logger = logging.getLogger(__name__) @@ -150,6 +151,8 @@ def _sum_dim0(x: torch.Tensor) -> torch.Tensor: class InklingBatchDenseMLP(nn.Module, FusedMoELoadingMixin): + _w13_gate_up_contiguous = False + def __init__( self, n_shared_experts: int, @@ -247,6 +250,11 @@ class InklingBatchDenseMLP(nn.Module, FusedMoELoadingMixin): else: self.register_buffer("_w2_lin", None, persistent=False) self._bf16_linearized_ready = False + self._w13_gate_up_contiguous = ( + self._linearized_bf16_enabled + and lora_compatible_layout_enabled() + and get_lora().lora_backend == "triton_v2" + ) def weight_loader_fused( self, @@ -255,6 +263,15 @@ class InklingBatchDenseMLP(nn.Module, FusedMoELoadingMixin): weight_name: str, shard_id: str, ) -> None: + if self._w13_gate_up_contiguous and param is self.w13_weight: + n, two_f, d = loaded_weight.shape + # Keep each TP block intact: the fused loader shards after conversion. + loaded_weight = deinterleave_gate_up( + loaded_weight.reshape( + n, self.moe_tp_size, two_f // self.moe_tp_size, d + ), + dim=2, + ).reshape(n, two_f, d) FusedMoELoadingMixin.weight_loader_fused( self, param, loaded_weight, weight_name, shard_id ) @@ -384,14 +401,21 @@ class InklingBatchDenseMLP(nn.Module, FusedMoELoadingMixin): def _swiglu(self, y_st2f: torch.Tensor, gammas_st: torch.Tensor) -> torch.Tensor: # Helion's kernel can produce NaNs for small shared-expert batches. from sglang.kernels.ops.moe.inkling_moe import ( + silu_and_mul, silu_and_mul_triton, ) - assert self.inference_moe_w13_interleaved, ( - "silu_and_mul_triton requires interleaved w13" - ) y_st_2f = y_st2f.view(-1, y_st2f.size(-1)) - y_st_f = silu_and_mul_triton(y_st_2f, gammas_st.reshape(-1)) + gammas = gammas_st.reshape(-1) + if self._w13_gate_up_contiguous: + # Same fp32 math and rounding as the interleaved kernel, reading + # the two contiguous halves of each row. + y_st_f = silu_and_mul(y_st_2f, gammas, use_interleaved=False) + else: + assert self.inference_moe_w13_interleaved, ( + "silu_and_mul_triton requires interleaved w13" + ) + y_st_f = silu_and_mul_triton(y_st_2f, gammas) return y_st_f.view(*y_st2f.shape[:-1], y_st2f.size(-1) // 2) # NVFP4 shared-expert serving uses the generic ModelOpt FP4 linears. diff --git a/python/sglang/srt/models/inkling_common/lora.py b/python/sglang/srt/models/inkling_common/lora.py index 92d9cea581..b17d7eefe2 100644 --- a/python/sglang/srt/models/inkling_common/lora.py +++ b/python/sglang/srt/models/inkling_common/lora.py @@ -3,13 +3,17 @@ from __future__ import annotations import torch from sglang.srt.lora.backend.base_backend import BaseLoRABackend +from sglang.srt.lora.dense.plan import DenseLoraKind +from sglang.srt.lora.utils import capturing_lora_graph from sglang.srt.models.inkling_common.dense_mlp import InklingBatchDenseMLP +from sglang.srt.models.inkling_common.kernels.comm import symm_mem_all_reduce class InklingBatchDenseMLPWithLoRA(InklingBatchDenseMLP): """LoRA layer for Inkling's dense shared-expert sink.""" - is_shared_fused_moe = True + set_lora = False + is_shared_fused_moe = False def initialize_lora(self, lora_backend: BaseLoRABackend) -> None: problems = [] @@ -31,6 +35,7 @@ class InklingBatchDenseMLPWithLoRA(InklingBatchDenseMLP): self.register_buffer("_w1_delta", None, persistent=False) self.register_buffer("_a_cat", None, persistent=False) self._lora_routing_cache = {} + self.is_shared_fused_moe = True lora_backend.is_moe_lora = True def set_lora_info( @@ -241,3 +246,166 @@ class InklingBatchDenseMLPWithLoRA(InklingBatchDenseMLP): linearized_weights, use_reduce_scatter, ) + + +class InklingBatchDenseMLPWithLoRAV2(InklingBatchDenseMLP): + """Dense-engine LoRA for Inkling's shared-expert sink.""" + + set_lora = False + is_shared_fused_moe = False + + def initialize_lora(self, lora_backend: BaseLoRABackend) -> None: + if getattr(lora_backend, "runner", None) is None: + raise ValueError( + f"{type(self).__name__} needs a backend with the dense engine" + ) + if not self._linearized_bf16_enabled: + raise ValueError( + f"{type(self).__name__} needs the linearized BF16 shared sink" + ) + if not self._w13_gate_up_contiguous: + raise ValueError( + "The V2 shared sink must select contiguous W13 before loading" + ) + self.lora_backend = lora_backend + self.set_lora = False + self.register_buffer("_down_cat", None, persistent=False) + self.is_shared_fused_moe = True + lora_backend.is_moe_lora = True + + def set_lora_info( + self, + gate_up_lora_a_weights: torch.Tensor, + gate_up_lora_b_weights: torch.Tensor, + down_lora_a_weights: torch.Tensor, + down_lora_b_weights: torch.Tensor, + ) -> None: + n = self.n_shared_experts + slots, outer, two_rank, _ = gate_up_lora_a_weights.shape + _, _, two_f, rank = gate_up_lora_b_weights.shape + hidden = down_lora_b_weights.shape[2] + if ( + outer not in (1, n) + or down_lora_b_weights.shape[1] != outer + or gate_up_lora_b_weights.shape[1] != n + or down_lora_a_weights.shape[1] != n + or two_rank != 2 * rank + or down_lora_a_weights.shape[2] != rank + or down_lora_b_weights.shape[-1] != rank + ): + raise ValueError( + "Inkling shared-sink LoRA pool buffers do not agree: expected gate-up A " + f"[slots, 1 or {n}, 2R, H], gate-up B [slots, {n}, 2F, R], down A " + f"[slots, {n}, R, F], down B [slots, 1 or {n}, H, R] with one layout" + ) + shared = outer == 1 + shape = (slots, rank, n * (two_f // 2)) if shared else (slots, hidden, n * rank) + down_cat = self._down_cat + if down_cat is None: + down_cat = down_lora_a_weights.new_empty(shape) + elif tuple(down_cat.shape) != shape: + raise RuntimeError( + "Shared-sink LoRA pool shape changed after initialization: " + f"{tuple(down_cat.shape)} -> {shape}" + ) + device = gate_up_lora_b_weights.device + # Pool factors are max-rank padded and already scaled. + ranks = torch.full((slots,), rank, dtype=torch.int32, device=device) + scalings = torch.ones(slots, dtype=torch.float32, device=device) + + gate_up = dict( + kind=DenseLoraKind.SINK_GATE_UP, + a=( + gate_up_lora_a_weights[:, 0] + if shared + else gate_up_lora_a_weights.reshape(slots, n * 2 * rank, -1) + ), + b=gate_up_lora_b_weights.view(slots, n * two_f, rank), + offsets=tuple(range(0, n * two_f + 1, two_f // 2)), + lora_ranks=ranks, + scalings=scalings, + a_blocks=2 if shared else 2 * n, + bridge_slices=2 if shared else 0, + ) + if shared: + down = dict( + kind=DenseLoraKind.LINEAR, + a=down_cat, + b=down_lora_b_weights[:, 0], + offsets=(0, hidden), + lora_ranks=ranks, + scalings=scalings, + ) + else: + # Each A block reads one expert's activation window. + down = dict( + kind=DenseLoraKind.SINK_DOWN, + a=down_lora_a_weights.view(slots, n * rank, -1), + b=down_cat, + offsets=(0, hidden), + lora_ranks=ranks * n, + scalings=scalings, + a_blocks=n, + a_windowed=True, + ) + source = (down_lora_a_weights if shared else down_lora_b_weights).permute( + 0, 2, 1, 3 + ) + self._down_refresh = source, down_cat.view_as(source) + self._down_cat = down_cat + self._gate_up, self._down = gate_up, down + self.set_lora = True + self.on_lora_slots_updated() + + def on_lora_slots_updated(self, slot_ids: set[int] | None = None) -> None: + if not self.set_lora: + return + source, target = self._down_refresh + # Keep the derived buffer's address stable across graph replays. + with torch.no_grad(): + for slot in range(source.shape[0]) if slot_ids is None else slot_ids: + target[slot].copy_(source[slot]) + + # Both wrappers receive the same pool factors and TP slicing geometry. + slice_moe_lora_a_weights = InklingBatchDenseMLPWithLoRA.slice_moe_lora_a_weights + slice_moe_lora_b_weights = InklingBatchDenseMLPWithLoRA.slice_moe_lora_b_weights + _slice_down_lora_a = InklingBatchDenseMLPWithLoRA._slice_down_lora_a + _slice_gate_up_lora_b = InklingBatchDenseMLPWithLoRA._slice_gate_up_lora_b + + def _forward_bf16_linearized( + self, + x_td: torch.Tensor, + gammas_ts: torch.Tensor, + linearized_weights: tuple[torch.Tensor, torch.Tensor], + use_reduce_scatter: bool, + ) -> torch.Tensor: + # Capture LoRA even without an active adapter, for later replay batches + # (except the decode runner's LoRA-free "nolora" graph). + if not self.set_lora or not ( + getattr(self.lora_backend.batch_info, "has_active_lora", False) + or capturing_lora_graph() + ): + return super()._forward_bf16_linearized( + x_td, gammas_ts, linearized_weights, use_reduce_scatter + ) + w13_lin, w2_lin = linearized_weights + t, n = x_td.shape[0], self.n_shared_experts + y = self._lora_gemm(x_td, lambda: torch.mm(x_td, w13_lin.T), **self._gate_up) + act_flat = self._swiglu(y.view(t, n, -1), gammas_ts).reshape(t, -1) + out_td = self._lora_gemm( + act_flat, lambda: torch.mm(act_flat, w2_lin), **self._down + ) + if not use_reduce_scatter and self.tp_group is not None: + out_td = symm_mem_all_reduce(out_td, self.tp_group) + return out_td + + def _lora_gemm(self, x: torch.Tensor, base_fn, *, kind, **site) -> torch.Tensor: + runner = self.lora_backend.runner + plan = runner.plan_for( + kind, + site["b"].shape[-1], + x.shape[-1], + site["offsets"][-1], + num_tokens=x.shape[0], + ) + return runner.apply(x, base_fn, plan, **site) diff --git a/python/sglang/srt/models/inkling_common/moe.py b/python/sglang/srt/models/inkling_common/moe.py index d776bfbe76..15d13e575b 100644 --- a/python/sglang/srt/models/inkling_common/moe.py +++ b/python/sglang/srt/models/inkling_common/moe.py @@ -56,7 +56,7 @@ from sglang.srt.models.inkling_common.util import ( lora_compatible_layout_enabled, use_inkling_shared_fused_moe, ) -from sglang.srt.runtime_context import get_exec, get_parallel +from sglang.srt.runtime_context import get_exec, get_lora, get_parallel from sglang.srt.state_capturer.routed_experts import get_global_experts_capturer from sglang.srt.utils import add_prefix, is_cuda, is_hip @@ -748,7 +748,19 @@ def _build_inkling_shared_experts( parallel_group="tp", tp_group=get_parallel().tp_group, ) - return InklingBatchDenseMLP( + sink_cls = InklingBatchDenseMLP + if get_lora().enable_lora: + from sglang.srt.models.inkling_common.lora import ( + InklingBatchDenseMLPWithLoRA, + InklingBatchDenseMLPWithLoRAV2, + ) + + sink_cls = ( + InklingBatchDenseMLPWithLoRAV2 + if get_lora().lora_backend == "triton_v2" + else InklingBatchDenseMLPWithLoRA + ) + return sink_cls( **dense_kwargs, linearized_bf16=( lora_compatible_layout_enabled() @@ -1018,7 +1030,7 @@ class InklingMoE(nn.Module): topk_weights, topk_ids, shared_gammas, packed_topk_ids = self.gate(x) allow_lora_overlap = True - if lora_compatible_layout_enabled(): + if lora_compatible_layout_enabled() and get_lora().lora_backend != "triton_v2": # ===== TO BE REFACTORED ==== from sglang.srt.lora.trtllm_lora_temp.inkling_dense import ( allow_inkling_moe_two_stream, diff --git a/test/registered/e2e/lora/test_lora_moe_prefill_cuda_graph.py b/test/registered/e2e/lora/test_lora_moe_prefill_cuda_graph.py index f43e3a5818..49de1cb581 100644 --- a/test/registered/e2e/lora/test_lora_moe_prefill_cuda_graph.py +++ b/test/registered/e2e/lora/test_lora_moe_prefill_cuda_graph.py @@ -43,14 +43,21 @@ class TestMoELoRAPrefillCudaGraph(CustomTestCase): prompts = (MOE_LORA_TEST_PROMPTS * 4)[:64] lora_paths = [None if i % 3 == 1 else "moe_lora" for i in range(len(prompts))] results = {} - for lora_backend, backend in ( - ("triton", "disabled"), - ("triton", "breakable"), - ("triton", "full"), - ("csgmv", "breakable"), - ("csgmv", "full"), + # (lora_backend, prefill graph backend, moe_runner_backend): the legacy + # MoE LoRA path on two dense backends, and the LoRA MoE runner with the + # dense engine (triton_v2), which must replay under both graph backends. + for lora_backend, backend, moe_runner_backend in ( + ("triton", "disabled", None), + ("triton", "breakable", None), + ("triton", "full", None), + ("csgmv", "breakable", None), + ("csgmv", "full", None), + ("triton_v2", "breakable", "lora_cutedsl"), + ("triton_v2", "full", "lora_cutedsl"), ): label = f"{lora_backend}/{backend}" + if moe_runner_backend is not None: + label += f"/{moe_runner_backend}" prefill_graph = backend != "disabled" if prefill_graph: # Isolate replay counts between engines. @@ -78,6 +85,8 @@ class TestMoELoRAPrefillCudaGraph(CustomTestCase): kwargs["cuda_graph_config"] = { "prefill": {"full_prefill_max_req": len(prompts)} } + if moe_runner_backend is not None: + kwargs["moe_runner_backend"] = moe_runner_backend collectors_before = set(REGISTRY._collector_to_names) engine = None diff --git a/test/registered/kernels/ops/lora/test_chunked_sgmv_cuda_graph.py b/test/registered/kernels/ops/lora/test_chunked_sgmv_cuda_graph.py index f189cfab5f..1813f97fc6 100644 --- a/test/registered/kernels/ops/lora/test_chunked_sgmv_cuda_graph.py +++ b/test/registered/kernels/ops/lora/test_chunked_sgmv_cuda_graph.py @@ -198,7 +198,7 @@ def test_prepare_batch_neutralizes_static_tail_segments(): device=torch.device("cuda"), server_args=server_args, ) - backend.init_cuda_graph_batch_info( + backend.init_decode_cuda_graph_batch_info( max_bs_in_cuda_graph=BS, num_tokens_per_req=1 ) lora_ranks = [MAX_RANK] * NUM_LORAS diff --git a/test/registered/kernels/ops/lora/test_dense_lora_backend.py b/test/registered/kernels/ops/lora/test_dense_lora_backend.py new file mode 100644 index 0000000000..21bd8313f7 --- /dev/null +++ b/test/registered/kernels/ops/lora/test_dense_lora_backend.py @@ -0,0 +1,762 @@ +"""Dense LoRA wrappers against the legacy backend in eager and graph execution.""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +import torch + +pytest.importorskip("triton") + +from sglang.srt.lora.backend.triton_backend import ( # noqa: E402 + TritonLoRABackend, +) +from sglang.srt.lora.backend.triton_v2_backend import TritonV2LoRABackend # noqa: E402 +from sglang.srt.lora.dense.plan import DenseLoraKind # noqa: E402 +from sglang.srt.model_executor.forward_batch_info import ForwardMode # noqa: E402 +from sglang.srt.runtime_context import reset_context # noqa: E402 +from sglang.test.ci.ci_register import register_cuda_ci # noqa: E402 + +register_cuda_ci(est_time=90, stage="base-b-kernel-unit", runner_config="1-gpu-large") + + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available(), reason="dense LoRA backends need CUDA" +) + +DEVICE = torch.device("cuda") +DTYPE = torch.bfloat16 +SLOTS = 4 +POOL_RANK = 32 +RANKS = [32, 16, 0, 8] # slot 2 carries no adapter +SCALINGS = [1.5, 0.5, 1.0, 2.0] +HIDDEN = 256 + + +@pytest.fixture(scope="module", autouse=True) +def _dist(): + """Publish world-size-one groups and the config/rank bundle; reset afterward.""" + import os + import socket + + from sglang.test.layer_ut_utils import init_single_process_dist + + # Probe on all addresses: a port free on 127.0.0.1 can be busy on another + # local address (an active connection), and the store binds them all. + for attempt in range(6): + with socket.socket() as sock: + sock.bind(("", 0)) + os.environ["MASTER_PORT"] = str(sock.getsockname()[1]) + try: + init_single_process_dist() + break + except Exception as exc: # torch raises DistNetworkError on EADDRINUSE + if "EADDRINUSE" not in str(exc) or attempt == 5: + raise + yield + reset_context() + + +def _pool(stack: int, k: int, width: int, seed: int): + """Dense pool slots as the memory pool writes them, stale past the rank.""" + g = torch.Generator(device=DEVICE).manual_seed(seed) + a = torch.randn(SLOTS, stack * POOL_RANK, k, generator=g, device=DEVICE) * 100 + b = torch.randn(SLOTS, width, POOL_RANK, generator=g, device=DEVICE) * 100 + for slot, rank in enumerate(RANKS): + a[slot, : stack * rank] = ( + torch.randn(stack * rank, k, generator=g, device=DEVICE) * 0.05 + ) + b[slot, :, :rank] = torch.randn(width, rank, generator=g, device=DEVICE) * 0.05 + return a.to(DTYPE).contiguous(), b.to(DTYPE).contiguous() + + +def _batch(seq_lens, slots, decode: bool): + seg_lens = torch.tensor(seq_lens, dtype=torch.int32, device=DEVICE) + fb = SimpleNamespace( + forward_mode=ForwardMode.DECODE if decode else ForwardMode.EXTEND, + batch_size=len(seq_lens), + extend_seq_lens=seg_lens, + extend_seq_lens_cpu=list(seq_lens), + extend_num_tokens=int(sum(seq_lens)), + spec_info=None, + return_logprob=False, + extend_logprob_start_lens_cpu=None, + ) + return fb, list(slots), list(RANKS), list(SCALINGS) + + +def _layers(kind: str): + from sglang.srt.layers.linear import ( + ColumnParallelLinear, + MergedColumnParallelLinear, + QKVParallelLinear, + ReplicatedLinear, + RowParallelLinear, + ) + from sglang.srt.lora.layers import get_lora_layer + + common = dict(bias=False, params_dtype=DTYPE) + if kind == "qkv": + base = QKVParallelLinear(HIDDEN, 32, 8, 2, **common) + elif kind == "merged": + base = MergedColumnParallelLinear(HIDDEN, [96, 96, 160, 160], **common) + elif kind == "row": + base = RowParallelLinear(512, HIDDEN, reduce_results=False, **common) + elif kind == "replicated": + base = ReplicatedLinear(HIDDEN, 320, **common) + else: + base = ColumnParallelLinear(HIDDEN, 192, **common) + base = base.to(DEVICE) + with torch.no_grad(): + base.weight.normal_(0, 0.02) + k = base.weight.shape[1] + width = base.weight.shape[0] + stack = {"qkv": 3, "merged": 4, "replicated": 2}.get(kind, 1) + a, b = _pool(stack, k, width, seed=sum(kind.encode())) + + def wrap(backend): + layer = get_lora_layer(base, backend) + if kind == "replicated": + layer.first_output_dim = 128 + layer.set_lora_info(a, b) + return layer + + return wrap, k + + +def _prepare_batch(backend, fb, wi, ranks, scal, *args, **kwargs): + """Fill backend metadata and record whether any request carries an adapter.""" + backend.prepare_lora_batch(fb, wi, ranks, scal, *args, **kwargs) + backend.batch_info.has_active_lora = any(ranks[i] > 0 for i in wi) + + +def _prepare( + backend, batch, use_decode_cuda_graph=False, *, use_prefill_cuda_graph=False +): + fb, wi, ranks, scal = batch + _prepare_batch( + backend, fb, wi, ranks, scal, use_decode_cuda_graph, use_prefill_cuda_graph + ) + + +@pytest.mark.parametrize("kind", ["qkv", "merged", "row", "replicated", "column"]) +@pytest.mark.parametrize("batch_name", ["decode13", "prefill4", "prefill_one_request"]) +def test_wrappers_match_legacy(kind, batch_name): + wrap, k = _layers(kind) + if batch_name == "decode13": + batch = _batch([1] * 13, [i % SLOTS for i in range(13)], decode=True) + elif batch_name == "prefill4": + batch = _batch([5, 17, 1, 9], [1, 0, 2, 3], decode=False) + else: + batch = _batch([23], [3], decode=False) + tokens = batch[0].extend_num_tokens + x = torch.randn(tokens, k, device=DEVICE, dtype=DTYPE) + + legacy = TritonLoRABackend(SLOTS, DEVICE) + _prepare(legacy, batch) + expected = wrap(legacy)(x)[0] + + ours = TritonV2LoRABackend(SLOTS, DEVICE) + _prepare(ours, batch) + out = wrap(ours)(x)[0] + torch.testing.assert_close(out.float(), expected.float(), rtol=2e-2, atol=2e-2) + + +class _FixedPlanTable: + def __init__(self, plan): + self.plan = plan + + def plan_for(self, kind, phase, num_tokens, *geometry): + return self.plan + + +def _cached_route_keys(runner): + return {key[-3:] for routes in runner.workspace.routes.values() for key in routes} + + +def test_eager_target_verify_batch_uses_the_draft_width(): + """TARGET_VERIFY uses draft-width segments without extend lengths.""" + wrap_col, k_col = _layers("column") + ours = TritonV2LoRABackend(SLOTS, DEVICE) + layer = wrap_col(ours) + draft, bs, slots = 8, 3, [0, 1, 3] + verify = SimpleNamespace( + forward_mode=ForwardMode.TARGET_VERIFY, + batch_size=bs, + extend_seq_lens=None, + extend_seq_lens_cpu=None, + extend_num_tokens=None, + spec_info=SimpleNamespace(draft_token_num=draft), + return_logprob=False, + extend_logprob_start_lens_cpu=None, + ) + x = torch.randn(bs * draft, k_col, device=DEVICE, dtype=DTYPE) + _prepare_batch( + ours, verify, slots, list(RANKS), list(SCALINGS), use_decode_cuda_graph=False + ) + info = ours.batch_info + assert info.seg_indptr.diff().tolist() == [draft] * bs + assert info.seg_indptr[: bs + 1].tolist() == [0, draft, 2 * draft, 3 * draft] + verified = layer(x)[0].clone() + _prepare(ours, _batch([draft] * bs, slots, decode=False)) + torch.testing.assert_close(verified, layer(x)[0], rtol=0, atol=0) + + +@pytest.mark.parametrize("request_capacity", [None, 48]) +def test_prefill_graph_admits_any_request_count_within_the_token_bucket( + request_capacity, +): + """Replay ragged requests with the captured bucket's plan and route storage.""" + from sglang.kernels.ops.lora.common.routing import _aligned_route_capacity + from sglang.srt.lora.dense.plan import DensePlan + + wrap_row, k_row = _layers("row") + ours = TritonV2LoRABackend(SLOTS, DEVICE) + ours.init_prefill_cuda_graph_batch_info(512, request_capacity) + assert ours.prefill_cuda_graph_max_bs == (request_capacity or 512) + table = _TokensPlanTable( + DensePlan(block_size=32), DensePlan(block_size=16), threshold=128 + ) + ours.runner._plan_tables[POOL_RANK] = table + layer = wrap_row(ours) + bucket = 256 + x = torch.randn(bucket, k_row, device=DEVICE, dtype=DTYPE) + out = torch.empty( + bucket, layer.base_layer.weight.shape[0], device=DEVICE, dtype=DTYPE + ) + + def forward(): + ours.reset_routing_cache() + out.copy_(layer(x)[0]) + + def route_buffers(route): + # The route pads per slot, so its capacity ignores the request count. + assert ( + bucket + <= route.sorted_pair_ids.numel() + <= _aligned_route_capacity(bucket, route.block_size, SLOTS) + ) + ids = route.sorted_pair_ids[: route.num_pairs_post_padded.item()] + valid_ids = ids[(ids >= 0) & (ids < bucket)] + active_tokens = torch.where(ours.runner.token_slots >= 0)[0] + assert torch.isin(active_tokens, valid_ids).all().item() + return ( + route.sorted_pair_ids.data_ptr(), + route.sorted_pair_ids.numel(), + route.block_bucket_ids.data_ptr(), + ) + + capture = _batch([bucket], [1], decode=False) + _prepare(ours, capture, use_prefill_cuda_graph=True) + assert not ours.runner.workspace.routes + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + forward() + warmup_route = ours.runner.route(table.large.block_size) + torch.cuda.current_stream().wait_stream(stream) + key = ("sorted", table.large.block_size, SLOTS) + assert _cached_route_keys(ours.runner) == {key} + buffers = route_buffers(warmup_route) + _prepare(ours, capture, use_prefill_cuda_graph=True) + assert not ours.runner.workspace.routes + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + forward() + captured_route = ours.runner.route(table.large.block_size) + assert _cached_route_keys(ours.runner) == {key} + + legacy = TritonLoRABackend(SLOTS, DEVICE) + seq_lens = [ + 1 + (i * 7) % 9 for i in range(48) + ] # 48 ragged requests, 1..9 tokens each + slots = [(i * 3) % SLOTS for i in range(48)] + live = sum(seq_lens) + assert len(seq_lens) > 32 and live <= bucket + for batch in ( + _batch(seq_lens, slots, decode=False), + _batch([90, 70, 50, 30], [2, 0, 3, 1], decode=False), + _batch([60, 40], [3, 0], decode=False), + ): + live = batch[0].extend_num_tokens + x.copy_(torch.randn_like(x)) + _prepare(ours, batch, use_prefill_cuda_graph=True) + assert ours.runner.token_slots.numel() == live + assert not ours.runner.workspace.routes + captured_route.sorted_pair_ids.fill_(-7) + captured_route.block_bucket_ids.fill_(-7) + captured_route.num_pairs_post_padded.zero_() + graph.replay() + torch.cuda.synchronize() + assert route_buffers(captured_route) == buffers + _prepare(legacy, batch) + expected = wrap_row(legacy)(x[:live])[0] + torch.testing.assert_close(out[:live], expected, rtol=2e-2, atol=2e-2) + _prepare(ours, batch) + site = (DenseLoraKind.LINEAR, POOL_RANK, k_row, layer.base_layer.weight.shape[0]) + eager = ours.runner.plan_for(*site, num_tokens=live) + assert eager.block_size != captured_route.block_size + + +class _TokensPlanTable: + def __init__(self, large, small, threshold): + self.large, self.small, self.threshold = large, small, threshold + self.queries = [] + + def plan_for(self, kind, phase, num_tokens, *geometry): + self.queries.append(num_tokens) + return self.large if num_tokens > self.threshold else self.small + + +@pytest.mark.parametrize("prefill", [False, True], ids=["decode", "prefill"]) +def test_variable_bucket_graphs_replay_without_dense_host_work(monkeypatch, prefill): + """Old graphs read refreshed metadata without Python planning or routing. + + Each graph holds a qkv and a row site, and capture rebuilds the warm-up + route exactly once, inside the graph. + """ + from sglang.srt.lora.dense.plan import DensePlan + + wrap_qkv, k_qkv = _layers("qkv") + wrap_row, k_row = _layers("row") + ours = TritonV2LoRABackend(SLOTS, DEVICE) + table = _TokensPlanTable( + DensePlan(block_size=32), + DensePlan(block_size=16), + threshold=16, + ) + ours.runner._plan_tables[POOL_RANK] = table + if prefill: + ours.init_prefill_cuda_graph_batch_info(64) + else: + ours.init_decode_cuda_graph_batch_info(64, 1) + layer_qkv, layer_row = wrap_qkv(ours), wrap_row(ours) + x_qkv = torch.randn(64, k_qkv, device=DEVICE, dtype=DTYPE) + x_row = torch.randn(64, k_row, device=DEVICE, dtype=DTYPE) + out_qkv = torch.empty( + 64, layer_qkv.base_layer.weight.shape[0], device=DEVICE, dtype=DTYPE + ) + out_row = torch.empty( + 64, layer_row.base_layer.weight.shape[0], device=DEVICE, dtype=DTYPE + ) + build_route = ours.runner._build_route + builds = [] # per route build: was the current stream capturing? + + def counted_build(*args, **kwargs): + builds.append(torch.cuda.is_current_stream_capturing()) + return build_route(*args, **kwargs) + + monkeypatch.setattr(ours.runner, "_build_route", counted_build) + + def batch_for(live, offset): + lengths = [live // 2, live - live // 2] if prefill else [1] * live + slots = [(i + offset) % SLOTS for i in range(len(lengths))] + return _batch(lengths, slots, decode=not prefill) + + def prepare(batch): + _prepare(ours, batch, not prefill, use_prefill_cuda_graph=prefill) + + graphs = {} + stream = torch.cuda.Stream() # one stream for every bucket, as in a graph runner + for bucket in (64, 16): + + def forward(bucket=bucket): + ours.reset_routing_cache() + out_qkv[:bucket].copy_(layer_qkv(x_qkv[:bucket])[0]) + out_row[:bucket].copy_(layer_row(x_row[:bucket])[0]) + + queries = len(table.queries) + prepare(batch_for(11, 0)) + assert len(table.queries) == queries + assert ours.runner._token_slots.numel() == 64 + assert ours.runner.token_slots.numel() == 11 + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + forward() + forward() + torch.cuda.current_stream().wait_stream(stream) + count = len(builds) + graphs[bucket] = torch.cuda.CUDAGraph() + with torch.cuda.graph(graphs[bucket], stream=stream): + forward() + # The warm-up route is rebuilt exactly once, inside the capture. + assert builds[count:] == [True] + assert ours.runner._token_slots.numel() == 64 + assert ours.runner.token_slots.numel() == bucket + plan = table.large if bucket > table.threshold else table.small + assert _cached_route_keys(ours.runner) == {("sorted", plan.block_size, SLOTS)} + assert table.queries == [64] * 6 + [16] * 6 # one plan per site per forward + + def unexpected_dense_work(*args, **kwargs): + pytest.fail("preparation and replay must not plan or build dense routes") + + monkeypatch.setattr(ours.runner, "plan_for", unexpected_dense_work) + monkeypatch.setattr(ours.runner, "_build_route", unexpected_dense_work) + legacy = TritonLoRABackend(SLOTS, DEVICE) + # The same local size can replay either bucket, including DP-wide padding. + for offset, (live, bucket) in enumerate( + ((11, 64), (11, 16), (40, 64), (16, 16), (64, 64)) + ): + x_qkv.copy_(torch.randn_like(x_qkv)) + x_row.copy_(torch.randn_like(x_row)) + batch = batch_for(live, offset + 1) + prepare(batch) + assert ours.runner.token_slots.numel() == live + assert not ours.runner.workspace.routes + graphs[bucket].replay() + torch.cuda.synchronize() + assert not ours.runner.workspace.routes + _prepare(legacy, batch) + expected_qkv = wrap_qkv(legacy)(x_qkv[:live])[0] + expected_row = wrap_row(legacy)(x_row[:live])[0] + torch.testing.assert_close(out_qkv[:live], expected_qkv, rtol=2e-2, atol=2e-2) + torch.testing.assert_close(out_row[:live], expected_row, rtol=2e-2, atol=2e-2) + + +@pytest.mark.parametrize("tokens", [1, 64]) # a partial and a full route block +def test_decode_lm_head_matches_legacy(tokens): + # Decode uses the main runner's generic plan; slot 2 has no adapter. + from sglang.srt.layers.vocab_parallel_embedding import ParallelLMHead + from sglang.srt.lora.layers import get_lora_layer + + vocab, embed = 4096, 2048 + batch = _batch([1] * tokens, [i % SLOTS for i in range(tokens)], decode=True) + g = torch.Generator(device=DEVICE).manual_seed(5) + a_head = torch.randn(SLOTS, POOL_RANK, embed, generator=g, device=DEVICE) * 0.05 + b_head = torch.randn(SLOTS, vocab, POOL_RANK, generator=g, device=DEVICE) * 0.05 + for slot, rank in enumerate(RANKS): + a_head[slot, rank:] = 1e4 # stale past the rank + b_head[slot, :, rank:] = 1e4 + a_head, b_head = a_head.to(DTYPE).contiguous(), b_head.to(DTYPE).contiguous() + base_head = ParallelLMHead(vocab, embed, params_dtype=DTYPE).to(DEVICE) + with torch.no_grad(): + base_head.weight.normal_(0, 0.02, generator=g) + hidden = torch.randn(tokens, embed, generator=g, device=DEVICE, dtype=DTYPE) + + def run(backend): + backend.validate_lora_targets(base_head, {"lm_head"}) + _prepare(backend, batch) + head = get_lora_layer(base_head, backend) + head.set_lora_info(a_head, b_head) + return head(hidden) + + expected = run(TritonLoRABackend(SLOTS, DEVICE)) + out = run(TritonV2LoRABackend(SLOTS, DEVICE)) + torch.testing.assert_close(out.float(), expected.float(), rtol=2e-2, atol=2e-2) + + +def test_embedding_and_lm_head_match_legacy(): + from sglang.srt.layers.vocab_parallel_embedding import ( + ParallelLMHead, + VocabParallelEmbedding, + ) + from sglang.srt.lora.layers import get_lora_layer + + vocab, embed = 1000, HIDDEN + batch = _batch([5, 17, 1, 9], [1, 0, 2, 3], decode=False) + tokens = batch[0].extend_num_tokens + g = torch.Generator(device=DEVICE).manual_seed(3) + ids = torch.randint(0, vocab, (tokens,), generator=g, device=DEVICE) + a_emb = torch.randn( + SLOTS, POOL_RANK, vocab, generator=g, device=DEVICE, dtype=torch.float32 + ) + b_emb = torch.randn( + SLOTS, embed, POOL_RANK, generator=g, device=DEVICE, dtype=torch.float32 + ) + a_head = torch.randn(SLOTS, POOL_RANK, embed, generator=g, device=DEVICE) * 0.05 + b_head = torch.randn(SLOTS, vocab, POOL_RANK, generator=g, device=DEVICE) * 0.05 + for slot, rank in enumerate(RANKS): + a_emb[slot, rank:] = 0 # the gather kernel keeps the tail zero-filled + a_emb[slot, :rank] *= 0.05 + b_emb[slot, :, rank:] = 1e4 # stale + b_emb[slot, :, :rank] *= 0.05 + a_head[slot, rank:] = 1e4 + b_head[slot, :, rank:] = 1e4 + a_emb, b_emb, a_head, b_head = ( + t.to(DTYPE).contiguous() for t in (a_emb, b_emb, a_head, b_head) + ) + + base_embed = VocabParallelEmbedding(vocab, embed, params_dtype=DTYPE).to(DEVICE) + base_head = ParallelLMHead(vocab, embed, params_dtype=DTYPE).to(DEVICE) + with torch.no_grad(): + base_embed.weight.normal_(0, 0.02, generator=g) + base_head.weight.copy_(base_embed.weight) + + def run(backend): + # Both backends wrap the same base layers, so only the LoRA path differs. + backend.validate_lora_targets(base_head, {"lm_head", "embed_tokens"}) + _prepare(backend, batch) + emb = get_lora_layer(base_embed, backend) + emb.set_lora_info(None, a_emb, b_emb) + hidden = emb(ids) + head = get_lora_layer(base_head, backend) + head.set_lora_info(a_head, b_head) + pruned = hidden[[4, 21, 22, 31]] # last token of each request + logits = head(pruned) + return hidden, logits + + hidden_l, logits_l = run(TritonLoRABackend(SLOTS, DEVICE)) + hidden_v, logits_v = run(TritonV2LoRABackend(SLOTS, DEVICE)) + torch.testing.assert_close(hidden_v.float(), hidden_l.float(), rtol=2e-2, atol=2e-2) + torch.testing.assert_close(logits_v.float(), logits_l.float(), rtol=2e-2, atol=2e-2) + + +def test_pruned_chunked_lm_head_numeric_and_single_binding(monkeypatch): + from sglang.srt.environ import envs + from sglang.srt.layers.vocab_parallel_embedding import ParallelLMHead + from sglang.srt.lora.dense.plan import DensePlan, Overlap + from sglang.srt.lora.layers import get_lora_layer + + monkeypatch.setenv("SGLANG_ENABLE_LOGPROB_CHUNK", "true") + monkeypatch.setenv("SGLANG_LOGPROB_CHUNK_SIZE", "4") + assert envs.SGLANG_ENABLE_LOGPROB_CHUNK.get() + backend = TritonV2LoRABackend(SLOTS, DEVICE) + backend.validate_lora_targets(None, {"lm_head"}) + backend.lm_head_runner._plan_tables[POOL_RANK] = _FixedPlanTable( + DensePlan(overlap=Overlap.NONE) # as the shipped vocab rows + ) + vocab = 128 + base = ParallelLMHead(vocab, HIDDEN, params_dtype=DTYPE).to(DEVICE) + with torch.no_grad(): + base.weight.normal_(0, 0.02) + head = get_lora_layer(base, backend) + a, b = _pool(1, HIDDEN, vocab, 117) + head.set_lora_info(a, b) + for assignments, ranks, scales in ( + ([1, 1, 3], RANKS, SCALINGS), + ([0, 2, 1], [8, 0, 0, 0], [0.25, 0, 0, 0]), + ): + fb, _, _, _ = _batch([5, 3, 4], assignments, False) + fb.return_logprob = True + fb.extend_logprob_start_lens_cpu = [2, 1, 1] + _prepare_batch(backend, fb, assignments, ranks, scales, False) + token_slots = [ + slot for slot, n in zip(assignments, [3, 2, 3]) for _ in range(n) + ] + hidden = torch.randn(8, HIDDEN, dtype=DTYPE, device=DEVICE) * 0.05 + expected = torch.nn.functional.linear(hidden, base.weight).float() + for i, slot in enumerate(token_slots): + rank = ranks[slot] + if rank: + bridge = (hidden[i].float() @ a[slot, :rank].float().T).to(DTYPE) + expected[i] += (bridge.float() @ b[slot, :, :rank].float().T) * scales[ + slot + ] + assert len(backend.lm_head_pass_batch_infos) == 2 + for idx in range(2): + head.set_lm_head_pass(idx) + result = head(hidden[idx * 4 : (idx + 1) * 4]) + torch.testing.assert_close( + result.float(), + expected[idx * 4 : (idx + 1) * 4], + rtol=2e-2, + atol=2e-2, + ) + head.reset_lm_head_pass() + result = head(hidden) + torch.testing.assert_close(result.float(), expected, rtol=2e-2, atol=2e-2) + + +@pytest.mark.parametrize( + "site,overlap", + # ab_delta guards the embedding's integer-input delta dtype; lm_head rows use none + [ + (site, overlap) + for site in ("embedding_decode", "embedding_prefill") + for overlap in ("none", "ab_delta") + ] + + [("head_decode", "none")], +) +@pytest.mark.parametrize("graph_mode", [False, True], ids=["eager", "graph"]) +def test_vocab_layers_use_unified_forward(site, overlap, graph_mode): + from sglang.srt.layers.vocab_parallel_embedding import ( + ParallelLMHead, + VocabParallelEmbedding, + ) + from sglang.srt.lora.dense.plan import DensePlan, Overlap + from sglang.srt.lora.layers import get_lora_layer + + embedding = site.startswith("embedding") + prefill = site.endswith("prefill") + # TP1 only: an uneven vocab gives lm_head a padded base output wider than + # its LoRA B. This checks the padding boundary, not multi-rank collectives. + vocab, width = 131, HIDDEN + backend = TritonV2LoRABackend(SLOTS, DEVICE) + backend.validate_lora_targets(None, {"embed_tokens" if embedding else "lm_head"}) + backend.runner._plan_tables[POOL_RANK] = _FixedPlanTable( + DensePlan(overlap=Overlap(overlap)) + ) + if graph_mode: + if prefill: + backend.init_prefill_cuda_graph_batch_info(64) + else: + backend.init_decode_cuda_graph_batch_info(64, 1) + base_type = VocabParallelEmbedding if embedding else ParallelLMHead + base = base_type(vocab, width, params_dtype=DTYPE).to(DEVICE) + with torch.no_grad(): + base.weight.normal_(0, 0.02) + layer = get_lora_layer(base, backend) + a, b = _pool(1, vocab if embedding else width, width if embedding else vocab, 219) + if embedding: + layer.set_lora_info(None, a, b) + x = torch.randint(vocab, (64,), device=DEVICE) + else: + layer.set_lora_info(a, b) + x = torch.randn(64, width, device=DEVICE, dtype=DTYPE) * 0.05 + output_width = width if embedding else base.weight.shape[0] + if not embedding: + assert output_width > vocab + assert layer.lora_offsets == (0, vocab) + output = torch.empty(64, output_width, device=DEVICE, dtype=DTYPE) + + def prepare(lengths, slots, ranks, scales): + fb, _, _, _ = _batch(lengths, slots, not prefill) + _prepare_batch( + backend, + fb, + slots, + ranks, + scales, + graph_mode and not prefill, + graph_mode and prefill, + ) + + def forward(bucket): + backend.reset_routing_cache() + output[:bucket].copy_(layer(x[:bucket])) + + graphs = {} + stream = torch.cuda.Stream() # one stream for every bucket, as in a graph runner + for bucket in (64, 16): + lengths = [bucket // 2, bucket // 2] if prefill else [1] * bucket + slots = [i % SLOTS for i in range(len(lengths))] + prepare(lengths, slots, RANKS, SCALINGS) + forward(bucket) + if graph_mode: + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + forward(bucket) + torch.cuda.current_stream().wait_stream(stream) + prepare(lengths, slots, RANKS, SCALINGS) + graphs[bucket] = torch.cuda.CUDAGraph() + with torch.cuda.graph(graphs[bucket], stream=stream): + forward(bucket) + + for step, bucket in enumerate((64, 16, 64, 16)): + lengths = [5, 0, 3, 1] if prefill else [1] * 9 + slots = [1, 0, 2, 3] if prefill else [1, 0, 2, 3, 1, 3, 0, 2, 1] + ranks = [8, 4, 0, 0] if step < 2 else [0] * SLOTS + scales = [0.25, 1.25, 0, 0.5] + if embedding: + x.random_(vocab) + else: + x.normal_(0, 0.05) + prepare(lengths, slots, ranks, scales) + extent = bucket if graph_mode else sum(lengths) + if graph_mode: + graphs[bucket].replay() + else: + forward(extent) + if embedding: + expected = torch.nn.functional.embedding(x[:extent], base.weight).float() + else: + expected = torch.nn.functional.linear(x[:extent], base.weight).float() + row = 0 + for length, slot in zip(lengths, slots): + rank = ranks[slot] + if rank and length: + values = x[row : row + length] + if embedding: + bridge = a[slot, :rank, values].T + else: + bridge = (values.float() @ a[slot, :rank].float().T).to(DTYPE) + expected[row : row + length, : b.shape[-2]] += ( + bridge.float() @ b[slot, :, :rank].float().T + ) * scales[slot] + row += length + torch.testing.assert_close( + output[:extent].float(), expected, rtol=2e-2, atol=2e-2 + ) + if not embedding: + torch.testing.assert_close( + output[:extent, vocab:].float(), + expected[:, vocab:], + rtol=0, + atol=0, + ) + assert output.dtype == DTYPE + + +@pytest.mark.parametrize("verify", [False, True]) +def test_graph_phases_replay_with_changed_ranks_scales_and_old_buckets(verify): + wrap, k = _layers("column") + backend = TritonV2LoRABackend(SLOTS, DEVICE) + backend.init_prefill_cuda_graph_batch_info(64) + width = 4 if verify else 1 + backend.init_decode_cuda_graph_batch_info(64 // width, width) + layer = wrap(backend) + x = torch.randn(64, k, device=DEVICE, dtype=DTYPE) * 0.05 + output = torch.empty(64, 192, device=DEVICE, dtype=DTYPE) + + def prepare(prefill, lengths, slots, ranks, scales): + fb, _, _, _ = _batch(lengths, slots, not prefill) + if verify and not prefill: + fb.forward_mode = ForwardMode.TARGET_VERIFY + fb.spec_info = SimpleNamespace(draft_token_num=width) + _prepare_batch(backend, fb, slots, ranks, scales, not prefill, prefill) + + graphs = {} + stream = torch.cuda.Stream() # one stream for every bucket, as in a graph runner + for prefill in (False, True): + for bucket in (64, 32): + lengths = [bucket] if prefill else [width] * (bucket // width) + slots = [i % SLOTS for i in range(len(lengths))] + prepare(prefill, lengths, slots, RANKS, SCALINGS) + + def forward(): + backend.reset_routing_cache() + output[:bucket].copy_(layer(x[:bucket])[0]) + + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + forward() + torch.cuda.current_stream().wait_stream(stream) + prepare(prefill, lengths, slots, RANKS, SCALINGS) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + forward() + graphs[prefill, bucket] = graph + + for step, (prefill, bucket) in enumerate( + ((False, 64), (True, 32), (False, 32), (True, 64)) * 2 + ): + lengths = [5, 0, 9] if prefill else [width] * 3 + slots = [3, 1, 0] if prefill else [1, 0, 3] + ranks = [8, 4, 0, 0] if step % 3 else [0] * SLOTS + scales = [0.25, 1.25, 0.0, 0.5] + x.normal_(0, 0.05) + prepare(prefill, lengths, slots, ranks, scales) + graphs[prefill, bucket].replay() + expected = torch.nn.functional.linear( + x[:bucket], layer.base_layer.weight + ).float() + row = 0 + for length, slot in zip(lengths, slots): + rank = ranks[slot] + if rank: + bridge = ( + x[row : row + length].float() + @ layer.A_buffer[slot, :rank].float().T + ).to(DTYPE) + expected[row : row + length] += ( + bridge.float() @ layer.B_buffer[slot, :, :rank].float().T + ) * scales[slot] + row += length + torch.testing.assert_close( + output[:bucket].float(), expected, rtol=2e-2, atol=2e-2 + ) + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/lora/test_dense_lora_geometry.py b/test/registered/kernels/ops/lora/test_dense_lora_geometry.py new file mode 100644 index 0000000000..629fc45968 --- /dev/null +++ b/test/registered/kernels/ops/lora/test_dense_lora_geometry.py @@ -0,0 +1,129 @@ +"""Expand geometry caching and graph lifetime.""" + +from __future__ import annotations + +import pytest +import torch + +from sglang.kernels.ops.lora.common.lora_b import ( + grouped_lora_b, + slice_geometry, +) +from sglang.kernels.ops.lora.common.route_view import RouteViewKind +from sglang.kernels.ops.lora.common.routing import build_route +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=60, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +DEVICE = torch.device("cuda") +DTYPE = torch.bfloat16 +SLOTS, RANK = 4, 32 +CONFIG = { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 3, +} +TOL = dict(rtol=2e-2, atol=2e-2) + + +def _site(offsets, tokens=41, seed=3): + """A ranked expand over ``offsets`` with a torch reference.""" + g = torch.Generator(device=DEVICE).manual_seed(seed) + token_slots = torch.tensor( + [i % (SLOTS + 1) - 1 for i in range(tokens)], dtype=torch.int32, device=DEVICE + ) + ranks = torch.tensor([32, 16, 8, 32], dtype=torch.int32, device=DEVICE) + scalings = torch.tensor([1.5, 0.5, 2.0, 1.0], dtype=torch.float32, device=DEVICE) + slices = len(offsets) - 1 + bridge = (torch.randn(tokens, slices * RANK, generator=g, device=DEVICE) * 0.5).to( + DTYPE + ) + weight = ( + torch.randn(SLOTS, offsets[-1], RANK, generator=g, device=DEVICE) * 0.05 + ).to(DTYPE) + base = torch.randn(tokens, offsets[-1], generator=g, device=DEVICE, dtype=DTYPE) + route = build_route( + token_slots, max_loras=SLOTS, block_size=16, view=RouteViewKind.ALIGNED + ) + expected = base.float().clone() + for t in range(tokens): + s = int(token_slots[t]) + if s < 0: + continue + r = int(ranks[s]) + for k in range(slices): + # slice k of a rank-r slot sits at bridge columns [k*r, (k+1)*r) + lo, hi = offsets[k], offsets[k + 1] + expected[t, lo:hi] += float(scalings[s]) * ( + weight[s, lo:hi, :r].float() @ bridge[t, k * r : (k + 1) * r].float() + ) + return ( + dict( + bridge=bridge, + weight=weight, + base=base, + route=route, + ranks=ranks, + scalings=scalings, + ), + expected, + ) + + +def _expand(site, geometry, out): + grouped_lora_b( + site["bridge"], + site["weight"], + out, + site["route"], + geometry=geometry, + config=CONFIG, + add_inplace=True, + zero_sentinel=False, + lora_ranks=site["ranks"], + scalings=site["scalings"], + ) + + +def test_cache_normalizes_device_and_keeps_distinct_destination_columns(): + rows = (0, 96, 192) + same = slice_geometry(rows, 64, DEVICE) + indexed = torch.device("cuda", torch.cuda.current_device()) + assert slice_geometry(rows, 64, indexed, out_offsets=rows[:-1]) is same + gapped = slice_geometry(rows, 64, indexed, out_offsets=(0, 128)) + assert gapped is not same + assert gapped.out_offsets.tolist() == [0, 128] and same.out_offsets.tolist() == [ + 0, + 96, + ] + + +def test_a_captured_graph_keeps_its_tables_when_other_geometries_appear(): + offsets = (0, 96, 224, 304) + site, expected = _site(offsets, seed=11) + geometry = slice_geometry(offsets, 64, DEVICE) + out = site["base"].clone() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + _expand(site, geometry, out) # warm-up compiles the kernel + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + out.copy_(site["base"]) + with torch.cuda.graph(graph, stream=stream): + _expand(site, geometry, out) + del geometry # Only the cache retains the tables after capture. + for i in range(3): + slice_geometry( + (0, 128 + 16 * (i + 1), 256 + 32 * (i + 1)), 64, DEVICE + ) # new entries after capture + out.copy_(site["base"]) + graph.replay() + torch.cuda.synchronize() + torch.testing.assert_close(out.float(), expected, **TOL) + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/lora/test_dense_lora_inkling_sink.py b/test/registered/kernels/ops/lora/test_dense_lora_inkling_sink.py new file mode 100644 index 0000000000..edcc4b3671 --- /dev/null +++ b/test/registered/kernels/ops/lora/test_dense_lora_inkling_sink.py @@ -0,0 +1,604 @@ +"""Inkling sink LoRA against a reference using raw, pre-scaled MoE pool buffers. +Covers both layouts, executor families, TP shards, and graph-visible adapter/base reloads. +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +import torch + +pytest.importorskip("triton") + +from sglang.kernels.ops.moe.inkling_moe import silu_and_mul_triton # noqa: E402 +from sglang.srt.lora.backend.triton_v2_backend import TritonV2LoRABackend # noqa: E402 +from sglang.srt.lora.dense.plan import ( # noqa: E402 + AFamily, + BFamily, + DensePlan, + Overlap, +) +from sglang.srt.model_executor.forward_batch_info import ForwardMode # noqa: E402 +from sglang.srt.model_executor.runner_utils.capture_mode import ( # noqa: E402 + capture_lora_variant, + model_capture_mode, +) +from sglang.srt.models.inkling_common.dense_mlp import ( # noqa: E402 + InklingBatchDenseMLP, +) +from sglang.srt.models.inkling_common.lora import ( # noqa: E402 + InklingBatchDenseMLPWithLoRAV2, +) +from sglang.srt.models.inkling_common.util import deinterleave_gate_up # noqa: E402 +from sglang.srt.runtime_context import get_context, get_parallel # noqa: E402 +from sglang.test.ci.ci_register import register_cuda_ci # noqa: E402 + +register_cuda_ci(est_time=300, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available(), reason="the sink kernels need CUDA" +) + +DEVICE = torch.device("cuda") +DTYPE = torch.bfloat16 +SLOTS, RMAX = 4, 32 +RANKS = [32, 16, 0, 8] # slot 2 holds no adapter +# A pool rank whose shared gate/up bridge (2R = 32 columns) is narrower than +# the shrink's 64-wide column tile. +SMALL_RMAX, SMALL_RANKS = 16, [16, 8, 0, 8] +HIDDEN, N_EXPERTS, F = 256, 2, 128 +TOL = dict(rtol=3e-2, atol=3e-2) +V2 = InklingBatchDenseMLPWithLoRAV2 + + +def _fill_slot(bufs, slot: int, rank: int, g: torch.Generator) -> None: + """One slot as the pool writes it: max-rank spaced, zero tails, pre-scaled B.""" + a_gu, b_gu, a_dn, b_dn = bufs + outer, f, rmax = a_gu.shape[1], b_gu.shape[2] // 2, b_gu.shape[3] + for buf in bufs: + buf[slot].zero_() + if rank == 0: + return + + def rnd(*shape): + return (torch.randn(*shape, generator=g, device=DEVICE) * 0.05).to(DTYPE) + + for half in range(2): + a_gu[slot, :, half * rmax : half * rmax + rank] = rnd(outer, rank, HIDDEN) + b_gu[slot, :, :, :rank] = rnd(N_EXPERTS, 2 * f, rank) + a_dn[slot, :, :rank] = rnd(N_EXPERTS, rank, f) + b_dn[slot, :, :, :rank] = rnd(outer, HIDDEN, rank) + + +def _pool(shared_outer: bool, seed: int, f: int = F, ranks=RANKS, rmax: int = RMAX): + outer = 1 if shared_outer else N_EXPERTS + bufs = ( + torch.zeros(SLOTS, outer, 2 * rmax, HIDDEN, device=DEVICE, dtype=DTYPE), + torch.zeros(SLOTS, N_EXPERTS, 2 * f, rmax, device=DEVICE, dtype=DTYPE), + torch.zeros(SLOTS, N_EXPERTS, rmax, f, device=DEVICE, dtype=DTYPE), + torch.zeros(SLOTS, outer, HIDDEN, rmax, device=DEVICE, dtype=DTYPE), + ) + g = torch.Generator(device=DEVICE).manual_seed(seed) + for slot, rank in enumerate(ranks): + _fill_slot(bufs, slot, rank, g) + return bufs + + +def _swiglu_interleaved(y, gammas): + """Run the fused gated activation for the served interleaved layout.""" + t, n, two_f = y.shape + return silu_and_mul_triton(y.reshape(t * n, two_f), gammas.reshape(-1)).view( + t, n, two_f // 2 + ) + + +def _base_w13(w13_lin): + """Convert each expert to [gate | up]; reference weights stay interleaved.""" + rows = w13_lin.shape[0] // N_EXPERTS + return torch.stack( + [deinterleave_gate_up(e, dim=0) for e in w13_lin.view(N_EXPERTS, rows, -1)] + ).reshape_as(w13_lin) + + +def _reference(layer, x, gammas, w13_lin, w2_lin, bufs, token_slots, shared_outer): + a_gu, b_gu, a_dn, b_dn = (b.float() for b in bufs) + t, n, f, rmax = x.shape[0], N_EXPERTS, b_gu.shape[2] // 2, b_gu.shape[3] + y = (x.float() @ w13_lin.float().T).view(t, n, 2 * f) + for i, s in enumerate(token_slots): + if s < 0: + continue + for e in range(n): + a = a_gu[s, 0 if shared_outer else e] # [2R, hidden] + bridge = ( + (x[i].float() @ a.T).to(DTYPE).float() + ) # bf16 bridge, as the kernels + y[i, e, 0::2] += bridge[:rmax] @ b_gu[s, e, :f].T + y[i, e, 1::2] += bridge[rmax:] @ b_gu[s, e, f:].T + act = _swiglu_interleaved(y.to(DTYPE), gammas) # [t, n, f] + out = act.reshape(t, -1).float() @ w2_lin.float() + for i, s in enumerate(token_slots): + if s < 0: + continue + if shared_outer: + bridge = sum(act[i, e].float() @ a_dn[s, e].T for e in range(n)) + out[i] += bridge.to(DTYPE).float() @ b_dn[s, 0].T + else: + for e in range(n): + bridge = (act[i, e].float() @ a_dn[s, e].T).to(DTYPE).float() + out[i] += bridge @ b_dn[s, e].T + return out + + +def _batch(decode: bool, slots: list[int] | None = None, ranks=RANKS): + seq_lens = [1] * 13 if decode else [5, 17, 1, 9] + if slots is None: + slots = [i % SLOTS for i in range(13)] if decode else [1, 0, 2, 3] + fb = SimpleNamespace( + forward_mode=ForwardMode.DECODE if decode else ForwardMode.EXTEND, + batch_size=len(seq_lens), + extend_seq_lens=torch.tensor(seq_lens, dtype=torch.int32, device=DEVICE), + extend_seq_lens_cpu=list(seq_lens), + extend_num_tokens=int(sum(seq_lens)), + spec_info=None, + return_logprob=False, + extend_logprob_start_lens_cpu=None, + ) + token_slots = [ + slot if ranks[slot] > 0 else -1 + for slot, length in zip(slots, seq_lens) + for _ in range(length) + ] + return fb, slots, token_slots + + +def _inputs(t: int, f: int = F, seed: int = 11): + g = torch.Generator(device=DEVICE).manual_seed(seed) + x = torch.randn(t, HIDDEN, generator=g, device=DEVICE, dtype=DTYPE) + gammas = torch.rand(t, N_EXPERTS, generator=g, device=DEVICE, dtype=DTYPE) + 0.5 + w13_lin = ( + torch.randn(N_EXPERTS * 2 * f, HIDDEN, generator=g, device=DEVICE) * 0.02 + ).to(DTYPE) + w2_lin = (torch.randn(N_EXPERTS * f, HIDDEN, generator=g, device=DEVICE) * 0.02).to( + DTYPE + ) + return x, gammas, w13_lin, w2_lin + + +def _layer(cls, backend, bufs, *, f: int = F, tp_size: int = 1, tp_rank: int = 0): + """The LoRA wrapper on a bare sink (no base weights to build).""" + layer = cls.__new__(cls) + torch.nn.Module.__init__(layer) + layer.n_shared_experts = N_EXPERTS + layer.tp_group = None + layer.inference_moe_w13_interleaved = True + layer._linearized_bf16_enabled = True + layer._w13_gate_up_contiguous = cls is V2 + layer.moe_tp_size, layer.moe_tp_rank = tp_size, tp_rank + layer.intermediate_size_per_partition = f + layer.initialize_lora(backend) + if bufs is not None: + layer.set_lora_info(*bufs) + return layer + + +def _v2_backend(): + backend = TritonV2LoRABackend(SLOTS, DEVICE) + backend.is_moe_lora = True + return backend + + +SINK_PREFIX = "model.layers.0.mlp.experts.shared_experts" + + +def _real_sink( + cls, *, f: int = F, tp_size: int = 1, tp_rank: int = 0, lora_backend=None +): + """Construct under the serving configuration before any weight is loaded.""" + if lora_backend is None: + lora_backend = "triton_v2" if cls is V2 else "triton" + default = torch.get_default_dtype() + torch.set_default_dtype(DTYPE) + try: + # The sink partitions its shared experts over the "tp" group, which + # resolves to the published tp_size and the overridden tp_rank before + # any process group exists. + with ( + get_context().override_server_args( + enable_lora=True, lora_backend=lora_backend, tp_size=tp_size + ), + get_parallel().override(tp_rank=tp_rank), + ): + layer = cls( + n_shared_experts=N_EXPERTS, + d_model=HIDDEN, + shared_d_mlp=f * tp_size, + layer_id=0, + prefix=SINK_PREFIX, + inference_moe_w13_interleaved=True, + parallel_group="tp", + linearized_bf16=True, + ) + finally: + torch.set_default_dtype(default) + return layer.to(DEVICE) + + +def _load_w13(layer, w13_lin): + """Load checkpoint [N, 2F, H] gate/up weights through the TP-sliced loader.""" + full = w13_lin.view(N_EXPERTS, -1, HIDDEN) + layer.weight_loader_fused( + layer.w13_weight, full, f"{SINK_PREFIX}.w13_weight", "w13" + ) + + +def _load_w2(layer, w2_lin): + """Load the linearized [N*F, H] down rows as the checkpoint's [N, H, F].""" + full = w2_lin.view(N_EXPERTS, -1, HIDDEN).transpose(1, 2).contiguous() + layer.weight_loader_fused(layer.w2_weight, full, f"{SINK_PREFIX}.w2_weight", "w2") + + +def _loaded_v2(backend, bufs, w13_lin, w2_lin): + """Load and post-process base weights before attaching the LoRA wrapper.""" + layer = _real_sink(V2) + _load_w13(layer, w13_lin) + _load_w2(layer, w2_lin) + layer.process_weights_after_loading() + layer.initialize_lora(backend) + layer.set_lora_info(*bufs) + return layer + + +def _prepare(backend, fb, slots, ranks=RANKS, *, graph=False, prefill_graph=False): + backend.prepare_lora_batch( + fb, + slots, + list(ranks), + [1.0] * SLOTS, + use_decode_cuda_graph=graph, + use_prefill_cuda_graph=prefill_graph, + ) + backend.batch_info.has_active_lora = any( + slot >= 0 and ranks[slot] > 0 for slot in slots + ) + + +def _forward(layer, x, gammas, w13_lin, w2_lin): + return layer._forward_bf16_linearized( + x, gammas, (w13_lin, w2_lin), use_reduce_scatter=True + ) + + +def _capture(backend, fn): + """Warm up, then capture one forward and return its graph and static output.""" + + def forward(): + backend.reset_routing_cache() + return fn() + + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with model_capture_mode(), capture_lora_variant(None): + with torch.cuda.stream(stream): + forward() + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + out = forward() + return graph, out + + +def _tiles(**overrides): + tiles = dict(DensePlan().a_tiles) + tiles.update(overrides) + return tiles + + +# Overlap.AB_DELTA is site-agnostic apply() plumbing; test_dense_lora_kernels covers it. +PLANS = { + "grouped": DensePlan(), + "grouped_sorted_splitk_serial": DensePlan(a_tiles=_tiles(SPLIT_K=4)), + "grouped_splitk_planes": DensePlan(a_tiles=_tiles(SPLIT_K=2, SPLIT_MODE="planes")), + "grouped_overlap_a": DensePlan(overlap=Overlap.A), + "per_row_a_grouped_b": DensePlan(a_family=AFamily.PER_ROW, overlap=Overlap.A), + "per_row": DensePlan( + a_family=AFamily.PER_ROW, b_family=BFamily.PER_ROW, overlap=Overlap.A + ), + "all_slots": DensePlan(a_family=AFamily.ALL_SLOTS, b_family=BFamily.PER_ROW), + "all_slots_overlap_a": DensePlan( + a_family=AFamily.ALL_SLOTS, b_family=BFamily.PER_ROW, overlap=Overlap.A + ), +} + + +def _pin_plan(backend, plan: DensePlan) -> None: + backend.runner.plan_for = ( + lambda kind, max_rank, in_features=0, out_features=0, *, num_tokens: plan + ) + + +@pytest.mark.parametrize( + "shared_outer,decode,rmax", + [(shared, decode, RMAX) for shared in (True, False) for decode in (True, False)] + + [(True, False, SMALL_RMAX)], +) +def test_v2_tail_width_matches_reference(shared_outer, decode, rmax): + f = 96 + ranks = RANKS if rmax == RMAX else SMALL_RANKS + bufs = _pool(shared_outer, seed=3 + shared_outer, f=f, ranks=ranks, rmax=rmax) + fb, slots, token_slots = _batch(decode, ranks=ranks) + x, gammas, w13_lin, w2_lin = _inputs(fb.extend_num_tokens, f=f) + backend = _v2_backend() + _prepare(backend, fb, slots, ranks) + layer = _layer(V2, backend, bufs, f=f) + out = _forward(layer, x, gammas, _base_w13(w13_lin), w2_lin) + expected = _reference( + layer, x, gammas, w13_lin, w2_lin, bufs, token_slots, shared_outer + ) + torch.testing.assert_close(out.float(), expected, **TOL) + + +@pytest.mark.parametrize( + "shared_outer,plan_name,decode,rmax", + [ + (shared, name, decode, RMAX) + for shared in (True, False) + for name in sorted(PLANS) + if shared or not name.startswith("all_slots") + for decode in (True, False) + ] + + [(shared, "grouped", False, SMALL_RMAX) for shared in (True, False)], +) +def test_v2_every_executor_family(shared_outer, plan_name, decode, rmax): + """Exercise every sink executor with full and partial shrink tiles.""" + ranks = RANKS if rmax == RMAX else SMALL_RANKS + bufs = _pool(shared_outer, seed=5, ranks=ranks, rmax=rmax) + fb, slots, token_slots = _batch(decode, ranks=ranks) + x, gammas, w13_lin, w2_lin = _inputs(fb.extend_num_tokens) + backend = _v2_backend() + _prepare(backend, fb, slots, ranks) + _pin_plan(backend, PLANS[plan_name]) + layer = _layer(V2, backend, bufs) + out = _forward(layer, x, gammas, _base_w13(w13_lin), w2_lin) + expected = _reference( + layer, x, gammas, w13_lin, w2_lin, bufs, token_slots, shared_outer + ) + torch.testing.assert_close(out.float(), expected, **TOL) + + +@pytest.mark.parametrize( + "prefill", [False, True], ids=["decode_graph", "prefill_graph"] +) +@pytest.mark.parametrize("shared_outer", [True, False], ids=["shared", "per_expert"]) +def test_v2_graph_replay_follows_adapters_and_slot_swaps(shared_outer, prefill): + bufs = _pool(shared_outer, seed=9) + fb, slots, token_slots = _batch(not prefill, slots=[2] * (4 if prefill else 13)) + t = fb.extend_num_tokens + x, gammas, w13_lin, w2_lin = _inputs(t) + backend = _v2_backend() + if prefill: + backend.init_prefill_cuda_graph_batch_info(t) + _prepare(backend, fb, slots, prefill_graph=True) + else: + backend.init_decode_cuda_graph_batch_info(fb.batch_size, 1) + _prepare(backend, fb, slots, graph=True) + assert not backend.batch_info.has_active_lora + layer = _layer(V2, backend, bufs) + w13_base = _base_w13(w13_lin) + graph, out = _capture(backend, lambda: _forward(layer, x, gammas, w13_base, w2_lin)) + + def check(token_slots): + graph.replay() + expected = _reference( + layer, x, gammas, w13_lin, w2_lin, bufs, token_slots, shared_outer + ) + torch.testing.assert_close(out.float(), expected, **TOL) + + # Captured on an empty route: every bucket is -1, so the replay is the base. + check(token_slots) + fb, slots, token_slots = _batch(not prefill) + _prepare(backend, fb, slots, graph=not prefill, prefill_graph=prefill) + check(token_slots) + # The next batch routes its requests to other adapters (and one to none). + new_slots = [3, 2, 1, 0] if prefill else [(i + 1) % SLOTS for i in range(13)] + fb2, _, token_slots2 = _batch(not prefill, slots=new_slots) + _prepare(backend, fb2, new_slots, graph=not prefill, prefill_graph=prefill) + check(token_slots2) + # A pool slot is replaced (the empty slot 2 takes a rank-8 adapter, slot 0 + # a new rank-32 one) after capture: the replay reads the new weights. + g = torch.Generator(device=DEVICE).manual_seed(99) + ranks = list(RANKS) + for slot, rank in ((2, 8), (0, 32)): + _fill_slot(bufs, slot, rank, g) + ranks[slot] = rank + layer.on_lora_slots_updated({slot}) + fb3, _, token_slots3 = _batch(not prefill, slots=new_slots, ranks=ranks) + _prepare(backend, fb3, new_slots, ranks, graph=not prefill, prefill_graph=prefill) + check(token_slots3) + + +@pytest.mark.parametrize("shared_outer", [True, False], ids=["shared", "per_expert"]) +def test_v2_tp4_local_shards_sum_to_the_unsharded_output(shared_outer): + """Sum four TP-local base/pool shards, sliced by the wrapper on one GPU.""" + tp, f_full = 4, 256 + f_local = f_full // tp + bufs = _pool(shared_outer, seed=13, f=f_full) + fb, slots, token_slots = _batch(False) + x, gammas, w13_lin, w2_lin = _inputs(fb.extend_num_tokens, f=f_full) + backend = _v2_backend() + _prepare(backend, fb, slots) + full = _layer(V2, backend, bufs, f=f_full) + expected = _reference( + full, x, gammas, w13_lin, w2_lin, bufs, token_slots, shared_outer + ) + torch.testing.assert_close( + _forward(full, x, gammas, _base_w13(w13_lin), w2_lin).float(), + expected, + **TOL, + ) + + a_gu, b_gu, a_dn, b_dn = bufs + total = torch.zeros_like(expected) + for rank in range(tp): + layer = _layer(V2, backend, None, f=f_local, tp_size=tp, tp_rank=rank) + b_gu_r = torch.stack( + [ + layer.slice_moe_lora_b_weights(b_gu[s], rank, "gate_up_proj_moe") + for s in range(SLOTS) + ] + ) + a_dn_r = torch.stack( + [ + layer.slice_moe_lora_a_weights(a_dn[s], rank, "down_proj_moe") + for s in range(SLOTS) + ] + ) + assert b_gu_r.shape == (SLOTS, N_EXPERTS, 2 * f_local, RMAX) + assert a_dn_r.shape == (SLOTS, N_EXPERTS, RMAX, f_local) + layer.set_lora_info(a_gu, b_gu_r, a_dn_r, b_dn) + # Interleaved gate/up rows of this rank's features, and its w2 rows. + w13_r = ( + w13_lin.view(N_EXPERTS, 2 * f_full, HIDDEN)[ + :, 2 * rank * f_local : 2 * (rank + 1) * f_local + ] + .reshape(-1, HIDDEN) + .contiguous() + ) + w2_r = ( + w2_lin.view(N_EXPERTS, f_full, HIDDEN)[ + :, rank * f_local : (rank + 1) * f_local + ] + .reshape(-1, HIDDEN) + .contiguous() + ) + # The layout conversion follows the shard, as it does on the loaded rows. + total += _forward(layer, x, gammas, _base_w13(w13_r), w2_r).float() + torch.testing.assert_close(total, expected, **TOL) + + +@pytest.mark.parametrize( + "prefill,shared_outer", + [(False, True), (True, False)], + ids=["decode_graph-shared", "prefill_graph-per_expert"], +) +def test_w13_reload_through_the_loader_reaches_the_captured_graph( + prefill, shared_outer +): + """Reloads reach the next replay without post-load processing or an eager repair.""" + bufs = _pool(shared_outer, seed=21) + fb, slots, token_slots = _batch(not prefill) + t = fb.extend_num_tokens + x, gammas, w13_lin, w2_lin = _inputs(t) + backend = _v2_backend() + if prefill: + backend.init_prefill_cuda_graph_batch_info(t) + _prepare(backend, fb, slots, prefill_graph=True) + else: + backend.init_decode_cuda_graph_batch_info(fb.batch_size, 1) + _prepare(backend, fb, slots, graph=True) + layer = _loaded_v2(backend, bufs, w13_lin, w2_lin) + assert torch.equal(layer.w13_weight.data.view_as(w13_lin), _base_w13(w13_lin)) + graph, out = _capture( + backend, lambda: layer.forward(x, gammas, use_reduce_scatter=True) + ) + addresses = ( + layer.w13_weight.data_ptr(), + layer.w2_weight.data_ptr(), + layer._w2_lin.data_ptr(), + ) + + def check(w13_now, w2_now): + # The loaded rows are converted exactly once (twice would not be + # [gate | up] either), then the existing graph replays on them. + assert torch.equal(layer.w13_weight.data.view_as(w13_now), _base_w13(w13_now)) + graph.replay() + expected = _reference( + layer, x, gammas, w13_now, w2_now, bufs, token_slots, shared_outer + ) + torch.testing.assert_close(out.float(), expected, **TOL) + assert ( + layer.w13_weight.data_ptr(), + layer.w2_weight.data_ptr(), + layer._w2_lin.data_ptr(), + ) == addresses + + check(w13_lin, w2_lin) + # From here on nothing may repair the weights but the loader itself. + layer.forward = layer.get_bf16_linearized_weights = lambda *a, **k: pytest.fail( + "a reload must not need an eager forward or the linearized getter" + ) + g = torch.Generator(device=DEVICE).manual_seed(31) + + def fresh(like): + return (torch.randn(like.shape, generator=g, device=DEVICE) * 0.02).to(DTYPE) + + w13_a = fresh(w13_lin) + _load_w13(layer, w13_a) # W13 alone + check(w13_a, w2_lin) + w2_b, w13_b = fresh(w2_lin), fresh(w13_lin) + _load_w2(layer, w2_b) # W2, then W13 + _load_w13(layer, w13_b) + check(w13_b, w2_b) + w13_c, w2_c = fresh(w13_lin), fresh(w2_lin) + _load_w13(layer, w13_c) # W13, then W2 + _load_w2(layer, w2_c) + check(w13_c, w2_c) + w13_d = fresh(w13_lin) + _load_w13(layer, w13_d) # and again + check(w13_d, w2_c) + + +@pytest.mark.parametrize("tp_rank", [0, 3]) +@pytest.mark.parametrize("lora_backend", ["triton_v2", "triton"], ids=["v2", "legacy"]) +def test_w13_initial_load_and_reload_use_the_tp_local_layout(tp_rank, lora_backend): + tp, f_full = 4, 256 + f_local = f_full // tp + sink = _real_sink( + InklingBatchDenseMLP, + f=f_local, + tp_size=tp, + tp_rank=tp_rank, + lora_backend=lora_backend, + ) + contiguous = lora_backend == "triton_v2" + assert sink._w13_gate_up_contiguous is contiguous + _, _, w13_lin, w2_lin = _inputs(4, f=f_full) + pointer = sink.w13_weight.data_ptr() + + def rank_rows(w13): + rows = w13.view(N_EXPERTS, 2 * f_full, HIDDEN)[ + :, 2 * tp_rank * f_local : 2 * (tp_rank + 1) * f_local + ] + return ( + torch.stack([deinterleave_gate_up(e, dim=0) for e in rows]) + if contiguous + else rows + ) + + def load_and_check(w13): + original = w13.clone() + _load_w13(sink, w13) + assert torch.equal(w13, original) + assert torch.equal(sink.w13_weight.data, rank_rows(w13)) + assert sink.w13_weight.data_ptr() == pointer + + load_and_check(w13_lin) + _load_w2(sink, w2_lin) + sink.process_weights_after_loading() + assert torch.equal(sink.w13_weight.data, rank_rows(w13_lin)) + lin = sink._w2_lin.clone() + g = torch.Generator(device=DEVICE).manual_seed(41) + for _ in range(2): + w13_new = (torch.randn(w13_lin.shape, generator=g, device=DEVICE) * 0.02).to( + DTYPE + ) + load_and_check(w13_new) + sink.process_weights_after_loading() + rows, _ = sink.get_bf16_linearized_weights() + assert torch.equal(rows, rank_rows(w13_new).reshape_as(rows)) + assert rows.data_ptr() == pointer + assert torch.equal(sink._w2_lin, lin) and sink._bf16_linearized_ready + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/lora/test_dense_lora_kernels.py b/test/registered/kernels/ops/lora/test_dense_lora_kernels.py new file mode 100644 index 0000000000..246e5d2647 --- /dev/null +++ b/test/registered/kernels/ops/lora/test_dense_lora_kernels.py @@ -0,0 +1,782 @@ +"""Dense executors against torch, including stale rank tails and no adapter.""" + +from __future__ import annotations + +import pytest +import torch + +pytest.importorskip("triton") + +from sglang.srt.lora.backend.base_backend import _compute_moe_lora_info # noqa: E402 +from sglang.srt.lora.dense.plan import ( # noqa: E402 + AFamily, + BFamily, + DensePlan, + Overlap, +) +from sglang.srt.lora.dense.runner import DenseLoraRunner # noqa: E402 +from sglang.srt.lora.utils import LoRABatchInfo # noqa: E402 +from sglang.srt.lora.utils import Phase # noqa: E402 +from sglang.srt.lora.workspace import LoraWorkspace # noqa: E402 +from sglang.test.ci.ci_register import register_cuda_ci # noqa: E402 + +register_cuda_ci(est_time=60, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available(), reason="dense LoRA kernels need CUDA" +) + + +DEVICE = torch.device("cuda") +DTYPE = torch.bfloat16 +SLOTS = 4 +RANK_MAX = 64 +RANKS = [64, 32, 0, 16] # slot 2 is the "no adapter" slot +SCALINGS = [2.0, 0.5, 1.0, 1.25] +K_IN = 384 + +SITES = { + "qkv": (0, 512, 640, 768), + "merged": (0, 384, 768), + "column": (0, 512), + "row": (0, 320), +} + +BATCHES = { + # (segment lengths, slot per segment) + "decode": ( + [1] * 37, + [0, 1, 2, 3, 0, 0, 1, 2, 3, 3, 1, 0, 2, 3, 1, 0, 0] * 2 + [1, 3, 0], + ), + "prefill": ([7, 33, 1, 64, 10, 5], [1, 0, 2, 3, 2, 0]), + "single": ([1], [3]), +} + + +def _pool(offsets: tuple[int, ...], generator: torch.Generator): + """Store slice s at A rows [s*r, (s+1)*r) and B columns [0, r). + Leave stale values beyond each adapter rank to catch out-of-rank reads. + """ + stack = len(offsets) - 1 + width = offsets[-1] + a = ( + torch.randn(SLOTS, stack * RANK_MAX, K_IN, generator=generator, device=DEVICE) + * 100 + ) + b = torch.randn(SLOTS, width, RANK_MAX, generator=generator, device=DEVICE) * 100 + for slot, rank in enumerate(RANKS): + a[slot, : stack * rank] = ( + torch.randn(stack * rank, K_IN, generator=generator, device=DEVICE) * 0.05 + ) + b[slot, :, :rank] = ( + torch.randn(width, rank, generator=generator, device=DEVICE) * 0.05 + ) + return a.to(DTYPE), b.to(DTYPE) + + +def _reference(x, a, b, offsets, token_slots): + out = torch.zeros(x.shape[0], offsets[-1], dtype=torch.float32, device=DEVICE) + stack = len(offsets) - 1 + for t in range(x.shape[0]): + slot = int(token_slots[t]) + if slot < 0: + continue + rank = RANKS[slot] + if rank == 0: + continue + for s in range(stack): + bridge = (x[t].float() @ a[slot, s * rank : (s + 1) * rank].float().T).to( + DTYPE + ) + out[t, offsets[s] : offsets[s + 1]] += SCALINGS[slot] * ( + bridge.float() @ b[slot, offsets[s] : offsets[s + 1], :rank].float().T + ) + return out + + +def _batch(name): + seg_lens, seg_slots = BATCHES[name] + seg_lens_t = torch.tensor(seg_lens, dtype=torch.int32, device=DEVICE) + seg_indptr = torch.zeros(len(seg_lens) + 1, dtype=torch.int32, device=DEVICE) + seg_indptr[1:] = torch.cumsum(seg_lens_t, 0) + weight_indices = torch.tensor(seg_slots, dtype=torch.int32, device=DEVICE) + token_slots = torch.repeat_interleave(weight_indices, seg_lens_t) + token_slots = torch.where( + torch.tensor( + [RANKS[s] > 0 for s in seg_slots], device=DEVICE + ).repeat_interleave(seg_lens_t), + token_slots, + torch.full_like(token_slots, -1), + ) + batch_info = LoRABatchInfo( + use_cuda_graph=False, + bs=len(seg_lens), + num_segments=len(seg_lens), + seg_indptr=seg_indptr, + weight_indices=weight_indices, + lora_ranks=torch.tensor(RANKS, dtype=torch.int64, device=DEVICE), + scalings=torch.tensor(SCALINGS, dtype=torch.float32, device=DEVICE), + max_len=max(seg_lens), + seg_lens=seg_lens_t, + permutation=None, + ) + return batch_info, token_slots + + +def _engine(batch_info, token_slots, phase): + engine = DenseLoraRunner(LoraWorkspace(), max_loras=SLOTS, device=DEVICE) + engine.begin_batch( + token_slots=token_slots, + lora_ranks=batch_info.lora_ranks, + scalings=batch_info.scalings, + num_tokens=int(batch_info.seg_indptr[-1]), + phase=phase, + graph_mode=False, + ) + return engine + + +PLANS = { + "sorted16": DensePlan(block_size=16), + "sorted64": DensePlan(block_size=64), + "sorted16_ov": DensePlan(block_size=16, overlap=Overlap.A), + "sorted16_gA_prB": DensePlan(block_size=16, b_family=BFamily.PER_ROW), + "sorted16_splitk4": DensePlan( + block_size=16, + a_tiles={**DensePlan().a_tiles, "SPLIT_K": 4}, + ), + "sorted16_splitk8_prB": DensePlan( + block_size=16, + b_family=BFamily.PER_ROW, + a_tiles={**DensePlan().a_tiles, "SPLIT_K": 8}, + ), + "grouped64_splitk3": DensePlan( + block_size=64, a_tiles={**DensePlan().a_tiles, "SPLIT_K": 3} + ), + "sorted16_splitk4_planes": DensePlan( + block_size=16, + a_tiles={**DensePlan().a_tiles, "SPLIT_K": 4, "SPLIT_MODE": "planes"}, + ), + "grouped64_splitk8_planes_ov": DensePlan( + block_size=64, + overlap=Overlap.A, + a_tiles={**DensePlan().a_tiles, "SPLIT_K": 8, "SPLIT_MODE": "planes"}, + ), + "sorted16_splitk8_planes_prB_ov": DensePlan( # planes summed by the per-row expand + block_size=16, + b_family=BFamily.PER_ROW, + overlap=Overlap.A, + a_tiles={**DensePlan().a_tiles, "SPLIT_K": 8, "SPLIT_MODE": "planes"}, + ), + "per_row": DensePlan(a_family=AFamily.PER_ROW, b_family=BFamily.PER_ROW), + "all_slots": DensePlan(a_family=AFamily.ALL_SLOTS, b_family=BFamily.PER_ROW), + "overlap_ab_delta": DensePlan(overlap=Overlap.AB_DELTA), + "per_row_ab_delta": DensePlan( + a_family=AFamily.PER_ROW, b_family=BFamily.PER_ROW, overlap=Overlap.AB_DELTA + ), +} + + +@pytest.mark.parametrize( + "batch_name,site_kind,plan_name", + [("decode", "qkv", plan) for plan in PLANS] + # overlap only reschedules streams, so its plans run on decode alone + + [("prefill", "qkv", plan) for plan in PLANS if not plan.endswith("_ov")] + + [ + ("prefill", site, plan) + for site in ("merged", "column") + for plan in ("sorted16", "per_row", "all_slots") + ] + + [("single", "column", plan) for plan in ("sorted16", "per_row", "all_slots")], +) +def test_engine_matches_reference(batch_name, site_kind, plan_name): + generator = torch.Generator(device=DEVICE).manual_seed(7) + offsets = SITES[site_kind] + a, b = _pool(offsets, generator) + batch_info, token_slots = _batch(batch_name) + num_tokens = int(batch_info.seg_indptr[-1]) + x = torch.randn(num_tokens, K_IN, generator=generator, device=DEVICE, dtype=DTYPE) + base = torch.randn( + num_tokens, offsets[-1], generator=generator, device=DEVICE, dtype=DTYPE + ) + + phase = Phase.PREFILL if batch_name == "prefill" else Phase.DECODE + engine = _engine(batch_info, token_slots, phase) + assert torch.equal(engine.token_slots, token_slots) + out = engine.apply( + x, + lambda: base.clone(), + PLANS[plan_name], + a=a, + b=b, + offsets=offsets, + ) + + expected = base.float() + _reference(x, a, b, offsets, token_slots) + torch.testing.assert_close(out.float(), expected, rtol=2e-2, atol=2e-2) + + +@pytest.mark.parametrize("overlap", [Overlap.NONE, Overlap.AB_DELTA]) +def test_row_site_with_all_reduce(overlap): + """Reduce the complete base + LoRA output exactly once.""" + generator = torch.Generator(device=DEVICE).manual_seed(3) + offsets = SITES["row"] + a, b = _pool(offsets, generator) + batch_info, token_slots = _batch("decode") + num_tokens = int(batch_info.seg_indptr[-1]) + x = torch.randn(num_tokens, K_IN, generator=generator, device=DEVICE, dtype=DTYPE) + base = torch.randn( + num_tokens, offsets[-1], generator=generator, device=DEVICE, dtype=DTYPE + ) + + engine = _engine(batch_info, token_slots, Phase.DECODE) + plan = DensePlan(overlap=overlap) + reduced_shapes = [] + + def all_reduce(tensor): + reduced_shapes.append(tensor.shape) + return tensor * 2 + + out = engine.apply( + x, + lambda: base.clone(), + plan, + all_reduce=all_reduce, + a=a, + b=b, + offsets=offsets, + ) + + expected = 2 * (base.float() + _reference(x, a, b, offsets, token_slots)) + torch.testing.assert_close(out.float(), expected, rtol=2e-2, atol=4e-2) + assert reduced_shapes == [base.shape] + + +@pytest.mark.parametrize("overlap", [Overlap.A, Overlap.AB_DELTA]) +def test_graph_mode_buffers_are_stable_and_capture_replays(overlap): + """Warm in graph mode, capture one forward, replay with new inputs.""" + generator = torch.Generator(device=DEVICE).manual_seed(5) + offsets = SITES["qkv"] + a, b = _pool(offsets, generator) + batch_info, token_slots = _batch("decode") + num_tokens = int(batch_info.seg_indptr[-1]) + x = torch.randn(num_tokens, K_IN, generator=generator, device=DEVICE, dtype=DTYPE) + base = torch.randn( + num_tokens, offsets[-1], generator=generator, device=DEVICE, dtype=DTYPE + ) + out = torch.empty_like(base) + + engine = DenseLoraRunner(LoraWorkspace(), max_loras=SLOTS, device=DEVICE) + plan = DensePlan(overlap=overlap) + # The graph-static map is larger than any live batch, as the backend + # allocates it at graph init. + static_slots = torch.full((num_tokens + 27,), -1, dtype=torch.int32, device=DEVICE) + + def begin(live_requests: int = num_tokens): + # Reset inactive slots to -1 but retain full static route capacity, + # padding sentinel, and pair count as the live batch changes. + _compute_moe_lora_info( + live_requests, + batch_info.seg_indptr[: live_requests + 1], + batch_info.lora_ranks, + batch_info.weight_indices[:live_requests], + None, + static_slots, + max_len=batch_info.max_len, + ) + engine.begin_batch( + token_slots=static_slots, + lora_ranks=batch_info.lora_ranks, + scalings=batch_info.scalings, + num_tokens=live_requests, + phase=Phase.DECODE, + graph_mode=True, + ) + + def forward(): + engine.reset_routes() + out.copy_( + engine.apply( + x, + lambda: base.clone(), + plan, + a=a, + b=b, + offsets=offsets, + ) + ) + + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + begin() + forward() # warmup allocates every workspace buffer + route_before = engine.route(plan.block_size).sorted_pair_ids.data_ptr() + torch.cuda.current_stream().wait_stream(stream) + + graph = torch.cuda.CUDAGraph() + begin() + with torch.cuda.graph(graph, stream=stream): + forward() + captured_route = engine.route(plan.block_size) + assert captured_route.sorted_pair_ids.data_ptr() == route_before + + # Only input metadata changes outside the graph; replay rebuilds routing. + x.copy_( + torch.randn(num_tokens, K_IN, generator=generator, device=DEVICE, dtype=DTYPE) + ) + base.copy_( + torch.randn( + num_tokens, offsets[-1], generator=generator, device=DEVICE, dtype=DTYPE + ) + ) + batch_info.weight_indices.copy_(torch.roll(batch_info.weight_indices, 1)) + begin() + assert not engine.workspace.routes + captured_route.sorted_pair_ids.fill_(-7) + captured_route.block_bucket_ids.fill_(-7) + captured_route.num_pairs_post_padded.zero_() + graph.replay() + torch.cuda.synchronize() + expected = base.float() + _reference(x, a, b, offsets, static_slots[:num_tokens]) + torch.testing.assert_close(out.float(), expected, rtol=2e-2, atol=2e-2) + + # A smaller live batch replays the same graph: rows past the live tokens + # must see no adapter (the map's tail is re-armed to -1 each batch). + live = num_tokens - 13 + begin(live) + assert torch.all(static_slots[live:] == -1) + assert not engine.workspace.routes + assert captured_route.sorted_pair_ids.data_ptr() == route_before + captured_route.sorted_pair_ids.fill_(-7) + captured_route.block_bucket_ids.fill_(-7) + captured_route.num_pairs_post_padded.zero_() + graph.replay() + torch.cuda.synchronize() + expected = base.float() + _reference(x, a, b, offsets, static_slots[:num_tokens]) + torch.testing.assert_close(out.float(), expected, rtol=2e-2, atol=2e-2) + + +def test_two_sites_on_two_streams_keep_separate_scratch(): + """Concurrent graph sites must not share scratch.""" + generator = torch.Generator(device=DEVICE).manual_seed(5) + sites = {"wide": SITES["qkv"], "narrow": (0, 64)} + pools = {name: _pool(offsets, generator) for name, offsets in sites.items()} + plans = { + "wide": DensePlan( + b_family=BFamily.PER_ROW, + overlap=Overlap.A, + a_tiles={**DensePlan().a_tiles, "SPLIT_K": 8}, + ), + "narrow": DensePlan( + b_family=BFamily.PER_ROW, + overlap=Overlap.A, + a_tiles={**DensePlan().a_tiles, "SPLIT_K": 4}, + ), + } + batch_info, token_slots = _batch("decode") + num_tokens = int(batch_info.seg_indptr[-1]) + x = torch.randn(num_tokens, K_IN, generator=generator, device=DEVICE, dtype=DTYPE) + bases = { + name: torch.randn( + num_tokens, offsets[-1], generator=generator, device=DEVICE, dtype=DTYPE + ) + for name, offsets in sites.items() + } + outs = {name: torch.empty_like(base) for name, base in bases.items()} + # the wider site's base GEMM in a model outlasts the narrower site's shrink; + # a fixed filler keeps that window, so a shared bridge would be overwritten + # before the wider expand reads it + filler = torch.randn(1536, 1536, generator=generator, device=DEVICE) + + def base_fn(name): + if name == "wide": + for _ in range(4): + torch.matmul(filler, filler) + return bases[name].clone() + + def apply(engine, name): + a, b = pools[name] + return engine.apply( + x, lambda: base_fn(name), plans[name], a=a, b=b, offsets=sites[name] + ) + + def bind(engine, graph_mode): + engine.begin_batch( + token_slots=token_slots, + lora_ranks=batch_info.lora_ranks, + scalings=batch_info.scalings, + num_tokens=num_tokens, + phase=Phase.DECODE, + graph_mode=graph_mode, + ) + + shared = DenseLoraRunner(LoraWorkspace(), max_loras=SLOTS, device=DEVICE) + stream, alt = torch.cuda.Stream(), torch.cuda.Stream() + + def forward(): + shared.reset_routes() + current = torch.cuda.current_stream() + alt.wait_stream(current) + outs["wide"].copy_(apply(shared, "wide")) + with torch.cuda.stream(alt): + outs["narrow"].copy_(apply(shared, "narrow")) + current.wait_stream(alt) + + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + bind(shared, graph_mode=True) + forward() # warm-up on the capture stream allocates both streams' scratch + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + bind(shared, graph_mode=True) + with torch.cuda.graph(graph, stream=stream): + forward() + + serial = { + name: DenseLoraRunner(LoraWorkspace(), max_loras=SLOTS, device=DEVICE) + for name in sites + } + for _ in range(4): + x.copy_(torch.randn_like(x)) + for base in bases.values(): + base.copy_(torch.randn_like(base)) + bind(shared, graph_mode=True) + graph.replay() + torch.cuda.synchronize() + for name in sites: + bind(serial[name], graph_mode=False) + expected = apply(serial[name], name) + torch.cuda.synchronize() + assert torch.equal(outs[name], expected), name + counters = [ + storage + for key, storage in shared.workspace._graph_storage.items() + if key[0] == "dense:splitk_counters" + ] + assert len(counters) >= 2 and not any(bool(c.any()) for c in counters) + + +def test_workspace_side_streams_are_keyed_by_the_calling_stream(): + """Different caller streams need independent side streams and fork/join events.""" + workspace = LoraWorkspace() + main, alt = torch.cuda.Stream(), torch.cuda.Stream() + with torch.cuda.stream(main): + side_main = workspace.side_stream(DEVICE) + ready_main = workspace.event(DEVICE, "x:ready") + with torch.cuda.stream(alt): + side_alt = workspace.side_stream(DEVICE) + ready_alt = workspace.event(DEVICE, "x:ready") + assert side_main is not side_alt and side_main not in (main, alt) + assert ready_main is not ready_alt + with torch.cuda.stream(main): + assert workspace.side_stream(DEVICE) is side_main # stable per calling stream + + # concurrent forks from both streams, each joining only its own side work + x = torch.randn(4096, 4096, device=DEVICE, dtype=DTYPE) + y = torch.randn(4096, 4096, device=DEVICE, dtype=DTYPE) + ref_main = (x @ y) + x.sum(dim=0, keepdim=True) + ref_alt = (y @ x) + y.sum(dim=0, keepdim=True) + outs = {} + + def run(name, a, b): + holder = {} + side = lambda: holder.__setitem__("s", a.sum(dim=0, keepdim=True)) + base = workspace.run_parallel( + name="x", device=DEVICE, compute=lambda: a @ b, side=side + ) + outs[name] = base + holder["s"] + + for _ in range(3): + with torch.cuda.stream(main): + run("main", x, y) + with torch.cuda.stream(alt): + run("alt", y, x) + torch.cuda.synchronize() + torch.testing.assert_close(outs["main"], ref_main) + torch.testing.assert_close(outs["alt"], ref_alt) + + +@pytest.mark.parametrize( + "zero_sentinel,add_inplace", + # dense never zeroes the sentinel; MoE zeroes it only when overwriting + [(False, False), (False, True), (True, False)], +) +@pytest.mark.parametrize("blocks", [9, 36], ids=["short", "oversized"]) +def test_grouped_b_retained_graphs_with_different_column_counts( + zero_sentinel, add_inplace, blocks +): + from sglang.kernels.ops.lora.common.lora_b import grouped_lora_b, slice_geometry + from sglang.kernels.ops.lora.common.route_view import RouteView, RouteViewKind + + def make_case(widths): + tokens, rank, block = 51, 16, 16 + width, slices = sum(widths), len(widths) + capacity = (blocks - 1) * block + 3 + bridge = torch.empty( + (tokens, slices * rank), dtype=torch.bfloat16, device="cuda" + ) + weight = torch.empty((2, width, rank), dtype=torch.bfloat16, device="cuda") + output = torch.empty((tokens, width), dtype=torch.bfloat16, device="cuda") + ranks = torch.empty(2, dtype=torch.int32, device="cuda") + scalings = torch.empty(2, dtype=torch.float32, device="cuda") + route = RouteView( + view=RouteViewKind.ALIGNED, + block_size=block, + token_slots=torch.full((tokens,), -1, dtype=torch.int32, device="cuda"), + group_ids=None, + groups_per_slot=1, + max_loras=2, + maybe_sorted_pair_ids=torch.empty( + capacity, dtype=torch.int32, device="cuda" + ), + maybe_block_bucket_ids=torch.empty( + blocks, dtype=torch.int32, device="cuda" + ), + maybe_num_pairs_post_padded=torch.empty( + 1, dtype=torch.int32, device="cuda" + ), + ) + starts = [0] + for size in widths: + starts.append(starts[-1] + size) + geometry = slice_geometry(starts, 64, torch.device("cuda")) + if len(set(widths)) > 1: + # An extra column tile exercises _slice_of_tile's no-slice return. + geometry = geometry._replace(num_column_tiles=geometry.num_column_tiles + 1) + + def launch(): + grouped_lora_b( + bridge, + weight, + output, + route, + geometry=geometry, + config={ + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 16, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2, + }, + add_inplace=add_inplace, + zero_sentinel=zero_sentinel, + lora_ranks=ranks, + scalings=scalings, + ) + + def prepare(live_blocks, iteration): + generator = torch.Generator().manual_seed(9127 + iteration) + bridge_cpu = ( + torch.randn(tokens, slices * rank, generator=generator) * 0.25 + ).bfloat16() + weight_cpu = ( + torch.randn(2, width, rank, generator=generator) * 0.25 + ).bfloat16() + ranks_cpu = [0 if iteration == 3 else 16, 8 if iteration % 2 == 0 else 16] + scales_cpu = [0.5 + iteration * 0.25, 1.5 - iteration * 0.125] + expected = torch.full((tokens, width), 7.0, dtype=torch.bfloat16) + ids = torch.full((capacity,), -(1 << 20), dtype=torch.int32) + bucket_ids = torch.full((blocks,), 12345, dtype=torch.int32) + mapping = torch.full((tokens,), -1, dtype=torch.int32) + ids[: min(live_blocks * block, capacity)] = tokens + bucket_ids[:live_blocks] = -1 + active = {} + if live_blocks: + active[0] = (1 - iteration % 2, list(range(16))) + if live_blocks >= 2: + active[1] = (-1, list(range(16, 32))) + if live_blocks == 3: + active[2] = (1, list(range(32, 48))) + if live_blocks == blocks: + active[3] = (-1 if iteration == 0 else 0, list(range(32, 48))) + active[blocks - 1] = (1, list(range(48, 51))) + for block_id, (bucket_id, rows) in active.items(): + bucket_ids[block_id] = bucket_id + begin = block_id * block + ids[begin : begin + len(rows)] = torch.tensor(rows, dtype=torch.int32) + mapping[rows] = bucket_id + if bucket_id == -1: + if zero_sentinel: + expected[rows] = 0 + elif ranks_cpu[bucket_id]: + active_rank = ranks_cpu[bucket_id] + for slice_id, size in enumerate(widths): + start, end = starts[slice_id : slice_id + 2] + bridge_start = slice_id * active_rank + delta = ( + bridge_cpu[ + rows, bridge_start : bridge_start + active_rank + ].float() + @ weight_cpu[bucket_id, start:end, :active_rank].float().T + ) + delta *= scales_cpu[bucket_id] + if add_inplace: + delta += expected[rows, start:end].float() + expected[rows, start:end] = delta.bfloat16() + bridge.copy_(bridge_cpu) + weight.copy_(weight_cpu) + ranks.copy_(torch.tensor(ranks_cpu, dtype=torch.int32)) + scalings.copy_(torch.tensor(scales_cpu, dtype=torch.float32)) + route.sorted_pair_ids.copy_(ids) + route.block_bucket_ids.copy_(bucket_ids) + route.num_pairs_post_padded.fill_(live_blocks * block) + route.token_slots.copy_(mapping) + output.fill_(7) + return expected + + prepare(blocks, 0) + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + launch() + launch() + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + launch() + torch.cuda.current_stream().wait_stream(stream) + + return prepare, launch, graph, output + + cases = [make_case(widths) for widths in ((64,), (128, 128), (65, 70))] + for iteration, live_blocks in enumerate((blocks, 2, 0, blocks, 3, blocks)): + for prepare, launch, graph, output in cases if iteration % 2 else cases[::-1]: + expected = prepare(live_blocks, iteration) + graph.replay() + torch.testing.assert_close(output.cpu(), expected, atol=5e-3, rtol=2e-2) + output.fill_(7) + launch() + torch.testing.assert_close(output.cpu(), expected, atol=5e-3, rtol=2e-2) + + +def _poisoned_tail_expand_case(family, planes, seed=4111): + """Expand inputs whose inactive rank tails hold NaN. + + Pool rank 128 with live ranks 96 and 128 and BLOCK_SIZE_K 64: the live + rank of slot 0 splits the second K block, so the whole-block loads read + the poisoned lanes and must drop them. Rows 38 and 39 carry no adapter. + Returns the launch, the output, the expected output and the inputs. + """ + from sglang.kernels.ops.lora.common.lora_b import ( + grouped_lora_b, + per_row_lora_b, + slice_geometry, + ) + from sglang.kernels.ops.lora.common.route_view import RouteView, RouteViewKind + + tokens, pool_rank, width, block = 40, 128, 256, 16 + ranks, scalings = [96, 128], [1.0, 0.5] + generator = torch.Generator().manual_seed(seed) + slot_rows = {0: list(range(24)), 1: list(range(24, 38))} + token_slots_cpu = torch.full((tokens,), -1, dtype=torch.int32) + for slot, rows in slot_rows.items(): + token_slots_cpu[rows] = slot + if planes == 1: + bridge_cpu = (torch.randn(tokens, pool_rank, generator=generator) * 0.25).to( + torch.bfloat16 + ) + else: + bridge_cpu = torch.randn(planes, tokens, pool_rank, generator=generator) * 0.05 + weight_cpu = ( + torch.randn(2, width, pool_rank, generator=generator) * 0.25 + ).bfloat16() + expected = torch.full((tokens, width), 7.0, dtype=torch.bfloat16) + for slot, rows in slot_rows.items(): + rank = ranks[slot] + if planes == 1: + summed = bridge_cpu[rows].float() + else: + # Planes are summed in order and rounded to bf16 before the expand. + summed = bridge_cpu[0, rows].clone() + for p in range(1, planes): + summed += bridge_cpu[p, rows] + summed = summed.bfloat16().float() + expected[rows] = ( + scalings[slot] * (summed[:, :rank] @ weight_cpu[slot, :, :rank].float().T) + ).bfloat16() + if rank < pool_rank: + bridge_cpu[..., rows, rank:] = float("nan") + weight_cpu[slot, :, rank:] = float("nan") + bridge_cpu[..., 38:, :] = float("nan") + + bridge = bridge_cpu.to(DEVICE) + weight = weight_cpu.to(DEVICE) + output = torch.full((tokens, width), 7.0, dtype=torch.bfloat16, device=DEVICE) + token_slots = token_slots_cpu.to(DEVICE) + lora_ranks = torch.tensor(ranks, dtype=torch.int32, device=DEVICE) + scales = torch.tensor(scalings, dtype=torch.float32, device=DEVICE) + geometry = slice_geometry([0, width], 128, DEVICE) + config = { + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2, + } + if family == "grouped": + # Three aligned blocks: slot 0 fills blocks 0-1, slot 1 block 2; the + # pad entries carry the pair count and the base-only rows stay out. + pad = tokens + ids = list(range(16)) + list(range(16, 24)) + [pad] * 8 + ids += list(range(24, 38)) + [pad] * 2 + route = RouteView( + view=RouteViewKind.ALIGNED, + block_size=block, + token_slots=token_slots, + group_ids=None, + groups_per_slot=1, + max_loras=2, + maybe_sorted_pair_ids=torch.tensor(ids, dtype=torch.int32, device=DEVICE), + maybe_block_bucket_ids=torch.tensor( + [0, 0, 1], dtype=torch.int32, device=DEVICE + ), + maybe_num_pairs_post_padded=torch.tensor( + [3 * block], dtype=torch.int32, device=DEVICE + ), + ) + expand = grouped_lora_b + else: + route = RouteView( + view=RouteViewKind.RAW, + block_size=block, + token_slots=token_slots, + group_ids=None, + groups_per_slot=1, + max_loras=2, + ) + expand = per_row_lora_b + + def launch(): + expand( + bridge, + weight, + output, + route, + geometry=geometry, + config=config, + add_inplace=False, + zero_sentinel=False, + lora_ranks=lora_ranks, + scalings=scales, + planes=planes, + ) + + return launch, output, expected, {"bridge": bridge, "weight": weight} + + +@pytest.mark.parametrize("planes", [1, 8]) +@pytest.mark.parametrize("family", ["grouped", "per_row"]) +def test_expand_whole_block_loads_drop_poisoned_rank_tails(family, planes): + launch, output, expected, inputs = _poisoned_tail_expand_case(family, planes) + assert not torch.isfinite(inputs["bridge"]).all() + assert not torch.isfinite(inputs["weight"]).all() + launch() + torch.cuda.synchronize() + result = output.float().cpu() + assert torch.isfinite(result).all() + torch.testing.assert_close(result, expected.float(), atol=5e-3, rtol=2e-2) + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/lora/test_dense_lora_mla_correction.py b/test/registered/kernels/ops/lora/test_dense_lora_mla_correction.py new file mode 100644 index 0000000000..7414381c13 --- /dev/null +++ b/test/registered/kernels/ops/lora/test_dense_lora_mla_correction.py @@ -0,0 +1,356 @@ +"""Absorbed MLA correction: legacy parity, rounded reference, and graph replay.""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +import torch + +pytest.importorskip("triton") + +from sglang.kernels.ops.lora.dense.kv_b_lora_absorbed import ( # noqa: E402 + step_a_q_fwd, + step_a_v_fwd, + step_b_q_fwd, + step_b_v_fwd, +) +from sglang.srt.lora.backend.base_backend import _compute_moe_lora_info # noqa: E402 +from sglang.srt.lora.dense import mla_correction # noqa: E402 +from sglang.srt.lora.dense.runner import DenseLoraRunner # noqa: E402 +from sglang.srt.lora.utils import LoRABatchInfo, Phase # noqa: E402 +from sglang.srt.lora.workspace import LoraWorkspace # noqa: E402 +from sglang.test.ci.ci_register import register_cuda_ci # noqa: E402 + +register_cuda_ci(est_time=40, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available(), reason="the correction kernels need CUDA" +) + +DEVICE = torch.device("cuda") +DTYPE = torch.bfloat16 +SLOTS = 4 +RANKS = [32, 16, 0, 8] +SCALINGS = [1.5, 0.5, 1.0, 2.0] +HEADS, QK_NOPE, V_HEAD, KV_RANK = 8, 128, 128, 512 +FULL_K = QK_NOPE + V_HEAD + + +def _batch(decode, tokens=None, *, ranks=RANKS): + seq_lens, slots = ( + ([1] * 13, [i % SLOTS for i in range(13)]) + if decode + else ([5, 17, 1, 9], [1, 0, 2, 3]) + ) + if tokens is not None: + seq_lens, slots = [1] * tokens, [i % SLOTS for i in range(tokens)] + seg_lens = torch.tensor(seq_lens, dtype=torch.int32, device=DEVICE) + seg_indptr = torch.zeros(len(seq_lens) + 1, dtype=torch.int32, device=DEVICE) + seg_indptr[1:] = torch.cumsum(seg_lens, 0) + info = LoRABatchInfo( + use_cuda_graph=False, + bs=len(seq_lens), + num_segments=len(seq_lens), + seg_indptr=seg_indptr, + weight_indices=torch.tensor(slots, dtype=torch.int32, device=DEVICE), + lora_ranks=torch.tensor(ranks, dtype=torch.int64, device=DEVICE), + scalings=torch.tensor(SCALINGS, dtype=torch.float32, device=DEVICE), + max_len=max(seq_lens), + seg_lens=seg_lens, + permutation=None, + ) + token_slots = [ + s if ranks[s] > 0 else -1 + for s, length in zip(slots, seq_lens) + for _ in range(length) + ] + return info, token_slots + + +def _engine(info, token_slots, decode, *, graph_mode=False): + engine = DenseLoraRunner(LoraWorkspace(), max_loras=SLOTS, device=DEVICE) + engine.begin_batch( + token_slots=torch.tensor(token_slots, dtype=torch.int32, device=DEVICE), + lora_ranks=info.lora_ranks, + scalings=info.scalings, + num_tokens=len(token_slots), + phase=Phase.DECODE if decode else Phase.PREFILL, + graph_mode=graph_mode, + is_prefill_graph=graph_mode and not decode, + ) + return engine + + +def _pool(seed, heads=HEADS, *, qk_nope=QK_NOPE, v_dim=V_HEAD, kv=KV_RANK, ranks=RANKS): + g = torch.Generator(device=DEVICE).manual_seed(seed) + full_k, rank_max = qk_nope + v_dim, max(ranks) + # Inactive rank tails deliberately contain stale pool contents. + a = torch.randn(SLOTS, rank_max, kv, generator=g, device=DEVICE) * 100 + b = torch.randn(SLOTS, heads * full_k, rank_max, generator=g, device=DEVICE) * 100 + for slot, rank in enumerate(ranks): + a[slot, :rank] = torch.randn(rank, kv, generator=g, device=DEVICE) * 0.05 + b[slot, :, :rank] = ( + torch.randn(heads * full_k, rank, generator=g, device=DEVICE) * 0.05 + ) + return a.to(DTYPE).contiguous(), b.to(DTYPE).contiguous() + + +def _attention(engine, info, a, b, heads=HEADS, *, qk_nope=QK_NOPE, v_dim=V_HEAD): + return SimpleNamespace( + num_local_heads=heads, + qk_nope_head_dim=qk_nope, + v_head_dim=v_dim, + kv_b_proj=SimpleNamespace( + set_lora=True, + A_buffer=a, + B_buffer=b, + lora_backend=SimpleNamespace( + name="triton_v2", runner=engine, batch_info=info + ), + ), + ) + + +def _reference(x, a, b, slots, side, *, ranks=RANKS, scales=SCALINGS, qk_nope=QK_NOPE): + tokens, heads, _ = x.shape + full_k = b.shape[1] // heads + width = a.shape[-1] if side == "q" else full_k - qk_nope + delta = torch.zeros(tokens, heads, width, dtype=torch.float32, device=x.device) + for token, slot in enumerate(slots): + if slot < 0 or ranks[slot] == 0: + continue + rank = ranks[slot] + b_heads = b[slot, :, :rank].reshape(heads, full_k, rank).float() + if side == "q": + bridge = torch.einsum("hk,hkr->hr", x[token].float(), b_heads[:, :qk_nope]) + bridge = bridge.to(DTYPE).float() # The shrink materializes a BF16 bridge. + value = bridge @ a[slot, :rank].float() + else: + bridge = (x[token].float() @ a[slot, :rank].float().T).to(DTYPE).float() + value = torch.einsum("hr,hkr->hk", bridge, b_heads[:, qk_nope:]) + delta[token] = value * scales[slot] + return delta + + +@pytest.mark.parametrize("decode", [True, False]) +@pytest.mark.parametrize("side", ["q", "v"]) +def test_correction_matches_legacy_and_reference(decode, side): + info, slots = _batch(decode) + a, b = _pool(5) + attention = _attention(_engine(info, slots, decode), info, a, b) + g = torch.Generator(device=DEVICE).manual_seed(7) + input_dim, output_dim = (QK_NOPE, KV_RANK) if side == "q" else (KV_RANK, V_HEAD) + x = torch.randn( + len(slots), HEADS, input_dim, generator=g, device=DEVICE, dtype=DTYPE + ) + base = torch.randn( + len(slots), HEADS, output_dim, generator=g, device=DEVICE, dtype=DTYPE + ) + prepare = ( + mla_correction.prepare_q_correction + if side == "q" + else mla_correction.prepare_v_correction + ) + prepared = prepare(attention, x) + assert (prepared.done is not None) == decode + destination = base.clone() + ours = mla_correction.apply_correction( + prepared, destination if side == "q" else destination.flatten(1, 2) + ).view_as(base) + if side == "q": + legacy = step_b_q_fwd(step_a_q_fwd(x, b, info, FULL_K), a, info, base.clone()) + else: + legacy = base.clone() + step_b_v_fwd(step_a_v_fwd(x, a, info), b, info, legacy, QK_NOPE, V_HEAD) + torch.testing.assert_close(ours.float(), legacy.float(), rtol=2e-2, atol=2e-2) + torch.testing.assert_close( + ours.float(), + base.float() + _reference(x, a, b, slots, side), + rtol=2e-2, + atol=2e-2, + ) + + +@pytest.mark.parametrize("mode", ["eager", "decode_graph", "prefill_graph"]) +def test_pair_route_stream_reuse_and_replay(monkeypatch, mode): + decode = mode != "prefill_graph" + info, slots = _batch(decode) + tokens = len(slots) + engine = _engine(info, slots, decode, graph_mode=mode != "eager") + layers = [_attention(engine, info, *_pool(seed)) for seed in (31, 37)] + # Flattening this Q copies; the copy must precede the side-stream ready event. + q = torch.randn(HEADS, tokens, QK_NOPE, device=DEVICE, dtype=DTYPE).transpose(0, 1) + v = torch.randn(tokens, HEADS, KV_RANK, device=DEVICE, dtype=DTYPE) + bases = [ + torch.randn(tokens, HEADS, width, device=DEVICE, dtype=DTYPE) + for width in (KV_RANK, V_HEAD) + ] + outputs = [[torch.empty_like(base) for base in bases] for _ in layers] + caller = torch.cuda.Stream() + builds = [] + build = engine._build_pair_route + + def checked_build(*args): + assert torch.cuda.current_stream() == caller + route = build(*args) + builds.append(route) + return route + + monkeypatch.setattr(engine, "_build_pair_route", checked_build) + + def forward(): + engine.reset_routes() + routes = [] + for layer, (q_out, v_out) in zip(layers, outputs): + q_prepared = mla_correction.prepare_q_correction(layer, q) + q_out.copy_(bases[0]) + mla_correction.apply_correction(q_prepared, q_out) + v_prepared = mla_correction.prepare_v_correction(layer, v) + v_out.copy_(bases[1]) + mla_correction.apply_correction(v_prepared, v_out) + routes.extend((q_prepared.route, v_prepared.route)) + assert all(route is routes[0] for route in routes) + + caller.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(caller): + forward() + forward() + torch.cuda.synchronize() + assert len(builds) == 2 + graph = None + if mode != "eager": + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=caller): + forward() + assert len(builds) == 3 + + for step in range(3): + current_slots = [(slot + step) % SLOTS if slot >= 0 else -1 for slot in slots] + current_slots = [ + slot if slot >= 0 and RANKS[slot] else -1 for slot in current_slots + ] + scales = [scale * (step + 1) for scale in SCALINGS] + engine.token_slots.copy_(torch.tensor(current_slots, device=DEVICE)) + info.scalings.copy_(torch.tensor(scales, device=DEVICE)) + q.add_(0.01) + v.sub_(0.01) + if graph is None: + caller.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(caller): + forward() + assert len(builds) == 3 + step + else: + graph.replay() + assert len(builds) == 3 # Replay cannot rebuild a Python route cache. + torch.cuda.synchronize() + for layer, (q_out, v_out) in zip(layers, outputs): + a, b = layer.kv_b_proj.A_buffer, layer.kv_b_proj.B_buffer + for side, x, out, base in zip(("q", "v"), (q, v), (q_out, v_out), bases): + expected = base.float() + _reference( + x, a, b, current_slots, side, scales=scales + ) + torch.testing.assert_close(out.float(), expected, rtol=2e-2, atol=2e-2) + + +@pytest.mark.parametrize("phase", [Phase.DECODE, Phase.PREFILL]) +def test_mla_pair_route_is_rebuilt_by_the_replayed_graph(phase): + ranks = [64, 32, 0, 16] + info, _ = _batch(True, tokens=37, ranks=ranks) + tokens, heads, qk_nope, v_dim, kv = 37, 4, 64, 32, 96 + a, b = _pool(23, heads, qk_nope=qk_nope, v_dim=v_dim, kv=kv, ranks=ranks) + generator = torch.Generator(device=DEVICE).manual_seed(23) + + def random(*shape): + return torch.randn(*shape, generator=generator, device=DEVICE, dtype=DTYPE) + + w_kc, w_vc = random(heads, qk_nope, kv) * 0.1, random(heads, kv, v_dim) * 0.1 + q, v = random(tokens, heads, qk_nope), random(tokens, heads, kv) + q_out, v_out = ( + torch.empty_like(v), + torch.empty(tokens, heads, v_dim, device=DEVICE, dtype=DTYPE), + ) + engine = DenseLoraRunner(LoraWorkspace(), max_loras=SLOTS, device=DEVICE) + attention = _attention(engine, info, a, b, heads, qk_nope=qk_nope, v_dim=v_dim) + static_slots = torch.full((tokens + 27,), -1, dtype=torch.int32, device=DEVICE) + block = mla_correction._mla_plan(phase).block_size + + def begin(live=tokens): + _compute_moe_lora_info( + live, + info.seg_indptr[: live + 1], + info.lora_ranks, + info.weight_indices[:live], + None, + static_slots, + max_len=info.max_len, + ) + engine.begin_batch( + token_slots=static_slots, + lora_ranks=info.lora_ranks, + scalings=info.scalings, + num_tokens=live, + phase=phase, + graph_mode=True, + ) + + def forward(): + engine.reset_routes() + for side, x, weight, out, prepare in ( + ("q", q, w_kc, q_out, mla_correction.prepare_q_correction), + ("v", v, w_vc, v_out, mla_correction.prepare_v_correction), + ): + prepared = prepare(attention, x) + assert (prepared.done is not None) == (phase is Phase.DECODE) + destination = torch.bmm(x.transpose(0, 1), weight).transpose(0, 1) + assert not destination.is_contiguous() + out.copy_(mla_correction.apply_correction(prepared, destination)) + + def check(): + slots = static_slots[:tokens].tolist() + for side, x, weight, out in (("q", q, w_kc, q_out), ("v", v, w_vc, v_out)): + expected = torch.bmm(x.transpose(0, 1), weight).transpose(0, 1).float() + expected += _reference(x, a, b, slots, side, ranks=ranks, qk_nope=qk_nope) + torch.testing.assert_close(out.float(), expected, rtol=2e-2, atol=2e-2) + + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + begin() + assert not engine.workspace.routes + forward() + route = engine.pair_route(heads, block, num_tokens=tokens) + pair_ptr, group_ptr = ( + route.sorted_pair_ids.data_ptr(), + route.group_ids.data_ptr(), + ) + torch.cuda.synchronize() + check() + graph = torch.cuda.CUDAGraph() + begin() + assert not engine.workspace.routes + with torch.cuda.graph(graph, stream=stream): + forward() + captured_route = engine.pair_route(heads, block, num_tokens=tokens) + assert captured_route.sorted_pair_ids.data_ptr() == pair_ptr + assert captured_route.group_ids.data_ptr() == group_ptr + + for live in (tokens, tokens - 13): + q.copy_(random(tokens, heads, qk_nope)) + v.copy_(random(tokens, heads, kv)) + info.weight_indices.copy_(torch.roll(info.weight_indices, 1)) + begin(live) + assert torch.all(static_slots[live:] == -1) + assert not engine.workspace.routes + assert captured_route.group_ids.data_ptr() == group_ptr + captured_route.group_ids.fill_(-7) + captured_route.sorted_pair_ids.fill_(-7) + captured_route.block_bucket_ids.fill_(-7) + captured_route.num_pairs_post_padded.zero_() + graph.replay() + torch.cuda.synchronize() + check() + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/lora/test_dense_lora_routing_graph.py b/test/registered/kernels/ops/lora/test_dense_lora_routing_graph.py new file mode 100644 index 0000000000..7ac4eba564 --- /dev/null +++ b/test/registered/kernels/ops/lora/test_dense_lora_routing_graph.py @@ -0,0 +1,243 @@ +"""Dense route cache lifetime across warmup, capture, and replay.""" + +from types import SimpleNamespace + +import pytest +import torch + +pytest.importorskip("triton") + +from sglang.kernels.ops.lora.common.lora_a import grouped_lora_a +from sglang.kernels.ops.lora.moe.lora_b import run_lora_b +from sglang.srt.lora.backend.triton_v2_backend import TritonV2LoRABackend +from sglang.srt.lora.dense.plan import DensePlan, Overlap +from sglang.srt.lora.moe.plan import ( + BFamily, + BSpec, + RouteBuilderFamily, + RouteRequirement, + Site, +) +from sglang.srt.lora.moe.routing import build_moe_routes +from sglang.srt.lora.utils import Phase +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=10, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA") + + +def _bind(runner, slots, *, graph_mode, prefill=False): + runner.begin_batch( + token_slots=slots, + lora_ranks=torch.tensor([16, 8, 0, 4], device="cuda", dtype=torch.int32), + scalings=torch.tensor([1.0, 0.5, 1.0, 2.0], device="cuda"), + num_tokens=slots.numel(), + phase=Phase.PREFILL if prefill else Phase.DECODE, + graph_mode=graph_mode, + is_prefill_graph=prefill, + ) + + +@pytest.mark.parametrize( + "overlap,moe_first", + # the two publication directions; NONE has no cross-stream traffic + [(Overlap.A, False), (Overlap.AB_DELTA, True)], + ids=["dense-first-a", "moe-first-ab_delta"], +) +def test_dense_moe_token_route_reuse_graph_replay(overlap, moe_first): + backend = TritonV2LoRABackend(4, torch.device("cuda")) + runner = backend.runner + workspace = runner.workspace + generator = torch.Generator(device="cuda").manual_seed(741) + + def rand(*shape): + return (torch.randn(shape, device="cuda", generator=generator) * 0.1).bfloat16() + + a, b, base_weight = rand(4, 16, 128), rand(4, 128, 16), rand(128, 128) + moe_a, moe_b = rand(4, 16, 128), rand(4, 3, 64, 16) + plan = DensePlan(overlap=overlap) + moe_plan = SimpleNamespace( + route_requirements=lambda: { + RouteRequirement.SHARED_TOKEN_PLAN, + RouteRequirement.RAW_PER_EXPERT, + }, + route_builder=RouteBuilderFamily.STANDARD, + ) + captures = {} + stream = torch.cuda.Stream() # one stream for every bucket, as in a graph runner + for tokens in (64, 8): + x = rand(tokens, 128) + slots = torch.arange(tokens, device="cuda", dtype=torch.int32) % 4 + _bind(runner, slots, graph_mode=True, prefill=True) + runner.lora_ranks.fill_(16) + runner.scalings.fill_(0.5) + ranks, scalings = runner.lora_ranks, runner.scalings + topk = ( + torch.arange(tokens * 2, device="cuda", dtype=torch.int32).view(tokens, 2) + % 3 + ) + bridge = torch.empty(tokens, 16, device="cuda", dtype=x.dtype) + delta = torch.empty(tokens * 2, 64, device="cuda", dtype=x.dtype) + + def moe_routes(): + return build_moe_routes( + moe_plan, + topk_ids=topk, + token_lora_mapping=slots, + num_local_experts=3, + max_loras=4, + block_size=16, + workspace=workspace, + ) + + def forward(): + backend.reset_routing_cache() + routes = moe_routes() if moe_first else None + dense = runner.apply( + x, + lambda: x @ base_weight.T, + plan, + a=a, + b=b, + offsets=(0, 128), + ) + if routes is None: + routes = moe_routes() + cached = runner.route(16) + assert ( + routes.shared_token.sorted_pair_ids.data_ptr() + == cached.sorted_pair_ids.data_ptr() + ) + assert routes.shared_token.groups_per_slot == 1 + grouped_lora_a( + dense, moe_a, bridge, routes.shared_token, config=plan.a_tiles + ) + run_lora_b( + BSpec(Site.GATE_UP, BFamily.PER_ROW), + bridge=bridge, + weight=moe_b.flatten(0, 1), + destination=delta, + routing=routes.raw_per_expert, + destination_offsets=(0,), + config=plan.b_tiles, + pair_bridge=False, + ) + again = runner.apply( + x, + lambda: x @ base_weight.T, + plan, + a=a, + b=b, + offsets=(0, 128), + ) + return dense, delta, again, cached + + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + forward() + forward() + torch.cuda.current_stream().wait_stream(stream) + torch.cuda.synchronize() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + outputs = forward() + captures[tokens] = graph, x, slots, topk, ranks, scalings, outputs + + for iteration, tokens in enumerate((8, 64, 8, 64)): + graph, x, slots, topk, ranks, scalings, (dense, delta, again, route) = captures[ + tokens + ] + x.copy_(rand(tokens, 128)) + slots.copy_( + (torch.arange(tokens, device="cuda", dtype=torch.int32) + iteration) % 5 - 1 + ) + ranks.copy_(torch.tensor([16, 8, 0, 4], device="cuda", dtype=ranks.dtype)) + scalings.fill_(0.25 + iteration * 0.25) + topk.copy_( + ( + torch.arange(tokens * 2, device="cuda", dtype=torch.int32).view( + tokens, 2 + ) + + iteration + ) + % 4 + - 1 + ) + if iteration == 2: + slots.fill_(-1) + route.sorted_pair_ids.fill_(-7) + route.num_pairs_post_padded.zero_() + graph.replay() + torch.cuda.synchronize() + expected = (x.float() @ base_weight.float().T).bfloat16().float() + for token, slot in enumerate(slots.tolist()): + if slot >= 0: + rank = ranks[slot].item() + low_rank = ( + (x[token].float() @ a[slot, :rank].float().T).bfloat16().float() + ) + expected[token] += scalings[slot] * ( + low_rank @ b[slot, :, :rank].float().T + ) + torch.testing.assert_close(dense.float(), expected, atol=0.012, rtol=0.04) + torch.testing.assert_close(again, dense) + expected_delta = torch.zeros_like(delta, dtype=torch.float32) + for token, slot in enumerate(slots.tolist()): + if slot < 0: + continue + low_rank = (dense[token].float() @ moe_a[slot].float().T).bfloat16().float() + for k, expert in enumerate(topk[token].tolist()): + if expert >= 0: + expected_delta[token * 2 + k] = ( + low_rank @ moe_b[slot, expert].float().T + ) + torch.testing.assert_close(delta.float(), expected_delta, atol=0.005, rtol=0.04) + + +def test_route_cache_visibility_follows_parallel_stream_joins(): + backend = TritonV2LoRABackend(4, torch.device("cuda")) + runner, workspace = backend.runner, backend.runner.workspace + slots = torch.arange(32, device="cuda", dtype=torch.int32) % 4 + _bind(runner, slots, graph_mode=True) + route = runner.route(16) + inherited = ("sorted", 16, 4) + side_only, not_joined, after_done = ("side",), ("unjoined",), ("late",) + side_stream = workspace.side_stream(slots.device) + + def unexpected_build(): + pytest.fail("the existing stream wait should make the route reusable") + + def side(): + assert workspace.route(slots, inherited, unexpected_build) is route + workspace.route(slots, side_only, lambda: route) + workspace.route(slots, not_joined, lambda: route) + + def compute(): + def unjoined_build(): + builds.append("unjoined") + return route + + workspace.route(slots, not_joined, unjoined_build) + # This work follows the outer done event, so its route cannot be + # exposed by that event's eventual caller-side wait. + with torch.cuda.stream(side_stream): + workspace.route(slots, after_done, lambda: route) + + builds = [] + workspace.run_parallel( + name="route-cache-test", device=slots.device, compute=compute, side=side + ) + assert builds == ["unjoined"] + assert workspace.route(slots, side_only, unexpected_build) is route + + def late_build(): + builds.append("late") + return route + + workspace.route(slots, after_done, late_build) + assert builds == ["unjoined", "late"] + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/lora/test_moe_lora_bind_execution.py b/test/registered/kernels/ops/lora/test_moe_lora_bind_execution.py new file mode 100644 index 0000000000..2d34b1301f --- /dev/null +++ b/test/registered/kernels/ops/lora/test_moe_lora_bind_execution.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +import torch + +from sglang.srt.layers.moe.utils import MoeRunnerBackend +from sglang.srt.lora.moe.runner import MoeLoraRunner +from sglang.srt.runtime_context import get_context, get_flags +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=10, stage="base-b-kernel-unit", runner_config="1-gpu-large") + + +class _FakeProvider: + hidden_size = 2048 + intermediate_size = 768 + num_local_experts = 256 + gate_up_slices = 2 + contract = SimpleNamespace(lora_delta_dtype=torch.bfloat16) + + +def _from_layer(monkeypatch, provider_cls): + monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device=None: (9, 0)) + monkeypatch.setattr(MoeLoraRunner, "_admit", staticmethod(lambda layer: "bf16")) + + def fake_build(_base_layer, *, base_gemm_rows, vendor, family): + return provider_cls() + + monkeypatch.setattr(MoeLoraRunner, "_build_provider", staticmethod(fake_build)) + # from_layer reads the published MoE runner backend; publish the engine's + # default name so the builds see its vendor. + with get_context().override_server_args(): + with get_flags().moe.override(runner_backend=MoeRunnerBackend.LORA_CUTEDSL): + return MoeLoraRunner.from_layer( + SimpleNamespace( + w2_weight=SimpleNamespace( + device=torch.device("cuda"), shape=(256, 2048, 768) + ), + num_local_experts=256, + hidden_size=2048, + moe_runner_config=SimpleNamespace( + activation="silu", + top_k=8, + routed_scaling_factor=1.0, + is_gated=True, + ), + ), + workspace=object(), + is_shared_outer=False, + physical_rank=64, + ) + + +def test_plan_validation_failure_propagates(monkeypatch) -> None: + class _NonGatedProvider(_FakeProvider): + gate_up_slices = 1 + + with pytest.raises(ValueError, match="gate/up slices"): + _from_layer(monkeypatch, _NonGatedProvider) + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/lora/test_moe_lora_contiguous_row_domain.py b/test/registered/kernels/ops/lora/test_moe_lora_contiguous_row_domain.py new file mode 100644 index 0000000000..eae4aa0b7b --- /dev/null +++ b/test/registered/kernels/ops/lora/test_moe_lora_contiguous_row_domain.py @@ -0,0 +1,520 @@ +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +import torch + +from sglang.srt.lora.moe.base_gemm_provider import select_provider_cls +from sglang.srt.lora.moe.base_gemm_provider.base import MoeBaseProviderContract +from sglang.srt.lora.moe.base_gemm_provider.contiguous_row_domain import ( + ContiguousRowDomainProvider, + contiguous_m_pad_ceiling, +) +from sglang.srt.lora.moe.plan import ( + ActivationFn, + SelectedPlan, + _build_plan, + _load_plans, + _tile_table, +) +from sglang.srt.lora.moe.quant_info import MoeLoraBf16QuantInfo +from sglang.srt.lora.utils import Phase +from sglang.srt.runtime_context import get_context +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=240, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +_GB300 = "sm100" +_H200 = "sm90" +_SWIGLU = ActivationFn.SILU + + +def _menu(architecture, layout, activation=_SWIGLU): + """Build every declared plan row, bypassing phase and rank selection.""" + table = _load_plans(architecture) + layout_name = "shared" if layout else "per_expert" + return { + row.name: SelectedPlan( + name=row.name, + base_gemm_rows=row.base_gemm_rows, + plan=_build_plan(row.plan, activation=activation, is_shared_outer=layout), + tiles=_tile_table(row.tiles, physical_rank=16), + ) + for row in (*table.scenarios, *table.fallback) + if row.layout in (None, layout_name) + } + + +def _shipped_launch(sel, *, num_tokens=4096): + return sel.tiles.config_for(num_tokens) + + +def _host_aligned_prefix(counts: list[int], alignment: int) -> list[int]: + offsets = [0] + for count in counts: + aligned = -(-count // alignment) * alignment + offsets.append(offsets[-1] + aligned) + return offsets + + +class _DomainStub(ContiguousRowDomainProvider): + """A row domain with a contract but no GEMM engine. Only ``prepare`` runs.""" + + contract = MoeBaseProviderContract( + key="contiguous_stub", + quant_info_cls=MoeLoraBf16QuantInfo, + gate_first=True, + interleaved=False, + gate_up_output_dtype=torch.bfloat16, + lora_delta_dtype=torch.bfloat16, + lora_activation_dtype=torch.bfloat16, + ) + + +class TestAlignedSegmentMath: + def test_ceiling_bounds_every_aligned_prefix_total(self) -> None: + import random + + rng = random.Random(0xA11C) + for _ in range(64): + alignment = rng.choice((8, 64, 128)) + num_experts = rng.randint(1, 32) + num_pairs = rng.randint(0, 4096) + counts = [0] * num_experts + for _ in range(num_pairs): + counts[rng.randrange(num_experts)] += 1 + total = _host_aligned_prefix(counts, alignment)[-1] + ceiling = contiguous_m_pad_ceiling(num_pairs, num_experts, alignment) + assert total <= ceiling, (counts, alignment, total, ceiling) + + +class TestCuteDslContiguousScheduleGeometry: + def test_capacity_bounds_every_actual_schedule_total(self) -> None: + import random + + from sglang.kernels.ops.lora.moe.cutedsl.schedule_builder import ( + dual_stage_schedule_capacities_contiguous, + ) + + rng = random.Random(0xC0DE) + for _ in range(64): + num_experts = rng.randint(1, 64) + num_pairs = rng.randint(0, 4096) + token_width = rng.choice((8, 64, 128)) + counts = [0] * num_experts + for _ in range(num_pairs): + counts[rng.randrange(num_experts)] += 1 + m_pad_ceiling = contiguous_m_pad_ceiling(num_pairs, num_experts, 128) + n_gemm1, n_gemm2 = 512, 256 + capacity1, capacity2 = dual_stage_schedule_capacities_contiguous( + num_experts=num_experts, + m_pad_ceiling=m_pad_ceiling, + max_expert_rows=max(num_pairs, 1), + m_alignment=128, + token_width=token_width, + n_gemm1=n_gemm1, + n_gemm2=n_gemm2, + output_width=128, + ) + # The builder writes cdiv(count, w) * out_clusters entries for + # each expert. The capacity must bound that total for any split of + # the counts. + clusters = sum(-(-count // token_width) for count in counts) + assert clusters * -(-n_gemm1 // 128) <= capacity1, (counts, token_width) + assert clusters * -(-n_gemm2 // 128) <= capacity2, (counts, token_width) + + +_TOP_K = 2 +_HIDDEN = 128 +_INTERMEDIATE = 128 +_PHYSICAL_RANK = 16 +_SLOTS = 2 +_ROUTED_SCALING = 0.75 + +triton_cuda_only = pytest.mark.skipif( + not torch.cuda.is_available(), + reason="the contiguous S1 dispatch needs any CUDA device (plain Triton)", +) + + +def _cutedsl_ready() -> bool: + if not torch.cuda.is_available() or torch.cuda.get_device_capability() < (9, 0): + return False + try: + import cuda.bindings.driver # noqa: F401 + import cutlass # noqa: F401 + except Exception: + return False + return True + + +cutedsl_cuda_only = pytest.mark.skipif( + not _cutedsl_ready(), + reason="the vendor oracle runs the CuTeDSL providers against Triton", +) + + +@pytest.fixture +def published_server_args(): + # The triton vendor's config loader reads the published exec namespace. + with get_context().override_server_args(): + yield + + +@triton_cuda_only +@pytest.mark.parametrize( + ("num_tokens", "top_k", "num_experts", "alignment"), + ((64, 8, 6, 128), (13, 3, 4, 8)), + ids=("lane-multiple-align128", "partial-tail-align8"), +) +def test_contiguous_dispatch_metadata_contract( + num_tokens: int, top_k: int, num_experts: int, alignment: int +) -> None: + """Dispatch writes aligned segments, compact rows, and expert labels. + The unused label tail must contain -1. + """ + device = torch.device("cuda") + generator = torch.Generator().manual_seed(0xC017 + num_tokens) + topk_ids = torch.randint( + 0, num_experts, (num_tokens, top_k), generator=generator, dtype=torch.int32 + ) + topk_ids[topk_ids == 1] = 0 # expert 1 gets no pair, so its segment is empty + topk_ids[torch.rand((num_tokens, top_k), generator=generator) < 0.15] = -1 + topk_ids[0] = -1 # a token with no routed pair + topk_ids = topk_ids.to(device) + hidden_states = ( + (torch.randn((num_tokens, _HIDDEN), generator=generator) * 0.2) + .to(torch.bfloat16) + .to(device) + ) + + quant_info = MoeLoraBf16QuantInfo( + w13_weight=torch.zeros( + (num_experts, 2 * _INTERMEDIATE, _HIDDEN), + dtype=torch.bfloat16, + device=device, + ), + w2_weight=torch.zeros( + (num_experts, _HIDDEN, _INTERMEDIATE), dtype=torch.bfloat16, device=device + ), + num_local_experts=num_experts, + intermediate_size=_INTERMEDIATE, + hidden_size=_HIDDEN, + ) + provider = _DomainStub(quant_info, m_alignment=alignment) + ws = provider.prepare(hidden_states, topk_ids, top_k, None) + + ids = topk_ids.view(-1).cpu() + counts = [(ids == expert).sum().item() for expert in range(num_experts)] + offsets = _host_aligned_prefix(counts, alignment) + assert ws.seg_counts.cpu().tolist() == counts + assert ws.seg_offsets.cpu().tolist() == offsets + assert ws.m_pad_ceiling == contiguous_m_pad_ceiling( + ids.numel(), num_experts, alignment + ) + assert offsets[-1] <= ws.m_pad_ceiling + + mapping = ws.pair_to_row.cpu() + compact = ws.hidden_compact.cpu() + host_hidden = hidden_states.cpu() + for expert in range(num_experts): + pairs = (ids == expert).nonzero().flatten() + rows = mapping[pairs] + assert sorted((rows - offsets[expert]).tolist()) == list(range(len(pairs))) + for pair, row in zip(pairs.tolist(), rows.tolist()): + torch.testing.assert_close( + compact[row], host_hidden[pair // top_k], atol=0.0, rtol=0.0 + ) + assert counts[1] == 0 and offsets[2] == offsets[1] # the empty expert + + # Poison outputs to prove the launch overwrites every count and offset. + from sglang.kernels.ops.lora.moe.dispatch_contiguous import ( + dispatch_layout_contiguous, + ) + + dirty = { + "seg_counts_out": torch.full( + (num_experts,), 0x2BAD, dtype=torch.int32, device=device + ), + "seg_offsets_out": torch.full( + (num_experts + 1,), -7, dtype=torch.int32, device=device + ), + "pair_to_row_out": torch.full( + (ids.numel(),), 0x7FFFFFFF, dtype=torch.int32, device=device + ), + } + dispatch_layout_contiguous( + hidden_states, topk_ids, num_experts, top_k, alignment, **dirty + ) + assert dirty["seg_counts_out"].cpu().tolist() == counts + assert dirty["seg_offsets_out"].cpu().tolist() == offsets + + # Two providers with different alignments can share one workspace. Their + # row counts differ, so each buffer name holds the alignment. + from sglang.srt.lora.workspace import LoraWorkspace + + workspace = LoraWorkspace() + workspace.begin_forward(graph_mode=False) + provider.prepare(hidden_states, topk_ids, top_k, workspace) + names = {key[0] for key in workspace._eager_buffers} + for suffix in ("seg_counts", "seg_offsets", "pair_to_row"): + assert f"contiguous:a{alignment}:{suffix}" in names, (suffix, names) + assert f"contiguous:a{alignment}:hidden_compact" in names + + +def _make_gpu_tensors( + num_tokens: int, num_experts: int, device: torch.device, *, shared: bool = False +) -> dict[str, torch.Tensor]: + generator = torch.Generator().manual_seed(0xC0A7 + num_experts + num_tokens) + + def rand_bf16(shape, scale): + return (torch.randn(shape, generator=generator) * scale).to(torch.bfloat16) + + # In the shared-outer layout, each adapter has one gate/up-A factor and + # one down-B factor. The gate/up-B and down-A factors stay per expert. + gate_up_a_experts = 1 if shared else num_experts + down_b_experts = 1 if shared else num_experts + tensors = { + "hidden_states": rand_bf16((num_tokens, _HIDDEN), 0.20), + "w13_weight": rand_bf16((num_experts, 2 * _INTERMEDIATE, _HIDDEN), 0.08), + "w2_weight": rand_bf16((num_experts, _HIDDEN, _INTERMEDIATE), 0.08), + "gate_up_lora_a": rand_bf16( + (_SLOTS, gate_up_a_experts, 2 * _PHYSICAL_RANK, _HIDDEN), 0.15 + ), + "gate_up_lora_b": rand_bf16( + (_SLOTS, num_experts, 2 * _INTERMEDIATE, _PHYSICAL_RANK), 0.15 + ), + "down_lora_a": rand_bf16( + (_SLOTS, num_experts, _PHYSICAL_RANK, _INTERMEDIATE), 0.15 + ), + "down_lora_b": rand_bf16( + (_SLOTS, down_b_experts, _HIDDEN, _PHYSICAL_RANK), 0.15 + ), + } + scores = torch.rand((num_tokens, num_experts), generator=generator) + # Skew the routing so the expert counts are uneven. Some segments then + # span many blocks, and some experts get no pair. + scores[: num_tokens // 2, 0] += 4.0 + topk_ids = torch.topk(scores, _TOP_K, dim=1).indices.to(torch.int32) + topk_ids[0] = -1 # a token with no routed pair + topk_ids[5, 1] = -1 # one sentinel pair inside a token that keeps a routed pair + tensors["topk_ids"] = topk_ids.contiguous() + weights = torch.rand((num_tokens, _TOP_K), generator=generator) + 0.1 + tensors["topk_weights"] = (weights / weights.sum(dim=1, keepdim=True)).float() + tensors["router_logits"] = torch.zeros( + (num_tokens, num_experts), dtype=torch.float32 + ) + return {name: tensor.to(device) for name, tensor in tensors.items()} + + +def _token_lora_mapping(traffic: str, num_tokens: int) -> torch.Tensor: + if traffic == "active": + return torch.zeros(num_tokens, dtype=torch.int32) + if traffic == "mixed": + pattern = torch.tensor([0, -1, -1, 0, -1, -1], dtype=torch.int32) + return pattern.repeat((num_tokens + pattern.numel() - 1) // pattern.numel())[ + :num_tokens + ].contiguous() + if traffic == "base_only": + return torch.full((num_tokens,), -1, dtype=torch.int32) + raise AssertionError(f"unknown traffic pattern {traffic}") + + +def _standalone_output_allocation(runner, *, num_tokens, dtype, device): + """Allocate the output with the eager shape and no tensor-parallel group.""" + return torch.empty((num_tokens, runner.hidden_size), dtype=dtype, device=device) + + +def _bind_test_menu(runner, plan, launch_config): + """Bind one plan to both phases to isolate execution from plan selection.""" + tiles = SimpleNamespace(config_for=lambda num_tokens: launch_config) + selected = SelectedPlan(name="test", base_gemm_rows="test", plan=plan, tiles=tiles) + runner.plans = {Phase.PREFILL: selected, Phase.DECODE: selected} + + +def _build_runner(choice, vendor: str, gpu, num_experts): + from sglang.srt.lora.moe.runner import MoeLoraRunner + + quant_info = MoeLoraBf16QuantInfo( + w13_weight=gpu["w13_weight"], + w2_weight=gpu["w2_weight"], + num_local_experts=num_experts, + intermediate_size=_INTERMEDIATE, + hidden_size=_HIDDEN, + ) + provider = select_provider_cls(choice.base_gemm_rows, "bf16", vendor)(quant_info) + runner = MoeLoraRunner( + providers={"test": provider}, + top_k=_TOP_K, + routed_scaling_factor=_ROUTED_SCALING, + activation=ActivationFn.SILU, + ) + runner.validate_plan(choice.plan, base_gemm_rows="test") + _bind_test_menu(runner, choice.plan, _shipped_launch(choice)) + return runner + + +def _run_once( + runner, gpu, token_lora_mapping, *, use_cuda_graph=False, is_prefill=True +): + from sglang.srt.layers.moe.token_dispatcher.standard import StandardDispatchOutput + from sglang.srt.layers.moe.topk import StandardTopKOutput + from sglang.srt.lora.moe.runner import MoeLoraBatch + + dispatch = StandardDispatchOutput( + hidden_states=gpu["hidden_states"], + hidden_states_scale=None, + topk_output=StandardTopKOutput( + topk_weights=gpu["topk_weights"], + topk_ids=gpu["topk_ids"], + router_logits=gpu["router_logits"], + ), + ) + batch = MoeLoraBatch( + gate_up_lora_a=gpu["gate_up_lora_a"], + gate_up_lora_b=gpu["gate_up_lora_b"], + down_lora_a=gpu["down_lora_a"], + down_lora_b=gpu["down_lora_b"], + token_lora_mapping=token_lora_mapping, + use_cuda_graph=use_cuda_graph, + is_prefill=is_prefill, + ) + return runner.run(dispatch, batch) + + +# The two vendors tile the same FP32 accumulation in different ways, and on a +# decode row in different row domains, so they round the BF16 output at +# different points. Every stage after the GEMM is the same kernel. +_ORACLE_TOLERANCE = {"atol": 2e-2, "rtol": 0.05} + +# One row for each eligible plan shape, each with its own factor layout. Both +# vendors run the same plan, so the test compares the base GEMMs alone. +_ELIGIBLE_PLAN_PARAMS = ( + pytest.param(_GB300, False, "fallback.decode", id="per-expert-materialized"), + pytest.param(_GB300, True, "prefill.shared", id="shared-outer-b-activation"), + pytest.param( + _H200, + True, + "prefill.shared.rank_le16", + id="shared-outer-token-gemm", + ), +) + + +@cutedsl_cuda_only +@pytest.mark.parametrize(("architecture", "layout", "fragment"), _ELIGIBLE_PLAN_PARAMS) +def test_cutedsl_matches_triton_in_eager_and_cuda_graph( + architecture, + layout, + fragment: str, + published_server_args, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Compare providers in eager mode and after in-place graph input updates.""" + from sglang.srt.lora.moe.runner import MoeLoraRunner + + device = torch.device("cuda") + monkeypatch.setattr( + MoeLoraRunner, "_allocate_output", _standalone_output_allocation + ) + num_tokens, num_experts = 64, 16 + choice = _menu(architecture, layout)[fragment] + gpu = _make_gpu_tensors(num_tokens, num_experts, device, shared=layout) + + triton = _build_runner(choice, "triton", gpu, num_experts) + cutedsl = _build_runner(choice, "cutedsl", gpu, num_experts) + + outputs = {} + for traffic in ("active", "mixed", "base_only"): + triton.workspace.routes.clear() + cutedsl.workspace.routes.clear() + token_lora_mapping = _token_lora_mapping(traffic, num_tokens).to(device) + reference = _run_once(triton, gpu, token_lora_mapping).hidden_states + actual = _run_once(cutedsl, gpu, token_lora_mapping).hidden_states + outputs[traffic] = actual + torch.testing.assert_close( + actual, + reference, + **_ORACLE_TOLERANCE, + msg=f"cutedsl vs triton: {choice.name}, {traffic} traffic", + ) + # The token with no routed pair must be exactly zero for both vendors. + assert actual[0].abs().max().item() == 0.0 + assert reference[0].abs().max().item() == 0.0 + # The vendor under test must apply the LoRA math. + assert (outputs["active"] - outputs["base_only"]).abs().max().item() > 0.02 + + token_lora_mapping = _token_lora_mapping("active", num_tokens).to(device) + + # The workspace keys scratch by stream: warm up on the capture stream. + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(2): # warm the JIT and keep the graph buffers before capture + _run_once(cutedsl, gpu, token_lora_mapping, use_cuda_graph=True) + torch.cuda.synchronize(device) + + # Cache only within a forward, so the shared-token rebuild is captured. + cutedsl.workspace.routes.clear() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + captured = _run_once(cutedsl, gpu, token_lora_mapping, use_cuda_graph=True) + output = captured.hidden_states + output_ptr = output.data_ptr() + + graph.replay() + torch.cuda.synchronize(device) + triton.workspace.routes.clear() + torch.testing.assert_close( + output, + _run_once(triton, gpu, token_lora_mapping).hidden_states, + **_ORACLE_TOLERANCE, + msg="initial routing replay", + ) + + original_ids = gpu["topk_ids"].clone() + mutated = torch.where( + original_ids >= 0, (original_ids + 3) % num_experts, original_ids + ).to(torch.int32) + gpu["topk_ids"].copy_(mutated) + graph.replay() + torch.cuda.synchronize(device) + assert output.data_ptr() == output_ptr + triton.workspace.routes.clear() + torch.testing.assert_close( + output, + _run_once(triton, gpu, token_lora_mapping).hidden_states, + **_ORACLE_TOLERANCE, + msg="mutated routing replay", + ) + + token_lora_mapping.copy_( + torch.arange(num_tokens, dtype=torch.int32, device=device) % _SLOTS + ) + graph.replay() + torch.cuda.synchronize(device) + assert output.data_ptr() == output_ptr + triton.workspace.routes.clear() + torch.testing.assert_close( + output, + _run_once(triton, gpu, token_lora_mapping).hidden_states, + **_ORACLE_TOLERANCE, + msg="reassigned active adapters replay", + ) + + token_lora_mapping.fill_(-1) + graph.replay() + torch.cuda.synchronize(device) + assert output.data_ptr() == output_ptr + triton.workspace.routes.clear() + torch.testing.assert_close( + output, + _run_once(triton, gpu, token_lora_mapping).hidden_states, + **_ORACLE_TOLERANCE, + msg="base-only replay", + ) + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/lora/test_moe_lora_down_b_into_base.py b/test/registered/kernels/ops/lora/test_moe_lora_down_b_into_base.py new file mode 100644 index 0000000000..23efc45c87 --- /dev/null +++ b/test/registered/kernels/ops/lora/test_moe_lora_down_b_into_base.py @@ -0,0 +1,647 @@ +from __future__ import annotations + +from dataclasses import replace +from types import SimpleNamespace + +import pytest +import torch + +from sglang.srt.lora.moe.base_gemm_provider import select_provider_cls +from sglang.srt.lora.moe.plan import ( + ActFamily, + ActivationFn, + ActSpec, + AFamily, + ASpec, + BFamily, + BridgeLayout, + BSpec, + DownOverlap, + FinalizeFamily, + FinalizeSpec, + MoePlan, + SelectedPlan, + Site, + _build_plan, + _load_plans, + _tile_table, +) +from sglang.srt.lora.utils import Phase +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=300, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +_GB300 = "sm100" +_SWIGLU = ActivationFn.SILU + + +def _menu(architecture, layout, activation=_SWIGLU): + """Build every declared plan row, bypassing phase and rank selection.""" + table = _load_plans(architecture) + layout_name = "shared" if layout else "per_expert" + return { + row.name: SelectedPlan( + name=row.name, + base_gemm_rows=row.base_gemm_rows, + plan=_build_plan(row.plan, activation=activation, is_shared_outer=layout), + tiles=_tile_table(row.tiles, physical_rank=16), + ) + for row in (*table.scenarios, *table.fallback) + if row.layout in (None, layout_name) + } + + +def _shipped_launch(sel, *, num_tokens=4096): + return sel.tiles.config_for(num_tokens) + + +def _make_plan( + *, + activation=_SWIGLU, + is_shared_outer=False, + act_family=ActFamily.MATERIALIZED, + finalize_family=FinalizeFamily.MATERIALIZED, + down_overlap=DownOverlap.NONE, + down_b_into_base=False, +) -> MoePlan: + consumes_down_b = finalize_family is not FinalizeFamily.MATERIALIZED + return MoePlan( + gate_up_a=ASpec( + Site.GATE_UP, + AFamily.GROUPED, + is_shared_outer, + BridgeLayout.PAIR_MAJOR, + ), + gate_up_b=( + None + if act_family is ActFamily.B_ACTIVATION + else BSpec(Site.GATE_UP, BFamily.GROUPED) + ), + act=ActSpec(act_family, activation), + down_a=ASpec(Site.DOWN, AFamily.GROUPED), + down_b=( + None + if consumes_down_b + else BSpec( + Site.DOWN, + BFamily.GROUPED, + is_shared_outer, + BridgeLayout.PAIR_MAJOR, + ) + ), + finalize=FinalizeSpec( + finalize_family, is_shared_outer if consumes_down_b else False + ), + down_overlap=down_overlap, + down_b_into_base=down_b_into_base, + ) + + +def _serial_plan(): + return _make_plan() + + +class TestDownBIntoBasePlan: + def test_flag_rejects_the_windows_that_race_the_base_gemm(self) -> None: + overlapped = _make_plan(down_overlap=DownOverlap.DOWN_A_B) + with pytest.raises(ValueError, match="down-B into-base"): + replace(overlapped, down_b_into_base=True) + + +cuda_only = pytest.mark.skipif( + not torch.cuda.is_available(), + reason="the scatter kernel needs any CUDA device (plain Triton)", +) + + +def _cutedsl_ready() -> bool: + if not torch.cuda.is_available() or torch.cuda.get_device_capability() < (9, 0): + return False + try: + import cuda.bindings.driver # noqa: F401 + import cutlass # noqa: F401 + except Exception: + return False + return True + + +cutedsl_cuda_only = pytest.mark.skipif( + not _cutedsl_ready(), + reason="the runner-level oracle runs the CuTeDSL providers", +) + +_HIDDEN = 128 +_INTERMEDIATE = 128 +_RANK = 16 +_SLOTS = 2 +_TOP_K = 2 +_ROUTED_SCALING = 0.75 +_ROW_POISON = -1 # a sentinel pair's pair_to_row entry; the finalize gates on it + + +def _kernel_case(num_tokens: int, top_k: int, num_experts: int, seed: int): + generator = torch.Generator().manual_seed(seed) + topk_ids = torch.randint( + 0, num_experts, (num_tokens, top_k), generator=generator, dtype=torch.int32 + ) + topk_ids[torch.rand((num_tokens, top_k), generator=generator) < 0.15] = -1 + topk_ids[0] = -1 # a token with no routed pair + pattern = torch.tensor([0, 1, -1, 0, -1, 1], dtype=torch.int32) + token_lora_mapping = pattern.repeat(-(-num_tokens // pattern.numel()))[:num_tokens] + weights = torch.rand((num_tokens, top_k), generator=generator) + 0.1 + topk_weights = (weights / weights.sum(dim=1, keepdim=True)).float() + + pairs = num_tokens * top_k + bridge = (torch.randn((pairs, _RANK), generator=generator) * 0.15).to( + torch.bfloat16 + ) + b_down = ( + torch.randn((_SLOTS * num_experts, _HIDDEN, _RANK), generator=generator) * 0.15 + ).to(torch.bfloat16) + # Slot 1 is a narrow adapter. Its rank padding is zero in the bridge and + # in down-B. A batch with mixed ranks reaches the kernels in this form. + b_down.view(_SLOTS, num_experts, _HIDDEN, _RANK)[1, :, :, _RANK // 2 :] = 0 + bridge_view = bridge.view(num_tokens, top_k, _RANK) + bridge_view[token_lora_mapping == 1, :, _RANK // 2 :] = 0 + return topk_ids, token_lora_mapping, topk_weights, bridge, b_down + + +def _pair_to_row_rows(topk_ids: torch.Tensor, num_experts: int, style: str, seed: int): + """Build the pair-to-row map of both row domains on the host.""" + ids = topk_ids.view(-1) + counts = [int((ids == expert).sum()) for expert in range(num_experts)] + if style == "masked": + m_max = -(-max(counts + [1]) // 8) * 8 + 8 + base = [expert * m_max for expert in range(num_experts)] + total_rows = num_experts * m_max + else: # contiguous rows, with each segment aligned to 8 rows + alignment = 8 + base, offset = [], 0 + for count in counts: + base.append(offset) + offset += -(-count // alignment) * alignment + total_rows = max(offset, alignment) + pair_to_row = torch.full((ids.numel(),), _ROW_POISON, dtype=torch.int32) + cursor = [0] * num_experts + for pair, expert in enumerate(ids.tolist()): + if expert >= 0: + pair_to_row[pair] = base[expert] + cursor[expert] + cursor[expert] += 1 + generator = torch.Generator().manual_seed(seed ^ 0xD05E) + down_rows = (torch.randn((total_rows, _HIDDEN), generator=generator) * 0.2).to( + torch.bfloat16 + ) + return pair_to_row, down_rows + + +def _fp32_finalize_oracle( + down_rows, + pair_to_row, + bridge, + b_down, + topk_ids, + token_lora_mapping, + topk_weights, + num_experts, +): + num_tokens, top_k = topk_ids.shape + out = torch.zeros((num_tokens, _HIDDEN), dtype=torch.float32) + for token in range(num_tokens): + slot = int(token_lora_mapping[token]) + for k in range(top_k): + expert = int(topk_ids[token, k]) + if expert < 0: + continue + pair = token * top_k + k + row = down_rows[int(pair_to_row[pair])].float() + if 0 <= slot < _SLOTS: + bucket_id = slot * num_experts + expert + row = row + b_down[bucket_id].float() @ bridge[pair].float() + out[token] += float(topk_weights[token, k]) * row + return out * _ROUTED_SCALING + + +# Both launches use one config. The scatter must keep the same down-B tiling +# as the shipped path. +_DOWN_B_CONFIG = { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 16, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2, +} + +# The scatter adds the FP32 delta to the base row, then rounds once. The +# shipped path rounds the delta to BF16 first, then adds. The two paths round +# at different points, so compare them with a tolerance. +_INTO_BASE_TOLERANCE = {"atol": 1e-2, "rtol": 0.05} + + +def _post_reorder( + down_rows, output, pair_to_row, topk_ids, topk_weights, lora_delta=None +): + from sglang.kernels.ops.moe.ep_moe_kernels import post_reorder_deepgemm + + num_tokens, top_k = topk_ids.shape + post_reorder_deepgemm( + down_rows, + output, + pair_to_row, + topk_ids, + topk_weights, + top_k, + num_tokens, + _HIDDEN, + _ROUTED_SCALING, + lora_delta=lora_delta, + ) + + +@cuda_only +@pytest.mark.parametrize("row_domain", ("masked", "contiguous")) +@pytest.mark.parametrize( + ("num_tokens", "top_k", "num_experts"), + ((64, 2, 4), (13, 3, 4)), + ids=("even", "partial"), +) +def test_into_base_matches_the_standalone_downb_plus_post_reorder( + row_domain: str, num_tokens: int, top_k: int, num_experts: int +) -> None: + from sglang.kernels.ops.lora.common.route_view import RouteViewKind + from sglang.kernels.ops.lora.common.routing import build_route + from sglang.kernels.ops.lora.moe.lora_b import ( + grouped_lora_b, + invoke_down_b_into_base, + ) + + device = torch.device("cuda") + seed = 0x5CA7 + num_tokens + num_experts + topk_ids, token_lora_mapping, topk_weights, bridge, b_down = _kernel_case( + num_tokens, top_k, num_experts, seed + ) + pair_to_row, down_rows = _pair_to_row_rows(topk_ids, num_experts, row_domain, seed) + gpu = { + name: tensor.to(device) + for name, tensor in { + "topk_ids": topk_ids, + "token_lora_mapping": token_lora_mapping, + "topk_weights": topk_weights, + "bridge": bridge, + "b_down": b_down, + "pair_to_row": pair_to_row, + "down_rows": down_rows, + }.items() + } + aligned = build_route( + gpu["token_lora_mapping"], + group_ids=gpu["topk_ids"], + groups_per_slot=num_experts, + max_loras=_SLOTS, + block_size=16, + view=RouteViewKind.ALIGNED, + ) + + # In the shipped path, down-B writes the LoRA delta to its own buffer. + # post_reorder then reads that buffer and the unchanged base rows. + lora_delta = torch.empty( + (num_tokens * top_k, _HIDDEN), dtype=torch.bfloat16, device=device + ) + grouped_lora_b( + gpu["bridge"], + gpu["b_down"], + lora_delta, + aligned, + destination_offsets=(0,), + config=_DOWN_B_CONFIG, + ) + reference = torch.empty((num_tokens, _HIDDEN), dtype=torch.float32, device=device) + _post_reorder( + gpu["down_rows"], + reference, + gpu["pair_to_row"], + gpu["topk_ids"], + gpu["topk_weights"], + lora_delta=lora_delta.view(num_tokens, top_k, _HIDDEN), + ) + + # In the scatter path, the same tiling adds the delta into a copy of the + # base rows. post_reorder then runs with no delta buffer. + scattered = gpu["down_rows"].clone() + invoke_down_b_into_base( + down_rows=scattered, + pair_to_row=gpu["pair_to_row"], + bridge=gpu["bridge"], + b_down=gpu["b_down"], + routing=aligned, + config=_DOWN_B_CONFIG, + ) + output = torch.empty_like(reference) + _post_reorder( + scattered, output, gpu["pair_to_row"], gpu["topk_ids"], gpu["topk_weights"] + ) + torch.testing.assert_close(output, reference, **_INTO_BASE_TOLERANCE) + + # A row stays bitwise equal if no active LoRA pair targets it. A base-only + # pair and a sentinel pair add nothing. The kernel never reads their + # pair_to_row entries. + lora_active = (topk_ids.view(-1) >= 0) & ( + token_lora_mapping.repeat_interleave(top_k) >= 0 + ) + touched = pair_to_row[lora_active].long() + untouched = torch.ones(down_rows.shape[0], dtype=torch.bool) + untouched[touched] = False + assert torch.equal( + scattered[untouched.to(device)], gpu["down_rows"][untouched.to(device)] + ) + + oracle = _fp32_finalize_oracle( + down_rows, + pair_to_row, + bridge, + b_down, + topk_ids, + token_lora_mapping, + topk_weights, + num_experts, + ) + torch.testing.assert_close(output.cpu(), oracle, atol=1.8e-2, rtol=0.06) + + # With base-only traffic, the kernel must not change any base row. + base_slots = torch.full_like(gpu["token_lora_mapping"], -1) + aligned_base = build_route( + base_slots, + group_ids=gpu["topk_ids"], + groups_per_slot=num_experts, + max_loras=_SLOTS, + block_size=16, + view=RouteViewKind.ALIGNED, + ) + scattered_base = gpu["down_rows"].clone() + invoke_down_b_into_base( + down_rows=scattered_base, + pair_to_row=gpu["pair_to_row"], + bridge=gpu["bridge"], + b_down=gpu["b_down"], + routing=aligned_base, + config=_DOWN_B_CONFIG, + ) + assert torch.equal(scattered_base, gpu["down_rows"]) + # The active routing must change the rows. + assert (scattered - gpu["down_rows"]).abs().max().item() > 1e-3 + + +def _make_gpu_tensors(num_tokens: int, num_experts: int, device: torch.device): + generator = torch.Generator().manual_seed(0x5CA1 + num_tokens) + + def rand_bf16(shape, scale): + return (torch.randn(shape, generator=generator) * scale).to(torch.bfloat16) + + tensors = { + "hidden_states": rand_bf16((num_tokens, _HIDDEN), 0.20), + "w13_weight": rand_bf16((num_experts, 2 * _INTERMEDIATE, _HIDDEN), 0.08), + "w2_weight": rand_bf16((num_experts, _HIDDEN, _INTERMEDIATE), 0.08), + "gate_up_lora_a": rand_bf16((_SLOTS, num_experts, 2 * _RANK, _HIDDEN), 0.15), + "gate_up_lora_b": rand_bf16( + (_SLOTS, num_experts, 2 * _INTERMEDIATE, _RANK), 0.15 + ), + "down_lora_a": rand_bf16((_SLOTS, num_experts, _RANK, _INTERMEDIATE), 0.15), + "down_lora_b": rand_bf16((_SLOTS, num_experts, _HIDDEN, _RANK), 0.15), + } + # Slot 1 is a narrow adapter. Its rank padding is zero in all four + # factors. A batch with mixed ranks reaches the kernels in this form. + half = _RANK // 2 + tensors["gate_up_lora_a"][1].view(num_experts, 2, _RANK, _HIDDEN)[ + :, :, half:, : + ] = 0 + tensors["down_lora_a"][1, :, half:, :] = 0 + tensors["gate_up_lora_b"][1, :, :, half:] = 0 + tensors["down_lora_b"][1, :, :, half:] = 0 + + scores = torch.rand((num_tokens, num_experts), generator=generator) + scores[: num_tokens // 2, 0] += 4.0 # one expert gets many more pairs + topk_ids = torch.topk(scores, _TOP_K, dim=1).indices.to(torch.int32) + topk_ids[0] = -1 # a token with no routed pair + topk_ids[5, 1] = -1 # one sentinel pair inside a token that keeps a routed pair + tensors["topk_ids"] = topk_ids.contiguous() + weights = torch.rand((num_tokens, _TOP_K), generator=generator) + 0.1 + tensors["topk_weights"] = (weights / weights.sum(dim=1, keepdim=True)).float() + tensors["router_logits"] = torch.zeros( + (num_tokens, num_experts), dtype=torch.float32 + ) + return {name: tensor.to(device) for name, tensor in tensors.items()} + + +def _token_lora_mapping(traffic: str, num_tokens: int) -> torch.Tensor: + if traffic == "active": + pattern = torch.tensor([0, 1], dtype=torch.int32) + elif traffic == "mixed": + pattern = torch.tensor([0, -1, 1, -1], dtype=torch.int32) + elif traffic == "base_only": + pattern = torch.tensor([-1], dtype=torch.int32) + else: + raise AssertionError(traffic) + return pattern.repeat(-(-num_tokens // pattern.numel()))[:num_tokens].contiguous() + + +def _standalone_output_allocation(runner, *, num_tokens, dtype, device): + return torch.empty((num_tokens, runner.hidden_size), dtype=dtype, device=device) + + +def _into_base_pair(): + """Build plans differing only in down-B finalization, using the same fallback tiles.""" + tiles_row = _menu(_GB300, False)["fallback.decode"] + assert tiles_row.plan.act.family is ActFamily.MATERIALIZED + reference_plan = _serial_plan() + reordered_plan = replace(reference_plan, down_b_into_base=True) + assert reordered_plan.act.family is ActFamily.MATERIALIZED + return reference_plan, reordered_plan, _shipped_launch(tiles_row) + + +def _bind_test_menu(runner, plan, launch_config): + """Bind one plan to both phases to isolate execution from plan selection.""" + tiles = SimpleNamespace(config_for=lambda num_tokens: launch_config) + selected = SelectedPlan(name="test", base_gemm_rows="test", plan=plan, tiles=tiles) + runner.plans = {Phase.PREFILL: selected, Phase.DECODE: selected} + + +def _build_runner(plan, launch_config, base_gemm_rows: str, gpu, num_experts: int): + from sglang.srt.lora.moe.quant_info import MoeLoraBf16QuantInfo + from sglang.srt.lora.moe.runner import MoeLoraRunner + + provider = select_provider_cls(base_gemm_rows, "bf16")( + MoeLoraBf16QuantInfo( + w13_weight=gpu["w13_weight"], + w2_weight=gpu["w2_weight"], + num_local_experts=num_experts, + intermediate_size=_INTERMEDIATE, + hidden_size=_HIDDEN, + ) + ) + runner = MoeLoraRunner( + providers={"test": provider}, + top_k=_TOP_K, + routed_scaling_factor=_ROUTED_SCALING, + activation=ActivationFn.SILU, + ) + runner.validate_plan(plan, base_gemm_rows="test") + _bind_test_menu(runner, plan, launch_config) + return runner + + +def _run_once(runner, gpu, token_lora_mapping, *, use_cuda_graph=False): + from sglang.srt.layers.moe.token_dispatcher.standard import StandardDispatchOutput + from sglang.srt.layers.moe.topk import StandardTopKOutput + from sglang.srt.lora.moe.runner import MoeLoraBatch + + dispatch = StandardDispatchOutput( + hidden_states=gpu["hidden_states"], + hidden_states_scale=None, + topk_output=StandardTopKOutput( + topk_weights=gpu["topk_weights"], + topk_ids=gpu["topk_ids"], + router_logits=gpu["router_logits"], + ), + ) + batch = MoeLoraBatch( + gate_up_lora_a=gpu["gate_up_lora_a"], + gate_up_lora_b=gpu["gate_up_lora_b"], + down_lora_a=gpu["down_lora_a"], + down_lora_b=gpu["down_lora_b"], + token_lora_mapping=token_lora_mapping, + use_cuda_graph=use_cuda_graph, + is_prefill=True, + ) + return runner.run(dispatch, batch) + + +def _workspace_buffer_names(runner) -> set[str]: + workspace = runner.workspace + return {key[0] for key in workspace._eager_buffers} | { + key[0] for key in workspace._graph_storage + } + + +@cutedsl_cuda_only +@pytest.mark.parametrize("base_gemm_rows", ("expert_major", "route_major")) +@pytest.mark.parametrize( + "act_family,into_base", + ( + (ActFamily.MATERIALIZED, True), + (ActFamily.B_ACTIVATION, False), + (ActFamily.B_ACTIVATION, True), + ), + ids=("into-base", "b-act", "b-act-into-base"), +) +def test_runner_fused_stages_match_the_materialized_reference( + base_gemm_rows: str, + act_family: ActFamily, + into_base: bool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Compare fused middles and tails across both provider row domains.""" + from sglang.srt.lora.moe.runner import MoeLoraRunner + + device = torch.device("cuda") + monkeypatch.setattr( + MoeLoraRunner, "_allocate_output", _standalone_output_allocation + ) + serial_plan, _, launch_config = _into_base_pair() + fused_plan = _make_plan(act_family=act_family, down_b_into_base=into_base) + num_tokens, num_experts = 64, 4 + gpu = _make_gpu_tensors(num_tokens, num_experts, device) + reference_runner = _build_runner( + serial_plan, launch_config, "expert_major", gpu, num_experts + ) + fused_runner = _build_runner( + fused_plan, launch_config, base_gemm_rows, gpu, num_experts + ) + # B_ACTIVATION adds the delta in FP32, unlike the BF16 materialized bridge. + tolerance = ( + {"atol": 1e-2, "rtol": 0.05} + if act_family is ActFamily.B_ACTIVATION + else _INTO_BASE_TOLERANCE + ) + + for traffic in ("active", "mixed", "base_only"): + token_lora_mapping = _token_lora_mapping(traffic, num_tokens).to(device) + reference = _run_once(reference_runner, gpu, token_lora_mapping).hidden_states + fused = _run_once(fused_runner, gpu, token_lora_mapping).hidden_states + torch.testing.assert_close( + fused, + reference, + **tolerance, + msg=f"{base_gemm_rows}: {act_family.value} into_base={into_base} {traffic}", + ) + + # The scatter path never allocates the pair-major delta buffer for down-B. + # The shipped path always allocates it. + assert "down_b:delta" in _workspace_buffer_names(reference_runner) + assert ("down_b:delta" not in _workspace_buffer_names(fused_runner)) == into_base + + +@cutedsl_cuda_only +def test_into_base_pipeline_replays_correctly_in_a_real_cuda_graph( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from sglang.srt.lora.moe.runner import MoeLoraRunner + + device = torch.device("cuda") + monkeypatch.setattr( + MoeLoraRunner, "_allocate_output", _standalone_output_allocation + ) + serial_plan, reordered_plan, launch_config = _into_base_pair() + num_tokens, num_experts = 64, 4 + gpu = _make_gpu_tensors(num_tokens, num_experts, device) + reference_runner = _build_runner( + serial_plan, launch_config, "expert_major", gpu, num_experts + ) + into_base_runner = _build_runner( + reordered_plan, launch_config, "expert_major", gpu, num_experts + ) + token_lora_mapping = _token_lora_mapping("active", num_tokens).to(device) + + # The workspace keys scratch by stream: warm up on the capture stream. + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(2): # warm the JIT and keep the graph buffers before capture + _run_once(into_base_runner, gpu, token_lora_mapping, use_cuda_graph=True) + torch.cuda.synchronize(device) + + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + captured = _run_once( + into_base_runner, gpu, token_lora_mapping, use_cuda_graph=True + ) + output = captured.hidden_states + output_ptr = output.data_ptr() + + graph.replay() + torch.cuda.synchronize(device) + reference = _run_once(reference_runner, gpu, token_lora_mapping).hidden_states + torch.testing.assert_close(output, reference, **_INTO_BASE_TOLERANCE) + + # Replay 2: every token in the batch becomes base-only. + token_lora_mapping.fill_(-1) + graph.replay() + torch.cuda.synchronize(device) + assert output.data_ptr() == output_ptr + reference = _run_once(reference_runner, gpu, token_lora_mapping).hidden_states + torch.testing.assert_close(output, reference, **_INTO_BASE_TOLERANCE) + + # Replay 3: new routing and new activations arrive in the same buffers. + gpu["topk_ids"].copy_(gpu["topk_ids"].flip(dims=(1,))) + gpu["hidden_states"].copy_((gpu["hidden_states"].float() * 1.5).to(torch.bfloat16)) + token_lora_mapping.copy_(_token_lora_mapping("mixed", num_tokens).to(device)) + graph.replay() + torch.cuda.synchronize(device) + assert output.data_ptr() == output_ptr + reference = _run_once(reference_runner, gpu, token_lora_mapping).hidden_states + torch.testing.assert_close(output, reference, **_INTO_BASE_TOLERANCE) + + assert "down_b:delta" not in _workspace_buffer_names(into_base_runner) + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/lora/test_moe_lora_fp8_provider_numerics.py b/test/registered/kernels/ops/lora/test_moe_lora_fp8_provider_numerics.py new file mode 100644 index 0000000000..48ba1a62ba --- /dev/null +++ b/test/registered/kernels/ops/lora/test_moe_lora_fp8_provider_numerics.py @@ -0,0 +1,201 @@ +"""FP8 providers against FP32 references from dequantized checkpoint bytes. +Tolerances cover per-token-group activation quantization and BF16 outputs. +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +import torch + +from sglang.srt.lora.moe.base_gemm_provider import select_provider_cls +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=60, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +_E = 4 +_H = 512 +_I = 512 +_TOPK = 2 +_T = 32 +_BLOCK = 128 + + +def _skip_unless_supported(vendor="cutedsl"): + if not torch.cuda.is_available(): + pytest.skip("CUDA required") + if vendor == "cutedsl" and torch.cuda.get_device_capability()[0] < 9: + pytest.skip("the FP8 CuTeDSL provider needs SM90+") + + +def _block_quant(weight: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """Per-[128,128]-block fp8 quant; returns (fp8 weight, fp32 inverse scale).""" + e, rows, cols = weight.shape + rb = (rows + _BLOCK - 1) // _BLOCK + cb = (cols + _BLOCK - 1) // _BLOCK + scale = torch.empty((e, rb, cb), dtype=torch.float32, device=weight.device) + q = torch.empty_like(weight, dtype=torch.float8_e4m3fn) + fmax = torch.finfo(torch.float8_e4m3fn).max + for i in range(rb): + for j in range(cb): + blk = weight[ + :, i * _BLOCK : (i + 1) * _BLOCK, j * _BLOCK : (j + 1) * _BLOCK + ] + amax = blk.float().abs().amax(dim=(1, 2)).clamp(min=1e-6) + s = amax / fmax + scale[:, i, j] = s + q[:, i * _BLOCK : (i + 1) * _BLOCK, j * _BLOCK : (j + 1) * _BLOCK] = ( + blk.float() / s[:, None, None] + ).to(torch.float8_e4m3fn) + return q, scale + + +def _case(device, hidden_size=_H): + g = torch.Generator(device="cpu").manual_seed(7) + + def rand(*shape): + return (torch.randn(*shape, generator=g) * 0.05).to(torch.bfloat16).to(device) + + w13 = rand(_E, 2 * _I, hidden_size) + w2 = rand(_E, hidden_size, _I) + hidden = rand(_T, hidden_size) + topk_ids = torch.stack( + [torch.randperm(_E, generator=g)[:_TOPK] for _ in range(_T)] + ).to(device=device, dtype=torch.int32) + return w13, w2, hidden, topk_ids + + +def _quant_info(w13, w2, hidden_size=_H): + """Quantize weights locally and use serving dequantization for the FP32 reference.""" + from sglang.srt.layers.quantization.fp8_utils import block_quant_dequant + from sglang.srt.lora.moe.quant_info import MoeLoraFp8QuantInfo + + w13_q, w13_s = _block_quant(w13) + w2_q, w2_s = _block_quant(w2) + w13_eff = block_quant_dequant(w13_q, w13_s, [128, 128], torch.float32) + w2_eff = block_quant_dequant(w2_q, w2_s, [128, 128], torch.float32) + info = MoeLoraFp8QuantInfo( + w13_weight=w13_q, + w13_scale=w13_s, + w2_weight=w2_q, + w2_scale=w2_s, + block_shape=(128, 128), + num_local_experts=_E, + intermediate_size=_I, + hidden_size=hidden_size, + ) + return info, w13_eff, w2_eff + + +def _gather_pairs(slab_or_rows, pair_to_row, pair_idx): + rows = ( + slab_or_rows.reshape(-1, slab_or_rows.shape[-1]) + if slab_or_rows.ndim == 3 + else slab_or_rows + ) + return rows[pair_to_row[pair_idx].long()] + + +def _rel_l2(a, b): + return (a - b).norm() / b.norm().clamp(min=1e-12) + + +# 7168 is a DeepSeek-V3-class hidden size: not a power of two. +@pytest.mark.parametrize("hidden_size", [_H, 7168]) +@pytest.mark.parametrize( + "vendor,rows", + [ + ("triton", "route_major"), + ("cutedsl", "expert_major"), + ("cutedsl", "route_major"), + ], +) +def test_fp8_gateup_and_down_match_reference(vendor, rows, hidden_size): + _skip_unless_supported(vendor) + device = torch.device("cuda") + w13, w2, hidden, topk_ids = _case(device, hidden_size) + quant_info, w13_eff, w2_eff = _quant_info(w13, w2, hidden_size=hidden_size) + + from sglang.srt.runtime_context import get_context + + provider = select_provider_cls(rows, "fp8", vendor)(quant_info) + with get_context().override_server_args(): + state = provider.prepare(hidden, topk_ids, _TOPK) + gateup = torch.empty( + provider.gateup_out_shape(state), dtype=torch.bfloat16, device=device + ) + provider.gateup(state, gateup) + + flat_ids = topk_ids.flatten() + pair_idx = torch.nonzero(flat_ids >= 0, as_tuple=True)[0] + experts = flat_ids[pair_idx].long() + tokens = (pair_idx // _TOPK).long() + pair_to_row = state.pair_to_row + + ref_gateup = torch.einsum("ph,pnh->pn", hidden[tokens].float(), w13_eff[experts]) + got_gateup = _gather_pairs(gateup, pair_to_row, pair_idx).float() + assert _rel_l2(got_gateup, ref_gateup) < 4e-2 + + # Down over a synthetic activation scattered into the provider's layout. + act_pairs = (torch.randn_like(ref_gateup[:, :_I]) * 0.1).to(torch.bfloat16) + act = torch.zeros( + provider.act_out_shape(state), dtype=torch.bfloat16, device=device + ) + act.reshape(-1, _I)[pair_to_row[pair_idx].long()] = act_pairs + down = torch.empty( + provider.down_out_shape(state), dtype=torch.bfloat16, device=device + ) + with get_context().override_server_args(): + provider.down(state, act, down) + + ref_down = torch.einsum("pi,phi->ph", act_pairs.float(), w2_eff[experts]) + got_down = _gather_pairs(down, pair_to_row, pair_idx).float() + assert _rel_l2(got_down, ref_down) < 4e-2 + + if vendor == "triton": + from sglang.kernels.ops.quantization.fp8_kernel import ( + sglang_per_token_group_quant_fp8, + ) + + state.act_quant = sglang_per_token_group_quant_fp8(act, _BLOCK) + # The supplied FP8 operands must bypass the unused BF16 activation. + act.fill_(float("nan")) + down.fill_(float("nan")) + with get_context().override_server_args(): + provider.down(state, act, down) + got_down = _gather_pairs(down, pair_to_row, pair_idx).float() + assert _rel_l2(got_down, ref_down) < 4e-2 + + +def test_fp8_admission_rejects_bad_geometry(): + from sglang.srt.lora.moe.quant_info import _admit_fp8_block_weights + + with pytest.raises(NotImplementedError, match=r"\[128, 128\]"): + _admit_fp8_block_weights(SimpleNamespace(block_shape=(64, 64))) + + +def test_fp8_kernel_rejects_tiles_the_scale_epilogue_cannot_index(): + """The SM100 FP8 epilogue indexes weight scales per 128-wide output tile and + stages one column scale per epilogue thread (128 threads).""" + cutlass = pytest.importorskip("cutlass") + from sglang.kernels.ops.lora.moe.cutedsl.kernel_sm100_fp8 import ( + GroupedGemmKernelSm100Fp8, + ) + + def build(mma_tiler_mn): + return GroupedGemmKernelSm100Fp8( + acc_dtype=cutlass.Float32, + use_2cta_instrs=False, + mma_tiler_mn=mma_tiler_mn, + cluster_shape_mn=(1, 1), + swap_ab=True, + ) + + for mma_tiler_mn in ((64, 128), (128, 256)): + with pytest.raises(ValueError, match="mma_tiler_mn"): + build(mma_tiler_mn) + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/lora/test_moe_lora_fused_dispatch.py b/test/registered/kernels/ops/lora/test_moe_lora_fused_dispatch.py new file mode 100644 index 0000000000..ce6f7546f4 --- /dev/null +++ b/test/registered/kernels/ops/lora/test_moe_lora_fused_dispatch.py @@ -0,0 +1,305 @@ +"""Dispatch invariants and fused FP8 row-mover/activation parity.""" + +from __future__ import annotations + +import pytest +import torch + +pytest.importorskip("triton") + +from sglang.kernels.ops.lora.moe.activation_delta import act_delta # noqa: E402 +from sglang.kernels.ops.lora.moe.dispatch_masked import ( # noqa: E402 + dispatch_fill_masked_bf16, +) +from sglang.kernels.ops.moe.ep_moe_kernels import ( # noqa: E402 + moe_ep_deepgemm_preprocess, +) +from sglang.srt.lora.moe.base_gemm_provider.base import ( # noqa: E402 + expected_rows_per_expert, +) +from sglang.test.ci.ci_register import register_cuda_ci # noqa: E402 + +register_cuda_ci(est_time=60, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available(), reason="fused LoRA stages require CUDA" +) + + +def _routed_topk_ids( + num_tokens: int, top_k: int, num_experts: int, *, seed: int +) -> torch.Tensor: + """Distinct experts per token (the capacity invariant both kernels rely on).""" + generator = torch.Generator().manual_seed(seed) + scores = torch.rand((num_tokens, num_experts), generator=generator) + return torch.topk(scores, top_k, dim=1).indices.to(torch.int32) + + +def _rand_hidden(num_tokens: int, hidden: int, *, seed: int) -> torch.Tensor: + generator = torch.Generator().manual_seed(seed) + return torch.randn((num_tokens, hidden), generator=generator).to(torch.bfloat16) + + +def _masked_buffers( + num_tokens: int, top_k: int, num_experts: int, hidden: int, *, device +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + m_max = (num_tokens // 256 + 1) * 256 + return ( + torch.empty(num_experts, dtype=torch.int32, device=device), + torch.empty(num_tokens * top_k, dtype=torch.int32, device=device), + torch.empty((num_experts, m_max, hidden), dtype=torch.bfloat16, device=device), + ) + + +def _assert_matches_reference( + topk_ids: torch.Tensor, + hidden_states: torch.Tensor, + num_local_experts: int, + top_k: int, +) -> None: + ref_masked, ref_expected, _ref_s2d, _ref_slab, ref_scale = ( + moe_ep_deepgemm_preprocess( + topk_ids, + num_local_experts, + hidden_states, + top_k, + None, + output_dtype=torch.bfloat16, + ) + ) + masked, pair_to_row, slab = _masked_buffers( + hidden_states.shape[0], + top_k, + num_local_experts, + hidden_states.shape[1], + device=hidden_states.device, + ) + pair_to_row.fill_(-777) + dispatch_fill_masked_bf16( + hidden_states, + topk_ids, + top_k, + masked_m_out=masked, + pair_to_row_out=pair_to_row, + rows_out=slab, + ) + assert ref_scale is None + assert expected_rows_per_expert(topk_ids.numel(), num_local_experts) == ref_expected + assert torch.equal(masked, ref_masked) + + hidden = hidden_states.shape[1] + m_max = slab.shape[1] + flat_ids = topk_ids.view(-1).long() + valid = flat_ids >= 0 + assert bool(torch.all(pair_to_row[~valid] == -1)) + experts = flat_ids[valid] + histogram = torch.bincount(experts, minlength=num_local_experts).to(torch.int32) + assert torch.equal(masked, histogram) + + dst = pair_to_row.long()[valid] + region_lo = experts * m_max + assert bool(torch.all(dst >= region_lo)) + assert bool(torch.all(dst < region_lo + masked.long()[experts])) + assert dst.unique().numel() == dst.numel() + + tokens = torch.div( + torch.nonzero(valid, as_tuple=True)[0], top_k, rounding_mode="floor" + ) + assert torch.equal(slab.view(-1, hidden)[dst], hidden_states[tokens]) + + +@pytest.mark.parametrize( + ("num_tokens", "top_k", "num_experts", "hidden", "skewed_expert"), + ((8, 2, 4, 128, None), (192, 8, 16, 320, None), (250, 1, 8, 128, 3)), + ids=("decode-single-block-ref", "prefill-multi-block-ref", "skewed-one-expert"), +) +def test_matches_two_kernel_composition( + num_tokens: int, top_k: int, num_experts: int, hidden: int, skewed_expert +) -> None: + """The skewed case sends all traffic to one expert: masked_m near m_max, + every other expert empty.""" + device = torch.device("cuda") + if skewed_expert is None: + topk_ids = _routed_topk_ids(num_tokens, top_k, num_experts, seed=0xD15) + else: + topk_ids = torch.full((num_tokens, top_k), skewed_expert, dtype=torch.int32) + hidden_states = _rand_hidden(num_tokens, hidden, seed=0xF111).to(device) + _assert_matches_reference(topk_ids.to(device), hidden_states, num_experts, top_k) + + +def test_sentinel_pairs_are_skipped() -> None: + """-1 pairs take no slot, map to pair_to_row == -1 (the finalize gate), copy nothing.""" + device = torch.device("cuda") + num_tokens, top_k, num_experts, hidden = 64, 4, 8, 128 + topk_ids = _routed_topk_ids(num_tokens, top_k, num_experts, seed=0x5E17) + drop = torch.rand(topk_ids.shape, generator=torch.Generator().manual_seed(7)) < 0.3 + assert bool(drop.any()) + topk_ids[drop] = -1 + topk_ids = topk_ids.to(device) + hidden_states = _rand_hidden(num_tokens, hidden, seed=0xB0B).to(device) + _assert_matches_reference(topk_ids, hidden_states, num_experts, top_k) + + +@pytest.mark.parametrize("hidden", [128, 1536, 7168]) +@pytest.mark.parametrize("domain", ["masked", "contiguous"]) +@pytest.mark.parametrize("captured", [False, True]) +def test_fp8_row_movers_match_upstream_quant(hidden, domain, captured) -> None: + from sglang.kernels.ops.lora.moe.dispatch_contiguous import ( + contiguous_m_pad_ceiling, + dispatch_fill_rows_contiguous_fp8, + dispatch_layout_contiguous, + ) + from sglang.kernels.ops.lora.moe.dispatch_masked import dispatch_fill_masked_fp8 + from sglang.kernels.ops.quantization.fp8_kernel import ( + sglang_per_token_group_quant_fp8, + ) + + num_tokens, top_k, num_experts = 16, 4, 8 + device = torch.device("cuda") + ids = _routed_topk_ids(num_tokens, top_k, num_experts, seed=5).to(device) + ids[0] = -1 + ids[1, 2] = -1 + x = _rand_hidden(num_tokens, hidden, seed=6).to(device) + x[2].zero_() + x[3, ::128] = 32 + counts = torch.empty(num_experts, dtype=torch.int32, device=device) + mapping = torch.empty(num_tokens * top_k, dtype=torch.int32, device=device) + if domain == "masked": + shape = (num_experts, num_tokens, hidden) + else: + offsets = torch.empty(num_experts + 1, dtype=torch.int32, device=device) + shape = (contiguous_m_pad_ceiling(mapping.numel(), num_experts, 8), hidden) + rows = torch.empty(shape, dtype=torch.float8_e4m3fn, device=device) + scales = torch.empty( + (*shape[:-1], hidden // 128), dtype=torch.float32, device=device + ) + + def dispatch(): + if domain == "masked": + dispatch_fill_masked_fp8( + x, + ids, + top_k, + masked_m_out=counts, + pair_to_row_out=mapping, + rows_fp8_out=rows, + scale_out=scales, + ) + else: + dispatch_layout_contiguous( + x, + ids, + num_experts, + top_k, + 8, + seg_counts_out=counts, + seg_offsets_out=offsets, + pair_to_row_out=mapping, + ) + dispatch_fill_rows_contiguous_fp8( + x, ids, mapping, rows_fp8_out=rows, scale_out=scales + ) + + if captured: + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + dispatch() + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + dispatch() + run = graph.replay + else: + run = dispatch + for step in range(2): + rows.fill_(0.25) + scales.fill_(-777) + if step: + x.mul_(0.5) + ids.copy_(ids.roll(1, dims=0)) + run() + ref_q, ref_s = sglang_per_token_group_quant_fp8(x, 128) + valid = ids.view(-1) >= 0 + tokens = torch.arange(num_tokens, device=device).repeat_interleave(top_k)[valid] + dst = mapping[valid].long() + flat_rows = rows.view(-1, hidden) + flat_scales = scales.view(-1, hidden // 128) + # A single 128-wide group takes upstream's per-token kernel, whose + # small-batch variant saturates the codes of an all-zero row (its scale + # is zero, so every code dequantizes to zero); compare those by scale. + live = ref_s[tokens].ne(0).any(dim=-1) + assert torch.equal( + flat_rows[dst][live].view(torch.uint8), + ref_q[tokens][live].view(torch.uint8), + ) + # The movers write zero codes for a zero-scale row (a NaN code would + # not dequantize to zero), so those rows must hold exactly zero. + assert bool(torch.all(flat_rows[dst][~live].float() == 0)) + assert torch.equal(flat_scales[dst], ref_s[tokens]) + assert bool(torch.all(mapping[~valid] == -1)) + unused = torch.ones(flat_rows.size(0), dtype=torch.bool, device=device) + unused[dst] = False + assert bool(torch.all(flat_rows[unused].float() == 0.25)) + assert bool(torch.all(flat_scales[unused] == -777)) + + +@pytest.mark.parametrize( + "inter,with_delta", [(128, False), (128, True), (384, True), (1152, False)] +) +def test_fused_act_quant_matches_unfused(inter, with_delta): + from sglang.kernels.ops.quantization.fp8_kernel import ( + sglang_per_token_group_quant_fp8, + ) + + torch.manual_seed(0) + device = torch.device("cuda") + num_tokens, top_k, num_experts, group = 7, 3, 8, 128 + num_pairs = num_tokens * top_k + gateup = torch.randn(num_pairs, 2 * inter, dtype=torch.bfloat16, device=device) + delta = ( + 0.1 + * torch.randn(num_tokens, top_k, 2 * inter, dtype=torch.bfloat16, device=device) + if with_delta + else None + ) + topk_ids = torch.randint( + 0, num_experts, (num_tokens, top_k), dtype=torch.int32, device=device + ) + topk_ids[0, 0] = -1 + pair_to_row = torch.arange(num_pairs, dtype=torch.int32, device=device) + + def run(act_quant): + act = torch.zeros(num_pairs, inter, dtype=torch.bfloat16, device=device) + pairs = torch.zeros( + num_tokens, top_k, inter, dtype=torch.bfloat16, device=device + ) + act_delta( + gateup, + delta, + act, + pairs, + pair_to_row, + topk_ids, + num_local_experts=num_experts, + act_quant=act_quant, + ) + return act, pairs + + ref_act, ref_pairs = run(None) + act_q = torch.zeros(num_pairs, inter, dtype=torch.float8_e4m3fn, device=device) + act_s = torch.zeros(num_pairs, inter // group, dtype=torch.float32, device=device) + fused_act, fused_pairs = run((act_q, act_s, group)) + assert torch.equal(fused_act, ref_act) + assert torch.equal(fused_pairs, ref_pairs) + + ref_q, ref_s = sglang_per_token_group_quant_fp8(ref_act, group) + valid_rows = (topk_ids.flatten() >= 0).nonzero(as_tuple=True)[0] + assert torch.equal(act_s[valid_rows], ref_s[valid_rows]) + assert torch.equal( + act_q[valid_rows].view(torch.uint8), ref_q[valid_rows].view(torch.uint8) + ) + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/lora/test_moe_lora_masked_capacity_graph.py b/test/registered/kernels/ops/lora/test_moe_lora_masked_capacity_graph.py new file mode 100644 index 0000000000..2b04194cbd --- /dev/null +++ b/test/registered/kernels/ops/lora/test_moe_lora_masked_capacity_graph.py @@ -0,0 +1,212 @@ +"""CuTe provider replay across slab boundaries.""" + +from __future__ import annotations + +import pytest +import torch +import torch.nn.functional as F + +from sglang.srt.lora.workspace import LoraWorkspace +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=90, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +_EXPERTS, _HIDDEN, _INTERMEDIATE, _TOP_K = 4, 128, 128, 2 + + +def _require_cuda(): + if not torch.cuda.is_available(): + pytest.skip("CUDA required") + + +@pytest.fixture( + scope="module", + params=(("bf16", False), ("fp8", False), ("fp8", True)), + ids=("bf16", "fp8", "fp8-separate-quant"), +) +def masked_provider(request): + _require_cuda() + if torch.cuda.get_device_capability()[0] not in (9, 10): + pytest.skip("CuTe providers require SM90 or SM100") + pytest.importorskip("cutlass") + pytest.importorskip("cuda.bindings.driver") + + from sglang.srt.lora.moe.base_gemm_provider import select_provider_cls + from sglang.srt.lora.moe.quant_info import ( + MoeLoraBf16QuantInfo, + MoeLoraFp8QuantInfo, + ) + from sglang.srt.runtime_context import get_context + + generator = torch.Generator().manual_seed(719) + + def weight(rows, cols): + return (torch.randn(_EXPERTS, rows, cols, generator=generator) * 0.05).to( + device="cuda", dtype=torch.bfloat16 + ) + + w13, w2 = weight(2 * _INTERMEDIATE, _HIDDEN), weight(_HIDDEN, _INTERMEDIATE) + geometry = dict( + num_local_experts=_EXPERTS, + intermediate_size=_INTERMEDIATE, + hidden_size=_HIDDEN, + ) + family, separate_quant = request.param + if family == "fp8": + # Legal block-128 checkpoint scales; reference the effective weights. + def quantize(w): + scale = torch.full( + (_EXPERTS, w.shape[1] // 128, w.shape[2] // 128), + 1 / 1024, + dtype=torch.float32, + device="cuda", + ) + q = (w.float() * 1024).to(torch.float8_e4m3fn) + return q, scale, q.float() / 1024 + + q13, s13, w13 = quantize(w13) + q2, s2, w2 = quantize(w2) + info = MoeLoraFp8QuantInfo( + w13_weight=q13, + w13_scale=s13, + w2_weight=q2, + w2_scale=s2, + block_shape=(128, 128), + **geometry, + ) + else: + info = MoeLoraBf16QuantInfo(w13_weight=w13, w2_weight=w2, **geometry) + with get_context().override_server_args(): + provider = select_provider_cls("expert_major", family, "cutedsl")(info) + return family, provider, w13.float(), w2.float(), separate_quant + + +def _capture(fn, stream): + # One capture stream per workspace, as in a graph runner: the workspace + # keys scratch by stream, so buckets grow and retire storage only within one. + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + fn() + fn() + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + result = fn() + torch.cuda.current_stream().wait_stream(stream) + return graph, result + + +def _set_routing(ids, traffic): + # Every token chooses distinct experts; the last expert receives N rows, + # testing the physical end of the slab rather than a balanced mean load. + ids[:, 0] = _EXPERTS - 2 + ids[:, 1] = _EXPERTS - 1 + if traffic == "padded": + ids[::2, 0] = -1 + ids[1::3, 1] = 0 + ids[-max(1, ids.shape[0] // 4) :] = -1 + elif traffic == "empty": + ids.fill_(-1) + + +def _check_pairs(hidden, ids, result, w13, w2, family): + state, gateup, act, down = result + flat_ids = ids.flatten().long() + valid = flat_ids >= 0 + pairs = torch.nonzero(valid, as_tuple=True)[0] + experts = flat_ids[pairs] + rows = state.pair_to_row[pairs].long() + torch.testing.assert_close( + state.masked_m.long(), torch.bincount(experts, minlength=_EXPERTS) + ) + assert bool((state.pair_to_row[~valid] == -1).all()) + assert bool( + ((rows >= experts * state.m_max) & (rows < (experts + 1) * state.m_max)).all() + ) + assert rows.unique().numel() == pairs.numel() + if not pairs.numel(): + assert state.gemm1_tiles.item() == state.gemm2_tiles.item() == 0 + return + + def gather(tensor): + return tensor.reshape(-1, tensor.shape[-1])[rows].float() + + ref_gateup = torch.einsum("th,enh->ten", hidden.float(), w13)[ + pairs // _TOP_K, experts + ] + got_gateup, got_act, got_down = map(gather, (gateup, act, down)) + ref_act = F.silu(got_gateup[:, :_INTERMEDIATE]) * got_gateup[:, _INTERMEDIATE:] + torch.testing.assert_close(got_act, ref_act, rtol=1e-2, atol=1e-5) + ref_down = torch.einsum("pi,ehi->peh", got_act, w2)[ + torch.arange(pairs.numel(), device=hidden.device), experts + ] + tolerance = 4e-2 if family == "fp8" else 1e-2 + for actual, expected in ((got_gateup, ref_gateup), (got_down, ref_down)): + assert bool(torch.isfinite(actual).all()) + relative_l2 = (actual - expected).norm() / expected.norm().clamp(min=1e-12) + assert relative_l2.item() < tolerance + + +@pytest.mark.parametrize("token_width", (8, 64, 128)) +def test_masked_capacity_boundary_graphs(masked_provider, monkeypatch, token_width): + from sglang.srt.runtime_context import get_context + + family, provider, w13, w2, separate_quant = masked_provider + # Exercise each already-compiled kernel without modifying dispatch policy. + monkeypatch.setattr(provider, "_token_width_for", lambda *_: token_width) + workspace = LoraWorkspace() + stream = torch.cuda.Stream() + workspace.begin_forward(graph_mode=True) + captured = [] + generator = torch.Generator().manual_seed(720) + with get_context().override_server_args(): + buckets = sorted( + {0, 1, token_width - 1, token_width, token_width + 1, 2 * token_width + 1} + ) + for n in reversed(buckets): + hidden = (torch.randn(n, _HIDDEN, generator=generator) * 0.1).to( + device="cuda", dtype=torch.bfloat16 + ) + ids = torch.empty((n, _TOP_K), dtype=torch.int32, device="cuda") + _set_routing(ids, "last") + + def run(): + state = provider.prepare(hidden, ids, _TOP_K, workspace) + + def buffer(name, shape): + return workspace.tensor( + name, shape, dtype=torch.bfloat16, device=hidden.device + ) + + gateup = buffer("test:gateup", provider.gateup_out_shape(state)) + act = buffer("test:act", provider.act_out_shape(state)) + down = buffer("test:down", provider.down_out_shape(state)) + act_pairs = buffer("test:act_pairs", (n, _TOP_K, _INTERMEDIATE)) + provider.gateup(state, gateup) + provider.act_with_delta(state, gateup, None, ids, act, act_pairs) + if separate_quant: + # Exercise the down-quantization path used by fused-B plans. + state.act_quant_ready = False + provider.down(state, act, down) + return state, gateup, act, down + + graph, result = _capture(run, stream) + alignment = token_width if family == "fp8" else 8 + expected_capacity = max( + alignment, (n + alignment - 1) // alignment * alignment + ) + assert result[0].m_max == expected_capacity + assert result[0].token_width == token_width + captured.append((graph, hidden, ids, result)) + + # Replay old graphs after every smaller bucket has reused their storage. + # Restoring a populated route after all -1 catches stale counters/maps. + for graph, hidden, ids, result in captured: + for traffic in ("last", "padded", "empty", "last"): + _set_routing(ids, traffic) + graph.replay() + _check_pairs(hidden, ids, result, w13, w2, family) + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/lora/test_moe_lora_moe_runner_numerics.py b/test/registered/kernels/ops/lora/test_moe_lora_moe_runner_numerics.py new file mode 100644 index 0000000000..4b0486bc4c --- /dev/null +++ b/test/registered/kernels/ops/lora/test_moe_lora_moe_runner_numerics.py @@ -0,0 +1,421 @@ +"""Per-expert MoE LoRA against independent FP32 and staged-BF16 references.""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +import torch +import torch.nn.functional as F + +from sglang.srt.layers.moe.token_dispatcher.standard import StandardDispatchOutput +from sglang.srt.layers.moe.topk import StandardTopKOutput +from sglang.srt.lora.moe.base_gemm_provider import select_provider_cls +from sglang.srt.lora.moe.plan import ( + ActFamily, + ActivationFn, + FinalizeFamily, + MoePlan, + SelectedPlan, + resolve_plans, +) +from sglang.srt.lora.moe.quant_info import MoeLoraBf16QuantInfo +from sglang.srt.lora.moe.runner import ( + MoeLoraBatch, + MoeLoraRunner, +) +from sglang.srt.lora.utils import Phase, architecture_for_capability +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=60, stage="base-b-kernel-unit", runner_config="1-gpu-large") + + +def _bind_test_menu(runner, plan, launch_config): + """Bind one plan to both phases to isolate execution from plan selection.""" + tiles = SimpleNamespace(config_for=lambda num_tokens: launch_config) + selected = SelectedPlan(name="test", base_gemm_rows="test", plan=plan, tiles=tiles) + runner.plans = {Phase.PREFILL: selected, Phase.DECODE: selected} + + +def _cutedsl_ready() -> bool: + if not torch.cuda.is_available() or torch.cuda.get_device_capability() < (9, 0): + return False + try: + import cuda.bindings.driver # noqa: F401 + import cutlass # noqa: F401 + except Exception: + return False + return True + + +pytestmark = pytest.mark.skipif( + not _cutedsl_ready(), reason="the numerical oracle runs the CuTeDSL providers" +) + +_EXPERTS = 2 +_TOP_K = 2 +_HIDDEN = 128 +_INTERMEDIATE = 128 +_PHYSICAL_RANK = 16 +_SLOTS = 2 +_ROUTED_SCALING = 0.75 + + +def _rand_bf16( + shape: tuple[int, ...], *, generator: torch.Generator, scale: float +) -> torch.Tensor: + return (torch.randn(shape, generator=generator) * scale).to(torch.bfloat16) + + +def _resolve_execution( + architecture, + mode: Phase, + num_tokens: int, + *, + hidden_size=_HIDDEN, + physical_rank=_PHYSICAL_RANK, +): + selected = resolve_plans( + quant_family="bf16", + architecture=architecture, + is_shared_outer=False, + physical_rank=physical_rank, + activation=ActivationFn.SILU, + hidden_size=hidden_size, + num_local_experts=_EXPERTS, + )[mode] + launch_config = selected.tiles.config_for(num_tokens) + if architecture == "sm100" and mode is Phase.DECODE: + # Small-rank decode exercises serial split-K; rank 256 must stay unsplit. + expected_split = 1 + if physical_rank <= 16: + expected_split = 8 if num_tokens <= 4 else 4 if num_tokens <= 16 else 1 + assert launch_config.gate_up_a.get("SPLIT_K", 1) == expected_split + assert launch_config.down_a.get("SPLIT_K", 1) == 1 + return selected, launch_config + + +def _make_cpu_tensors( + num_tokens: int, + *, + hidden_size=_HIDDEN, + intermediate_size=_INTERMEDIATE, + physical_rank=_PHYSICAL_RANK, +) -> dict[str, torch.Tensor]: + generator = torch.Generator().manual_seed(0x5A17 + num_tokens) + # Keep each projection's variance comparable as fan-in and rank grow. + hidden_scale = (_HIDDEN / hidden_size) ** 0.5 + intermediate_scale = (_INTERMEDIATE / intermediate_size) ** 0.5 + rank_scale = (_PHYSICAL_RANK / physical_rank) ** 0.5 + tensors = { + "hidden_states": _rand_bf16( + (num_tokens, hidden_size), generator=generator, scale=0.20 + ), + "w13_weight": _rand_bf16( + (_EXPERTS, 2 * intermediate_size, hidden_size), + generator=generator, + scale=0.08 * hidden_scale, + ), + "w2_weight": _rand_bf16( + (_EXPERTS, hidden_size, intermediate_size), + generator=generator, + scale=0.08 * intermediate_scale, + ), + "gate_up_lora_a": _rand_bf16( + (_SLOTS, _EXPERTS, 2 * physical_rank, hidden_size), + generator=generator, + scale=0.15 * hidden_scale, + ), + "gate_up_lora_b": _rand_bf16( + (_SLOTS, _EXPERTS, 2 * intermediate_size, physical_rank), + generator=generator, + scale=0.15 * rank_scale, + ), + "down_lora_a": _rand_bf16( + (_SLOTS, _EXPERTS, physical_rank, intermediate_size), + generator=generator, + scale=0.15 * intermediate_scale, + ), + "down_lora_b": _rand_bf16( + (_SLOTS, _EXPERTS, hidden_size, physical_rank), + generator=generator, + scale=0.15 * rank_scale, + ), + } + + alternating_ids = torch.tensor([[0, 1], [1, 0]], dtype=torch.int32) + tensors["topk_ids"] = alternating_ids.repeat((num_tokens + 1) // 2, 1)[ + :num_tokens + ].contiguous() + tensors["topk_weights"] = torch.tensor([[0.65, 0.35]], dtype=torch.float32).repeat( + num_tokens, 1 + ) + tensors["router_logits"] = torch.zeros((num_tokens, _EXPERTS), dtype=torch.float32) + tensors["adapter_enabled"] = torch.tensor([1, 0], dtype=torch.int32) + return tensors + + +def _token_lora_mapping(traffic: str, num_tokens: int) -> torch.Tensor: + if traffic == "active": + return torch.zeros(num_tokens, dtype=torch.int32) + if traffic == "mixed": + # Batch preparation normalizes every inactive resident assignment + # to -1 before any MoE layer consumes the mapping. + pattern = torch.tensor([0, -1, -1, 0, -1, -1], dtype=torch.int32) + return pattern.repeat((num_tokens + pattern.numel() - 1) // pattern.numel())[ + :num_tokens + ].contiguous() + if traffic == "base_only": + # Config choice and graph shape stay fixed while every token follows + # the base sentinel; one topology serves every batch. + return torch.full((num_tokens,), -1, dtype=torch.int32) + raise AssertionError(f"unknown traffic pattern {traffic}") + + +def _reference( + tensors: dict[str, torch.Tensor], + token_lora_mapping: torch.Tensor, + *, + plan: MoePlan | None = None, +) -> torch.Tensor: + """FP32 matvecs, optionally rounded at the selected plan's BF16 buffers. + + No production routing or kernels, nor a backend-dependent BF16 matmul. + The default retains the full-FP32 oracle for the original small fixtures. + """ + + if plan is not None: + assert plan.finalize.family is FinalizeFamily.MATERIALIZED + + def boundary(value): + return value.to(torch.bfloat16).float() if plan is not None else value + + hidden_states = tensors["hidden_states"].float() + w13_weight = tensors["w13_weight"].float() + w2_weight = tensors["w2_weight"].float() + gate_up_lora_a = tensors["gate_up_lora_a"].float() + gate_up_lora_b = tensors["gate_up_lora_b"].float() + down_lora_a = tensors["down_lora_a"].float() + down_lora_b = tensors["down_lora_b"].float() + topk_ids = tensors["topk_ids"] + topk_weights = tensors["topk_weights"].float() + adapter_enabled = tensors["adapter_enabled"] + hidden_size = hidden_states.shape[-1] + intermediate_size = w2_weight.shape[-1] + physical_rank = down_lora_a.shape[-2] + + output = torch.zeros((hidden_states.shape[0], hidden_size), dtype=torch.float32) + for token_idx, hidden in enumerate(hidden_states): + slot = int(token_lora_mapping[token_idx]) + slot_is_active = slot >= 0 and bool(adapter_enabled[slot]) + for topk_idx in range(_TOP_K): + expert = int(topk_ids[token_idx, topk_idx]) + gate_up = boundary(torch.mv(w13_weight[expert], hidden)) + gate = gate_up[:intermediate_size] + up = gate_up[intermediate_size:] + + if slot_is_active: + gate_up_a = gate_up_lora_a[slot, expert] + gate_up_b = gate_up_lora_b[slot, expert] + gate_rank = boundary(torch.mv(gate_up_a[:physical_rank], hidden)) + up_rank = boundary(torch.mv(gate_up_a[physical_rank:], hidden)) + gate_delta = torch.mv(gate_up_b[:intermediate_size], gate_rank) + up_delta = torch.mv(gate_up_b[intermediate_size:], up_rank) + # Fused B+activation consumes FP32 deltas without a BF16 store. + if plan is None or plan.act.family is ActFamily.MATERIALIZED: + gate_delta, up_delta = boundary(gate_delta), boundary(up_delta) + gate = gate + gate_delta + up = up + up_delta + + activation = boundary(F.silu(gate) * up) + pair_output = boundary(torch.mv(w2_weight[expert], activation)) + if slot_is_active: + down_rank = boundary(torch.mv(down_lora_a[slot, expert], activation)) + down_delta = torch.mv(down_lora_b[slot, expert], down_rank) + if plan is not None and plan.down_b_into_base: + pair_output = boundary(pair_output + down_delta) + else: + pair_output = pair_output + boundary(down_delta) + + output[token_idx].add_( + pair_output, alpha=float(topk_weights[token_idx, topk_idx]) + ) + + return boundary(output * _ROUTED_SCALING) + + +def _standalone_output_allocation( + runner: MoeLoraRunner, + *, + num_tokens: int, + dtype: torch.dtype, + device: torch.device, +) -> torch.Tensor: + """Match eager output geometry without requiring a serving TP group.""" + + return torch.empty((num_tokens, runner.hidden_size), dtype=dtype, device=device) + + +@pytest.mark.parametrize( + ("mode", "num_tokens", "hidden_size", "intermediate_size", "physical_rank"), + ( + (Phase.DECODE, 4, _HIDDEN, _INTERMEDIATE, _PHYSICAL_RANK), + (Phase.DECODE, 8, _HIDDEN, _INTERMEDIATE, _PHYSICAL_RANK), + (Phase.PREFILL, 64, _HIDDEN, _INTERMEDIATE, _PHYSICAL_RANK), + (Phase.DECODE, 4, 4096, 1024, 256), + (Phase.PREFILL, 8, 4096, 1024, 256), + ), + ids=("decode-small", "decode", "lab-prefill", "wide-decode", "wide-prefill"), +) +def test_selected_pipeline_matches_reference_in_eager_and_cuda_graph( + monkeypatch: pytest.MonkeyPatch, + mode: Phase, + num_tokens: int, + hidden_size: int, + intermediate_size: int, + physical_rank: int, +) -> None: + device = torch.device("cuda") + capability = torch.cuda.get_device_capability(device) + if capability[0] not in (9, 10): # the table mapper itself never raises + pytest.skip(f"MoE LoRA does not support SM{capability[0]}{capability[1]}") + + monkeypatch.setattr( + MoeLoraRunner, "_allocate_output", _standalone_output_allocation + ) + + cpu = _make_cpu_tensors( + num_tokens, + hidden_size=hidden_size, + intermediate_size=intermediate_size, + physical_rank=physical_rank, + ) + gpu = {name: tensor.to(device) for name, tensor in cpu.items()} + + choice, launch_config = _resolve_execution( + architecture_for_capability(capability[0]), + mode, + num_tokens, + hidden_size=hidden_size, + physical_rank=physical_rank, + ) + assert choice.base_gemm_rows is not None + assert choice.plan is not None + # Preserve the small FP32 cases; wide/rank-256 cases model BF16 stage stores. + reference_plan = choice.plan if physical_rank == 256 else None + + provider_cls = select_provider_cls(choice.base_gemm_rows, "bf16") + provider = provider_cls( + MoeLoraBf16QuantInfo( + w13_weight=gpu["w13_weight"], + w2_weight=gpu["w2_weight"], + num_local_experts=_EXPERTS, + intermediate_size=intermediate_size, + hidden_size=hidden_size, + ) + ) + runner = MoeLoraRunner( + providers={"test": provider}, + top_k=_TOP_K, + routed_scaling_factor=_ROUTED_SCALING, + activation=ActivationFn.SILU, + ) + runner.validate_plan(choice.plan, base_gemm_rows="test") + _bind_test_menu(runner, choice.plan, launch_config) + + dispatch = StandardDispatchOutput( + hidden_states=gpu["hidden_states"], + hidden_states_scale=None, + topk_output=StandardTopKOutput( + topk_weights=gpu["topk_weights"], + topk_ids=gpu["topk_ids"], + router_logits=gpu["router_logits"], + ), + ) + references: dict[str, torch.Tensor] = {} + for traffic in ("active", "mixed", "base_only"): + cpu_slots = _token_lora_mapping(traffic, num_tokens) + references[traffic] = _reference(cpu, cpu_slots, plan=reference_plan) + batch = MoeLoraBatch( + gate_up_lora_a=gpu["gate_up_lora_a"], + gate_up_lora_b=gpu["gate_up_lora_b"], + down_lora_a=gpu["down_lora_a"], + down_lora_b=gpu["down_lora_b"], + token_lora_mapping=cpu_slots.to(device), + use_cuda_graph=False, + is_prefill=mode is Phase.PREFILL, + ) + actual = runner.run(dispatch, batch) + torch.testing.assert_close( + actual.hidden_states.detach().float().cpu(), + references[traffic], + atol=0.018, + rtol=0.06, + msg=f"{choice.name}: {traffic} traffic", + ) + + # Make the test sensitive to accidentally bypassing all LoRA math despite + # the unavoidable BF16-vs-FP32 comparison tolerance above. + assert (references["active"] - references["base_only"]).abs().max().item() > 0.02 + + token_lora_mapping = batch.token_lora_mapping + token_lora_mapping.copy_(_token_lora_mapping("active", num_tokens).to(device)) + batch.use_cuda_graph = True + + # The workspace keys scratch by stream: warm up on the capture stream. + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(2): # JIT + workspace graph-buffer retention before capture + runner.run(dispatch, batch) + torch.cuda.synchronize(device) + + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + captured = runner.run(dispatch, batch) + output = captured.hidden_states + output_ptr = output.data_ptr() + + graph.replay() + torch.cuda.synchronize(device) + torch.testing.assert_close( + output.detach().float().cpu(), + _reference(cpu, _token_lora_mapping("active", num_tokens), plan=reference_plan), + atol=0.018, + rtol=0.06, + msg=f"{choice.name}: active replay", + ) + + token_lora_mapping.fill_(-1) + graph.replay() + torch.cuda.synchronize(device) + assert output.data_ptr() == output_ptr + torch.testing.assert_close( + output.detach().float().cpu(), + _reference( + cpu, _token_lora_mapping("base_only", num_tokens), plan=reference_plan + ), + atol=0.018, + rtol=0.06, + msg=f"{choice.name}: base-only replay", + ) + + cpu["topk_ids"] = cpu["topk_ids"].flip(dims=(1,)).contiguous() + cpu["hidden_states"] = (cpu["hidden_states"].float() * 1.5).to(torch.bfloat16) + gpu["topk_ids"].copy_(cpu["topk_ids"]) + gpu["hidden_states"].copy_(cpu["hidden_states"]) + token_lora_mapping.copy_(_token_lora_mapping("mixed", num_tokens).to(device)) + graph.replay() + torch.cuda.synchronize(device) + assert output.data_ptr() == output_ptr + torch.testing.assert_close( + output.detach().float().cpu(), + _reference(cpu, _token_lora_mapping("mixed", num_tokens), plan=reference_plan), + atol=0.018, + rtol=0.06, + msg=f"{choice.name}: mutated-routing replay", + ) + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/lora/test_moe_lora_nvfp4_provider_numerics.py b/test/registered/kernels/ops/lora/test_moe_lora_nvfp4_provider_numerics.py new file mode 100644 index 0000000000..5dceecefe2 --- /dev/null +++ b/test/registered/kernels/ops/lora/test_moe_lora_nvfp4_provider_numerics.py @@ -0,0 +1,461 @@ +"""NVFP4 provider against exact dequantization, using the serving repack helper. +Checkpoint format: packed E2M1 (even index in low nibble), group-16 E4M3 scales, +and an FP32 per-expert global scale. Compare raw pair-major outputs, then drive +the sm100 shared-outer decode plan through the runner. +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +import torch +import torch.nn.functional as F + +from sglang.srt.layers.moe.token_dispatcher.standard import StandardDispatchOutput +from sglang.srt.layers.moe.topk import StandardTopKOutput +from sglang.srt.lora.moe.base_gemm_provider import select_provider_cls +from sglang.srt.lora.moe.plan import ActivationFn, AFamily, BFamily, resolve_plans +from sglang.srt.lora.moe.runner import MoeLoraBatch, MoeLoraRunner +from sglang.srt.lora.utils import Phase, architecture_for_capability +from sglang.srt.runtime_context import get_context +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=60, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +_E = 4 +_H = 256 +_I = 128 +_TOPK = 2 +_T = 32 + +_E2M1_VALUES = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0]) + + +def _skip_unless_supported(): + if not torch.cuda.is_available(): + pytest.skip("CUDA required") + if torch.cuda.get_device_capability()[0] < 9: + pytest.skip("Marlin NVFP4 needs SM90+ here") + + +def _quant_nvfp4(weight: torch.Tensor): + """[E, N, K] bf16 -> (packed uint8 [E,N,K/2], e4m3 [E,N,K/16], fp32 [E]) + plus the exact dequantized weights.""" + e, n, k = weight.shape + w = weight.float() + global_scale = (w.abs().amax(dim=(1, 2)) / (448.0 * 6.0)).clamp(min=1e-12) + groups = w.view(e, n, k // 16, 16) + amax16 = groups.abs().amax(dim=-1) + block_scale = ( + (amax16 / (6.0 * global_scale[:, None, None])) + .clamp(min=2**-6) + .to(torch.float8_e4m3fn) + ) + denom = block_scale.float() * global_scale[:, None, None] + scaled = groups / denom[..., None] + table = _E2M1_VALUES.to(weight.device) + idx = (scaled.abs().unsqueeze(-1) - table).abs().argmin(dim=-1) + sign = scaled < 0 + codes = (idx | (sign.long() << 3)).to(torch.uint8).view(e, n, k) + packed = codes[..., 0::2] | (codes[..., 1::2] << 4) + dequant = (torch.where(sign, -table[idx], table[idx]) * denom[..., None]).view( + e, n, k + ) + return packed, block_scale, global_scale, dequant + + +def _fake_layer(w13, w2, gated=True): + w13_q, w13_bs, w13_gs, w13_eff = _quant_nvfp4(w13) + w2_q, w2_bs, w2_gs, w2_eff = _quant_nvfp4(w2) + layer = SimpleNamespace( + w13_weight=SimpleNamespace(data=w13_q), + w2_weight=SimpleNamespace(data=w2_q), + w13_weight_scale=SimpleNamespace(data=w13_bs), + w2_weight_scale=SimpleNamespace(data=w2_bs), + w13_weight_scale_2=SimpleNamespace(data=w13_gs), + w2_weight_scale_2=SimpleNamespace(data=w2_gs), + quant_config=SimpleNamespace(group_size=16), + moe_runner_config=SimpleNamespace(is_gated=gated), + num_local_experts=w2.shape[0], + intermediate_size_per_partition=w2.shape[2], + hidden_size=w2.shape[1], + params_dtype=torch.bfloat16, + ) + return layer, w13_eff, w2_eff + + +def _marlin_quant_info(layer): + """Repack the fake layer in place and bind it as serving does.""" + from sglang.srt.layers.quantization.marlin_utils_fp4 import ( + prepare_moe_nvfp4_layer_for_marlin, + ) + from sglang.srt.lora.moe.quant_info import MoeLoraNvFp4MarlinQuantInfo + + prepare_moe_nvfp4_layer_for_marlin(layer) + # The fake layer has no quant_method: use the repacked tensors directly. + return MoeLoraNvFp4MarlinQuantInfo.from_layer(layer) + + +def _rel_l2(a, b): + return (a - b).norm() / b.norm().clamp(min=1e-12) + + +def _standalone_output_allocation(runner, *, num_tokens, dtype, device): + return torch.empty((num_tokens, runner.hidden_size), dtype=dtype, device=device) + + +@pytest.mark.parametrize("slices,intermediate", [(2, _I), (1, _I), (1, 64)]) +def test_nvfp4_marlin_gateup_and_down_match_reference(slices, intermediate): + _skip_unless_supported() + device = torch.device("cuda") + g = torch.Generator(device="cpu").manual_seed(11) + + def rand(*shape): + return (torch.randn(*shape, generator=g) * 0.05).to(torch.bfloat16).to(device) + + w13 = rand(_E, slices * intermediate, _H) + w2 = rand(_E, _H, intermediate) + hidden = rand(_T, _H) + topk_ids = torch.stack( + [torch.randperm(_E, generator=g)[:_TOPK] for _ in range(_T)] + ).to(device=device, dtype=torch.int32) + + layer, w13_eff, w2_eff = _fake_layer(w13, w2, gated=slices == 2) + quant_info = _marlin_quant_info(layer) + assert (quant_info.gate_up_slices, quant_info.intermediate_size) == ( + slices, + intermediate, + ) + + provider = select_provider_cls("route_major", "nvfp4", "marlin")(quant_info) + + with get_context().override_server_args(): + state = provider.prepare(hidden, topk_ids, _TOPK) + gateup = torch.zeros( + provider.gateup_out_shape(state), dtype=torch.bfloat16, device=device + ) + assert gateup.shape[1] == slices * intermediate + provider.gateup(state, gateup) + + flat_ids = topk_ids.flatten() + pair_idx = torch.nonzero(flat_ids >= 0, as_tuple=True)[0] + experts = flat_ids[pair_idx].long() + tokens = (pair_idx // _TOPK).long() + + ref_gateup = torch.einsum( + "ph,pnh->pn", hidden[tokens].float(), w13_eff[experts] + ) + got_gateup = gateup[pair_idx].float() + assert _rel_l2(got_gateup, ref_gateup) < 2e-2 + + act_pairs = (torch.randn_like(ref_gateup[:, :intermediate]) * 0.1).to( + torch.bfloat16 + ) + act = torch.zeros( + provider.act_out_shape(state), dtype=torch.bfloat16, device=device + ) + act[pair_idx] = act_pairs + down = torch.zeros( + provider.down_out_shape(state), dtype=torch.bfloat16, device=device + ) + provider.down(state, act, down) + + ref_down = torch.einsum("pi,phi->ph", act_pairs.float(), w2_eff[experts]) + got_down = down[pair_idx].float() + assert _rel_l2(got_down, ref_down) < 2e-2 + + if intermediate == _I: + return + + from sglang.srt.lora.workspace import LoraWorkspace + + assert layer.w2_weight.shape[1] * 16 == 128 + rank = 16 + a13 = rand(_E, rank, _H).float()[experts] + b13 = rand(_E, intermediate, rank).float()[experts] + a2 = rand(_E, rank, intermediate).float()[experts] + b2 = rand(_E, _H, rank).float()[experts] + weights = torch.tensor([0.65, 0.35], device=device).repeat(_T, 1) + output = torch.empty((_T, _H), dtype=torch.bfloat16, device=device) + act_pairs = torch.empty( + (_T, _TOPK, intermediate), dtype=torch.bfloat16, device=device + ) + workspace = LoraWorkspace() + workspace.begin_forward(graph_mode=True) + + def delta(a, b, x): + return torch.bmm(b, torch.bmm(a, x.unsqueeze(-1))).squeeze(-1) + + def run(): + state = provider.prepare(hidden, topk_ids, _TOPK, workspace=workspace) + provider.gateup(state, gateup) + gate_delta = delta(a13, b13, hidden[tokens].float()).to(torch.bfloat16) + provider.act_with_delta( + state, + gateup, + gate_delta.view(_T, _TOPK, intermediate), + topk_ids, + act, + act_pairs, + activation="relu2", + ) + # Padding must be cleared even when its reusable storage is poisoned. + state.padded_intermediate[:, intermediate:].fill_(float("nan")) + provider.down(state, act, down) + down_delta = delta(a2, b2, act_pairs.flatten(0, 1).float()).to( + torch.bfloat16 + ) + provider.finalize( + state, + down, + topk_ids, + weights, + 0.75, + output, + lora_delta=down_delta.view(_T, _TOPK, _H), + ) + + def reference(): + inputs = hidden[tokens].float() + gate = torch.einsum("ph,pih->pi", inputs, w13_eff[experts]) + activation = (gate + delta(a13, b13, inputs)).relu().square() + pairs = torch.einsum("pi,phi->ph", activation, w2_eff[experts]) + pairs += delta(a2, b2, activation) + return (pairs.view(_T, _TOPK, _H) * weights[..., None]).sum(1) * 0.75 + + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(2): + run() + torch.cuda.synchronize() + assert _rel_l2(output.float(), reference()) < 3e-2 + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + run() + for _ in range(2): + hidden.mul_(-0.5) + graph.replay() + torch.cuda.synchronize() + assert _rel_l2(output.float(), reference()) < 3e-2 + + +@pytest.mark.parametrize("slices", (2, 1), ids=("gated-silu", "relu2")) +def test_nvfp4_shared_outer_decode_plan_matches_reference( + monkeypatch: pytest.MonkeyPatch, slices: int +) -> None: + """Run the sm100 ``decode.shared.nvfp4`` row end to end: token_dense gate/up-A + planes selected by per_row B, Marlin base GEMMs, per_row down-A, and the + shared one-pass finalize. Eager first, then a graph replayed with changed + adapter slots, routing, and inputs. + """ + _skip_unless_supported() + device = torch.device("cuda") + major = torch.cuda.get_device_capability(device)[0] + if major != 10: + pytest.skip("decode.shared.nvfp4 is an sm100 plan row") + monkeypatch.setattr( + MoeLoraRunner, "_allocate_output", _standalone_output_allocation + ) + g = torch.Generator(device="cpu").manual_seed(23) + + def rand(*shape, scale=0.05): + return (torch.randn(*shape, generator=g) * scale).to(torch.bfloat16).to(device) + + tokens, slots, rank = 8, 2, 16 + activation = ActivationFn.SILU if slices == 2 else ActivationFn.RELU2 + layer, w13_eff, w2_eff = _fake_layer( + rand(_E, slices * _I, _H), rand(_E, _H, _I), gated=slices == 2 + ) + quant_info = _marlin_quant_info(layer) + selected = resolve_plans( + architecture=architecture_for_capability(major), + is_shared_outer=True, + physical_rank=rank, + activation=activation, + hidden_size=_H, + num_local_experts=_E, + quant_family="nvfp4", + )[Phase.DECODE] + assert ( + selected.name, + selected.plan.gate_up_a.family, + selected.plan.gate_up_b.family, + ) == ("decode.shared.nvfp4", AFamily.TOKEN_DENSE, BFamily.PER_ROW) + provider = select_provider_cls(selected.base_gemm_rows, "nvfp4", "marlin")( + quant_info + ) + runner = MoeLoraRunner( + providers={selected.base_gemm_rows: provider}, + top_k=_TOPK, + routed_scaling_factor=0.75, + activation=activation, + is_gated=slices == 2, + ) + runner.validate_plan(selected.plan, base_gemm_rows=selected.base_gemm_rows) + runner.plans = {Phase.DECODE: selected} + + hidden = rand(tokens, _H, scale=0.2) + topk_ids = torch.stack( + [torch.randperm(_E, generator=g)[:_TOPK] for _ in range(tokens)] + ).to(device=device, dtype=torch.int32) + topk_ids[3, 1] = -1 # an EP hole on an adapter token + weights = torch.tensor([0.65, 0.35], device=device).repeat(tokens, 1) + # Outer factors (gate/up-A, down-B) per slot; inner ones per (slot, expert). + gate_up_a = rand(slots, 1, slices * rank, _H, scale=0.1) + gate_up_b = rand(slots, _E, slices * _I, rank, scale=0.1) + down_a = rand(slots, _E, rank, _I, scale=0.1) + down_b = rand(slots, 1, _H, rank, scale=0.1) + mapping = torch.tensor([0, 1, -1, 0, 1, -1, 0, 1], dtype=torch.int32, device=device) + + def reference(mapping): + pair_tokens = torch.arange(tokens, device=device).repeat_interleave(_TOPK) + experts = topk_ids.flatten().long() + routed = (experts >= 0).float()[:, None] + experts = experts.clamp(min=0) + slot = mapping[pair_tokens].long() + adapted = (slot >= 0).float()[:, None] + slot = slot.clamp(min=0) + inputs = hidden.float()[pair_tokens] + gate_up = torch.einsum("ph,pnh->pn", inputs, w13_eff[experts]) + outer = torch.einsum("ph,prh->pr", inputs, gate_up_a.float()[slot, 0]) + inner = gate_up_b.float()[slot, experts] + delta = torch.cat( + [ + torch.einsum( + "pir,pr->pi", + inner[:, s * _I : (s + 1) * _I], + outer[:, s * rank : (s + 1) * rank], + ) + for s in range(slices) + ], + dim=1, + ) + gate_up = gate_up + adapted * delta + if slices == 2: + act = F.silu(gate_up[:, :_I]) * gate_up[:, _I:] + else: + act = gate_up.relu().square() + pairs = torch.einsum("pi,phi->ph", act, w2_eff[experts]) + down_rank = torch.einsum("pi,pri->pr", act, down_a.float()[slot, experts]) + pairs = pairs + adapted * torch.einsum( + "pr,phr->ph", down_rank, down_b.float()[slot, 0] + ) + pairs = pairs * routed + return (pairs.view(tokens, _TOPK, _H) * weights[..., None]).sum(1) * 0.75 + + dispatch = StandardDispatchOutput( + hidden_states=hidden, + hidden_states_scale=None, + topk_output=StandardTopKOutput( + topk_weights=weights, + topk_ids=topk_ids, + router_logits=torch.zeros((tokens, _E), device=device), + ), + ) + batch = MoeLoraBatch( + gate_up_lora_a=gate_up_a, + gate_up_lora_b=gate_up_b, + down_lora_a=down_a, + down_lora_b=down_b, + token_lora_mapping=mapping, + ) + + def forward(): + with get_context().override_server_args(): + return runner.run(dispatch, batch).hidden_states + + output = forward() + torch.cuda.synchronize() + assert _rel_l2(output.float(), reference(mapping)) < 3e-2 + # LoRA math must be present, not bypassed within tolerance. + assert _rel_l2(reference(torch.full_like(mapping, -1)), reference(mapping)) > 0.1 + + batch.use_cuda_graph = True + # Workspace scratch is stream-local: warm up on the capture stream. + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(2): + forward() + torch.cuda.synchronize() + runner.workspace.routes.clear() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + captured = forward() + graph.replay() + torch.cuda.synchronize() + assert _rel_l2(captured.float(), reference(mapping)) < 3e-2 + + # Replay over new adapter slots, routing, and inputs in the captured buffers. + mapping.copy_(mapping.roll(1)) + topk_ids.copy_(topk_ids.flip(1)) + hidden.mul_(-0.5) + graph.replay() + torch.cuda.synchronize() + assert _rel_l2(captured.float(), reference(mapping)) < 3e-2 + + +def test_single_token_align_matches_general_path_with_invalid_ids(): + """Single-token alignment matches the general path with invalid EP ids excluded, + and all-valid ids match the upstream CUDA warp kernel. ``align_rows`` takes + the single-token path for one token and the general path for more; both + write -1 into pair_to_row for invalid pairs. + """ + _skip_unless_supported() + from sglang.kernels.ops.lora.moe.align_rows import ( + moe_align_single_token, + ) + from sglang.kernels.ops.moe.moe_align_single_token import ( + moe_align_single_token as moe_align_single_token_cuda, + ) + from sglang.srt.layers.moe.moe_runner.triton_utils.moe_align_block_size import ( + moe_align_block_size, + ) + from sglang.srt.lora.moe.base_gemm_provider.input_alignment import align_rows + + device = torch.device("cuda") + g = torch.Generator(device="cpu").manual_seed(7) + num_experts, topk = 64, 8 + + def random_ids(tokens, n_invalid): + ids = torch.stack( + [torch.randperm(num_experts, generator=g)[:topk] for _ in range(tokens)] + ) + if n_invalid: + ids[0, torch.randperm(topk, generator=g)[:n_invalid]] = -1 + return ids.to(device=device, dtype=torch.int32) + + def assert_aligned(got, ids, block_size): + sorted_got, experts_got, post_got = got + sorted_ref, experts_ref, post_ref = moe_align_block_size( + ids, block_size, num_experts, ignore_invalid_expert=True + ) + post = int(post_ref.item()) + assert int(post_got.item()) == post + assert torch.equal(sorted_got[:post], sorted_ref[:post]) + blocks = post // block_size + assert torch.equal(experts_got[:blocks], experts_ref[:blocks]) + + for block_size in (8, 16, 48, 256): + for n_invalid in (0, 3, topk): + ids = random_ids(1, n_invalid) + fast = moe_align_single_token(ids, block_size) + assert_aligned(fast, ids, block_size) + if n_invalid == 0: + cuda = moe_align_single_token_cuda(ids, block_size) + assert all(torch.equal(a, b) for a, b in zip(fast, cuda)) + + for tokens in (1, 2): + ids = random_ids(tokens, 1) + pair_to_row = torch.full_like(ids.flatten(), -777) + got = align_rows(ids, 16, num_experts, pair_to_row_out=pair_to_row) + expected_rows = torch.arange(ids.numel(), device=device, dtype=torch.int32) + expected_rows[ids.flatten() < 0] = -1 + assert torch.equal(pair_to_row, expected_rows) + assert_aligned(got, ids, 16) + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/lora/test_moe_lora_per_row_b.py b/test/registered/kernels/ops/lora/test_moe_lora_per_row_b.py new file mode 100644 index 0000000000..c423fe36a8 --- /dev/null +++ b/test/registered/kernels/ops/lora/test_moe_lora_per_row_b.py @@ -0,0 +1,248 @@ +from __future__ import annotations + +import pytest +import torch + +from sglang.kernels.ops.lora.common.route_view import RouteView, RouteViewKind +from sglang.kernels.ops.lora.common.routing import build_route +from sglang.kernels.ops.lora.moe.lora_b import run_lora_b +from sglang.srt.lora.moe.plan import ( + BFamily, + BridgeLayout, + BSpec, + Site, +) +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=60, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available(), reason="per_row LoRA-B needs any CUDA device" +) + +_SLOTS = 2 +_RANK = 16 +_INTERMEDIATE = 96 +_HIDDEN = 128 +_POISON = 7.0 + +_GROUPED_CONFIG = { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 16, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2, +} +# The per_row family reads only these keys; BLOCK_SIZE_K matches grouped +# so the FP32 k-tile accumulation order is identical. +_PER_ROW_CONFIG = { + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 16, + "num_warps": 4, + "num_stages": 2, +} +# Same FP32 k-tile accumulation of exact BF16 products; only within-tile +# reduction order differs (tl.sum vs tl.dot), so allclose, not bitwise. +_TOLERANCE = {"atol": 5e-3, "rtol": 2e-2} + + +def _routing_case(num_tokens: int, top_k: int, num_experts: int, seed: int): + generator = torch.Generator().manual_seed(seed) + topk_ids = torch.randint( + 0, num_experts, (num_tokens, top_k), generator=generator, dtype=torch.int32 + ) + topk_ids[torch.rand((num_tokens, top_k), generator=generator) < 0.15] = -1 + topk_ids[0] = -1 # a token with zero routed pairs + pattern = torch.tensor([0, 1, -1, 0, -1, 1], dtype=torch.int32) + token_lora_mapping = pattern.repeat(-(-num_tokens // pattern.numel()))[:num_tokens] + return topk_ids, token_lora_mapping + + +def _views(topk_ids, token_lora_mapping, num_experts, device): + kwargs = dict( + group_ids=topk_ids.to(device), + groups_per_slot=num_experts, + max_loras=_SLOTS, + block_size=16, + ) + aligned = build_route( + token_lora_mapping.to(device), view=RouteViewKind.ALIGNED, **kwargs + ) + raw = build_route(token_lora_mapping.to(device), view=RouteViewKind.RAW, **kwargs) + return aligned, raw + + +def _site_tensors(site: str, num_pairs: int, num_experts: int, seed: int, device): + generator = torch.Generator().manual_seed(seed) + num_route_buckets = _SLOTS * num_experts + if site == "gate_up": + num_slices, width = 2, _INTERMEDIATE + offsets = (0, _INTERMEDIATE) + else: + num_slices, width = 1, _HIDDEN + offsets = (0,) + bridge = ( + torch.randn((num_pairs, num_slices * _RANK), generator=generator) * 0.2 + ).to(torch.bfloat16) + weight = ( + torch.randn((num_route_buckets, num_slices * width, _RANK), generator=generator) + * 0.2 + ).to(torch.bfloat16) + return bridge.to(device), weight.to(device), offsets, num_slices, width + + +def _destination(num_pairs: int, num_slices: int, width: int, device): + return torch.full( + (num_pairs, num_slices * width), _POISON, dtype=torch.bfloat16, device=device + ) + + +@pytest.mark.parametrize("site", ("gate_up", "down")) +@pytest.mark.parametrize( + ("num_tokens", "top_k", "num_experts"), + ((32, 4, 64), (13, 3, 4)), + ids=("sparse", "partial"), +) +def test_per_row_matches_grouped_on_identical_inputs( + site: str, num_tokens: int, top_k: int, num_experts: int +) -> None: + device = torch.device("cuda") + seed = 0x1DB0 + num_tokens + num_experts + topk_ids, token_lora_mapping = _routing_case(num_tokens, top_k, num_experts, seed) + aligned, raw = _views(topk_ids, token_lora_mapping, num_experts, device) + num_pairs = num_tokens * top_k + bridge, weight, offsets, num_slices, width = _site_tensors( + site, num_pairs, num_experts, seed, device + ) + b_site = Site.GATE_UP if site == "gate_up" else Site.DOWN + indexed = _destination(num_pairs, num_slices, width, device) + + def launch(): + run_lora_b( + BSpec(b_site, BFamily.PER_ROW), + bridge=bridge, + weight=weight, + destination=indexed, + routing=raw, + destination_offsets=offsets, + config=_PER_ROW_CONFIG, + ) + + launch() + if b_site is Site.GATE_UP and num_tokens == 13: + torch.cuda.synchronize() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + launch() + topk_ids, token_lora_mapping = _routing_case( + num_tokens, top_k, num_experts, seed + 1 + ) + token_lora_mapping = token_lora_mapping.roll(1) + raw.group_ids.copy_(topk_ids.to(device)) + raw.token_slots.copy_(token_lora_mapping.to(device)) + bridge.mul_(0.5) + indexed.fill_(_POISON) + graph.replay() + torch.cuda.synchronize() + aligned = build_route( + raw.token_slots, + view=RouteViewKind.ALIGNED, + group_ids=raw.group_ids, + groups_per_slot=num_experts, + max_loras=_SLOTS, + block_size=16, + ) + + reference = _destination(num_pairs, num_slices, width, device) + run_lora_b( + BSpec(b_site, BFamily.GROUPED), + bridge=bridge, + weight=weight, + destination=reference, + routing=aligned, + destination_offsets=offsets, + config=_GROUPED_CONFIG, + ) + torch.testing.assert_close(indexed, reference, **_TOLERANCE) + + # Invalid pairs (base tokens, unrouted -1 experts) must be ZERO-stored, + # not left at the poison: B owns every consumed destination cell. + pair_valid = (topk_ids.view(-1) >= 0) & ( + token_lora_mapping.repeat_interleave(top_k) >= 0 + ) + invalid_rows = indexed[~pair_valid.to(device)] + assert invalid_rows.numel() > 0 + assert torch.count_nonzero(invalid_rows) == 0 + assert torch.count_nonzero(indexed[pair_valid.to(device)]) > 0 + + +@pytest.mark.parametrize("top_k", (6, 1)) +def test_per_row_on_slot_planes_matches_reference(top_k: int) -> None: + """Expand slot-plane token-major A through per-expert B against FP32. + Include EP holes, no adapter, and top-k 1; invalid pairs must be zero. + """ + + device = torch.device("cuda") + num_tokens, slots, num_experts, rank, inter = 9, 3, 16, 32, 128 + generator = torch.Generator().manual_seed(11) + topk_ids = torch.stack( + [ + torch.randperm(num_experts, generator=generator)[:top_k] + for _ in range(num_tokens) + ] + ).to(torch.int32) + topk_ids[2, top_k - 1] = -1 # locally invalid expert (EP hole) + mapping = torch.randint( + 0, slots, (num_tokens,), generator=generator, dtype=torch.int32 + ) + mapping[5] = -1 # no resident adapter + topk_ids, mapping = topk_ids.to(device), mapping.to(device) + per_expert = RouteView( + view=RouteViewKind.RAW, + block_size=16, + group_ids=topk_ids, + token_slots=mapping, + groups_per_slot=num_experts, + max_loras=slots, + ) + planes = (torch.randn(slots, num_tokens, 2 * rank, generator=generator) * 0.1).to( + device, torch.bfloat16 + ) + weight = ( + torch.randn(slots * num_experts, 2 * inter, rank, generator=generator) * 0.1 + ).to(device, torch.bfloat16) + num_pairs = num_tokens * top_k + reference = torch.zeros((num_pairs, 2 * inter), dtype=torch.float32, device=device) + planes_f, weight_f = planes.float(), weight.float() + for token in range(num_tokens): + slot = int(mapping[token]) + for k in range(top_k): + expert = int(topk_ids[token, k]) + if slot < 0 or expert < 0: + continue + block = weight_f[slot * num_experts + expert] + pair = token * top_k + k + reference[pair, :inter] = block[:inter] @ planes_f[slot, token, :rank] + reference[pair, inter:] = block[inter:] @ planes_f[slot, token, rank:] + + per_row_out = torch.full( + (num_pairs, 2 * inter), _POISON, device=device, dtype=torch.bfloat16 + ) + # The runner hands the planes over as [S, M, 2R]; the slot stride selects a plane. + run_lora_b( + BSpec(Site.GATE_UP, BFamily.PER_ROW, False, BridgeLayout.TOKEN_MAJOR), + bridge=planes, + weight=weight, + destination=per_row_out, + routing=per_expert, + destination_offsets=(0, inter), + config=_PER_ROW_CONFIG, + pair_bridge=False, + slot_planes=True, + ) + torch.testing.assert_close(per_row_out.float(), reference, atol=2e-2, rtol=2e-2) + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/lora/test_moe_lora_prepared_input_reuse.py b/test/registered/kernels/ops/lora/test_moe_lora_prepared_input_reuse.py new file mode 100644 index 0000000000..bc2a7d2447 --- /dev/null +++ b/test/registered/kernels/ops/lora/test_moe_lora_prepared_input_reuse.py @@ -0,0 +1,231 @@ +"""Prepared-row reuse through BF16/FP8 CuTe GEMMs and graph replay.""" + +from __future__ import annotations + +import pytest +import torch +import torch.nn.functional as F + +from sglang.srt.lora.workspace import LoraWorkspace +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=120, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +_E, _H, _I, _K = 4, 128, 128, 2 + + +@pytest.fixture( + scope="module", + params=( + ("bf16", "expert_major", False), + ("bf16", "route_major", False), + ("fp8", "expert_major", False), + ("fp8", "expert_major", True), + ("fp8", "route_major", False), + ), + ids=( + "bf16-masked", + "bf16-contiguous", + "fp8-masked-fused-quant", + "fp8-masked-separate-quant", + "fp8-contiguous", + ), +) +def provider_case(request): + if not torch.cuda.is_available(): + pytest.skip("CUDA required") + if torch.cuda.get_device_capability()[0] not in (9, 10): + pytest.skip("CuTe provider requires SM90 or SM100") + pytest.importorskip("cutlass") + pytest.importorskip("cuda.bindings.driver") + from sglang.srt.lora.moe.base_gemm_provider import select_provider_cls + from sglang.srt.lora.moe.quant_info import MoeLoraBf16QuantInfo, MoeLoraFp8QuantInfo + from sglang.srt.runtime_context import get_context + + generator = torch.Generator().manual_seed(1631) + w13 = (torch.randn(_E, 2 * _I, _H, generator=generator) * 0.08).to( + device="cuda", dtype=torch.bfloat16 + ) + w2 = (torch.randn(_E, _H, _I, generator=generator) * 0.08).to( + device="cuda", dtype=torch.bfloat16 + ) + family, row_mode, separate_quant = request.param + weights = dict(w13_weight=w13, w2_weight=w2) + info_cls = MoeLoraBf16QuantInfo + if family == "fp8": + q13, s13, w13 = _block_quant(w13) + q2, s2, w2 = _block_quant(w2) + weights = dict( + w13_weight=q13, + w13_scale=s13, + w2_weight=q2, + w2_scale=s2, + block_shape=(128, 128), + ) + info_cls = MoeLoraFp8QuantInfo + info = info_cls( + **weights, + num_local_experts=_E, + intermediate_size=_I, + hidden_size=_H, + ) + with get_context().override_server_args(): + provider = select_provider_cls(row_mode, family, "cutedsl")(info) + yield provider, w13, w2, family, separate_quant + + +def _block_quant(weight): + experts, rows, cols = weight.shape + blocks = weight.float().view(experts, rows // 128, 128, cols // 128, 128) + scales = blocks.abs().amax(dim=(2, 4)).clamp(min=1e-6) / 448 + expanded = scales.repeat_interleave(128, dim=1).repeat_interleave(128, dim=2) + quantized = (weight.float() / expanded).to(torch.float8_e4m3fn) + return quantized, scales, quantized.float() * expanded + + +def _traffic(ids, pattern): + ids[:, 0] = _E - 2 + ids[:, 1] = _E - 1 + if pattern == "padded": + ids[::2, 0] = -1 + ids[1::3, 1] = 0 + ids[-max(1, ids.shape[0] // 4) :] = -1 + elif pattern == "empty": + ids.fill_(-1) + + +def _reference(hidden, ids, weights, w13, w2): + output = torch.zeros_like(hidden, dtype=torch.float32) + for expert in range(_E): + coefficients = (weights * (ids == expert)).sum(dim=1) + gateup = (hidden.float() @ w13[expert].float().T).to(torch.bfloat16).float() + act = (F.silu(gateup[:, :_I]) * gateup[:, _I:]).to(torch.bfloat16) + down = (act.float() @ w2[expert].float().T).to(torch.bfloat16).float() + output.add_(down * coefficients[:, None]) + return output * 0.75 + + +def _case(provider, workspace, n, is_prefill, *, graph_mode=True, separate_quant=False): + hidden = torch.randn(n, _H, device="cuda", dtype=torch.bfloat16) * 0.2 + ids = torch.empty(n, _K, device="cuda", dtype=torch.int32) + _traffic(ids, "skewed") + weights = torch.tensor([0.65, 0.35], device="cuda").expand(n, _K).contiguous() + + def run(): + workspace.begin_forward(graph_mode=graph_mode, is_prefill_graph=is_prefill) + state = provider.prepare(hidden, ids, _K, workspace) + + def buffer(name, shape): + return workspace.tensor(name, shape, dtype=torch.bfloat16, device="cuda") + + gateup = buffer("test:gateup", provider.gateup_out_shape(state)) + act = buffer("test:act", provider.act_out_shape(state)) + pairs = buffer("test:pairs", (n, _K, _I)) + provider.gateup(state, gateup) + provider.release_prepared_inputs(state) + provider.act_with_delta(state, gateup, None, ids, act, pairs) + if separate_quant: + state.act_quant_ready = False + down = provider.down_output(state, workspace) + provider.down(state, act, down) + output = torch.empty_like(hidden) + provider.finalize(state, down, ids, weights, 0.75, output) + return state, down, output + + return run, hidden, ids, weights + + +def _check(output, hidden, ids, weights, w13, w2, family): + expected = _reference(hidden, ids, weights, w13, w2) + actual = output.float() + assert bool(torch.isfinite(actual).all()) + error = (actual - expected).abs() + relative_l2 = error.norm() / expected.norm().clamp(min=1e-12) + assert relative_l2.item() < (0.08 if family == "fp8" else 0.02) + assert bool((actual[(ids < 0).all(dim=1)] == 0).all()) + + +def _capture(run, stream): + # One capture stream per workspace, as in a graph runner: the workspace + # keys scratch by stream, so buckets grow and retire storage only within one. + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + run() + run() + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + result = run() + torch.cuda.current_stream().wait_stream(stream) + return graph, result + + +@pytest.mark.parametrize("n", (0, 257)) +def test_prepared_rows_reused_in_eager(provider_case, n): + provider, w13, w2, family, separate_quant = provider_case + workspace = LoraWorkspace() + run, hidden, ids, weights = _case( + provider, workspace, n, False, graph_mode=False, separate_quant=separate_quant + ) + for pattern in ("skewed", "padded", "empty", "skewed"): + hidden.mul_(-0.9).add_(0.01) + _traffic(ids, pattern) + state, down, output = run() + assert down.data_ptr() == provider._input_rows(state).data_ptr() + assert down.data_ptr() != hidden.data_ptr() + _check(output, hidden, ids, weights, w13, w2, family) + assert ("base:down" in {key[0] for key in workspace._eager_buffers}) == ( + family == "fp8" + ) + + +def test_reused_rows_old_graphs_survive_growth_and_other_phase(provider_case): + provider, w13, w2, family, separate_quant = provider_case + workspace = LoraWorkspace() + stream = torch.cuda.Stream() + captured = [] + # The non-monotonic order explicitly grows storage after capture. + buckets = ( + (False, 9), + (True, 129), + (False, 7), + (False, 257), + (True, 4096), + (False, 8), + (False, 0), + ) + for is_prefill, n in buckets: + run, hidden, ids, weights = _case( + provider, workspace, n, is_prefill, separate_quant=separate_quant + ) + graph, result = _capture(run, stream) + state, down, output = result + assert down.data_ptr() == provider._input_rows(state).data_ptr() + assert down.data_ptr() != hidden.data_ptr() + assert down.shape == provider.down_out_shape(state) + captured.append((graph, hidden, ids, weights, down, output)) + + addresses = [item[4].data_ptr() for item in captured] + assert addresses[0] == addresses[2] + assert addresses[3] == addresses[5] + assert addresses[0] != addresses[3] + assert addresses[1] != addresses[4] + assert not {addresses[0], addresses[3]} & {addresses[1], addresses[4]} + retired = {tensor.data_ptr() for tensor in workspace._retired} + assert {addresses[0], addresses[1]} <= retired + assert ("base:down" in {key[0] for key in workspace._graph_storage}) == ( + family == "fp8" + ) + + for pattern in ("skewed", "padded", "empty", "skewed"): + for graph, hidden, ids, weights, down, output in reversed(captured): + hidden.mul_(-0.9).add_(0.01) + _traffic(ids, pattern) + # Poison all rows; dispatch must restore every subsequently read row. + down.fill_(float("nan")) + graph.replay() + _check(output, hidden, ids, weights, w13, w2, family) + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/lora/test_moe_lora_routing.py b/test/registered/kernels/ops/lora/test_moe_lora_routing.py new file mode 100644 index 0000000000..e19ba7f448 --- /dev/null +++ b/test/registered/kernels/ops/lora/test_moe_lora_routing.py @@ -0,0 +1,285 @@ +"""Numerical routing and CUDA-graph workspace regressions.""" + +import unittest +from collections import defaultdict + +import torch + +from sglang.kernels.ops.lora.common import routing as routing_module +from sglang.kernels.ops.lora.common.routing import build_route +from sglang.srt.lora.workspace import LoraWorkspace +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=45, stage="base-b-kernel-unit", runner_config="1-gpu-large") + + +def _tensors(route): + return route.sorted_pair_ids, route.block_bucket_ids, route.num_pairs_post_padded + + +class TestMoeLoraRouting(CustomTestCase): + @classmethod + def setUpClass(cls): + if not torch.cuda.is_available(): + raise unittest.SkipTest("CUDA required") + cls.device = torch.device("cuda", torch.cuda.current_device()) + + @staticmethod + def _inputs(rows, width, groups_per_slot, max_loras, dtype, shift=0): + slots = (torch.arange(rows // width, dtype=dtype) + shift) % max_loras + slots[::7] = -1 + slots[1::11] = max_loras + if width == 1: + return slots, None + groups = ( + (torch.arange(rows, dtype=dtype) * 37 + shift) % groups_per_slot + ).reshape(-1, width) + groups[shift % 11 :: 11, -1] = -2 + groups[2 + shift :: 13, 0] = 37 if groups_per_slot == 1 else groups_per_slot + slots[3] = max_loras - 1 + groups[3, 0] = groups_per_slot - 1 + return slots, groups + + @staticmethod + def _expected(slots, groups, groups_per_slot, max_loras): + # Independent host oracle: never call the production bucket-ID kernel. + expected = defaultdict(list) + width = 1 if groups is None else groups.shape[1] + for token, slot in enumerate(slots.tolist()): + for column in range(width): + group = 0 if groups is None else int(groups[token, column]) + live = ( + 0 <= slot < max_loras + and group >= 0 + and (groups_per_slot == 1 or group < groups_per_slot) + ) + bucket = slot * groups_per_slot if live else -1 + if live and groups_per_slot != 1: + bucket += group + expected[bucket].append(token * width + column) + return expected + + def _assert_layout(self, result, expected, block_size, sentinel_last=False): + sorted_ids, block_ids, total = result + self.assertTrue(all(tensor.dtype == torch.int32 for tensor in result)) + rows = sum(map(len, expected.values())) + # Large routing places the invalid bucket last; small/JIT place it first. + order = sorted( + expected.items(), + key=lambda item: (sentinel_last and item[0] < 0, item[0]), + ) + labels = [ + bucket + for bucket, pairs in order + for _ in range((len(pairs) + block_size - 1) // block_size) + ] + padded = int(total.item()) + self.assertEqual(padded, len(labels) * block_size) + self.assertLessEqual(padded, sorted_ids.numel()) + self.assertEqual(block_ids[: len(labels)].cpu().tolist(), labels) + values, offset = sorted_ids[:padded].cpu().tolist(), 0 + for _, wanted in order: + size = ((len(wanted) + block_size - 1) // block_size) * block_size + bucket_rows = values[offset : offset + size] + # Atomic placement may permute rows, but must not lose or duplicate any. + self.assertEqual( + sorted(pair for pair in bucket_rows if pair != rows), wanted + ) + self.assertEqual(bucket_rows.count(rows), size - len(wanted)) + offset += size + + def _parity_builders(self, slots, groups, groups_per_slot, max_loras, block_size): + small_workspace, cuda_workspace = LoraWorkspace(), LoraWorkspace() + for workspace in (small_workspace, cuda_workspace): + workspace.begin_forward(graph_mode=True) + buckets = cuda_workspace.tensor( + "parity:bucket_ids", + (slots.numel(), 1) if groups is None else groups.shape, + dtype=torch.int32, + device=self.device, + ) + + def small(): + return _tensors( + routing_module._build_small_route( + slots, + groups, + groups_per_slot=groups_per_slot, + max_loras=max_loras, + block_size=block_size, + workspace=small_workspace, + tensor_prefix="parity:small", + ) + ) + + def cuda(): + routing_module._build_route_bucket_ids( + slots, + groups, + groups_per_slot=groups_per_slot, + max_loras=max_loras, + out=buckets, + ) + return routing_module._align_block_size_jit( + buckets, + block_size, + groups_per_slot * max_loras, + scratch=lambda size: cuda_workspace.tensor( + "parity:scratch", (size,), dtype=torch.int32, device=self.device + ), + ) + + return small, cuda + + @staticmethod + def _capture(build): + # Workspace storage is stream-local: warm on the stream used for capture. + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + build() + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + result = build() + return graph, result + + def test_small_route_matches_cuda_and_host(self): + # Sparse/dense capacities, 4/8 warps, shared folding, int64 and wide bins. + for rows, width, groups_per_slot, max_loras, block_size, dtype in ( + (1, 1, 1, 4, 16, torch.int32), + (512, 8, 64, 4, 32, torch.int32), + (513, 1, 1, 4, 128, torch.int64), + (768, 1, 1, 4, 128, torch.int32), + (768, 8, 1, 4, 63, torch.int64), + (512, 8, 1024, 4, 16, torch.int32), + ): + with self.subTest(rows=rows, width=width, groups=groups_per_slot): + slots, groups = self._inputs( + rows, width, groups_per_slot, max_loras, dtype + ) + expected = self._expected(slots, groups, groups_per_slot, max_loras) + for build in self._parity_builders( + slots.to(self.device), + None if groups is None else groups.to(self.device), + groups_per_slot, + max_loras, + block_size, + ): + self._assert_layout(build(), expected, block_size) + + def test_small_and_cuda_graphs_replay_changed_inputs(self): + rows, width, max_loras, block_size = 768, 8, 4, 128 + host_slots, host_groups = self._inputs(rows, width, 1, max_loras, torch.int64) + slots, groups = host_slots.to(self.device), host_groups.to(self.device) + captures = [ + self._capture(build) + for build in self._parity_builders(slots, groups, 1, max_loras, block_size) + ] + for shift in (1, 2, 0): + new_slots, new_groups = self._inputs( + rows, width, 1, max_loras, torch.int64, shift + ) + if shift == 2: + new_slots.fill_(-1) + slots.copy_(new_slots) + groups.copy_(new_groups) + expected = self._expected(new_slots, new_groups, 1, max_loras) + for graph, result in captures: + for tensor in result: + tensor.fill_(-7) + graph.replay() + self._assert_layout(result, expected, block_size) + + def test_large_route_without_workspace(self): + rows = routing_module._LARGE_ROUTE_MIN_PAIRS + slots, _ = self._inputs(rows, 1, 1, 4, torch.int32) + expected = self._expected(slots, None, 1, 4) + slots = slots.to(self.device) + routes = [build_route(slots, max_loras=4, block_size=16) for _ in range(2)] + for route in routes: + self._assert_layout(_tensors(route), expected, 16, sentinel_last=True) + self.assertNotEqual( + routes[0].sorted_pair_ids.data_ptr(), routes[1].sorted_pair_ids.data_ptr() + ) + + def test_large_graph_resets_shared_and_per_expert_scratch(self): + rows, width, experts, max_loras, block_size = 768, 8, 384, 32, 16 + host_slots, host_groups = self._inputs( + rows, width, experts, max_loras, torch.int64 + ) + slots, groups = host_slots.to(self.device), host_groups.to(self.device) + workspace = LoraWorkspace() + workspace.begin_forward(graph_mode=True) + + def build(): + return [ + _tensors( + build_route( + slots, + group_ids=groups, + groups_per_slot=buckets, + max_loras=max_loras, + block_size=block_size, + workspace=workspace, + tensor_prefix="route:aligned", + capacity=2 * rows if buckets == 1 else None, + ) + ) + for buckets in (1, experts) + ] + + graph, results = self._capture(build) + counts = [ + value + for key, value in workspace._graph_storage.items() + if key[0].endswith(":counts") + ] + self.assertEqual(len(counts), 2) + for shift in (1, 2, 0): + new_slots, new_groups = self._inputs( + rows, width, experts, max_loras, torch.int64, shift + ) + if shift == 2: + new_slots.fill_(-1) + slots.copy_(new_slots) + groups.copy_(new_groups) + graph.replay() + for buckets, result in zip((1, experts), results): + expected = self._expected(new_slots, new_groups, buckets, max_loras) + self._assert_layout(result, expected, block_size, sentinel_last=True) + for count in counts: + self.assertEqual(torch.count_nonzero(count).item(), 0) + + def test_parallel_workspace_joins_reused_graph_regions(self): + workspace = LoraWorkspace() + source = torch.full((64,), 3.0, device=self.device) + side_output, output = torch.empty_like(source), torch.empty_like(source) + + def side(): + side_output.copy_(source).add_(1) + + def compute(): + return output.copy_(source).mul_(2) + + def build(): + # Consecutive layers reuse the same ready/done events. + for _ in range(2): + workspace.run_parallel( + name="shared_region", device=self.device, compute=compute, side=side + ) + output.add_(side_output) + + graph, _ = self._capture(build) + for value in (5, 11): + source.fill_(value) + graph.replay() + torch.cuda.synchronize(self.device) + torch.testing.assert_close( + output, torch.full_like(output, 3 * value + 1), rtol=0, atol=0 + ) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/test/registered/kernels/ops/lora/test_moe_lora_runner_attach.py b/test/registered/kernels/ops/lora/test_moe_lora_runner_attach.py new file mode 100644 index 0000000000..a663a39e5d --- /dev/null +++ b/test/registered/kernels/ops/lora/test_moe_lora_runner_attach.py @@ -0,0 +1,146 @@ +from __future__ import annotations + +import unittest +from types import SimpleNamespace +from unittest import mock + +import torch + +from sglang.srt.layers.moe.utils import MoeRunnerBackend +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=10, stage="base-b-kernel-unit", runner_config="1-gpu-large") + + +class TestEngineAdmission(CustomTestCase): + """Layers the runner would otherwise serve with silently wrong numerics.""" + + def _base_layer(self, **overrides): + from sglang.srt.layers.moe.token_dispatcher.standard import StandardDispatcher + from sglang.srt.layers.quantization.unquant import UnquantizedFusedMoEMethod + + quant_method = object.__new__(UnquantizedFusedMoEMethod) + dispatcher = object.__new__(StandardDispatcher) + dispatcher.skip_local_expert_mapping = overrides.get("skip_local", False) + return SimpleNamespace( + quant_method=quant_method, + dispatcher=dispatcher, + w13_weight=torch.zeros(2, 8, 4, dtype=torch.bfloat16), + w2_weight=torch.zeros(2, 4, 4, dtype=torch.bfloat16), + num_local_experts=2, + should_fuse_routed_scaling_factor_in_topk=overrides.get( + "fused_scaling", False + ), + with_bias=overrides.get("with_bias", False), + moe_runner_config=SimpleNamespace( + activation="silu", + is_gated=True, + gemm1_alpha=None, + gemm1_clamp_limit=None, + swiglu_limit=None, + apply_router_weight_on_input=overrides.get( + "apply_router_weight_on_input", False + ), + no_combine=overrides.get("no_combine", False), + num_fused_shared_experts=overrides.get("num_fused_shared_experts", 0), + top_k=2, + routed_scaling_factor=1.0, + ), + ) + + def _admit(self, **overrides): + from sglang.srt.lora.moe.runner import MoeLoraRunner + + MoeLoraRunner._admit(self._base_layer(**overrides)) + + def test_rejects_global_expert_id_dispatch(self): + with self.assertRaisesRegex(NotImplementedError, "EP-local"): + self._admit(skip_local=True) + + def test_rejects_prefolded_routed_scaling(self): + """Scaling folded into top-k would be applied twice.""" + with self.assertRaisesRegex(NotImplementedError, "routed scaling"): + self._admit(fused_scaling=True) + + def test_rejects_expert_biases(self): + """Providers add no bias term; a biased layer would lose it.""" + with self.assertRaisesRegex(NotImplementedError, "expert biases"): + self._admit(with_bias=True) + + def test_rejects_router_weight_applied_on_input(self): + """The runner weights routes in finalize, never on the input rows.""" + with self.assertRaisesRegex(NotImplementedError, "owned by finalize"): + self._admit(apply_router_weight_on_input=True) + + def test_rejects_no_combine(self): + """The runner's finalize always combines the top-k rows.""" + with self.assertRaisesRegex(NotImplementedError, "owned by finalize"): + self._admit(no_combine=True) + + def test_rejects_fused_shared_experts(self): + with self.assertRaisesRegex(NotImplementedError, "fused shared experts"): + self._admit(num_fused_shared_experts=1) + + +class TestLayerRunnerBackendResolution(CustomTestCase): + """The selected lora runner backend binds the new MoE runner and rebinds + run_moe_core.""" + + def test_v2_accepts_each_new_moe_runner(self): + from sglang.srt.layers.moe.moe_runner.base import MoeRunnerConfig + from sglang.srt.lora.layers import FusedMoEWithLoRA + from sglang.srt.lora.moe.runner import MoeLoraRunner + + base_layer = SimpleNamespace( + quant_method=mock.MagicMock(), + moe_runner_config=MoeRunnerConfig( + num_experts=8, + num_local_experts=8, + hidden_size=64, + intermediate_size_per_partition=32, + layer_id=0, + top_k=2, + num_fused_shared_experts=0, + params_dtype=torch.bfloat16, + activation="silu", + inplace=True, + ), + dispatcher=None, + num_local_experts=8, + should_fuse_routed_scaling_factor_in_topk=False, + moe_tp_size=1, + moe_tp_rank=0, + intermediate_size_per_partition=32, + runner=SimpleNamespace(runner_backend=MoeRunnerBackend.DEEP_GEMM), + run_moe_core=mock.Mock(), + ) + backend = SimpleNamespace(name="triton_v2", lora_workspace=object()) + original_run_moe_core = base_layer.run_moe_core + with ( + mock.patch( + "sglang.srt.layers.moe.utils.get_moe_runner_backend", + return_value=MoeRunnerBackend.LORA_CUTEDSL, + ), + mock.patch.object(MoeLoraRunner, "from_layer") as bind, + ): + layer = FusedMoEWithLoRA( + base_layer, + backend, + experts_shared_outer_loras=True, + max_lora_rank=16, + ) + self.assertIs(layer._lora_runner_backend, MoeRunnerBackend.LORA_CUTEDSL) + bind.assert_called_once_with( + base_layer, + workspace=backend.lora_workspace, + is_shared_outer=True, + physical_rank=16, + ) + self.assertIs(layer._moe_lora_runner, bind.return_value) + self.assertIs(layer._base_run_moe_core, original_run_moe_core) + self.assertEqual(base_layer.run_moe_core, layer._run_moe_core_with_lora) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/registered/kernels/ops/lora/test_moe_lora_schedule_builder.py b/test/registered/kernels/ops/lora/test_moe_lora_schedule_builder.py new file mode 100644 index 0000000000..b9cb69447c --- /dev/null +++ b/test/registered/kernels/ops/lora/test_moe_lora_schedule_builder.py @@ -0,0 +1,131 @@ +"""Packed schedule coverage, caller-owned output reuse, and geometry admission.""" + +from __future__ import annotations + +import unittest + +import torch + +from sglang.kernels.ops.lora.moe.cutedsl.schedule_builder import ( + EXPERT_MASK, + MAX_EXPERTS, + MAX_OUTPUT_CLUSTERS, + MAX_TOKEN_CLUSTERS, + OUTPUT_CLUSTER_MASK, + OUTPUT_CLUSTER_SHIFT, + TOKEN_CLUSTER_MASK, + TOKEN_CLUSTER_SHIFT, + build_dual_stage_schedules_masked, + dual_stage_schedule_capacities_masked, +) +from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.test_utils import CustomTestCase + +register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="1-gpu-large") + + +def _decode(packed: int) -> tuple[int, int, int]: + return ( + packed & EXPERT_MASK, + (packed >> TOKEN_CLUSTER_SHIFT) & TOKEN_CLUSTER_MASK, + (packed >> OUTPUT_CLUSTER_SHIFT) & OUTPUT_CLUSTER_MASK, + ) + + +class TestMoeLoraScheduleBuilder(CustomTestCase): + @classmethod + def setUpClass(cls): + if not torch.cuda.is_available(): + raise unittest.SkipTest("CUDA is required") + cls.device = torch.device("cuda") + + def _expected_entries(self, rows, token_width, out_clusters): + expected = set() + for expert, valid in enumerate(rows): + for token_cluster in range((valid + token_width - 1) // token_width): + for output_cluster in range(out_clusters): + expected.add((expert, token_cluster, output_cluster)) + return expected + + def test_ragged_tiles_and_output_reuse(self): + rows = [5, 0, 96, 1, 129, 64] + masked_m = torch.tensor(rows, dtype=torch.int32, device=self.device) + token_width, output_width = 8, 128 + n_gemm1, n_gemm2 = 512, 256 + common = dict( + m_max=256, + token_width=token_width, + n_gemm1=n_gemm1, + n_gemm2=n_gemm2, + output_width=output_width, + ) + buffers = build_dual_stage_schedules_masked(masked_m, **common) + pointers = tuple(tensor.data_ptr() for tensor in buffers) + + for current_rows in (rows, [0, 8, 17, 64, 3, 1]): + if current_rows is not rows: + masked_m.copy_( + torch.tensor(current_rows, dtype=torch.int32, device=self.device) + ) + reused = build_dual_stage_schedules_masked( + masked_m, + schedule1_out=buffers[0], + tiles1_out=buffers[1], + schedule2_out=buffers[2], + tiles2_out=buffers[3], + **common, + ) + for actual, original in zip(reused, buffers): + self.assertIs(actual, original) + self.assertEqual( + tuple(tensor.data_ptr() for tensor in reused), pointers + ) + + for schedule, tiles, n_out in ( + (buffers[0], buffers[1], n_gemm1), + (buffers[2], buffers[3], n_gemm2), + ): + out_clusters = (n_out + output_width - 1) // output_width + expected = self._expected_entries( + current_rows, token_width, out_clusters + ) + count = int(tiles[0].item()) + self.assertEqual(count, len(expected)) + decoded = [_decode(int(v)) for v in schedule[:count].tolist()] + self.assertEqual(len(decoded), len(set(decoded))) + self.assertEqual(set(decoded), expected) + + def test_rejects_geometry_the_packing_cannot_represent(self): + common = dict( + num_experts=4, + m_max=256, + token_width=8, + n_gemm1=128, + n_gemm2=128, + output_width=128, + ) + dual_stage_schedule_capacities_masked(**{**common, "num_experts": MAX_EXPERTS}) + for overrides, error in ( + ({"num_experts": MAX_EXPERTS + 1}, "expert"), + ({"m_max": (MAX_TOKEN_CLUSTERS + 1) * 8}, "token clusters"), + ({"n_gemm2": (MAX_OUTPUT_CLUSTERS + 1) * 128}, "output clusters"), + ( + { + "num_experts": 1024, + "m_max": 1024 * 8, + "n_gemm1": MAX_OUTPUT_CLUSTERS * 128, + }, + "capacity", + ), + ({"cluster_shape_mn": (2, 1)}, "cluster"), + ({"use_2cta_instrs": True}, "cluster"), + ): + with ( + self.subTest(overrides=overrides), + self.assertRaisesRegex(ValueError, error), + ): + dual_stage_schedule_capacities_masked(**{**common, **overrides}) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/registered/kernels/ops/lora/test_moe_lora_shared_outer_numerics.py b/test/registered/kernels/ops/lora/test_moe_lora_shared_outer_numerics.py new file mode 100644 index 0000000000..c088afc93b --- /dev/null +++ b/test/registered/kernels/ops/lora/test_moe_lora_shared_outer_numerics.py @@ -0,0 +1,333 @@ +"""Shared-outer LoRA against an independent FP32 reference. +Gate/up-A and down-B are per adapter slot; gate/up-B and down-A are per +(slot, expert). Cover mixed adapter traffic, changed-input graph replay, and +the non-gated ReLU2 layout. +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +import torch +import torch.nn.functional as F + +from sglang.srt.layers.moe.token_dispatcher.standard import StandardDispatchOutput +from sglang.srt.layers.moe.topk import StandardTopKOutput +from sglang.srt.lora.moe.base_gemm_provider import select_provider_cls +from sglang.srt.lora.moe.plan import ActivationFn, SelectedPlan, resolve_plans +from sglang.srt.lora.moe.quant_info import MoeLoraBf16QuantInfo +from sglang.srt.lora.moe.runner import MoeLoraBatch, MoeLoraRunner +from sglang.srt.lora.utils import Phase, architecture_for_capability +from sglang.srt.runtime_context import get_context +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=60, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available(), reason="production MoE LoRA requires CUDA" +) + + +@pytest.fixture(autouse=True) +def _published_server_args(): + # The triton vendor's config loader reads the published exec namespace. + with get_context().override_server_args(): + yield + + +_EXPERTS = 2 +_TOP_K = 2 +_HIDDEN = 128 +_INTERMEDIATE = 128 +_PHYSICAL_RANK = 16 +_SLOTS = 2 +_ROUTED_SCALING = 0.75 +_NUM_TOKENS = 8 + + +def _rand_bf16(shape, *, generator, scale): + return (torch.randn(shape, generator=generator) * scale).to(torch.bfloat16) + + +def _make_cpu_tensors(gated: bool = True) -> dict[str, torch.Tensor]: + generator = torch.Generator().manual_seed(0xF01D) + slices = 2 if gated else 1 + tensors = { + "hidden_states": _rand_bf16( + (_NUM_TOKENS, _HIDDEN), generator=generator, scale=0.20 + ), + "w13_weight": _rand_bf16( + (_EXPERTS, slices * _INTERMEDIATE, _HIDDEN), + generator=generator, + scale=0.08, + ), + "w2_weight": _rand_bf16( + (_EXPERTS, _HIDDEN, _INTERMEDIATE), generator=generator, scale=0.08 + ), + # Outer factors: one per slot. Inner factors: per (slot, expert). + "gate_up_lora_a": _rand_bf16( + (_SLOTS, 1, slices * _PHYSICAL_RANK, _HIDDEN), + generator=generator, + scale=0.15, + ), + "gate_up_lora_b": _rand_bf16( + (_SLOTS, _EXPERTS, slices * _INTERMEDIATE, _PHYSICAL_RANK), + generator=generator, + scale=0.15, + ), + "down_lora_a": _rand_bf16( + (_SLOTS, _EXPERTS, _PHYSICAL_RANK, _INTERMEDIATE), + generator=generator, + scale=0.15, + ), + "down_lora_b": _rand_bf16( + (_SLOTS, 1, _HIDDEN, _PHYSICAL_RANK), generator=generator, scale=0.15 + ), + } + alternating = torch.tensor([[0, 1], [1, 0]], dtype=torch.int32) + tensors["topk_ids"] = alternating.repeat((_NUM_TOKENS + 1) // 2, 1)[ + :_NUM_TOKENS + ].contiguous() + tensors["topk_weights"] = torch.tensor([[0.65, 0.35]], dtype=torch.float32).repeat( + _NUM_TOKENS, 1 + ) + tensors["router_logits"] = torch.zeros((_NUM_TOKENS, _EXPERTS), dtype=torch.float32) + tensors["adapter_enabled"] = torch.tensor([1, 1], dtype=torch.int32) + # Mixed traffic: two slots and base-only tokens in one batch. + tensors["token_lora_mapping"] = torch.tensor( + [0, 1, -1, 0, 1, -1, 0, 1], dtype=torch.int32 + ) + return tensors + + +def _fp32_reference( + tensors: dict[str, torch.Tensor], gated: bool = True +) -> torch.Tensor: + hidden_states = tensors["hidden_states"].float() + w13 = tensors["w13_weight"].float() + w2 = tensors["w2_weight"].float() + gua = tensors["gate_up_lora_a"].float() + gub = tensors["gate_up_lora_b"].float() + da = tensors["down_lora_a"].float() + db = tensors["down_lora_b"].float() + topk_ids = tensors["topk_ids"] + topk_weights = tensors["topk_weights"].float() + mapping = tensors["token_lora_mapping"] + + output = torch.zeros((_NUM_TOKENS, _HIDDEN), dtype=torch.float32) + for token_idx, hidden in enumerate(hidden_states): + slot = int(mapping[token_idx]) + for topk_idx in range(_TOP_K): + expert = int(topk_ids[token_idx, topk_idx]) + gate_up = torch.mv(w13[expert], hidden) + if slot >= 0: + rank = torch.mv(gua[slot, 0], hidden) + for s in range(2 if gated else 1): + cols = slice(s * _INTERMEDIATE, (s + 1) * _INTERMEDIATE) + ranks = slice(s * _PHYSICAL_RANK, (s + 1) * _PHYSICAL_RANK) + gate_up[cols] += torch.mv(gub[slot, expert, cols], rank[ranks]) + if gated: + activation = F.silu(gate_up[:_INTERMEDIATE]) * gate_up[_INTERMEDIATE:] + else: + activation = F.relu(gate_up).square() + pair_output = torch.mv(w2[expert], activation) + if slot >= 0: + down_rank = torch.mv(da[slot, expert], activation) + pair_output = pair_output + torch.mv(db[slot, 0], down_rank) + output[token_idx].add_( + pair_output, alpha=float(topk_weights[token_idx, topk_idx]) + ) + return output * _ROUTED_SCALING + + +def _standalone_output_allocation(runner, *, num_tokens, dtype, device): + return torch.empty((num_tokens, runner.hidden_size), dtype=dtype, device=device) + + +def _bind_test_menu(runner, plan, launch_config): + """Bind one plan to both phases to isolate execution from plan selection.""" + tiles = SimpleNamespace(config_for=lambda num_tokens: launch_config) + selected = SelectedPlan(name="test", base_gemm_rows="test", plan=plan, tiles=tiles) + runner.plans = {Phase.PREFILL: selected, Phase.DECODE: selected} + + +def _build_runner( + gpu: dict[str, torch.Tensor], + vendor: str = "cutedsl", + activation: ActivationFn = ActivationFn.SILU, + gated: bool = True, + phase: Phase = Phase.DECODE, +): + device = torch.device("cuda") + major, _ = torch.cuda.get_device_capability(device) + architecture = architecture_for_capability(major) + choice = resolve_plans( + quant_family="bf16", + architecture=architecture, + is_shared_outer=True, + physical_rank=_PHYSICAL_RANK, + activation=activation, + hidden_size=_HIDDEN, + num_local_experts=_EXPERTS, + )[phase] + launch_config = choice.tiles.config_for(_NUM_TOKENS) + provider_cls = select_provider_cls(choice.base_gemm_rows, "bf16", vendor) + provider = provider_cls( + MoeLoraBf16QuantInfo( + w13_weight=gpu["w13_weight"], + w2_weight=gpu["w2_weight"], + num_local_experts=_EXPERTS, + intermediate_size=_INTERMEDIATE, + hidden_size=_HIDDEN, + ) + ) + runner = MoeLoraRunner( + providers={"test": provider}, + top_k=_TOP_K, + routed_scaling_factor=_ROUTED_SCALING, + activation=activation, + is_gated=gated, + ) + runner.validate_plan(choice.plan, base_gemm_rows="test") + _bind_test_menu(runner, choice.plan, launch_config) + return runner + + +def _run_once(runner, gpu, use_cuda_graph=False, is_prefill=False): + dispatch = StandardDispatchOutput( + hidden_states=gpu["hidden_states"], + hidden_states_scale=None, + topk_output=StandardTopKOutput( + topk_weights=gpu["topk_weights"], + topk_ids=gpu["topk_ids"], + router_logits=gpu["router_logits"], + ), + ) + batch = MoeLoraBatch( + gate_up_lora_a=gpu["gate_up_lora_a"], + gate_up_lora_b=gpu["gate_up_lora_b"], + down_lora_a=gpu["down_lora_a"], + down_lora_b=gpu["down_lora_b"], + token_lora_mapping=gpu["token_lora_mapping"], + use_cuda_graph=use_cuda_graph, + is_prefill=is_prefill, + ) + return runner.run(dispatch, batch) + + +def _skip_unless_supported(device): + # The runner admits SM90 and SM100 only; the table mapper itself never raises. + major, minor = torch.cuda.get_device_capability(device) + if major not in (9, 10): + pytest.skip(f"MoE LoRA does not support SM{major}{minor}") + + +@pytest.mark.parametrize("vendor", ("cutedsl", "triton")) +def test_shared_outer_decode_matches_fp32_reference( + monkeypatch: pytest.MonkeyPatch, vendor: str +) -> None: + device = torch.device("cuda") + _skip_unless_supported(device) + monkeypatch.setattr( + MoeLoraRunner, "_allocate_output", _standalone_output_allocation + ) + cpu = _make_cpu_tensors() + gpu = {name: tensor.to(device) for name, tensor in cpu.items()} + reference = _fp32_reference(cpu) + runner = _build_runner(gpu, vendor) + actual = _run_once(runner, gpu).hidden_states.detach().float().cpu() + torch.testing.assert_close(actual, reference, atol=0.018, rtol=0.06) + # LoRA math must be present, not bypassed within tolerance. + base_only = dict(cpu) + base_only["token_lora_mapping"] = torch.full((_NUM_TOKENS,), -1, dtype=torch.int32) + assert (reference - _fp32_reference(base_only)).abs().max().item() > 0.02 + + +@pytest.mark.parametrize("vendor", ("cutedsl", "triton")) +@pytest.mark.parametrize("phase", (Phase.DECODE, Phase.PREFILL)) +def test_shared_outer_graph_replays_changed_inputs_and_token_assignments( + monkeypatch: pytest.MonkeyPatch, vendor: str, phase: Phase +) -> None: + device = torch.device("cuda") + _skip_unless_supported(device) + monkeypatch.setattr( + MoeLoraRunner, "_allocate_output", _standalone_output_allocation + ) + cpu = _make_cpu_tensors() + if phase is Phase.PREFILL: + cpu["token_lora_mapping"].fill_(0) + gpu = {name: tensor.to(device) for name, tensor in cpu.items()} + runner = _build_runner(gpu, vendor, phase=phase) + capture = dict(is_prefill=phase is Phase.PREFILL, use_cuda_graph=True) + # Workspace scratch is stream-local: warm up on the capture stream. + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + _run_once(runner, gpu, **capture) + torch.cuda.synchronize() + # Capture the route rebuild, as the backend does for every forward. + runner.workspace.routes.clear() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + captured = _run_once(runner, gpu, **capture) + graph.replay() + torch.cuda.synchronize() + torch.testing.assert_close( + captured.hidden_states.detach().float().cpu(), + _fp32_reference(cpu), + atol=0.018, + rtol=0.06, + ) + + cpu["hidden_states"].mul_(-0.5) + cpu["token_lora_mapping"] = ( + torch.tensor([0, 0, 0, 1, 1, 1, 1, 1], dtype=torch.int32) + if phase is Phase.PREFILL + else cpu["token_lora_mapping"].roll(1) + ) + for name in ("hidden_states", "token_lora_mapping"): + gpu[name].copy_(cpu[name]) + graph.replay() + torch.cuda.synchronize() + torch.testing.assert_close( + captured.hidden_states.detach().float().cpu(), + _fp32_reference(cpu), + atol=0.018, + rtol=0.06, + ) + + +@pytest.mark.parametrize("vendor", ("cutedsl", "triton")) +@pytest.mark.parametrize("phase", (Phase.DECODE, Phase.PREFILL)) +def test_shared_outer_relu2_non_gated_matches_fp32_reference( + monkeypatch: pytest.MonkeyPatch, vendor: str, phase: Phase +) -> None: + """Inkling's layout: one up projection (S = 1) and relu2, real adapters.""" + device = torch.device("cuda") + _skip_unless_supported(device) + monkeypatch.setattr( + MoeLoraRunner, "_allocate_output", _standalone_output_allocation + ) + cpu = _make_cpu_tensors(gated=False) + gpu = {name: tensor.to(device) for name, tensor in cpu.items()} + reference = _fp32_reference(cpu, gated=False) + runner = _build_runner( + gpu, vendor, activation=ActivationFn.RELU2, gated=False, phase=phase + ) + actual = ( + _run_once(runner, gpu, is_prefill=phase is Phase.PREFILL) + .hidden_states.detach() + .float() + .cpu() + ) + torch.testing.assert_close(actual, reference, atol=0.018, rtol=0.06) + base_only = dict(cpu) + base_only["token_lora_mapping"] = torch.full((_NUM_TOKENS,), -1, dtype=torch.int32) + assert ( + reference - _fp32_reference(base_only, gated=False) + ).abs().max().item() > 0.02 + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/lora/test_moe_lora_small_masked_prepare_paths.py b/test/registered/kernels/ops/lora/test_moe_lora_small_masked_prepare_paths.py new file mode 100644 index 0000000000..d3d9956545 --- /dev/null +++ b/test/registered/kernels/ops/lora/test_moe_lora_small_masked_prepare_paths.py @@ -0,0 +1,213 @@ +"""Small masked prepare matches standard metadata and live rows, including replay.""" + +from __future__ import annotations + +import pytest +import torch + +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=4, stage="base-b-kernel-unit", runner_config="1-gpu-large") + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] < 9, + reason="the cutedsl masked providers need an SM90+ GPU", +) + + +def _provider(num_experts: int, hidden: int, intermediate: int, gen): + from sglang.srt.lora.moe.base_gemm_provider.cutedsl_bf16 import ( + CuteDslBf16MaskedProvider, + ) + from sglang.srt.lora.moe.quant_info import MoeLoraBf16QuantInfo + + w13 = ( + torch.randn((num_experts, 2 * intermediate, hidden), generator=gen) * 0.05 + ).to(torch.bfloat16) + w2 = (torch.randn((num_experts, hidden, intermediate), generator=gen) * 0.05).to( + torch.bfloat16 + ) + return CuteDslBf16MaskedProvider( + MoeLoraBf16QuantInfo( + w13_weight=w13.cuda(), + w2_weight=w2.cuda(), + num_local_experts=num_experts, + intermediate_size=intermediate, + hidden_size=hidden, + ) + ) + + +def _same_rows(ref, got, ids, hidden): + rows_ref = ref.hidden_permuted.view(-1, hidden) + rows_got = got.hidden_permuted.view(-1, hidden) + for pair in range(ids.numel()): + expert = int(ids.view(-1)[pair].item()) + r_ref, r_got = ( + int(ref.pair_to_row[pair].item()), + int(got.pair_to_row[pair].item()), + ) + if expert < 0: + assert r_ref == -1 and r_got == -1 + continue + assert r_got // ref.m_max == expert + assert torch.equal( + rows_ref[r_ref].view(torch.int8), rows_got[r_got].view(torch.int8) + ) + + +def test_small_prepare_admission_boundaries(): + from sglang.kernels.ops.lora.moe.dispatch_masked_small import ( + small_masked_prepare_applies, + ) + + assert small_masked_prepare_applies(8, 32) + assert not small_masked_prepare_applies(8, 33) + assert not small_masked_prepare_applies(9, 32) + assert not small_masked_prepare_applies(1, 0) + + +@pytest.mark.parametrize( + "hidden,tokens,top_k", [(768, 1, 2), (1536, 3, 3), (1032, 8, 4)] +) +def test_single_launch_prepare_matches_the_standard_path( + monkeypatch, hidden, tokens, top_k +): + from sglang.kernels.ops.lora.moe import dispatch_masked_small as small + from sglang.srt.lora.moe.base_gemm_provider import cutedsl_bf16 as provider_module + + num_experts, intermediate = 16, 256 + gen = torch.Generator(device="cpu").manual_seed(7 + hidden + tokens) + provider = _provider(num_experts, hidden, intermediate, gen) + hidden_states = ( + (torch.randn((tokens, hidden), generator=gen) * 0.2).to(torch.bfloat16).cuda() + ) + ids = torch.stack( + [torch.randperm(num_experts, generator=gen)[:top_k] for _ in range(tokens)] + ).to(torch.int32) + if tokens >= 2: + ids[1, 0] = -1 # a pair without an expert + ids = ids.cuda() + + calls = [] + fast_path = small.small_masked_prepare + + def counted(*args, **kwargs): + calls.append(1) + return fast_path(*args, **kwargs) + + monkeypatch.setattr(provider_module, "small_masked_prepare", counted) + + max_pairs = small._SMALL_PREPARE_MAX_PAIRS + monkeypatch.setattr(small, "_SMALL_PREPARE_MAX_PAIRS", 0) + ref = provider.prepare(hidden_states, ids, top_k) + assert not calls, "the standard path must not enter the single launch" + + monkeypatch.setattr(small, "_SMALL_PREPARE_MAX_PAIRS", max_pairs) + got = provider.prepare(hidden_states, ids, top_k) + torch.cuda.synchronize() + assert len(calls) == 1, "the single-launch path did not run" + + _same_state(ref, got, ids, hidden) + + +def _capture(fn): + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + fn() + fn() + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + result = fn() + torch.cuda.current_stream().wait_stream(stream) + return graph, result + + +def _same_state(ref, got, ids, hidden): + assert torch.equal(ref.masked_m, got.masked_m) + assert torch.equal(ref.gemm1_tiles, got.gemm1_tiles) + assert torch.equal(ref.gemm2_tiles, got.gemm2_tiles) + n1, n2 = int(ref.gemm1_tiles.item()), int(ref.gemm2_tiles.item()) + assert torch.equal( + ref.gemm1_schedule[:n1].sort().values, got.gemm1_schedule[:n1].sort().values + ) + assert torch.equal( + ref.gemm2_schedule[:n2].sort().values, got.gemm2_schedule[:n2].sort().values + ) + _same_rows(ref, got, ids, hidden) + + +def test_single_launch_prepare_replays_under_a_cuda_graph(monkeypatch): + """Replay changed values/routes, including all-dead pairs followed by a full route.""" + from sglang.kernels.ops.lora.moe import dispatch_masked_small as small + from sglang.srt.lora.moe.base_gemm_provider import cutedsl_bf16 as provider_module + from sglang.srt.lora.workspace import LoraWorkspace + from sglang.srt.runtime_context import get_context + + num_experts, intermediate, top_k, tokens, hidden = 16, 256, 4, 8, 1032 + gen = torch.Generator(device="cpu").manual_seed(11 + hidden) + provider = _provider(num_experts, hidden, intermediate, gen) + + def values(): + return (torch.randn((tokens, hidden), generator=gen) * 0.2).to(torch.bfloat16) + + def routes(dead_pair, offset=0): + ids = torch.stack( + [ + (torch.randperm(num_experts, generator=gen)[:top_k] + offset) + % num_experts + for _ in range(tokens) + ] + ).to(torch.int32) + if dead_pair is not None: + ids.view(-1)[dead_pair] = -1 + return ids + + hidden_states = values().cuda() + ids = routes(1).cuda() + + calls = [] + fast_path = small.small_masked_prepare + + def counted(*args, **kwargs): + calls.append(1) + return fast_path(*args, **kwargs) + + monkeypatch.setattr(provider_module, "small_masked_prepare", counted) + max_pairs = small._SMALL_PREPARE_MAX_PAIRS + workspace = LoraWorkspace() + workspace.begin_forward(graph_mode=True) + with get_context().override_server_args(): + graph, state = _capture( + lambda: provider.prepare(hidden_states, ids, top_k, workspace) + ) + assert len(calls) == 3, ( + "two warm-ups and the capture must all take the single launch" + ) + + variants = [ + (values(), routes(1)), # the captured route shape with new values + (values(), routes(5)), # the dead pair elsewhere + (values(), routes(None, offset=7)), # other experts, no dead pair + ( + values(), + torch.full((tokens, top_k), -1, dtype=torch.int32), + ), # every pair dead + (values(), routes(0)), # a full route again after the empty one + ] + for new_values, new_ids in variants: + hidden_states.copy_(new_values) + ids.copy_(new_ids) + graph.replay() + torch.cuda.synchronize() + monkeypatch.setattr(small, "_SMALL_PREPARE_MAX_PAIRS", 0) + ref = provider.prepare(hidden_states, ids, top_k) # the standard path, eagerly + monkeypatch.setattr(small, "_SMALL_PREPARE_MAX_PAIRS", max_pairs) + assert len(calls) == 3, "the reference must come from the standard path" + _same_state(ref, state, ids, hidden) + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/lora/test_moe_lora_info.py b/test/registered/lora/test_moe_lora_info.py index 4842537910..ec1588a9ad 100644 --- a/test/registered/lora/test_moe_lora_info.py +++ b/test/registered/lora/test_moe_lora_info.py @@ -7,6 +7,7 @@ import torch from sglang.srt.lora.backend.base_backend import ( BaseLoRABackend, _compute_moe_lora_info, + _compute_token_lora_mapping, ) from sglang.srt.lora.backend.triton_backend import TritonLoRABackend from sglang.srt.lora.utils import LoRABatchInfo @@ -72,7 +73,12 @@ def test_compute_moe_lora_info_expands_segments(use_preallocated_buffers: bool): ) torch.get_device_module(device).synchronize() - expected_mapping = torch.repeat_interleave(weight_indices, seg_lens) + raw_mapping = torch.repeat_interleave(weight_indices, seg_lens) + expected_mapping = torch.where( + lora_ranks[raw_mapping.long()] > 0, + raw_mapping, + -1, + ) expected_enabled = _expected_adapter_enabled(lora_ranks, weight_indices) torch.testing.assert_close(actual_mapping, expected_mapping) @@ -80,6 +86,83 @@ def test_compute_moe_lora_info_expands_segments(use_preallocated_buffers: bool): if use_preallocated_buffers: assert actual_mapping.data_ptr() == token_lora_mapping.data_ptr() + assert token_lora_mapping[num_tokens:].tolist() == [-1] * 11 + + +def test_compute_moe_lora_info_cpu_fallback_normalizes_inactive_slots(): + # One CPU pin of the torch fallback, with mixed active and inactive slots. + seg_lens = torch.tensor([2, 3, 1], dtype=torch.int32) + seg_indptr = torch.tensor([0, 2, 5, 6], dtype=torch.int32) + weight_indices = torch.tensor([0, 1, 2], dtype=torch.int32) + lora_ranks = torch.tensor([0, 8, 0], dtype=torch.int32) + adapter_enabled = torch.full((3,), 123, dtype=torch.int32) + mapping_buffer = torch.full((9,), 456, dtype=torch.int32) + + actual_enabled, actual_mapping = _compute_moe_lora_info( + 6, + seg_indptr, + lora_ranks, + weight_indices, + adapter_enabled, + mapping_buffer, + max_len=int(seg_lens.max().item()), + ) + + assert actual_mapping.data_ptr() == mapping_buffer.data_ptr() + assert actual_mapping.tolist() == [-1, -1, 1, 1, 1, -1] + assert actual_enabled.tolist() == [0, 1, 0] + assert mapping_buffer[6:].tolist() == [-1, -1, -1] + + +@pytest.mark.parametrize("mode", ["legacy", "mapping_only"]) +def test_token_mapping_reuse_clears_padding_and_optional_mask(mode): + storage = torch.full((516,), 777, dtype=torch.int32, device=DEVICE) + mask, mapping_storage = storage[:4], storage[4:] + mask.fill_(13) + cases = ( + ([257, 0, 7], [1, 2, 3], [0, 16, 8, 4]), + ([1, 0, 3], [2, 1, 0], [0, 0, 8, 0]), + ([2, 1], [1, 3], [0, 0, 0, 0]), + ([0, 0], [1, 2], [0, 16, 8, 4]), + ([], [], [0, 16, 8, 4]), + ) + for lengths, slots, ranks in cases: + pointers = [0] + expected = [] + for length, slot in zip(lengths, slots): + pointers.append(pointers[-1] + length) + expected.extend([slot if ranks[slot] > 0 else -1] * length) + indptr = torch.tensor(pointers, dtype=torch.int32, device=DEVICE) + assignments = torch.tensor(slots, dtype=torch.int32, device=DEVICE) + rank_tensor = torch.tensor(ranks, dtype=torch.int32, device=DEVICE) + common = dict(max_len=max(lengths, default=0), bucket_len=512) + if mode == "mapping_only": + actual = _compute_token_lora_mapping( + len(expected), + indptr, + rank_tensor, + assignments, + mapping_storage, + **common, + ) + else: + _, actual = _compute_moe_lora_info( + len(expected), + indptr, + rank_tensor, + assignments, + mask, + mapping_storage, + **common, + ) + assert actual.tolist() == expected + assert mapping_storage[len(expected) :].tolist() == [-1] * (512 - len(expected)) + if mode == "legacy": + assert mask.tolist() == [ + int(i in slots and rank > 0) for i, rank in enumerate(ranks) + ] + else: + assert mask.tolist() == [13] * 4 def test_moe_graph_metadata_uses_matching_static_buffers(): diff --git a/test/registered/unit/layers/moe/test_moe_runner_extensions.py b/test/registered/unit/layers/moe/test_moe_runner_extensions.py index 3dede2654b..8ffab29547 100644 --- a/test/registered/unit/layers/moe/test_moe_runner_extensions.py +++ b/test/registered/unit/layers/moe/test_moe_runner_extensions.py @@ -203,7 +203,7 @@ def test_lora_uses_quant_method_contract_for_registered_backend( base_layer.moe_tp_rank = 0 base_layer.intermediate_size_per_partition = 8 base_layer.runner = SimpleNamespace(runner_backend=backend) - lora_backend = SimpleNamespace(is_moe_lora=False) + lora_backend = SimpleNamespace(name="triton", is_moe_lora=False) created_runners = [] monkeypatch.setattr( runner_module, diff --git a/test/registered/unit/lora/test_inkling_linearized_lora_unit.py b/test/registered/unit/lora/test_inkling_linearized_lora_unit.py index c69de1a163..d504d53644 100644 --- a/test/registered/unit/lora/test_inkling_linearized_lora_unit.py +++ b/test/registered/unit/lora/test_inkling_linearized_lora_unit.py @@ -1,12 +1,11 @@ -"""CPU-only regression tests for Inkling's linearized shared-sink LoRA path: -in-place refresh of the derived decode operands on an adapter swap, and the -shared-sink factor layout from checkpoint to one moe-TP shard's operands.""" +"""Inkling legacy/V2 sink operand layouts, in-place adapter refresh, and TP sharding.""" from __future__ import annotations import importlib import sys import types +from contextlib import nullcontext from types import SimpleNamespace from unittest import mock @@ -39,8 +38,8 @@ _DOWN_B = f"{_PREFIX}.down_proj.lora_B.weight" class _FakeSharedSink(nn.Module): - """Stand-in for ``InklingBatchDenseMLP``: only the attributes - ``InklingBatchDenseMLPWithLoRA`` reads.""" + """Stand-in for ``InklingBatchDenseMLP``: only the attributes the LoRA + wrappers read.""" def __init__( self, @@ -48,6 +47,7 @@ class _FakeSharedSink(nn.Module): num_shared: int = _NUM_SHARED, intermediate: int = _SHARD, moe_tp_size: int = 1, + contiguous_gate_up: bool = False, ): super().__init__() self.n_shared_experts = num_shared @@ -55,10 +55,11 @@ class _FakeSharedSink(nn.Module): self.moe_tp_size = moe_tp_size self.moe_tp_rank = 0 self._linearized_bf16_enabled = True + self._w13_gate_up_contiguous = contiguous_gate_up -def _load_sink_lora_class(): - """Import the real Inkling LoRA layer against the fake dense-sink base.""" +def _load_sink_lora_module(): + """Import the real Inkling LoRA layers against the fake dense-sink base.""" stub = types.ModuleType("sglang.srt.models.inkling_common.dense_mlp") stub.InklingBatchDenseMLP = _FakeSharedSink patched = dict(sys.modules) @@ -68,23 +69,36 @@ def _load_sink_lora_class(): patched.pop("sglang.srt.models.inkling_common.lora", None) with mock.patch.dict(sys.modules, patched, clear=True): module = importlib.import_module("sglang.srt.models.inkling_common.lora") - return module.InklingBatchDenseMLPWithLoRA + return module -InklingSharedSinkWithLoRA = _load_sink_lora_class() +_lora_module = _load_sink_lora_module() +InklingSharedSinkWithLoRA = _lora_module.InklingBatchDenseMLPWithLoRA +InklingSharedSinkWithLoRAV2 = _lora_module.InklingBatchDenseMLPWithLoRAV2 +WRAPPERS = [InklingSharedSinkWithLoRA, InklingSharedSinkWithLoRAV2] +WRAPPER_IDS = ["legacy", "v2"] -def _new_sink(*, slots: int = 1, moe_tp_size: int = 1, intermediate: int = _SHARD): - layer = InklingSharedSinkWithLoRA( - moe_tp_size=moe_tp_size, intermediate=intermediate +def _new_sink( + cls=InklingSharedSinkWithLoRA, + *, + slots: int = 1, + moe_tp_size: int = 1, + intermediate: int = _SHARD, +): + layer = cls( + moe_tp_size=moe_tp_size, + intermediate=intermediate, + contiguous_gate_up=cls is InklingSharedSinkWithLoRAV2, ) - # initialize_lora() reads only these two backend fields (and flips - # is_moe_lora on the backend it is handed). + # initialize_lora() reads only these backend fields (and flips is_moe_lora + # on the backend it is handed); V2 needs the dense engine present. layer.initialize_lora( SimpleNamespace( name="triton" if slots > 1 else "torch-test", max_loras_per_batch=slots, is_moe_lora=False, + runner=object(), ) ) return layer @@ -188,8 +202,8 @@ def _pool_from_shards(shards, *, max_rank: int, slots: int = 1): return buffers -def _sink_with_shard(shards, *, max_rank: int): - layer = _new_sink(moe_tp_size=_MOE_TP_SIZE) +def _sink_with_shard(cls, shards, *, max_rank: int): + layer = _new_sink(cls, moe_tp_size=_MOE_TP_SIZE) layer.set_lora_info(*_pool_from_shards(shards, max_rank=max_rank)) return layer @@ -205,19 +219,59 @@ def _consumer_delta(layer, x, act): ) -def _reference_delta(shards, x, act): - """The same delta straight from the sharded adapter factors; the sink's w13 is - gate/up *interleaved*, so gate lands at ``[..., 0::2]`` and up at - ``[..., 1::2]`` of each expert's block.""" +def _site_delta(layer, x, act): + """The V2 wrapper's two deltas by the dense engine's contract on its bound + sites: shrink over ``a``, expand slice s from bridge block + s % bridge_slices (s when 0) into its output columns.""" + + def run(site, x): + a, b = site["a"][0], site["b"][0] + rank = b.shape[-1] + assert int(site["lora_ranks"][0]) == rank + if site.get("a_windowed"): + k, r = a.shape[-1], a.shape[0] // site["a_blocks"] + bridge = torch.cat( + [ + x[:, e * k : (e + 1) * k] @ a[e * r : (e + 1) * r].T + for e in range(site["a_blocks"]) + ], + dim=1, + ) + else: + bridge = x @ a.T + blocks = site.get("bridge_slices", 0) + offsets = site["offsets"] + starts = site.get("out_offsets", offsets[:-1]) + out = x.new_zeros(x.shape[0], offsets[-1]) + for s, (lo, hi) in enumerate(zip(offsets, offsets[1:])): + block = s % blocks if blocks else s + columns = starts[s] + torch.arange(hi - lo) + out[:, columns] += bridge[:, block * rank : (block + 1) * rank] @ b[lo:hi].T + return out + + return run(layer._gate_up, x), run(layer._down, act) + + +def _reference_delta(shards, x, act, contiguous: bool = False): + """The same delta straight from the sharded adapter factors. With the + sink's w13 gate/up *interleaved* (the legacy wrapper) gate lands at + ``[..., 0::2]`` and up at ``[..., 1::2]`` of each expert's block; on the + dense-engine wrapper's contiguous layout gate is the block's first half and + up its second.""" a_gate_up, b_gate_up, a_down, b_down = shards rank = b_gate_up.shape[-1] experts, f = b_gate_up.shape[0], b_gate_up.shape[1] // 2 gate_shrink = x @ a_gate_up[0, :rank].T up_shrink = x @ a_gate_up[0, rank:].T y = x.new_zeros(x.shape[0], experts, 2 * f) + gate_cols, up_cols = ( + (slice(0, f), slice(f, 2 * f)) + if contiguous + else (slice(0, None, 2), slice(1, None, 2)) + ) for expert in range(experts): - y[:, expert, 0::2] = gate_shrink @ b_gate_up[expert, :f].T - y[:, expert, 1::2] = up_shrink @ b_gate_up[expert, f:].T + y[:, expert, gate_cols] = gate_shrink @ b_gate_up[expert, :f].T + y[:, expert, up_cols] = up_shrink @ b_gate_up[expert, f:].T down_shrink = torch.einsum("tef,ekf->tk", act.view(-1, experts, f), a_down) return y.reshape(x.shape[0], -1), down_shrink @ b_down[0].T @@ -243,6 +297,11 @@ def _fake_adapter(*, gate_up_b: float, down_a: float, max_rank: int): def _derived_signature(layer): """Which adapter the derived operands currently hold.""" + if isinstance(layer, InklingSharedSinkWithLoRAV2): + return ( + layer._gate_up["b"].abs().max().item(), + layer._down_cat.abs().max().item(), + ) return ( layer._w1_delta.abs().max().item(), layer._a_cat.abs().max().item(), @@ -323,15 +382,13 @@ def _record_refreshes(layer, events: list) -> None: layer.on_lora_slots_updated = record -def test_derived_operands_refresh_in_place_after_slot_copy(monkeypatch): - """Guards adapter swaps landing in the pre-allocated derived operands; reds when - a swap rebinds instead of copying in place, notifies before the pool copies the - new adapter, or skips the refresh on an unload, a reload, or a base-only batch.""" +@pytest.mark.parametrize("cls", WRAPPERS, ids=WRAPPER_IDS) +def test_derived_operands_refresh_in_place_after_slot_copy(monkeypatch, cls): + """Pool copies precede refreshes, including eviction, unload, and reload.""" max_rank = _ADAPTER_RANK buffers = _empty_pool(slots=1, max_rank=max_rank) - layer = _new_sink(slots=1) + layer = _new_sink(cls, slots=1) layer.set_lora_info(*buffers) - assert layer.experts_shared_outer_loras is True events: list = [] _record_refreshes(layer, events) @@ -341,7 +398,7 @@ def test_derived_operands_refresh_in_place_after_slot_copy(monkeypatch): "uid-a": _fake_adapter(gate_up_b=1.0, down_a=0.5, max_rank=max_rank), "uid-b": _fake_adapter(gate_up_b=2.0, down_a=0.25, max_rank=max_rank), } - pointers = (layer._w1_delta.data_ptr(), layer._a_cat.data_ptr()) + pointers = tuple(buffer.data_ptr() for buffer in layer.buffers()) # The pool copies the adapter into its slot first; only then is the slot's # derived operand rebuilt. Refreshing first would derive it from zeros. @@ -396,12 +453,13 @@ def test_derived_operands_refresh_in_place_after_slot_copy(monkeypatch): assert _derived_signature(layer) == (3.0, 0.75) # Every refresh wrote through the buffers allocated at set_lora_info() time. - assert (layer._w1_delta.data_ptr(), layer._a_cat.data_ptr()) == pointers + assert tuple(buffer.data_ptr() for buffer in layer.buffers()) == pointers -def test_shared_sink_factor_layout_roundtrip(): +@pytest.mark.parametrize("cls", WRAPPERS, ids=WRAPPER_IDS) +def test_shared_sink_factor_layout_roundtrip(cls): """Guards the shared-sink factor layout from checkpoint to one moe-TP shard's - decode operands; reds on a lost ``down_proj`` transpose, gate-major gate/up + operands; reds on a lost ``down_proj`` transpose, gate-major gate/up LoRA-B, a collapsed gate/up shard, or a rank offset from the wrong rank.""" rank, hidden = _ADAPTER_RANK, _HIDDEN experts, full = _NUM_SHARED, _INTERMEDIATE @@ -450,7 +508,7 @@ def test_shared_sink_factor_layout_roundtrip(): # -- layer side: this moe-TP rank's shard ----------------------------- normalized = _normalize(_inkling_config(), dict(flat)) - layer = _new_sink(moe_tp_size=_MOE_TP_SIZE) + layer = _new_sink(cls, moe_tp_size=_MOE_TP_SIZE) shards = _shard_factors(layer, normalized) start = _MOE_TP_RANK * _SHARD # The gate half and the up half are sharded independently and re-paired, so @@ -492,18 +550,63 @@ def test_shared_sink_factor_layout_roundtrip(): x = torch.tensor([[0.5, -1.0, 0.25], [1.25, 0.75, -0.5]]) act = torch.tensor([[0.5, -0.25, 1.0, 0.75], [-1.0, 0.25, 0.5, -0.75]]) assert x.shape[-1] == hidden and act.shape[-1] == experts * _SHARD - expected_gate_up_delta, expected_down_delta = _reference_delta(shards, x, act) + expected_gate_up_delta, expected_down_delta = _reference_delta( + shards, x, act, contiguous=cls is InklingSharedSinkWithLoRAV2 + ) # A pool padded past the adapter's rank must produce the same delta as an # exactly-sized one: the up half's column offset comes from the padded # max_rank, matching where the pool stacks the up half of LoRA-A. for max_rank in (rank, rank + 1): - sink = _sink_with_shard(shards, max_rank=max_rank) - assert sink.experts_shared_outer_loras is True - gate_up_delta, down_delta = _consumer_delta(sink, x, act) + sink = _sink_with_shard(cls, shards, max_rank=max_rank) + if cls is InklingSharedSinkWithLoRA: + assert sink.experts_shared_outer_loras is True + else: + assert sink._down["kind"] == "linear" + delta = _consumer_delta if cls is InklingSharedSinkWithLoRA else _site_delta + gate_up_delta, down_delta = delta(sink, x, act) torch.testing.assert_close(gate_up_delta, expected_gate_up_delta) torch.testing.assert_close(down_delta, expected_down_delta) +def test_outer_overlap_dispatch(monkeypatch): + from sglang.srt.lora.trtllm_lora_temp import inkling_dense + from sglang.srt.models.inkling_common import moe + + sink, routed = SimpleNamespace(), SimpleNamespace() + calls = [] + alt_stream, current_stream = mock.Mock(), mock.Mock() + layer = SimpleNamespace( + shared_experts=sink, + experts=routed, + alt_stream=alt_stream, + gate=lambda x: (None, None, None, None), + _clone_fused_sink_input=False, + _forward_routed=lambda *args: calls.append("routed"), + _forward_shared=lambda *args: calls.append("sink"), + ) + legacy_gate = mock.Mock(return_value=False) + monkeypatch.setattr(inkling_dense, "allow_inkling_moe_two_stream", legacy_gate) + monkeypatch.setattr(moe, "lora_compatible_layout_enabled", lambda: True) + monkeypatch.setattr( + moe, "get_lora", lambda: SimpleNamespace(lora_backend="triton_v2") + ) + monkeypatch.setattr(moe, "get_is_capture_mode", lambda: True) + monkeypatch.setattr( + moe.envs.SGLANG_OPT_USE_INKLING_MULTI_STREAM_OVERLAP, "get", lambda: True + ) + monkeypatch.setattr(moe.torch.cuda, "current_stream", lambda: current_stream) + monkeypatch.setattr(moe.torch.cuda, "stream", lambda stream: nullcontext()) + moe.InklingMoE.forward( + layer, SimpleNamespace(is_cuda=True, shape=(64, 6144)), reduce=False + ) + # The v2 path never consults the legacy gate, and the sink runs on the side + # stream between a fork wait and a join wait. + legacy_gate.assert_not_called() + assert calls == ["sink", "routed"] + alt_stream.wait_stream.assert_called_once_with(current_stream) + current_stream.wait_stream.assert_called_once_with(alt_stream) + + if __name__ == "__main__": sys.exit(pytest.main([__file__, "-v"])) diff --git a/test/registered/unit/lora/test_lora_forward_with_base.py b/test/registered/unit/lora/test_lora_forward_with_base.py new file mode 100644 index 0000000000..dda2f08f10 --- /dev/null +++ b/test/registered/unit/lora/test_lora_forward_with_base.py @@ -0,0 +1,156 @@ +"""CPU contracts for LoRA MoE batch metadata and manager graph-mode plumbing.""" + +from __future__ import annotations + +import ast +import sys +from pathlib import Path +from types import MethodType, ModuleType, SimpleNamespace +from unittest.mock import Mock, sentinel + +import pytest + +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=1, suite="base-a-test-cpu") + + +def _lora_method(module, class_name, name): + # Load the exact method without importing the CUDA backend dependency graph. + path = Path(__file__).resolve().parents[4] / "python/sglang/srt/lora" / module + backend = next( + node + for node in ast.parse(path.read_text()).body + if isinstance(node, ast.ClassDef) and node.name == class_name + ) + method = next( + node + for node in backend.body + if isinstance(node, ast.FunctionDef) and node.name == name + ) + scope = {} + exec( + compile(ast.Module(body=[method], type_ignores=[]), str(path), "exec"), + scope, + ) + return scope[name] + + +@pytest.mark.parametrize("is_prefill,use_cuda_graph", [(False, True), (True, False)]) +def test_moe_core_calls_bound_runner_with_batch_metadata( + monkeypatch, is_prefill, use_cuda_graph +): + module = ModuleType("sglang.srt.lora.moe.runner") + module.MoeLoraBatch = SimpleNamespace + monkeypatch.setitem(sys.modules, module.__name__, module) + layout = SimpleNamespace(TP_GLOBAL=sentinel.global_layout) + metadata = SimpleNamespace( + token_slots=[-1, 1, -1], + num_tokens=2, + is_prefill=is_prefill, + use_cuda_graph=use_cuda_graph, + ) + calls = Mock() + calls.get_batch_info.return_value = metadata + calls.run.return_value = sentinel.combine_input + layer = SimpleNamespace( + lora_backend=SimpleNamespace(get_batch_info=calls.get_batch_info), + _moe_lora_runner=SimpleNamespace(run=calls.run), + gate_up_lora_a_weights=sentinel.gate_up_a, + gate_up_lora_b_weights=sentinel.gate_up_b, + down_lora_a_weights=sentinel.down_a, + down_lora_b_weights=sentinel.down_b, + ) + method = _lora_method("layers.py", "FusedMoEWithLoRA", "_run_moe_core_with_lora") + method.__globals__["LoRABatchLayout"] = layout + + assert method(layer, sentinel.dispatch) is sentinel.combine_input + calls.run.assert_called_once() + dispatch, batch = calls.run.call_args.args + assert dispatch is sentinel.dispatch + assert batch.gate_up_lora_a is sentinel.gate_up_a + assert batch.gate_up_lora_b is sentinel.gate_up_b + assert batch.down_lora_a is sentinel.down_a + assert batch.down_lora_b is sentinel.down_b + assert batch.token_lora_mapping == [-1, 1] + assert batch.is_prefill is is_prefill + assert batch.use_cuda_graph is use_cuda_graph + calls.get_batch_info.assert_called_once_with(sentinel.global_layout) + + +@pytest.mark.parametrize("graph_enabled", [False, True], ids=["eager", "graph"]) +@pytest.mark.parametrize("mode", ["decode", "prefill", "target_verify"]) +def test_manager_preserves_graph_flags_and_phase(graph_enabled, mode): + metadata = { + family: SimpleNamespace(use_cuda_graph=family != "eager") + for family in ("eager", "decode", "prefill") + } + backend = SimpleNamespace( + skip_inactive_lora_batches=False, + init_decode_cuda_graph_batch_info=lambda **_: None, + resize_cuda_graph_moe_buffers=lambda _: False, + ) + calls = Mock() + + def prepare( + batch, indices, ranks, scalings, use_cuda_graph, use_prefill_cuda_graph=False + ): + calls(batch, indices, ranks, scalings, use_cuda_graph, use_prefill_cuda_graph) + family = ( + "decode" + if use_cuda_graph + else "prefill" + if use_prefill_cuda_graph + else "eager" + ) + backend.batch_info = metadata[family] + + backend.prepare_lora_batch = prepare + slots = {None: 0, "adapter": 1} + manager = SimpleNamespace( + lora_backend=backend, + attn_dp_enabled=False, + max_loras_per_batch=2, + memory_pool=SimpleNamespace( + uid_to_buffer_id=slots, get_buffer_id=slots.__getitem__ + ), + loras={"adapter": SimpleNamespace(config=SimpleNamespace(r=8), scaling=0.5)}, + can_use_prefill_cuda_graph=lambda batch: graph_enabled and mode == "prefill", + ) + if graph_enabled: + # The real init sets the attribute _use_cuda_graph_batch probes by name, + # so a one-sided rename of either side fails the decode-graph cases. + init_decode_graph = _lora_method( + "lora_manager.py", "LoRAManager", "init_decode_cuda_graph_batch_info" + ) + init_decode_graph.__globals__["_SGLANG_EXPERIMENTAL_LORA_OPTI"] = False + init_decode_graph(manager, max_bs_in_cuda_graph=2, num_tokens_per_req=1) + manager._use_cuda_graph_batch = MethodType( + _lora_method("lora_manager.py", "LoRAManager", "_use_cuda_graph_batch"), manager + ) + batch = SimpleNamespace( + batch_size=2, + lora_ids=["adapter", None], + forward_mode=SimpleNamespace( + is_cuda_graph=lambda: mode != "prefill", + is_extend=lambda: mode != "decode", + ), + ) + + _lora_method("lora_manager.py", "LoRAManager", "prepare_lora_batch")(manager, batch) + + decode_graph = graph_enabled and mode != "prefill" + prefill_graph = graph_enabled and mode == "prefill" + calls.assert_called_once_with( + batch, [1, 0], [0, 8], [0, 0.5], decode_graph, prefill_graph + ) + family = "decode" if decode_graph else "prefill" if prefill_graph else "eager" + assert backend.batch_info is metadata[family] + assert backend.batch_info.use_cuda_graph is graph_enabled + assert backend.batch_info.has_active_lora + # MoE keeps target verification on its decode plan even on eager fallback. + assert backend.batch_info.is_prefill is (mode == "prefill") + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/unit/lora/test_lora_inactive_batch_skip.py b/test/registered/unit/lora/test_lora_inactive_batch_skip.py new file mode 100644 index 0000000000..3ce407fa1a --- /dev/null +++ b/test/registered/unit/lora/test_lora_inactive_batch_skip.py @@ -0,0 +1,89 @@ +"""Skip dense LoRA for adapter-free batches, except when capturing adapter graphs. +Decode uses the separate nolora graph variant for adapter-free batches. +""" + +from types import SimpleNamespace + +import pytest + +from sglang.srt.lora.layers import BaseLayerWithLoRA +from sglang.srt.lora.utils import kv_b_lora_correction +from sglang.srt.model_executor.runner_utils import capture_mode +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="base-a-test-cpu") + + +class _Layer(SimpleNamespace): + """A LoRA layer stand-in with the real ``lora_active`` rule.""" + + @property + def lora_active(self): + return BaseLayerWithLoRA.lora_active.fget(self) + + +class _Backend(SimpleNamespace): + def get_batch_info(self): + return self.batch_info + + +def _layer(active, *, skip_dense, set_lora=True, batch=True, backend_name="triton_v2"): + backend = _Backend( + name=backend_name, + batch_info=SimpleNamespace(has_active_lora=active) if batch else None, + skip_inactive_lora_batches=False, + skip_inactive_dense_lora=skip_dense, + ) + return _Layer(set_lora=set_lora, lora_backend=backend) + + +def _attn(layer): + return SimpleNamespace(kv_b_proj=layer) + + +@pytest.fixture +def capture(monkeypatch): + def set_state(capturing, variant=None): + monkeypatch.setattr(capture_mode, "is_capture_mode", capturing) + monkeypatch.setattr(capture_mode, "_capture_lora_variant", variant) + + return set_state + + +def test_outside_capture_only_an_inactive_v2_batch_skips_lora(capture): + capture(False) + assert _layer(True, skip_dense=True).lora_active + assert _layer(False, skip_dense=False).lora_active + assert not _layer(False, skip_dense=True).lora_active + assert not _layer(True, skip_dense=True, set_lora=False).lora_active + assert not _layer(True, skip_dense=True, batch=False).lora_active + + +@pytest.mark.parametrize( + "variant,expected", [(None, True), ("lora", True), ("nolora", False)] +) +def test_capture_keeps_lora_except_for_the_nolora_variant(capture, variant, expected): + capture(True, variant) + layer = _layer(False, skip_dense=True) + assert layer.lora_active is expected + # The kv_b correction shares the capture boundary. + assert kv_b_lora_correction(_attn(layer)) == ("v2" if expected else None) + + +def test_kv_b_correction_runs_v2_legacy_or_nothing(capture): + capture(False) + assert kv_b_lora_correction(_attn(_layer(True, skip_dense=True))) == "v2" + # An inactive triton_v2 batch runs neither correction: the legacy one + # cannot read the v2 batch info. + assert kv_b_lora_correction(_attn(_layer(False, skip_dense=True))) is None + legacy = dict(skip_dense=False, backend_name="triton") + assert kv_b_lora_correction(_attn(_layer(True, **legacy))) == "legacy" + assert kv_b_lora_correction(_attn(_layer(False, **legacy))) == "legacy" + assert ( + kv_b_lora_correction(_attn(_layer(True, skip_dense=True, set_lora=False))) + is None + ) + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/unit/lora/test_lora_manager_init_modules.py b/test/registered/unit/lora/test_lora_manager_init_modules.py index 115238c0cf..7d542eeadc 100644 --- a/test/registered/unit/lora/test_lora_manager_init_modules.py +++ b/test/registered/unit/lora/test_lora_manager_init_modules.py @@ -12,19 +12,21 @@ # limitations under the License. # ============================================================================== -"""Module-scan regressions in LoRAManager.init_lora_modules.""" +"""LoRA attachment and target-validation contracts.""" import sys import types import unittest from types import SimpleNamespace -from unittest.mock import patch +from unittest.mock import Mock, patch import torch +from sglang.srt.layers.linear import ReplicatedLinear from sglang.srt.layers.moe.fused_moe_triton.layer import FusedMoE from sglang.srt.layers.vocab_parallel_embedding import VocabParallelEmbedding from sglang.srt.lora import lora_manager as lora_manager_module +from sglang.srt.lora.lora_config import LoRAConfig from sglang.srt.lora.lora_manager import LoRAManager from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import CustomTestCase @@ -201,5 +203,69 @@ class TestShouldApplyLoRAGate(CustomTestCase): manager.init_lora_modules() +class TestTargetValidation(CustomTestCase): + """init_state rejects unsupported targets before any module is wrapped.""" + + @staticmethod + def _manager(adapter_targets=None): + manager = LoRAManager.__new__(LoRAManager) + modules = [("model.layers.0.experts", FusedMoE.__new__(FusedMoE))] + manager.base_model = SimpleNamespace(named_modules=lambda: modules) + manager.configs = {} + if adapter_targets is not None: + manager.configs["adapter"] = LoRAConfig.from_dict( + {"target_modules": adapter_targets, "r": 8, "lora_alpha": 8} + ) + manager.lora_refs = { + "adapter": SimpleNamespace(lora_name="adapter", lora_path="/unused") + } + manager.init_lora_adapters = Mock() + manager.lora_backend = Mock() + manager.init_lora_modules = Mock() + manager.init_memory_pool = Mock() + manager.lora_added_tokens_size = None + return manager + + @staticmethod + def _replicated_q(): + return patch.object( + lora_manager_module, + "get_parallel", + return_value=SimpleNamespace(dcp_replicate_q_proj=True), + ) + + def test_normalized_q_target_rejects_replication_before_attachment(self): + """Explicit and adapter-inferred q_proj targets hit the same check.""" + explicit = self._manager() + inferred = self._manager("all-linear") + inferred.base_model.named_modules().append( + ("model.layers.0.q_proj", ReplicatedLinear.__new__(ReplicatedLinear)) + ) + for manager, kwargs in ( + (explicit, dict(target_modules={"q_proj"})), + (inferred, dict(lora_paths=[object()])), + ): + with ( + self.subTest(**kwargs), + self._replicated_q(), + self.assertRaisesRegex(ValueError, "Replicated-Q"), + ): + manager.init_state(max_lora_rank=8, **kwargs) + self.assertIn("qkv_proj", manager.target_modules) + manager.init_lora_modules.assert_not_called() + manager.init_memory_pool.assert_not_called() + + def test_indexer_target_requires_unfused_projection(self): + manager = self._manager() + manager.base_model.named_modules().append( + ( + "model.layers.0.self_attn.indexer", + SimpleNamespace(use_dsa_indexer_fusion=True), + ) + ) + with self.assertRaisesRegex(ValueError, "DSA indexer Q/K fusion"): + manager.init_lora_shapes(max_lora_rank=8, target_modules={"wk"}) + + if __name__ == "__main__": unittest.main() diff --git a/test/registered/unit/lora/test_lora_moe_inplace_unit.py b/test/registered/unit/lora/test_lora_moe_inplace_unit.py index b8ce80a823..7b493790bc 100644 --- a/test/registered/unit/lora/test_lora_moe_inplace_unit.py +++ b/test/registered/unit/lora/test_lora_moe_inplace_unit.py @@ -74,7 +74,7 @@ class FusedMoEWithLoRAInplaceTest(unittest.TestCase): from sglang.srt.lora.layers import FusedMoEWithLoRA base_layer = _make_base_layer(quant_method) - lora_backend = types.SimpleNamespace() + lora_backend = types.SimpleNamespace(name="triton") self.assertTrue(base_layer.moe_runner_config.inplace) layer = FusedMoEWithLoRA(base_layer, lora_backend) return layer, base_layer diff --git a/test/registered/unit/lora/test_lora_spec_verify_batch_info.py b/test/registered/unit/lora/test_lora_spec_verify_batch_info.py index e2160cca3b..8be0708893 100644 --- a/test/registered/unit/lora/test_lora_spec_verify_batch_info.py +++ b/test/registered/unit/lora/test_lora_spec_verify_batch_info.py @@ -71,7 +71,9 @@ class TestLoRASpecVerifyBatchInfo(CustomTestCase): The matching case also pins that bs is rebound per batch, which is what makes a mixed-adapter batch index the right slots.""" backend = self._backend() - backend.init_cuda_graph_batch_info(max_bs_in_cuda_graph=4, num_tokens_per_req=4) + backend.init_decode_cuda_graph_batch_info( + max_bs_in_cuda_graph=4, num_tokens_per_req=4 + ) batch_info = self._prepare( backend, _verify_batch(bs=2, draft_token_num=4), use_cuda_graph=True diff --git a/test/registered/unit/lora/test_moe_lora_gemm_config_store.py b/test/registered/unit/lora/test_moe_lora_gemm_config_store.py new file mode 100644 index 0000000000..fe04a8df72 --- /dev/null +++ b/test/registered/unit/lora/test_moe_lora_gemm_config_store.py @@ -0,0 +1,112 @@ +"""Tuned GEMM tables load from the env override dir, fall back per file to the +packaged tables, and pick the nearest token bucket; every shipped table loads.""" + +from __future__ import annotations + +import json +import re +from pathlib import Path + +import pytest + +from sglang.srt.environ import envs +from sglang.srt.lora.moe.base_gemm_provider import gemm_config_store +from sglang.srt.lora.moe.base_gemm_provider.gemm_config_store import ( + config_file_name, + load_config_table, +) +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=3, suite="base-a-test-cpu") + +_GEOMETRY = dict(num_local_experts=32, n_gemm1=1536, n_gemm2=7168, k=7168) +_VALID = { + "version": {"cutedsl": "4.2.0", "generated_on": "GB300-152SM"}, + "tiles": [ + {"token_width": 64, "persistent_clusters": 128}, + {"token_width": 128, "persistent_clusters": 152}, + ], + "buckets": { + "8": {"token_width": 8}, + "16": {"token_width": 64}, + "96": {"token_width": 128}, + "192": {"token_width": 64}, + }, +} + + +def _write( + tmp_path: Path, payload, *, provider_key: str = "cutedsl_bf16_masked" +) -> Path: + name = config_file_name(provider_key, device_name="MOCK GPU", **_GEOMETRY) + (tmp_path / "base_gemm").mkdir(exist_ok=True) + path = tmp_path / "base_gemm" / name + path.write_text(json.dumps(payload)) + return path + + +def _load(tmp_path: Path): + with envs.SGLANG_LORA_MOE_CONFIG_DIR.override(str(tmp_path)): + return load_config_table( + "cutedsl_bf16_masked", device_name="MOCK GPU", **_GEOMETRY + ) + + +def test_valid_table_loads_via_env_override(tmp_path: Path) -> None: + _write(tmp_path, _VALID) + table = _load(tmp_path) + assert table is not None + assert table.buckets[96] == {"token_width": 128} + assert tuple((t.token_width, t.persistent_clusters) for t in table.tiles) == ( + (64, 128), + (128, 152), + ) + assert table.version["generated_on"] == "GB300-152SM" + # The nearest-M pick runs on the parsed int bucket keys. + assert table.pick(1)["token_width"] == 8 + assert table.pick(8)["token_width"] == 8 + assert table.pick(13) is table.buckets[16] + assert table.pick(90) is table.buckets[96] + assert table.pick(150) is table.buckets[192] + assert table.pick(100_000) is table.buckets[192] + + +def test_an_override_dir_without_the_file_inherits_the_packaged_one( + tmp_path: Path, monkeypatch +) -> None: + # The env-override dir is a tuner output dir carrying plans/tiles only; + # without per-file fallback it silently disables every packaged table. + package, override = tmp_path / "pkg", tmp_path / "override" + override.mkdir() + package.mkdir() + _write(package, _VALID) + monkeypatch.setattr(gemm_config_store, "_PACKAGE_CONFIG_DIR", str(package)) + table = _load(override) + assert table is not None + assert table.buckets[96] == {"token_width": 128} + + +def test_every_shipped_table_loads() -> None: + shipped = sorted( + (Path(gemm_config_store._PACKAGE_CONFIG_DIR) / "base_gemm").glob("*.json") + ) + assert shipped + pattern = re.compile( + r"provider=(\w+),E=(\d+),N1=(\d+),N2=(\d+),K=(\d+),device_name=(.+)\.json" + ) + with envs.SGLANG_LORA_MOE_CONFIG_DIR.override(None): + for path in shipped: + key, experts, n1, n2, k, device = pattern.fullmatch(path.name).groups() + table = load_config_table( + key, + num_local_experts=int(experts), + n_gemm1=int(n1), + n_gemm2=int(n2), + k=int(k), + device_name=device, + ) + assert table is not None, path.name + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/unit/lora/test_moe_lora_masked_capacity.py b/test/registered/unit/lora/test_moe_lora_masked_capacity.py new file mode 100644 index 0000000000..f373ed8273 --- /dev/null +++ b/test/registered/unit/lora/test_moe_lora_masked_capacity.py @@ -0,0 +1,27 @@ +"""Masked capacity is the smallest positive aligned bound; anything smaller +spills an expert's rows into the next expert's slab.""" + +import pytest + +from sglang.srt.lora.moe.base_gemm_provider.masked_row_domain import masked_m_max +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=2, suite="base-a-test-cpu") + + +@pytest.mark.parametrize( + ("alignment", "num_tokens"), + [(8, 0), (8, 1), (8, 8), (8, 9), (128, 128), (128, 129)], +) +def test_masked_capacity_is_minimal_positive_alignment(num_tokens, alignment): + capacity = masked_m_max(num_tokens, alignment) + assert capacity >= num_tokens + assert capacity > 0 + assert capacity % alignment == 0 + assert capacity - alignment < max(1, num_tokens) + if num_tokens and num_tokens % alignment == 0: + assert capacity == num_tokens + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/unit/lora/test_moe_lora_plan_tables.py b/test/registered/unit/lora/test_moe_lora_plan_tables.py new file mode 100644 index 0000000000..5da211ac22 --- /dev/null +++ b/test/registered/unit/lora/test_moe_lora_plan_tables.py @@ -0,0 +1,77 @@ +"""Invalid plan-table rows fail at load, even rows the selector never picks.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from sglang.srt.lora.moe import plan as ep +from sglang.srt.lora.moe.plan import ActivationFn +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="base-a-test-cpu") + + +@pytest.fixture(autouse=True) +def _packaged_plans(monkeypatch): + monkeypatch.delenv("SGLANG_LORA_MOE_CONFIG_DIR", raising=False) + ep._load_plans.cache_clear() + try: + yield + finally: + ep._load_plans.cache_clear() + + +@pytest.fixture +def override_table(tmp_path, monkeypatch): + path = tmp_path / "sm100.plans.json" + data = json.loads((Path(ep._CONFIG_DIR) / path.name).read_text()) + monkeypatch.setenv("SGLANG_LORA_MOE_CONFIG_DIR", str(tmp_path)) + + def write(): + path.write_text(json.dumps(data)) + ep._load_plans.cache_clear() + + return data, write + + +def _resolve(): + """Per-expert sm100 selection; it never picks the rows the test mutates.""" + return ep.resolve_plans( + quant_family="bf16", + architecture="sm100", + is_shared_outer=False, + physical_rank=16, + activation=ActivationFn.SILU, + hidden_size=4096, + num_local_experts=256, + ) + + +@pytest.mark.parametrize( + "defect", ("wildcard", "token_dense_b_act", "per_expert_token_a") +) +def test_invalid_unselected_rows_fail_at_load(override_table, defect): + data, write = override_table + rows = {row["name"]: row for row in (*data["scenarios"], *data["fallback"])} + if defect == "wildcard": + row = rows["decode.shared"] + row["layout"] = None + error = "requires shared-outer down-B ownership" + elif defect == "token_dense_b_act": + row = rows["prefill.shared"] + row["plan"]["gate_up_a_family"] = "token_dense" + error = "only a standalone per_row gate/up B" + else: + row = rows["fallback.prefill.per_expert"] + row["plan"]["gate_up_a_family"] = "token_grouped" + error = "requires shared-outer A ownership" + write() + with pytest.raises(ValueError, match=error): + _resolve() + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/unit/lora/test_moe_lora_prefill_graph_contract.py b/test/registered/unit/lora/test_moe_lora_prefill_graph_contract.py new file mode 100644 index 0000000000..c9687f1eb1 --- /dev/null +++ b/test/registered/unit/lora/test_moe_lora_prefill_graph_contract.py @@ -0,0 +1,415 @@ +"""CPU contracts for graph metadata and scratch using exact production method bodies. +Narrow dependencies avoid importing the scheduler/CUDA stack. +""" + +from __future__ import annotations + +import ast +import sys +from dataclasses import dataclass +from pathlib import Path +from types import MethodType, ModuleType, SimpleNamespace + +import pytest +import torch + +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=5, suite="base-a-test-cpu") + + +REPO_ROOT = Path(__file__).resolve().parents[4] +BASE_BACKEND_PATH = REPO_ROOT / "python/sglang/srt/lora/backend/base_backend.py" +V2_BACKEND_PATH = REPO_ROOT / "python/sglang/srt/lora/backend/triton_v2_backend.py" +LAYERS_PATH = REPO_ROOT / "python/sglang/srt/lora/layers.py" +MOE_RUNNER_PATH = REPO_ROOT / "python/sglang/srt/lora/moe/runner.py" +SHRINK_PATH = REPO_ROOT / "python/sglang/kernels/ops/lora/common/lora_a.py" +WORKSPACE_PATH = REPO_ROOT / "python/sglang/srt/lora/workspace.py" + + +def _load_class_with_members( + path: Path, + source_class: str, + *member_names: str, + include_fields: bool = False, + namespace: dict[str, object] | None = None, +): + tree = ast.parse(path.read_text()) + class_node = next( + node + for node in tree.body + if isinstance(node, ast.ClassDef) and node.name == source_class + ) + members = [ + node + for node in class_node.body + if ( + isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + and node.name in member_names + ) + or (include_fields and isinstance(node, ast.AnnAssign)) + ] + assert { + node.name + for node in members + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + } == set(member_names) + test_class = ast.ClassDef( + name=f"_{source_class}UnderTest", + bases=[], + keywords=[], + body=members, + decorator_list=class_node.decorator_list if include_fields else [], + ) + scope = {"__name__": __name__, **(namespace or {})} + exec( + compile( + ast.fix_missing_locations(ast.Module(body=[test_class], type_ignores=[])), + str(path), + "exec", + ), + scope, + ) + return scope[test_class.name] + + +def _load_function( + path: Path, + function_name: str, + *, + namespace: dict[str, object] | None = None, +): + tree = ast.parse(path.read_text()) + function = next( + node + for node in tree.body + if isinstance(node, ast.FunctionDef) and node.name == function_name + ) + scope = dict(namespace or {}) + exec( + compile( + ast.fix_missing_locations(ast.Module(body=[function], type_ignores=[])), + str(path), + "exec", + ), + scope, + ) + return scope[function_name] + + +@pytest.fixture +def grouped_a_runner(): + # Keep allocation and grid arithmetic real; only record the GPU call. + triton = SimpleNamespace(cdiv=lambda a, b: -(-a // b)) + shrink_tiles = _load_function( + SHRINK_PATH, "shrink_column_tiles", namespace={"triton": triton} + ) + workspace_type = _load_class_with_members( + WORKSPACE_PATH, + "LoraWorkspace", + "__init__", + "tensor", + "_capturing", + namespace={"torch": torch}, + ) + workspace = workspace_type() + allocations, launches = [], [] + + def tensor(name, shape, **kwargs): + value = workspace.tensor(name, shape, **kwargs) + allocations.append((name, tuple(shape), kwargs, value)) + return value + + site = SimpleNamespace(GATE_UP=object(), DOWN=object()) + runner_type = _load_class_with_members( + MOE_RUNNER_PATH, + "MoeLoraRunner", + "_run_a", + namespace={ + "torch": torch, + "triton": triton, + "shrink_column_tiles": shrink_tiles, + "AFamily": SimpleNamespace( + TOKEN_GROUPED=object(), PER_ROW=object(), TOKEN_DENSE=object() + ), + "BridgeLayout": SimpleNamespace(TOKEN_MAJOR=object()), + "Site": site, + "grouped_lora_a": lambda *args, **kwargs: launches.append((args, kwargs)), + }, + ) + runner = runner_type() + runner.workspace = SimpleNamespace(tensor=tensor) + runner.lora_delta_dtype = torch.bfloat16 + return runner, site, allocations, launches + + +@pytest.mark.parametrize( + ( + "split_k", + "down", + "tokens", + "rows", + "capacity", + "block_m", + "columns", + "block_n", + "tiles", + ), + [ + (4, False, 7, 21, 84, 16, 35, 32, 12), + (8, True, 3, 9, 40, 16, 16, 64, 3), + ], +) +def test_grouped_a_splitk_scratch_and_forwarded_operands( + grouped_a_runner, + split_k, + down, + tokens, + rows, + capacity, + block_m, + columns, + block_n, + tiles, +): + runner, site, allocations, launches = grouped_a_runner + spec = SimpleNamespace( + site=site.DOWN if down else site.GATE_UP, + family=SimpleNamespace(value="grouped"), + is_shared_outer=False, + output_layout=object(), + ) + route = SimpleNamespace( + num_tokens=tokens, + num_rows=rows, + sorted_pair_ids=torch.empty(capacity, dtype=torch.int32), + block_size=block_m, + ) + config = {"SPLIT_K": split_k, "BLOCK_SIZE_N": block_n} + requested_sites = [] + + def for_a(selected_site): + requested_sites.append(selected_site) + return config + + input = torch.empty((rows if down else tokens, 128), dtype=torch.bfloat16) + weight = torch.empty((4, columns, 128), dtype=torch.bfloat16) + pair_to_row = torch.arange(rows, dtype=torch.int32) if down else None + output = runner._run_a( + SimpleNamespace(for_a=for_a), + spec, + input, + weight, + SimpleNamespace(aligned=lambda shared: route), + "down_a" if down else "gate_up_a", + pair_to_row=pair_to_row, + ) + name = "down_a" if down else "gate_up_a" + assert requested_sites == [spec.site] + assert output.shape == (rows, columns) # Neither token count nor padded capacity. + assert output.dtype == torch.bfloat16 + assert allocations[0][:2] == (f"{name}:output", (rows, columns)) + assert all(kwargs["device"] == input.device for _, _, kwargs, _ in allocations) + assert len(launches) == 1 + args, kwargs = launches[0] + assert len(args) == 4 + assert all( + actual is expected + for actual, expected in zip(args, (input, weight, output, route)) + ) + assert kwargs["config"] is config + assert kwargs["pair_input"] is down + assert kwargs["pair_to_row"] is pair_to_row + assert len(allocations) == 3 + partial, counters = kwargs["partial"], kwargs["counters"] + assert partial is allocations[1][3] + assert counters is allocations[2][3] + assert allocations[1][:2] == (f"{name}:partial", (split_k, rows, columns)) + assert allocations[2][:2] == (f"{name}:splitk_counters", (tiles,)) + assert partial.shape == (split_k, rows, columns) + assert counters.shape == (tiles,) + assert partial.dtype == torch.float32 + assert counters.dtype == torch.int32 + assert allocations[2][2]["zero_on_first_allocation"] is True + assert counters.count_nonzero().item() == 0 + + +@pytest.fixture +def mapping_functions(): + return _load_function( + BASE_BACKEND_PATH, + "_compute_token_lora_mapping", + namespace={ + "torch": torch, + "triton": SimpleNamespace(cdiv=lambda a, b: -(-a // b)), + }, + ) + + +@pytest.fixture +def v2_backend(mapping_functions): + def unpinned_empty(*args, **kwargs): + # CPU-only builds have no pinned allocator; tensor operations stay real. + kwargs.pop("pin_memory", None) + return torch.empty(*args, **kwargs) + + cpu_torch = SimpleNamespace( + empty=unpinned_empty, + zeros=torch.zeros, + arange=torch.arange, + as_tensor=torch.as_tensor, + int32=torch.int32, + float32=torch.float32, + ) + batch_type = _load_class_with_members( + V2_BACKEND_PATH, + "_BatchInfo", + include_fields=True, + namespace={"torch": torch, "dataclass": dataclass}, + ) + get_counts = _load_function( + REPO_ROOT / "python/sglang/srt/lora/utils.py", "get_batch_token_counts" + ) + backend_type = _load_class_with_members( + V2_BACKEND_PATH, + "TritonV2LoRABackend", + "_new_batch", + "_fill_batch", + "prepare_lora_batch", + "init_decode_cuda_graph_batch_info", + "init_prefill_cuda_graph_batch_info", + namespace={ + "torch": cpu_torch, + "_BatchInfo": batch_type, + "_compute_token_lora_mapping": mapping_functions, + "get_batch_token_counts": get_counts, + "Phase": SimpleNamespace(PREFILL="prefill", DECODE="decode"), + }, + ) + backend = backend_type() + backend.name = "triton_v2" + backend.max_loras_per_batch = 3 + backend.device = torch.device("cpu") + backend.get_batch_info = MethodType( + _load_class_with_members( + BASE_BACKEND_PATH, "BaseLoRABackend", "get_batch_info" + ).get_batch_info, + backend, + ) + backend.lm_head_runner = None + bindings = [] + backend.runner = SimpleNamespace( + begin_batch=lambda **kwargs: bindings.append(kwargs) + ) + backend.bindings = bindings + return backend + + +@pytest.fixture +def moe_payload_builder(monkeypatch): + module_name = "sglang.srt.lora.moe.runner" + module = ModuleType(module_name) + module.MoeLoraBatch = SimpleNamespace + monkeypatch.setitem(sys.modules, module_name, module) + layer_type = _load_class_with_members( + LAYERS_PATH, + "FusedMoEWithLoRA", + "_run_moe_core_with_lora", + namespace={"LoRABatchLayout": SimpleNamespace(TP_GLOBAL=object())}, + ) + layer = layer_type() + layer.gate_up_lora_a_weights = torch.empty(1) + layer.gate_up_lora_b_weights = torch.empty(1) + layer.down_lora_a_weights = torch.empty(1) + layer.down_lora_b_weights = torch.empty(1) + + def build(backend): + layer.lora_backend = backend + layer._moe_lora_runner = SimpleNamespace(run=lambda dispatch, batch: batch) + payload = layer._run_moe_core_with_lora(object()) + assert payload.gate_up_lora_a is layer.gate_up_lora_a_weights + assert payload.gate_up_lora_b is layer.gate_up_lora_b_weights + assert payload.down_lora_a is layer.down_lora_a_weights + assert payload.down_lora_b is layer.down_lora_b_weights + return payload + + return build + + +@pytest.mark.parametrize("mode", ["eager", "prefill_graph", "decode_graph"]) +def test_v2_live_moe_views_preserve_dense_graph_capacity( + v2_backend, moe_payload_builder, mode +): + decode = mode == "decode_graph" + graph = mode != "eager" + if decode: + v2_backend.init_decode_cuda_graph_batch_info(6, 1) + cases = [([1, 1, 1], [1, 2, 0]), ([1], [2]), ([], [])] + else: + if graph: + v2_backend.init_prefill_cuda_graph_batch_info(12) + cases = [([2, 0, 3, 1], [1, 2, 0, 1]), ([1, 2], [2, 0]), ([0, 0], [1, 2])] + addresses = None + for lengths, slots in cases: + forward_batch = SimpleNamespace( + batch_size=len(lengths), + extend_num_tokens=sum(lengths), + extend_seq_lens_cpu=lengths, + forward_mode=SimpleNamespace( + is_decode=lambda: decode, + is_target_verify=lambda: False, + is_idle=lambda: False, + is_extend=lambda: not decode, + is_extend_without_speculative=lambda: not decode, + ), + ) + ranks = [0, 8, 0] + v2_backend.prepare_lora_batch( + forward_batch, + slots, + ranks, + [0.0, 0.25, 0.0], + use_decode_cuda_graph=decode, + use_prefill_cuda_graph=mode == "prefill_graph", + ) + batch = v2_backend.batch_info + # The manager selects the MoE phase after backend preparation. + batch.is_prefill = not decode + expected = [ + slot if ranks[slot] else -1 + for length, slot in zip(lengths, slots) + for _ in range(length) + ] + assert batch.num_tokens == len(expected) + capacity = (6 if decode else 12) if graph else len(expected) + request_capacity = capacity if graph else len(lengths) + assert batch.token_slots.tolist() == expected + [-1] * ( + capacity - len(expected) + ) + assert batch.weight_indices.numel() == request_capacity + assert batch.seg_indptr.numel() == request_capacity + 1 + assert batch.weight_indices[: len(slots)].tolist() == slots + bound = v2_backend.bindings[-1] + assert bound["token_slots"] is batch.token_slots + assert bound["token_slots"].shape == (capacity,) + assert bound["num_tokens"] == len(expected) + assert bound["graph_mode"] is graph + assert bound["is_prefill_graph"] is (mode == "prefill_graph") + + payload = moe_payload_builder(v2_backend) + assert payload.token_lora_mapping.tolist() == expected + assert payload.token_lora_mapping.shape == (batch.num_tokens,) + assert payload.token_lora_mapping.untyped_storage().data_ptr() == ( + batch.token_slots.untyped_storage().data_ptr() + ) + assert payload.use_cuda_graph is graph + assert payload.is_prefill is (not decode) + if graph: + current = batch.packed.data_ptr(), batch.token_slots.data_ptr() + if addresses is not None: + assert current == addresses + addresses = current + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/unit/lora/test_moe_lora_provider_contract.py b/test/registered/unit/lora/test_moe_lora_provider_contract.py new file mode 100644 index 0000000000..2c5a5f9c9c --- /dev/null +++ b/test/registered/unit/lora/test_moe_lora_provider_contract.py @@ -0,0 +1,137 @@ +"""Real provider methods test admission, geometry, and finalization with GPU boundaries mocked.""" + +from __future__ import annotations + +import ast +import sys +import types +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest import mock + +import torch + +from sglang.test.ci.ci_register import register_cpu_ci +from sglang.test.test_utils import CustomTestCase + +register_cpu_ci(est_time=3, suite="base-a-test-cpu") + + +ROOT = Path(__file__).resolve().parents[4] +PROVIDER = ROOT / "python/sglang/srt/lora/moe/base_gemm_provider" + + +def _function(source: str, name: str) -> str: + tree = ast.parse(source) + for node in ast.walk(tree): + if ( + isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + and node.name == name + ): + return ast.get_source_segment(source, node) or "" + raise AssertionError(f"function {name!r} not found") + + +class TestNvFp4PreparedQuantInfo(CustomTestCase): + def test_non_bf16_activations_fail_without_mutation(self): + from sglang.srt.lora.moe.quant_info import MoeLoraNvFp4MarlinQuantInfo + + # FP16 is the silent case: Marlin accepts half activations while the + # runner allocates BF16 stage buffers; FP32 fails loudly in the JIT. + layer = SimpleNamespace( + params_dtype=torch.float16, + w13_weight=torch.zeros((2, 4, 512), dtype=torch.int32), + w2_weight=torch.zeros((2, 8, 128), dtype=torch.int32), + w13_weight_scale=torch.zeros((2, 4, 256), dtype=torch.float8_e4m3fn), + w2_weight_scale=torch.zeros((2, 8, 64), dtype=torch.float8_e4m3fn), + w13_weight_scale_2=torch.ones(2, dtype=torch.float16), + w2_weight_scale_2=torch.zeros(2, dtype=torch.float16), + moe_runner_config=SimpleNamespace(is_gated=True), + num_local_experts=2, + intermediate_size_per_partition=128, + hidden_size=64, + ) + original = vars(layer).copy() + with self.assertRaisesRegex(NotImplementedError, "BF16 activations"): + MoeLoraNvFp4MarlinQuantInfo.from_layer(layer) + for name, value in original.items(): + self.assertIs(getattr(layer, name), value) + + +class TestProviderGeometry(CustomTestCase): + def test_triton_fp8_k_tiles_stay_within_scale_groups(self): + source = _function((PROVIDER / "triton_bf16.py").read_text(), "_config_for") + namespace = {} + exec("from __future__ import annotations\n" + source, namespace) + config_for = namespace["_config_for"] + module = types.ModuleType( + "sglang.srt.layers.moe.moe_runner.triton_utils.fused_moe_triton_config" + ) + # The FP8 GEMM loads one scale per K block: a 256-wide block over + # [128, 128] scale groups would apply the first group's scale to its + # second half, and upstream never clamps override or table configs. + original = {"BLOCK_SIZE_K": 256, "USE_TMA": True} + upstream = (dict(original), dict(original)) + module.try_get_optimal_moe_config = mock.Mock( + return_value=(upstream[0], (upstream[1], None)) + ) + provider = SimpleNamespace( + quant_info=SimpleNamespace( + w13_weight=SimpleNamespace(shape=(2, 256, 128)), + w2_weight=SimpleNamespace(shape=(2, 128, 128)), + ), + _config_dtype_tag="fp8_w8a8", + _config_block_shape=[128, 128], + _configs={}, + ) + with mock.patch.dict(sys.modules, {module.__name__: module}): + resolved = config_for(provider, 32, 2) + self.assertIs(config_for(provider, 32, 2), resolved) + for actual, cached in zip(resolved, upstream): + self.assertEqual(actual, {"BLOCK_SIZE_K": 128}) + self.assertEqual(cached, original) + self.assertIsNot(actual, cached) + module.try_get_optimal_moe_config.assert_called_once() + + +class TestMaterializedFinalize(CustomTestCase): + """Execute the host dispatch with real CPU buffers and mocked GPU launches.""" + + def test_materialized_finalize_preserves_strided_weights(self): + from sglang.srt.lora.moe.base_gemm_provider.base import MoeBaseProvider + + finalize = types.ModuleType("sglang.kernels.ops.lora.moe.finalize") + finalize.invoke_small_finalize = mock.Mock() + reorder = types.ModuleType("sglang.kernels.ops.moe.ep_moe_kernels") + reorder.post_reorder_deepgemm = mock.Mock() + # Production hands over strided top-k weight views; post_reorder_deepgemm + # addresses them contiguously, so even a small batch must not take the + # gather path and must receive a contiguous copy. + tokens = 64 + weights = torch.arange(tokens * 6).view(tokens, 6)[:, ::2] + ids = torch.zeros((tokens, 3), dtype=torch.int64) + output = torch.empty((tokens, 5)) + delta = torch.empty((tokens, 3, 5)) + with mock.patch.dict( + sys.modules, {finalize.__name__: finalize, reorder.__name__: reorder} + ): + MoeBaseProvider().finalize( + SimpleNamespace(pair_to_row=torch.arange(tokens * 3)), + torch.empty((tokens * 3, 5)), + ids, + weights, + 2.5, + output, + lora_delta=delta, + ) + finalize.invoke_small_finalize.assert_not_called() + call = reorder.post_reorder_deepgemm.call_args + actual = call.args[4] + self.assertTrue(actual.is_contiguous()) + torch.testing.assert_close(actual, weights) + self.assertIs(call.kwargs["lora_delta"], delta) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/registered/unit/lora/test_moe_lora_route_factory.py b/test/registered/unit/lora/test_moe_lora_route_factory.py new file mode 100644 index 0000000000..b6bbf88fe6 --- /dev/null +++ b/test/registered/unit/lora/test_moe_lora_route_factory.py @@ -0,0 +1,186 @@ +"""CPU routing/workspace contracts; CUDA tests check route contents and replay.""" + +from __future__ import annotations + +import importlib.util +import sys +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock, patch + +import pytest +import torch + +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=2, suite="base-a-test-cpu") + +_PYTHON = Path(__file__).resolve().parents[4] / "python" + + +def _load(name, source): + spec = importlib.util.spec_from_file_location(name, _PYTHON / source) + module = importlib.util.module_from_spec(spec) + with patch.dict(sys.modules, {name: module}): + spec.loader.exec_module(module) + return module + + +_VIEW = _load("_route_view", "sglang/kernels/ops/lora/common/route_view.py") +_TRITON = SimpleNamespace( + jit=lambda function: function, + cdiv=lambda value, divisor: (value + divisor - 1) // divisor, + language=SimpleNamespace(), +) +with patch.dict( + sys.modules, + { + "triton": _TRITON, + "triton.language": _TRITON.language, + "sglang.kernels.ops.lora.common.route_view": _VIEW, + "sglang.kernels.ops.lora.moe.virtual_experts": SimpleNamespace( + _align_block_size_jit=None + ), + }, +): + ROUTING = _load("_route_factory", "sglang/kernels/ops/lora/common/routing.py") +Workspace = _load("_route_workspace", "sglang/srt/lora/workspace.py").LoraWorkspace + + +@pytest.mark.parametrize("cached", [False, True]) +def test_large_route_scratch_is_fresh_or_workspace_backed(cached): + workspace = Workspace() if cached else None + + def allocate(num_buckets=5): + return ROUTING._aligned_route_scratch( + workspace, + prefix="route", + num_buckets=num_buckets, + capacity=64, + block_size=16, + device=torch.device("cpu"), + ) + + first = allocate() + assert first["sorted"].shape == (64,) + assert first["block_bucket_ids"].shape == (4,) + assert torch.equal(first["counts"], torch.zeros(5, dtype=torch.int32)) + first["counts"].fill_(7) + second = allocate() + assert (first["sorted"].data_ptr() == second["sorted"].data_ptr()) == cached + assert torch.equal(second["counts"], torch.full((5,), 7 if cached else 0)) + grown = allocate(num_buckets=8)["counts"] + assert grown.data_ptr() != first["counts"].data_ptr() + assert not grown.any() + + +def test_stream_keys_separate_scratch_and_routes(monkeypatch): + workspace = Workspace() + device, stream = torch.device("cuda:0"), 11 + mapping = SimpleNamespace( + device=device, + is_cuda=True, + dtype=torch.int32, + data_ptr=lambda: 1234, + numel=lambda: 8, + stride=lambda: (1,), + ) + monkeypatch.setattr(workspace, "_caller", lambda _: stream) + monkeypatch.setattr(workspace, "_capturing", lambda _: False) + empty = torch.empty + # CPU storage stands in for CUDA storage: this tests keys, not synchronization. + monkeypatch.setattr( + torch, "empty", lambda shape, *, dtype, device: empty(shape, dtype=dtype) + ) + build = Mock(side_effect=object) + + def lookup(): + return workspace.route(mapping, ("sorted", 16), build) + + first = workspace.tensor("rank", (8,), dtype=torch.float32, device=device) + first_route = lookup() + assert lookup() is first_route + stream = 22 + second = workspace.tensor("rank", (8,), dtype=torch.float32, device=device) + assert second.data_ptr() != first.data_ptr() + assert lookup() is not first_route + stream = 11 + assert lookup() is first_route + assert ( + workspace.tensor("rank", (4,), dtype=torch.float32, device=device).data_ptr() + == first.data_ptr() + ) + workspace.begin_forward(graph_mode=True) + decode = lookup() + workspace.begin_forward(graph_mode=True, is_prefill_graph=True) + prefill = lookup() + assert prefill is not decode + workspace.routes.clear() + assert lookup() is not prefill + assert build.call_count == 5 + + +def test_route_cache_keys_match_mapping_and_options(): + workspace = Workspace() + slots = torch.arange(32, dtype=torch.int32) % 4 + key, build = ("sorted", 16, 4), Mock(side_effect=object) + first = workspace.route(slots, key, build) + assert workspace.route(slots[:], key, build) is first + build.assert_called_once_with() + for mapping, options in ( + (slots.clone(), key), + (slots[:16], key), + (slots[1:17], key), + (slots[::2], key), + (slots.view(torch.float32), key), + (slots, ("sorted", 32, 4)), + (slots, ("sorted", 16, 8)), + ): + build.reset_mock() + route = workspace.route(mapping, options, build) + assert workspace.route(mapping, options, build) is route + build.assert_called_once_with() + + +def test_moe_route_bundle_passes_each_route_its_view_groups_and_prefix(monkeypatch): + from sglang.srt.lora.moe import routing as moe_routing + from sglang.srt.lora.moe.plan import RouteBuilderFamily, RouteRequirement + + slots = torch.tensor([0, 1, -1], dtype=torch.int32) + topk = torch.tensor([[0, 2], [1, 0], [-1, 2]], dtype=torch.int32) + built = {} + + def build(mapping, **kwargs): + route = object() + built[route] = mapping, kwargs + return route + + monkeypatch.setattr(moe_routing, "build_route", build) + plan = SimpleNamespace( + route_requirements=lambda: set(RouteRequirement), + route_builder=RouteBuilderFamily.STANDARD, + ) + routes = moe_routing.build_moe_routes( + plan, + topk_ids=topk, + token_lora_mapping=slots, + num_local_experts=3, + max_loras=2, + block_size=16, + workspace=Workspace(), + ) + for requirement in RouteRequirement: + name = requirement.name + field = name.lower().removesuffix("_plan") + _, args = built[getattr(routes, field)] + assert args["view"].value == ("raw" if name.startswith("RAW_") else "aligned") + assert args.get("group_ids") is (None if name == "SHARED_TOKEN_PLAN" else topk) + assert args.get("groups_per_slot", 1) == ( + 3 if name.endswith("PER_EXPERT") else 1 + ) + if name.startswith("ALIGNED_"): + assert args["tensor_prefix"] == f"route:{field}" + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/unit/lora/test_moe_lora_stage_dispatch.py b/test/registered/unit/lora/test_moe_lora_stage_dispatch.py new file mode 100644 index 0000000000..9830983951 --- /dev/null +++ b/test/registered/unit/lora/test_moe_lora_stage_dispatch.py @@ -0,0 +1,76 @@ +"""The token-dense LoRA-A family reaches its executor and writes its bridge. + +Only the SM100 shared-outer NVFP4 decode plan selects it, so this real CPU +matmul is its only executor oracle; the other families run on GPU through the +runner with real routes. +""" + +import ast +from pathlib import Path +from types import SimpleNamespace + +import pytest +import torch + +from sglang.srt.lora.moe.plan import AFamily, BridgeLayout, Site +from sglang.test.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=2, suite="base-a-test-cpu") + +ROOT = Path(__file__).resolve().parents[4] +SOURCE = ROOT / "python/sglang/srt/lora/moe" + + +def _method(path, name, **scope): + """Execute the production host method without importing CUDA extensions.""" + tree = ast.parse((SOURCE / path).read_text()) + method = next( + node + for node in ast.walk(tree) + if isinstance(node, ast.FunctionDef) and node.name == name + ) + method.decorator_list = [] + module = ast.Module( + body=[*ast.parse("from __future__ import annotations").body, method], + type_ignores=[], + ) + exec(compile(module, str(SOURCE / path), "exec"), scope) + return scope[name] + + +def test_a_family_writes_its_bridge(): + # Regression: NVFP4 shared plans admitted token_dense before it had an executor. + spec = SimpleNamespace( + family=AFamily.TOKEN_DENSE, + site=Site.GATE_UP, + is_shared_outer=True, + output_layout=BridgeLayout.TOKEN_MAJOR, + ) + owner = SimpleNamespace( + workspace=SimpleNamespace( + tensor=lambda _, shape, **kw: torch.empty(shape, **kw) + ), + lora_delta_dtype=torch.float32, + ) + routes = SimpleNamespace( + raw=lambda _: SimpleNamespace(num_tokens=5, num_rows=10, max_loras=3) + ) + run = _method( + "runner.py", + "_run_a", + torch=torch, + AFamily=AFamily, + BridgeLayout=BridgeLayout, + Site=Site, + ) + x = torch.arange(5 * 16, dtype=torch.float32).reshape(5, 16) / 80 + weight = torch.arange(3 * 8 * 16, dtype=torch.float32).reshape(3, 8, 16) / 384 + result = run( + owner, SimpleNamespace(for_a=lambda _: {}), spec, x, weight, routes, "a" + ) + # One bridge plane per resident slot, dense over every token. + torch.testing.assert_close(result, torch.stack([x @ slot.T for slot in weight])) + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v"])) diff --git a/test/registered/unit/lora/test_triton_dp_attention_unit.py b/test/registered/unit/lora/test_triton_dp_attention_unit.py index e6352cf003..0cec265334 100644 --- a/test/registered/unit/lora/test_triton_dp_attention_unit.py +++ b/test/registered/unit/lora/test_triton_dp_attention_unit.py @@ -286,7 +286,7 @@ def test_communicator_publishes_layout_at_each_transition( def test_manager_uses_current_dp_cuda_graph_eligibility(can_run_decode_cuda_graph): manager = LoRAManager.__new__(LoRAManager) manager.attn_dp_enabled = True - manager.max_bs_in_cuda_graph = 4 + manager.max_bs_in_decode_cuda_graph = 4 tokens = torch.zeros(2, dtype=torch.int64) forward_batch = ForwardBatch( forward_mode=ForwardMode.DECODE, diff --git a/test/registered/unit/models/test_nemotron_h_shared_add.py b/test/registered/unit/models/test_nemotron_h_shared_add.py index e8e757fe2e..c98b8108aa 100644 --- a/test/registered/unit/models/test_nemotron_h_shared_add.py +++ b/test/registered/unit/models/test_nemotron_h_shared_add.py @@ -17,6 +17,7 @@ import torch import torch.nn.functional as F from sglang.srt.layers.linear import ReplicatedLinear +from sglang.srt.lora.backend.base_backend import BaseLoRABackend from sglang.srt.lora.layers import ReplicatedLinearWithLoRA from sglang.srt.models.nemotron_h import ( NemotronHMoE, @@ -34,6 +35,8 @@ class _DoubleMethod: class _FakeLoRABackend: batch_info = object() skip_inactive_lora_batches = False + skip_inactive_dense_lora = False + forward_with_base = BaseLoRABackend.forward_with_base def get_batch_info(self, layout=None): return self.batch_info diff --git a/test/registered/unit/server_args/test_server_args.py b/test/registered/unit/server_args/test_server_args.py index a8a9975a85..a43b9fc73b 100644 --- a/test/registered/unit/server_args/test_server_args.py +++ b/test/registered/unit/server_args/test_server_args.py @@ -48,6 +48,7 @@ from sglang.srt.arg_groups.kv_shard_hook import ( handle_kv_cache_sharding, validate_kv_shard_attention_backend, ) +from sglang.srt.arg_groups.lora_hook import check_lora_server_args from sglang.srt.arg_groups.mamba_hook import handle_mamba_backend from sglang.srt.arg_groups.memory_hook import handle_gpu_memory_settings from sglang.srt.arg_groups.model_path_hook import handle_load_format @@ -1281,6 +1282,28 @@ class TestKV4Compatibility(unittest.TestCase): handle_kv4_compatibility(args) +class TestLoraForwardDomains(unittest.TestCase): + def test_rejects_concurrent_forwards(self): + for runner in ("auto", "lora_cutedsl"): + for options in ( + {"enable_pdmux": True}, + {"enable_two_batch_overlap": True}, + ): + with self.subTest(runner=runner, options=options): + args = ServerArgs( + model_path="dummy", + tp_size=2, + enable_lora=True, + lora_backend="triton_v2", + moe_runner_backend=runner, + max_lora_rank=8, + lora_target_modules=["down_proj"], + **options, + ) + with self.assertRaises(ValueError): + check_lora_server_args(args) + + class TestLoadBalanceMethod(unittest.TestCase): def _load_balance_args(self, **kwargs): server_args = ServerArgs(model_path="dummy", **kwargs)